diff --git a/flutter/engine/src/flutter/shell/platform/android/context/BUILD.gn b/flutter/engine/src/flutter/shell/platform/android/context/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..31c5f0ecb95aba74a1e48a8d88e9e09a4d2d88db --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/context/BUILD.gn @@ -0,0 +1,26 @@ +# 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. + +import("//flutter/common/config.gni") +import("//flutter/shell/config.gni") + +source_set("context") { + sources = [ + "android_context.cc", + "android_context.h", + ] + + public_configs = [ "//flutter:config" ] + + deps = [ + "//flutter/common", + "//flutter/fml", + "//flutter/impeller/renderer", + "//flutter/skia", + ] + + if (shell_enable_vulkan) { + deps += [ "//flutter/vulkan" ] + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/context/android_context.cc b/flutter/engine/src/flutter/shell/platform/android/context/android_context.cc new file mode 100644 index 0000000000000000000000000000000000000000..ed0970cb73d12cbe0a85aef76b0e821ec480a36c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/context/android_context.cc @@ -0,0 +1,47 @@ +// 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/shell/platform/android/context/android_context.h" + +namespace flutter { + +AndroidContext::AndroidContext(AndroidRenderingAPI rendering_api) + : rendering_api_(rendering_api) {} + +AndroidContext::~AndroidContext() { + if (main_context_) { + main_context_->releaseResourcesAndAbandonContext(); + } + if (impeller_context_) { + impeller_context_->Shutdown(); + } +}; + +AndroidRenderingAPI AndroidContext::RenderingApi() const { + return rendering_api_; +} + +bool AndroidContext::IsValid() const { + return true; +} + +void AndroidContext::SetMainSkiaContext( + const sk_sp& main_context) { + main_context_ = main_context; +} + +sk_sp AndroidContext::GetMainSkiaContext() const { + return main_context_; +} + +std::shared_ptr AndroidContext::GetImpellerContext() const { + return impeller_context_; +} + +void AndroidContext::SetImpellerContext( + const std::shared_ptr& context) { + impeller_context_ = context; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/context/android_context.h b/flutter/engine/src/flutter/shell/platform/android/context/android_context.h new file mode 100644 index 0000000000000000000000000000000000000000..e2ac4e97fad275abe94ec02fbe619666af33b052 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/context/android_context.h @@ -0,0 +1,86 @@ +// 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_SHELL_PLATFORM_ANDROID_CONTEXT_ANDROID_CONTEXT_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_CONTEXT_ANDROID_CONTEXT_H_ + +#include "flutter/fml/macros.h" +#include "flutter/impeller/base/flags.h" +#include "flutter/impeller/renderer/context.h" +#include "flutter/shell/platform/android/android_rendering_selector.h" +#include "third_party/skia/include/gpu/ganesh/GrDirectContext.h" + +namespace flutter { + +//------------------------------------------------------------------------------ +/// @brief Holds state that is shared across Android surfaces. +/// +class AndroidContext { + public: + explicit AndroidContext(AndroidRenderingAPI rendering_api); + + virtual ~AndroidContext(); + + struct ContextSettings { + bool enable_validation = false; + bool enable_gpu_tracing = false; + bool enable_surface_control = false; + bool quiet = false; + impeller::Flags impeller_flags; + }; + + AndroidRenderingAPI RenderingApi() const; + + virtual bool IsValid() const; + + //---------------------------------------------------------------------------- + /// @brief Setter for the Skia context to be used by subsequent + /// AndroidSurfaces. + /// @details This is useful to reduce memory consumption when creating + /// multiple AndroidSurfaces for the same AndroidContext. + /// + /// The first AndroidSurface should set this for the + /// AndroidContext if the AndroidContext does not yet have a + /// Skia context to share via GetMainSkiaContext. + /// + void SetMainSkiaContext(const sk_sp& main_context); + + //---------------------------------------------------------------------------- + /// @brief Accessor for the Skia context associated with AndroidSurfaces + /// and the raster thread. + /// @details This context is created lazily by the AndroidSurface based + /// on their respective rendering backend and set on this + /// AndroidContext to share via SetMainSkiaContext. + /// @returns `nullptr` when no Skia context has been set yet by its + /// AndroidSurface via SetMainSkiaContext. + /// @attention The software context doesn't have a Skia context, so this + /// value will be nullptr. + /// + sk_sp GetMainSkiaContext() const; + + //---------------------------------------------------------------------------- + /// @brief Accessor for the Impeller context associated with + /// AndroidSurfaces and the raster thread. + /// + std::shared_ptr GetImpellerContext() const; + + protected: + /// Intended to be called from a subclass constructor after setup work for the + /// context has completed. + void SetImpellerContext(const std::shared_ptr& context); + + private: + const AndroidRenderingAPI rendering_api_; + + // This is the Skia context used for on-screen rendering. + sk_sp main_context_; + + std::shared_ptr impeller_context_; + + FML_DISALLOW_COPY_AND_ASSIGN(AndroidContext); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_CONTEXT_ANDROID_CONTEXT_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/BUILD.gn b/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..0c85a4d2fd1dd67a932ea86da0886e57173136c4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/BUILD.gn @@ -0,0 +1,55 @@ +# 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. + +import("//flutter/common/config.gni") +import("//flutter/testing/testing.gni") + +source_set("external_view_embedder") { + sources = [ + "external_view_embedder.cc", + "external_view_embedder.h", + "external_view_embedder_2.cc", + "external_view_embedder_2.h", + "surface_pool.cc", + "surface_pool.h", + ] + + public_configs = [ "//flutter:config" ] + + deps = [ + "//flutter/common", + "//flutter/flow", + "//flutter/fml", + "//flutter/shell/platform/android/context", + "//flutter/shell/platform/android/jni", + "//flutter/shell/platform/android/surface", + "//flutter/skia", + ] +} + +test_fixtures("external_view_embedder_fixtures") { + fixtures = [] +} + +executable("android_external_view_embedder_unittests") { + testonly = true + + sources = [ + "external_view_embedder_unittests.cc", + "surface_pool_unittests.cc", + ] + + deps = [ + ":external_view_embedder", + ":external_view_embedder_fixtures", + "//flutter/flow", + "//flutter/shell/gpu:gpu_surface_gl", + "//flutter/shell/platform/android/jni:jni_mock", + "//flutter/shell/platform/android/surface", + "//flutter/shell/platform/android/surface:surface_mock", + "//flutter/testing", + "//flutter/testing:dart", + "//flutter/testing:skia", + ] +} diff --git a/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder.cc b/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder.cc new file mode 100644 index 0000000000000000000000000000000000000000..77962bcb3fccb5facb6266c53ab58c3bb8d29f4c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder.cc @@ -0,0 +1,277 @@ +// 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/shell/platform/android/external_view_embedder/external_view_embedder.h" +#include "flow/view_slicer.h" +#include "flutter/common/constants.h" +#include "flutter/fml/synchronization/waitable_event.h" +#include "flutter/fml/trace_event.h" + +namespace flutter { + +AndroidExternalViewEmbedder::AndroidExternalViewEmbedder( + const AndroidContext& android_context, + std::shared_ptr jni_facade, + std::shared_ptr surface_factory, + const TaskRunners& task_runners) + : ExternalViewEmbedder(), + android_context_(android_context), + jni_facade_(std::move(jni_facade)), + surface_factory_(std::move(surface_factory)), + surface_pool_( + std::make_unique(/*use_new_surface_methods=*/false)), + task_runners_(task_runners) {} + +// |ExternalViewEmbedder| +void AndroidExternalViewEmbedder::PrerollCompositeEmbeddedView( + int64_t view_id, + std::unique_ptr params) { + TRACE_EVENT0("flutter", + "AndroidExternalViewEmbedder::PrerollCompositeEmbeddedView"); + + SkRect view_bounds = SkRect::Make(frame_size_); + std::unique_ptr view; + view = std::make_unique(view_bounds); + slices_.insert_or_assign(view_id, std::move(view)); + + composition_order_.push_back(view_id); + // Update params only if they changed. + if (view_params_.count(view_id) == 1 && + view_params_.at(view_id) == *params.get()) { + return; + } + view_params_.insert_or_assign(view_id, EmbeddedViewParams(*params.get())); +} + +// |ExternalViewEmbedder| +DlCanvas* AndroidExternalViewEmbedder::CompositeEmbeddedView(int64_t view_id) { + if (slices_.count(view_id) == 1) { + return slices_.at(view_id)->canvas(); + } + return nullptr; +} + +SkRect AndroidExternalViewEmbedder::GetViewRect(int64_t view_id) const { + const EmbeddedViewParams& params = view_params_.at(view_id); + // TODO(egarciad): The rect should be computed from the mutator stack. + // (Clipping is missing) + // https://github.com/flutter/flutter/issues/59821 + return SkRect::MakeXYWH(params.finalBoundingRect().x(), // + params.finalBoundingRect().y(), // + params.finalBoundingRect().width(), // + params.finalBoundingRect().height() // + ); +} + +// |ExternalViewEmbedder| +void AndroidExternalViewEmbedder::SubmitFlutterView( + int64_t flutter_view_id, + GrDirectContext* context, + const std::shared_ptr& aiks_context, + std::unique_ptr frame) { + TRACE_EVENT0("flutter", "AndroidExternalViewEmbedder::SubmitFlutterView"); + // TODO(dkwingsmt): This class only supports rendering into the implicit view. + // Properly support multi-view in the future. + FML_DCHECK(flutter_view_id == kFlutterImplicitViewId); + + if (!FrameHasPlatformLayers()) { + frame->Submit(); + return; + } + + std::unordered_map view_rects; + for (auto platform_id : composition_order_) { + view_rects[platform_id] = GetViewRect(platform_id); + } + + std::unordered_map overlay_layers = + SliceViews(frame->Canvas(), // + composition_order_, // + slices_, // + view_rects // + ); + + // Submit the background canvas frame before switching the GL context to + // the overlay surfaces. + // + // Skip a frame if the embedding is switching surfaces, and indicate in + // `PostPrerollAction` that this frame must be resubmitted. + auto should_submit_current_frame = previous_frame_view_count_ > 0; + if (should_submit_current_frame) { + frame->Submit(); + } + + for (int64_t view_id : composition_order_) { + SkRect view_rect = GetViewRect(view_id); + const EmbeddedViewParams& params = view_params_.at(view_id); + // Display the platform view. If it's already displayed, then it's + // just positioned and sized. + jni_facade_->FlutterViewOnDisplayPlatformView( + view_id, // + view_rect.x(), // + view_rect.y(), // + view_rect.width(), // + view_rect.height(), // + params.sizePoints().width() * device_pixel_ratio_, + params.sizePoints().height() * device_pixel_ratio_, + params.mutatorsStack() // + ); + std::unordered_map::const_iterator overlay = + overlay_layers.find(view_id); + if (overlay == overlay_layers.end()) { + continue; + } + std::unique_ptr frame = + CreateSurfaceIfNeeded(context, // + view_id, // + slices_.at(view_id).get(), // + overlay->second // + ); + if (should_submit_current_frame) { + frame->Submit(); + } + } +} + +// |ExternalViewEmbedder| +std::unique_ptr +AndroidExternalViewEmbedder::CreateSurfaceIfNeeded(GrDirectContext* context, + int64_t view_id, + EmbedderViewSlice* slice, + const SkRect& rect) { + std::shared_ptr layer = surface_pool_->GetLayer( + context, android_context_, jni_facade_, surface_factory_); + + std::unique_ptr frame = + layer->surface->AcquireFrame(frame_size_); + // Display the overlay surface. If it's already displayed, then it's + // just positioned and sized. + jni_facade_->FlutterViewDisplayOverlaySurface(layer->id, // + rect.x(), // + rect.y(), // + rect.width(), // + rect.height() // + ); + DlCanvas* overlay_canvas = frame->Canvas(); + overlay_canvas->Clear(DlColor::kTransparent()); + // Offset the picture since its absolute position on the scene is determined + // by the position of the overlay view. + overlay_canvas->Translate(-rect.x(), -rect.y()); + slice->render_into(overlay_canvas); + return frame; +} + +// |ExternalViewEmbedder| +PostPrerollResult AndroidExternalViewEmbedder::PostPrerollAction( + const fml::RefPtr& raster_thread_merger) { + if (!FrameHasPlatformLayers()) { + return PostPrerollResult::kSuccess; + } + if (!raster_thread_merger->IsMerged()) { + // The raster thread merger may be disabled if the rasterizer is being + // created or teared down. + // + // In such cases, the current frame is dropped, and a new frame is attempted + // with the same layer tree. + // + // Eventually, the frame is submitted once this method returns `kSuccess`. + // At that point, the raster tasks are handled on the platform thread. + CancelFrame(); + raster_thread_merger->MergeWithLease(kDefaultMergedLeaseDuration); + return PostPrerollResult::kSkipAndRetryFrame; + } + raster_thread_merger->ExtendLeaseTo(kDefaultMergedLeaseDuration); + // Surface switch requires to resubmit the frame. + // TODO(egarciad): https://github.com/flutter/flutter/issues/65652 + if (previous_frame_view_count_ == 0) { + return PostPrerollResult::kResubmitFrame; + } + return PostPrerollResult::kSuccess; +} + +bool AndroidExternalViewEmbedder::FrameHasPlatformLayers() { + return !composition_order_.empty(); +} + +// |ExternalViewEmbedder| +DlCanvas* AndroidExternalViewEmbedder::GetRootCanvas() { + // On Android, the root surface is created from the on-screen render target. + return nullptr; +} + +void AndroidExternalViewEmbedder::Reset() { + previous_frame_view_count_ = composition_order_.size(); + + composition_order_.clear(); + slices_.clear(); +} + +// |ExternalViewEmbedder| +void AndroidExternalViewEmbedder::BeginFrame( + GrDirectContext* context, + const fml::RefPtr& raster_thread_merger) { + // JNI method must be called on the platform thread. + if (raster_thread_merger->IsOnPlatformThread()) { + jni_facade_->FlutterViewBeginFrame(); + } +} + +// |ExternalViewEmbedder| +void AndroidExternalViewEmbedder::PrepareFlutterView( + SkISize frame_size, + double device_pixel_ratio) { + Reset(); + + // The surface size changed. Therefore, destroy existing surfaces as + // the existing surfaces in the pool can't be recycled. + if (frame_size_ != frame_size) { + DestroySurfaces(); + } + surface_pool_->SetFrameSize(frame_size); + + frame_size_ = frame_size; + device_pixel_ratio_ = device_pixel_ratio; +} + +// |ExternalViewEmbedder| +void AndroidExternalViewEmbedder::CancelFrame() { + Reset(); +} + +// |ExternalViewEmbedder| +void AndroidExternalViewEmbedder::EndFrame( + bool should_resubmit_frame, + const fml::RefPtr& raster_thread_merger) { + surface_pool_->RecycleLayers(); + // JNI method must be called on the platform thread. + if (raster_thread_merger->IsOnPlatformThread()) { + jni_facade_->FlutterViewEndFrame(); + } +} + +// |ExternalViewEmbedder| +bool AndroidExternalViewEmbedder::SupportsDynamicThreadMerging() { + return true; +} + +// |ExternalViewEmbedder| +void AndroidExternalViewEmbedder::Teardown() { + DestroySurfaces(); +} + +// |ExternalViewEmbedder| +void AndroidExternalViewEmbedder::DestroySurfaces() { + if (!surface_pool_->HasLayers()) { + return; + } + fml::AutoResetWaitableEvent latch; + fml::TaskRunner::RunNowOrPostTask(task_runners_.GetPlatformTaskRunner(), + [&]() { + surface_pool_->DestroyLayers(jni_facade_); + latch.Signal(); + }); + latch.Wait(); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder.h b/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder.h new file mode 100644 index 0000000000000000000000000000000000000000..616eb36c9db2088ad2eabc168c29d9badfd91f75 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder.h @@ -0,0 +1,154 @@ +// 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_SHELL_PLATFORM_ANDROID_EXTERNAL_VIEW_EMBEDDER_EXTERNAL_VIEW_EMBEDDER_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_EXTERNAL_VIEW_EMBEDDER_EXTERNAL_VIEW_EMBEDDER_H_ + +#include + +#include "flutter/common/task_runners.h" +#include "flutter/flow/embedded_views.h" +#include "flutter/shell/platform/android/context/android_context.h" +#include "flutter/shell/platform/android/external_view_embedder/surface_pool.h" +#include "flutter/shell/platform/android/jni/platform_view_android_jni.h" +#include "flutter/shell/platform/android/surface/android_surface.h" + +namespace flutter { + +//------------------------------------------------------------------------------ +/// Allows to embed Android views into a Flutter application. +/// +/// This class calls Java methods via |PlatformViewAndroidJNI| to manage the +/// lifecycle of the Android view corresponding to |flutter::PlatformViewLayer|. +/// +/// It also orchestrates overlay surfaces. These are Android views +/// that render above (by Z order) the Android view corresponding to +/// |flutter::PlatformViewLayer|. +/// +class AndroidExternalViewEmbedder final : public ExternalViewEmbedder { + public: + AndroidExternalViewEmbedder( + const AndroidContext& android_context, + std::shared_ptr jni_facade, + std::shared_ptr surface_factory, + const TaskRunners& task_runners); + + // |ExternalViewEmbedder| + void PrerollCompositeEmbeddedView( + int64_t view_id, + std::unique_ptr params) override; + + // |ExternalViewEmbedder| + DlCanvas* CompositeEmbeddedView(int64_t view_id) override; + + // |ExternalViewEmbedder| + void SubmitFlutterView( + int64_t flutter_view_id, + GrDirectContext* context, + const std::shared_ptr& aiks_context, + std::unique_ptr frame) override; + + // |ExternalViewEmbedder| + PostPrerollResult PostPrerollAction( + const fml::RefPtr& raster_thread_merger) + override; + + // |ExternalViewEmbedder| + DlCanvas* GetRootCanvas() override; + + // |ExternalViewEmbedder| + void BeginFrame(GrDirectContext* context, + const fml::RefPtr& + raster_thread_merger) override; + + // |ExternalViewEmbedder| + void PrepareFlutterView(SkISize frame_size, + double device_pixel_ratio) override; + + // |ExternalViewEmbedder| + void CancelFrame() override; + + // |ExternalViewEmbedder| + void EndFrame(bool should_resubmit_frame, + const fml::RefPtr& + raster_thread_merger) override; + + // |ExternalViewEmbedder| + bool SupportsDynamicThreadMerging() override; + + // |ExternalViewEmbedder| + void Teardown() override; + + // Gets the rect based on the device pixel ratio of a platform view displayed + // on the screen. + SkRect GetViewRect(int64_t view_id) const; + + private: + // The number of frames the rasterizer task runner will continue + // to run on the platform thread after no platform view is rendered. + // + // Note: this is an arbitrary number that attempts to account for cases + // where the platform view might be momentarily off the screen. + static const int kDefaultMergedLeaseDuration = 10; + + // Provides metadata to the Android surfaces. + const AndroidContext& android_context_; + + // Allows to call methods in Java. + const std::shared_ptr jni_facade_; + + // Allows to create surfaces. + const std::shared_ptr surface_factory_; + + // Holds surfaces. Allows to recycle surfaces or allocate new ones. + const std::unique_ptr surface_pool_; + + // The task runners. + const TaskRunners task_runners_; + + // The size of the root canvas. + SkISize frame_size_; + + // The pixel ratio used to determinate the size of a platform view layer + // relative to the device layout system. + double device_pixel_ratio_; + + // The order of composition. Each entry contains a unique id for the platform + // view. + std::vector composition_order_; + + // The |EmbedderViewSlice| implementation keyed off the platform view id, + // which contains any subsequent operations until the next platform view or + // the end of the last leaf node in the layer tree. + std::unordered_map> slices_; + + // The params for a platform view, which contains the size, position and + // mutation stack. + std::unordered_map view_params_; + + // The number of platform views in the previous frame. + int64_t previous_frame_view_count_; + + // Destroys the surfaces created from the surface factory. + // This method schedules a task on the platform thread, and waits for + // the task until it completes. + void DestroySurfaces(); + + // Resets the state. + void Reset(); + + // Whether the layer tree in the current frame has platform layers. + bool FrameHasPlatformLayers(); + + // Creates a Surface when needed or recycles an existing one. + // Finally, draws the picture on the frame's canvas. + std::unique_ptr CreateSurfaceIfNeeded(GrDirectContext* context, + int64_t view_id, + EmbedderViewSlice* slice, + const SkRect& rect); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_EXTERNAL_VIEW_EMBEDDER_EXTERNAL_VIEW_EMBEDDER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder_2.cc b/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder_2.cc new file mode 100644 index 0000000000000000000000000000000000000000..9c5838806be646bc294d606aea4613d6c3c2d9fc --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder_2.cc @@ -0,0 +1,269 @@ +// 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/shell/platform/android/external_view_embedder/external_view_embedder_2.h" +#include "display_list/dl_color.h" +#include "flow/view_slicer.h" +#include "flutter/fml/synchronization/waitable_event.h" +#include "flutter/fml/trace_event.h" +#include "fml/make_copyable.h" +#include "fml/synchronization/count_down_latch.h" + +namespace flutter { + +AndroidExternalViewEmbedder2::AndroidExternalViewEmbedder2( + const AndroidContext& android_context, + std::shared_ptr jni_facade, + std::shared_ptr surface_factory, + const TaskRunners& task_runners) + : ExternalViewEmbedder(), + android_context_(android_context), + jni_facade_(std::move(jni_facade)), + surface_factory_(std::move(surface_factory)), + surface_pool_( + std::make_unique(/*use_new_surface_methods=*/true)), + task_runners_(task_runners) {} + +// |ExternalViewEmbedder| +void AndroidExternalViewEmbedder2::PrerollCompositeEmbeddedView( + int64_t view_id, + std::unique_ptr params) { + TRACE_EVENT0("flutter", + "AndroidExternalViewEmbedder2::PrerollCompositeEmbeddedView"); + + SkRect view_bounds = SkRect::Make(frame_size_); + std::unique_ptr view; + view = std::make_unique(view_bounds); + slices_.insert_or_assign(view_id, std::move(view)); + + composition_order_.push_back(view_id); + // Update params only if they changed. + if (view_params_.count(view_id) == 1 && + view_params_.at(view_id) == *params.get()) { + return; + } + view_params_.insert_or_assign(view_id, EmbeddedViewParams(*params.get())); +} + +// |ExternalViewEmbedder| +DlCanvas* AndroidExternalViewEmbedder2::CompositeEmbeddedView(int64_t view_id) { + if (slices_.count(view_id) == 1) { + return slices_.at(view_id)->canvas(); + } + return nullptr; +} + +SkRect AndroidExternalViewEmbedder2::GetViewRect( + int64_t view_id, + const std::unordered_map& view_params) { + const EmbeddedViewParams& params = view_params.at(view_id); + // https://github.com/flutter/flutter/issues/59821 + return SkRect::MakeXYWH(params.finalBoundingRect().x(), // + params.finalBoundingRect().y(), // + params.finalBoundingRect().width(), // + params.finalBoundingRect().height() // + ); +} + +// |ExternalViewEmbedder| +void AndroidExternalViewEmbedder2::SubmitFlutterView( + int64_t flutter_view_id, + GrDirectContext* context, + const std::shared_ptr& aiks_context, + std::unique_ptr frame) { + TRACE_EVENT0("flutter", "AndroidExternalViewEmbedder2::SubmitFlutterView"); + + if (!FrameHasPlatformLayers()) { + frame->Submit(); + // If the previous frame had platform views, hide the overlay surface. + if (previous_frame_view_count_ > 0) { + jni_facade_->hideOverlaySurface2(); + } + jni_facade_->applyTransaction(); + return; + } + + bool prev_frame_no_platform_views = previous_frame_view_count_ == 0; + std::unordered_map view_rects; + for (auto platform_id : composition_order_) { + view_rects[platform_id] = GetViewRect(platform_id, view_params_); + } + + std::unordered_map overlay_layers = + SliceViews(frame->Canvas(), // + composition_order_, // + slices_, // + view_rects // + ); + + // If there is no overlay Surface, initialize one on the platform thread. This + // will only be done once per application launch, as the singular overlay + // surface is never released. + if (!surface_pool_->HasLayers()) { + std::shared_ptr latch = + std::make_shared(1u); + task_runners_.GetPlatformTaskRunner()->PostTask( + fml::MakeCopyable([&, latch]() { + surface_pool_->GetLayer(context, android_context_, jni_facade_, + surface_factory_); + latch->CountDown(); + })); + latch->Wait(); + } + surface_pool_->ResetLayers(); + + // Create Overlay frame. If overlay surface creation failed, + // all this work must be skipped. + std::unique_ptr overlay_frame; + if (surface_pool_->HasLayers()) { + for (size_t i = 0; i < composition_order_.size(); i++) { + int64_t view_id = composition_order_[i]; + std::unordered_map::const_iterator overlay = + overlay_layers.find(view_id); + + if (overlay == overlay_layers.end()) { + continue; + } + if (overlay_frame == nullptr) { + std::shared_ptr layer = surface_pool_->GetLayer( + context, android_context_, jni_facade_, surface_factory_); + overlay_frame = layer->surface->AcquireFrame(frame_size_); + overlay_frame->Canvas()->Clear(flutter::DlColor::kTransparent()); + } + + DlCanvas* overlay_canvas = overlay_frame->Canvas(); + int restore_count = overlay_canvas->GetSaveCount(); + overlay_canvas->Save(); + overlay_canvas->ClipRect(ToDlRect(overlay->second)); + + // For all following platform views that would cover this overlay, + // emulate the effect by adding a difference clip. This makes the + // overlays appear as if they are under the platform view, when in + // reality there is only a single layer. + for (size_t j = i + 1; j < composition_order_.size(); j++) { + SkRect view_rect = GetViewRect(composition_order_[j], view_params_); + overlay_canvas->ClipRect( + DlRect::MakeLTRB(view_rect.left(), view_rect.top(), + view_rect.right(), view_rect.bottom()), + DlClipOp::kDifference); + } + + slices_[view_id]->render_into(overlay_canvas); + overlay_canvas->RestoreToCount(restore_count); + } + } + if (overlay_frame != nullptr) { + overlay_frame->set_submit_info({.frame_boundary = false}); + overlay_frame->Submit(); + } + frame->Submit(); + + task_runners_.GetPlatformTaskRunner()->PostTask(fml::MakeCopyable( + [&, composition_order = composition_order_, view_params = view_params_, + jni_facade = jni_facade_, device_pixel_ratio = device_pixel_ratio_, + slices = std::move(slices_), prev_frame_no_platform_views]() -> void { + jni_facade->swapTransaction(); + + if (prev_frame_no_platform_views) { + jni_facade_->showOverlaySurface2(); + } + + for (int64_t view_id : composition_order) { + SkRect view_rect = GetViewRect(view_id, view_params); + const EmbeddedViewParams& params = view_params.at(view_id); + jni_facade->onDisplayPlatformView2( + view_id, // + view_rect.x(), // + view_rect.y(), // + view_rect.width(), // + view_rect.height(), // + params.sizePoints().width() * device_pixel_ratio, + params.sizePoints().height() * device_pixel_ratio, + params.mutatorsStack() // + ); + } + jni_facade_->onEndFrame2(); + })); +} + +// |ExternalViewEmbedder| +PostPrerollResult AndroidExternalViewEmbedder2::PostPrerollAction( + const fml::RefPtr& raster_thread_merger) { + return PostPrerollResult::kSuccess; +} + +bool AndroidExternalViewEmbedder2::FrameHasPlatformLayers() { + return !composition_order_.empty(); +} + +// |ExternalViewEmbedder| +DlCanvas* AndroidExternalViewEmbedder2::GetRootCanvas() { + // On Android, the root surface is created from the on-screen render target. + return nullptr; +} + +void AndroidExternalViewEmbedder2::Reset() { + previous_frame_view_count_ = composition_order_.size(); + + composition_order_.clear(); + slices_.clear(); +} + +// |ExternalViewEmbedder| +void AndroidExternalViewEmbedder2::BeginFrame( + GrDirectContext* context, + const fml::RefPtr& raster_thread_merger) {} + +// |ExternalViewEmbedder| +void AndroidExternalViewEmbedder2::PrepareFlutterView( + SkISize frame_size, + double device_pixel_ratio) { + Reset(); + + // The surface size changed. Therefore, destroy existing surfaces as + // the existing surfaces in the pool can't be recycled. + if (frame_size_ != frame_size) { + DestroySurfaces(); + } + surface_pool_->SetFrameSize(frame_size); + + frame_size_ = frame_size; + device_pixel_ratio_ = device_pixel_ratio; +} + +// |ExternalViewEmbedder| +void AndroidExternalViewEmbedder2::CancelFrame() { + Reset(); +} + +// |ExternalViewEmbedder| +void AndroidExternalViewEmbedder2::EndFrame( + bool should_resubmit_frame, + const fml::RefPtr& raster_thread_merger) {} + +// |ExternalViewEmbedder| +bool AndroidExternalViewEmbedder2::SupportsDynamicThreadMerging() { + return false; +} + +// |ExternalViewEmbedder| +void AndroidExternalViewEmbedder2::Teardown() { + DestroySurfaces(); +} + +// |ExternalViewEmbedder| +void AndroidExternalViewEmbedder2::DestroySurfaces() { + if (!surface_pool_->HasLayers()) { + return; + } + fml::AutoResetWaitableEvent latch; + fml::TaskRunner::RunNowOrPostTask(task_runners_.GetPlatformTaskRunner(), + [&]() { + surface_pool_->DestroyLayers(jni_facade_); + latch.Signal(); + }); + latch.Wait(); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder_2.h b/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder_2.h new file mode 100644 index 0000000000000000000000000000000000000000..fe5dd0059f57e0a8a7c23d7d9502074bf0e1246b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder_2.h @@ -0,0 +1,152 @@ +// 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_SHELL_PLATFORM_ANDROID_EXTERNAL_VIEW_EMBEDDER_EXTERNAL_VIEW_EMBEDDER_2_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_EXTERNAL_VIEW_EMBEDDER_EXTERNAL_VIEW_EMBEDDER_2_H_ + +#include + +#include "flutter/common/task_runners.h" +#include "flutter/flow/embedded_views.h" +#include "flutter/shell/platform/android/context/android_context.h" +#include "flutter/shell/platform/android/external_view_embedder/surface_pool.h" +#include "flutter/shell/platform/android/jni/platform_view_android_jni.h" +#include "flutter/shell/platform/android/surface/android_surface.h" + +namespace flutter { + +//------------------------------------------------------------------------------ +/// Allows to embed Android views into a Flutter application. +/// +/// This class calls Java methods via |PlatformViewAndroidJNI| to manage the +/// lifecycle of the Android view corresponding to |flutter::PlatformViewLayer|. +/// +/// It also orchestrates overlay surfaces. These are Android views +/// that render above (by Z order) the Android view corresponding to +/// |flutter::PlatformViewLayer|. +/// +/// This implementation of the external view embedder is designed only to use +/// HC++ mode. Mixing old HC modes is not supported, but either of the texture +/// composition based platform views can be used with either mode. +class AndroidExternalViewEmbedder2 final : public ExternalViewEmbedder { + public: + AndroidExternalViewEmbedder2( + const AndroidContext& android_context, + std::shared_ptr jni_facade, + std::shared_ptr surface_factory, + const TaskRunners& task_runners); + + // |ExternalViewEmbedder| + void PrerollCompositeEmbeddedView( + int64_t view_id, + std::unique_ptr params) override; + + // |ExternalViewEmbedder| + DlCanvas* CompositeEmbeddedView(int64_t view_id) override; + + // |ExternalViewEmbedder| + void SubmitFlutterView( + int64_t flutter_view_id, + GrDirectContext* context, + const std::shared_ptr& aiks_context, + std::unique_ptr frame) override; + + // |ExternalViewEmbedder| + PostPrerollResult PostPrerollAction( + const fml::RefPtr& raster_thread_merger) + override; + + // |ExternalViewEmbedder| + DlCanvas* GetRootCanvas() override; + + // |ExternalViewEmbedder| + void BeginFrame(GrDirectContext* context, + const fml::RefPtr& + raster_thread_merger) override; + + // |ExternalViewEmbedder| + void PrepareFlutterView(SkISize frame_size, + double device_pixel_ratio) override; + + // |ExternalViewEmbedder| + void CancelFrame() override; + + // |ExternalViewEmbedder| + void EndFrame(bool should_resubmit_frame, + const fml::RefPtr& + raster_thread_merger) override; + + // |ExternalViewEmbedder| + bool SupportsDynamicThreadMerging() override; + + // |ExternalViewEmbedder| + void Teardown() override; + + // Gets the rect based on the device pixel ratio of a platform view displayed + // on the screen. + static SkRect GetViewRect( + int64_t view_id, + const std::unordered_map& view_params); + + private: + // The number of frames the rasterizer task runner will continue + // to run on the platform thread after no platform view is rendered. + // + // Note: this is an arbitrary number that attempts to account for cases + // where the platform view might be momentarily off the screen. + static const int kDefaultMergedLeaseDuration = 10; + + // Provides metadata to the Android surfaces. + const AndroidContext& android_context_; + + // Allows to call methods in Java. + const std::shared_ptr jni_facade_; + + // Allows to create surfaces. + const std::shared_ptr surface_factory_; + + // Holds surfaces. Allows to recycle surfaces or allocate new ones. + const std::unique_ptr surface_pool_; + + // The task runners. + const TaskRunners task_runners_; + + // The size of the root canvas. + SkISize frame_size_; + + // The pixel ratio used to determinate the size of a platform view layer + // relative to the device layout system. + double device_pixel_ratio_; + + // The order of composition. Each entry contains a unique id for the platform + // view. + std::vector composition_order_; + + // The |EmbedderViewSlice| implementation keyed off the platform view id, + // which contains any subsequent operations until the next platform view or + // the end of the last leaf node in the layer tree. + std::unordered_map> slices_; + + // The params for a platform view, which contains the size, position and + // mutation stack. + std::unordered_map view_params_; + + // The number of platform views in the previous frame. + int64_t previous_frame_view_count_; + + // Destroys the surfaces created from the surface factory. + // This method schedules a task on the platform thread, and waits for + // the task until it completes. + void DestroySurfaces(); + + // Resets the state. + void Reset(); + + // Whether the layer tree in the current frame has platform layers. + bool FrameHasPlatformLayers(); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_EXTERNAL_VIEW_EMBEDDER_EXTERNAL_VIEW_EMBEDDER_2_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder_unittests.cc b/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..dd62ed8c7deac62af64bd25c0e57ac66d82b8abf --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder_unittests.cc @@ -0,0 +1,1082 @@ +// 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. + +#define FML_USED_ON_EMBEDDER + +#include + +#include "flutter/shell/platform/android/external_view_embedder/external_view_embedder.h" + +#include "flutter/flow/embedded_views.h" +#include "flutter/flow/surface.h" +#include "flutter/fml/raster_thread_merger.h" +#include "flutter/fml/thread.h" +#include "flutter/shell/platform/android/jni/jni_mock.h" +#include "flutter/shell/platform/android/surface/android_surface.h" +#include "flutter/shell/platform/android/surface/android_surface_mock.h" + +#include "gmock/gmock.h" +#include "gtest/gtest.h" +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/include/gpu/ganesh/GrDirectContext.h" + +namespace flutter { +namespace testing { + +using ::testing::_; +using ::testing::ByMove; +using ::testing::Return; + +constexpr int64_t kImplicitViewId = 0; + +class TestAndroidSurfaceFactory : public AndroidSurfaceFactory { + public: + using TestSurfaceProducer = + std::function(void)>; + explicit TestAndroidSurfaceFactory(TestSurfaceProducer&& surface_producer) { + surface_producer_ = surface_producer; + } + + ~TestAndroidSurfaceFactory() override = default; + + std::unique_ptr CreateSurface() override { + return surface_producer_(); + } + + private: + TestSurfaceProducer surface_producer_; +}; + +class SurfaceMock : public Surface { + public: + MOCK_METHOD(bool, IsValid, (), (override)); + + MOCK_METHOD(std::unique_ptr, + AcquireFrame, + (const SkISize& size), + (override)); + + MOCK_METHOD(SkMatrix, GetRootTransformation, (), (const, override)); + + MOCK_METHOD(GrDirectContext*, GetContext, (), (override)); + + MOCK_METHOD(std::unique_ptr, + MakeRenderContextCurrent, + (), + (override)); +}; + +fml::RefPtr GetThreadMergerFromPlatformThread( + fml::Thread* rasterizer_thread = nullptr) { + // Assume the current thread is the platform thread. + fml::MessageLoop::EnsureInitializedForCurrentThread(); + auto platform_queue_id = fml::MessageLoop::GetCurrentTaskQueueId(); + + if (!rasterizer_thread) { + return fml::MakeRefCounted(platform_queue_id, + platform_queue_id); + } + auto rasterizer_queue_id = + rasterizer_thread->GetTaskRunner()->GetTaskQueueId(); + return fml::MakeRefCounted(platform_queue_id, + rasterizer_queue_id); +} + +fml::RefPtr GetThreadMergerFromRasterThread( + fml::Thread* platform_thread) { + auto platform_queue_id = platform_thread->GetTaskRunner()->GetTaskQueueId(); + + // Assume the current thread is the raster thread. + fml::MessageLoop::EnsureInitializedForCurrentThread(); + auto rasterizer_queue_id = fml::MessageLoop::GetCurrentTaskQueueId(); + + return fml::MakeRefCounted(platform_queue_id, + rasterizer_queue_id); +} + +TaskRunners GetTaskRunnersForFixture() { + fml::MessageLoop::EnsureInitializedForCurrentThread(); + auto& loop = fml::MessageLoop::GetCurrent(); + return { + "test", + loop.GetTaskRunner(), // platform + loop.GetTaskRunner(), // raster + loop.GetTaskRunner(), // ui + loop.GetTaskRunner() // io + }; +} + +TEST(AndroidExternalViewEmbedder, CompositeEmbeddedView) { + auto android_context = AndroidContext(AndroidRenderingAPI::kSoftware); + auto embedder = std::make_unique( + android_context, nullptr, nullptr, GetTaskRunnersForFixture()); + + ASSERT_EQ(nullptr, embedder->CompositeEmbeddedView(0)); + embedder->PrerollCompositeEmbeddedView( + 0, std::make_unique()); + ASSERT_NE(nullptr, embedder->CompositeEmbeddedView(0)); + + ASSERT_EQ(nullptr, embedder->CompositeEmbeddedView(1)); + embedder->PrerollCompositeEmbeddedView( + 1, std::make_unique()); + ASSERT_NE(nullptr, embedder->CompositeEmbeddedView(1)); +} + +TEST(AndroidExternalViewEmbedder, CancelFrame) { + auto android_context = AndroidContext(AndroidRenderingAPI::kSoftware); + auto embedder = std::make_unique( + android_context, nullptr, nullptr, GetTaskRunnersForFixture()); + + embedder->PrerollCompositeEmbeddedView( + 0, std::make_unique()); + embedder->CancelFrame(); + + ASSERT_EQ(embedder->CompositeEmbeddedView(0), nullptr); +} + +TEST(AndroidExternalViewEmbedder, RasterizerRunsOnPlatformThread) { + auto jni_mock = std::make_shared(); + auto android_context = AndroidContext(AndroidRenderingAPI::kSoftware); + auto embedder = std::make_unique( + android_context, jni_mock, nullptr, GetTaskRunnersForFixture()); + + fml::Thread rasterizer_thread("rasterizer"); + auto raster_thread_merger = + GetThreadMergerFromPlatformThread(&rasterizer_thread); + ASSERT_FALSE(raster_thread_merger->IsMerged()); + + EXPECT_CALL(*jni_mock, FlutterViewBeginFrame()); + embedder->BeginFrame(nullptr, raster_thread_merger); + embedder->PrepareFlutterView(SkISize::Make(10, 20), 1.0); + + // Push a platform view. + embedder->PrerollCompositeEmbeddedView( + 0, std::make_unique()); + + auto postpreroll_result = embedder->PostPrerollAction(raster_thread_merger); + ASSERT_EQ(PostPrerollResult::kSkipAndRetryFrame, postpreroll_result); + + EXPECT_CALL(*jni_mock, FlutterViewEndFrame()); + embedder->EndFrame(/*should_resubmit_frame=*/true, raster_thread_merger); + + ASSERT_TRUE(raster_thread_merger->IsMerged()); + + int pending_frames = 0; + while (raster_thread_merger->IsMerged()) { + raster_thread_merger->DecrementLease(); + pending_frames++; + } + ASSERT_EQ(10, pending_frames); // kDefaultMergedLeaseDuration +} + +TEST(AndroidExternalViewEmbedder, RasterizerRunsOnRasterizerThread) { + auto jni_mock = std::make_shared(); + auto android_context = AndroidContext(AndroidRenderingAPI::kSoftware); + auto embedder = std::make_unique( + android_context, jni_mock, nullptr, GetTaskRunnersForFixture()); + + fml::Thread rasterizer_thread("rasterizer"); + auto raster_thread_merger = + GetThreadMergerFromPlatformThread(&rasterizer_thread); + ASSERT_FALSE(raster_thread_merger->IsMerged()); + + PostPrerollResult result = embedder->PostPrerollAction(raster_thread_merger); + ASSERT_EQ(PostPrerollResult::kSuccess, result); + + EXPECT_CALL(*jni_mock, FlutterViewEndFrame()); + embedder->EndFrame(/*should_resubmit_frame=*/true, raster_thread_merger); + + ASSERT_FALSE(raster_thread_merger->IsMerged()); +} + +TEST(AndroidExternalViewEmbedder, PlatformViewRect) { + auto jni_mock = std::make_shared(); + + auto android_context = AndroidContext(AndroidRenderingAPI::kSoftware); + auto embedder = std::make_unique( + android_context, jni_mock, nullptr, GetTaskRunnersForFixture()); + fml::Thread rasterizer_thread("rasterizer"); + auto raster_thread_merger = + GetThreadMergerFromPlatformThread(&rasterizer_thread); + + EXPECT_CALL(*jni_mock, FlutterViewBeginFrame()); + embedder->BeginFrame(nullptr, raster_thread_merger); + embedder->PrepareFlutterView(SkISize::Make(100, 100), 1.5); + + MutatorsStack stack; + SkMatrix matrix; + matrix.setIdentity(); + // The framework always push a scale matrix based on the screen ratio. + matrix.setConcat(matrix, SkMatrix::Scale(1.5, 1.5)); + matrix.setConcat(matrix, SkMatrix::Translate(10, 20)); + auto view_params = + std::make_unique(matrix, SkSize::Make(30, 40), stack); + + auto view_id = 0; + embedder->PrerollCompositeEmbeddedView(view_id, std::move(view_params)); + ASSERT_EQ(SkRect::MakeXYWH(15, 30, 45, 60), embedder->GetViewRect(view_id)); +} + +TEST(AndroidExternalViewEmbedder, PlatformViewRectChangedParams) { + auto jni_mock = std::make_shared(); + + auto android_context = AndroidContext(AndroidRenderingAPI::kSoftware); + auto embedder = std::make_unique( + android_context, jni_mock, nullptr, GetTaskRunnersForFixture()); + fml::Thread rasterizer_thread("rasterizer"); + auto raster_thread_merger = + GetThreadMergerFromPlatformThread(&rasterizer_thread); + + EXPECT_CALL(*jni_mock, FlutterViewBeginFrame()); + embedder->BeginFrame(nullptr, raster_thread_merger); + embedder->PrepareFlutterView(SkISize::Make(100, 100), 1.5); + + auto view_id = 0; + + MutatorsStack stack1; + SkMatrix matrix1; + matrix1.setIdentity(); + // The framework always push a scale matrix based on the screen ratio. + matrix1.setConcat(SkMatrix::Scale(1.5, 1.5), SkMatrix::Translate(10, 20)); + auto view_params_1 = std::make_unique( + matrix1, SkSize::Make(30, 40), stack1); + + embedder->PrerollCompositeEmbeddedView(view_id, std::move(view_params_1)); + + MutatorsStack stack2; + SkMatrix matrix2; + matrix2.setIdentity(); + // The framework always push a scale matrix based on the screen ratio. + matrix2.setConcat(matrix2, SkMatrix::Scale(1.5, 1.5)); + matrix2.setConcat(matrix2, SkMatrix::Translate(50, 60)); + auto view_params_2 = std::make_unique( + matrix2, SkSize::Make(70, 80), stack2); + + embedder->PrerollCompositeEmbeddedView(view_id, std::move(view_params_2)); + + ASSERT_EQ(SkRect::MakeXYWH(75, 90, 105, 120), embedder->GetViewRect(view_id)); +} + +TEST(AndroidExternalViewEmbedder, SubmitFlutterView) { + auto jni_mock = std::make_shared(); + auto android_context = + std::make_shared(AndroidRenderingAPI::kSoftware); + + auto window = fml::MakeRefCounted(nullptr); + auto gr_context = GrDirectContext::MakeMock(nullptr); + auto frame_size = SkISize::Make(1000, 1000); + SurfaceFrame::FramebufferInfo framebuffer_info; + auto surface_factory = std::make_shared( + [gr_context, window, frame_size, framebuffer_info]() { + auto surface_frame_1 = std::make_unique( + SkSurfaces::Null(1000, 1000), framebuffer_info, + [](const SurfaceFrame& surface_frame, DlCanvas* canvas) { + return true; + }, + [](const SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + auto surface_frame_2 = std::make_unique( + SkSurfaces::Null(1000, 1000), framebuffer_info, + [](const SurfaceFrame& surface_frame, DlCanvas* canvas) { + return true; + }, + [](const SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + + auto surface_mock = std::make_unique(); + EXPECT_CALL(*surface_mock, AcquireFrame(frame_size)) + .Times(2 /* frames */) + .WillOnce(Return(ByMove(std::move(surface_frame_1)))) + .WillOnce(Return(ByMove(std::move(surface_frame_2)))); + + auto android_surface_mock = std::make_unique(); + EXPECT_CALL(*android_surface_mock, IsValid()).WillOnce(Return(true)); + + EXPECT_CALL(*android_surface_mock, CreateGPUSurface(gr_context.get())) + .WillOnce(Return(ByMove(std::move(surface_mock)))); + + EXPECT_CALL(*android_surface_mock, SetNativeWindow(window, _)); + + return android_surface_mock; + }); + auto embedder = std::make_unique( + *android_context, jni_mock, surface_factory, GetTaskRunnersForFixture()); + + auto raster_thread_merger = GetThreadMergerFromPlatformThread(); + + // ------------------ First frame ------------------ // + { + auto did_submit_frame = false; + auto surface_frame = std::make_unique( + SkSurfaces::Null(1000, 1000), framebuffer_info, + [&did_submit_frame](const SurfaceFrame& surface_frame, + DlCanvas* canvas) mutable { + if (canvas != nullptr) { + did_submit_frame = true; + } + return true; + }, + [](const SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + + embedder->SubmitFlutterView(kImplicitViewId, gr_context.get(), nullptr, + std::move(surface_frame)); + // Submits frame if no Android view in the current frame. + EXPECT_TRUE(did_submit_frame); + // Doesn't resubmit frame. + auto postpreroll_result = embedder->PostPrerollAction(raster_thread_merger); + ASSERT_EQ(PostPrerollResult::kSuccess, postpreroll_result); + + EXPECT_CALL(*jni_mock, FlutterViewEndFrame()); + embedder->EndFrame(/*should_resubmit_frame=*/false, raster_thread_merger); + } + + // ------------------ Second frame ------------------ // + { + EXPECT_CALL(*jni_mock, FlutterViewBeginFrame()); + embedder->BeginFrame(nullptr, raster_thread_merger); + embedder->PrepareFlutterView(frame_size, 1.5); + + // Add an Android view. + MutatorsStack stack1; + DlMatrix scale = DlMatrix::MakeScale({1.5, 1.5, 1}); + DlMatrix trans = DlMatrix::MakeTranslation({100, 100}); + DlMatrix matrix1 = scale * trans; + stack1.PushTransform(scale); + stack1.PushTransform(trans); + // TODO(egarciad): Investigate why Flow applies the device pixel ratio to + // the offsetPixels, but not the sizePoints. + auto view_params_1 = std::make_unique( + ToSkMatrix(matrix1), SkSize::Make(200, 200), stack1); + + embedder->PrerollCompositeEmbeddedView(0, std::move(view_params_1)); + // This is the recording canvas flow writes to. + auto canvas_1 = embedder->CompositeEmbeddedView(0); + + DlPaint rect_paint; + rect_paint.setColor(DlColor::kCyan()); + rect_paint.setDrawStyle(DlDrawStyle::kFill); + + // This simulates Flutter UI that doesn't intersect with the Android view. + canvas_1->DrawRect(DlRect::MakeXYWH(0, 0, 50, 50), rect_paint); + // This simulates Flutter UI that intersects with the Android view. + canvas_1->DrawRect(DlRect::MakeXYWH(50, 50, 200, 200), rect_paint); + canvas_1->DrawRect(DlRect::MakeXYWH(150, 150, 100, 100), rect_paint); + + // Create a new overlay surface. + EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()) + .WillOnce(Return( + ByMove(std::make_unique( + 0, window)))); + // The JNI call to display the Android view. + EXPECT_CALL(*jni_mock, FlutterViewOnDisplayPlatformView( + 0, 150, 150, 300, 300, 300, 300, stack1)); + // The JNI call to display the overlay surface. + EXPECT_CALL(*jni_mock, + FlutterViewDisplayOverlaySurface(0, 150, 150, 100, 100)); + + auto did_submit_frame = false; + auto surface_frame = std::make_unique( + SkSurfaces::Null(1000, 1000), framebuffer_info, + [&did_submit_frame](const SurfaceFrame& surface_frame, + DlCanvas* canvas) mutable { + if (canvas != nullptr) { + did_submit_frame = true; + } + return true; + }, + [](const SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + + embedder->SubmitFlutterView(kImplicitViewId, gr_context.get(), nullptr, + std::move(surface_frame)); + // Doesn't submit frame if there aren't Android views in the previous frame. + EXPECT_FALSE(did_submit_frame); + // Resubmits frame. + auto postpreroll_result = embedder->PostPrerollAction(raster_thread_merger); + ASSERT_EQ(PostPrerollResult::kResubmitFrame, postpreroll_result); + + EXPECT_CALL(*jni_mock, FlutterViewEndFrame()); + embedder->EndFrame(/*should_resubmit_frame=*/false, raster_thread_merger); + } + + // ------------------ Third frame ------------------ // + { + EXPECT_CALL(*jni_mock, FlutterViewBeginFrame()); + embedder->BeginFrame(nullptr, raster_thread_merger); + embedder->PrepareFlutterView(frame_size, 1.5); + + // Add an Android view. + MutatorsStack stack1; + DlMatrix scale = DlMatrix::MakeScale({1.5, 1.5, 1}); + DlMatrix trans = DlMatrix::MakeTranslation({100, 100}); + DlMatrix matrix1 = scale * trans; + stack1.PushTransform(scale); + stack1.PushTransform(trans); + // TODO(egarciad): Investigate why Flow applies the device pixel ratio to + // the offsetPixels, but not the sizePoints. + auto view_params_1 = std::make_unique( + ToSkMatrix(matrix1), SkSize::Make(200, 200), stack1); + + embedder->PrerollCompositeEmbeddedView(0, std::move(view_params_1)); + // This is the recording canvas flow writes to. + auto canvas_1 = embedder->CompositeEmbeddedView(0); + + DlPaint rect_paint; + rect_paint.setColor(DlColor::kCyan()); + rect_paint.setDrawStyle(DlDrawStyle::kFill); + + // This simulates Flutter UI that doesn't intersect with the Android view. + canvas_1->DrawRect(DlRect::MakeXYWH(0, 0, 50, 50), rect_paint); + // This simulates Flutter UI that intersects with the Android view. + canvas_1->DrawRect(DlRect::MakeXYWH(50, 50, 200, 200), rect_paint); + canvas_1->DrawRect(DlRect::MakeXYWH(150, 150, 100, 100), rect_paint); + + // Don't create a new overlay surface since it's recycled from the first + // frame. + EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()).Times(0); + // The JNI call to display the Android view. + EXPECT_CALL(*jni_mock, FlutterViewOnDisplayPlatformView( + 0, 150, 150, 300, 300, 300, 300, stack1)); + // The JNI call to display the overlay surface. + EXPECT_CALL(*jni_mock, + FlutterViewDisplayOverlaySurface(0, 150, 150, 100, 100)); + + auto did_submit_frame = false; + auto surface_frame = std::make_unique( + SkSurfaces::Null(1000, 1000), framebuffer_info, + [&did_submit_frame](const SurfaceFrame& surface_frame, + DlCanvas* canvas) mutable { + if (canvas != nullptr) { + did_submit_frame = true; + } + return true; + }, + [](const SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + embedder->SubmitFlutterView(kImplicitViewId, gr_context.get(), nullptr, + std::move(surface_frame)); + // Submits frame if there are Android views in the previous frame. + EXPECT_TRUE(did_submit_frame); + // Doesn't resubmit frame. + auto postpreroll_result = embedder->PostPrerollAction(raster_thread_merger); + ASSERT_EQ(PostPrerollResult::kSuccess, postpreroll_result); + + EXPECT_CALL(*jni_mock, FlutterViewEndFrame()); + embedder->EndFrame(/*should_resubmit_frame=*/false, raster_thread_merger); + } +} + +TEST(AndroidExternalViewEmbedder, OverlayCoverTwoPlatformViews) { + // In this test we will simulate two Android views appearing on the screen + // with a rect intersecting both of them + + auto jni_mock = std::make_shared(); + auto android_context = + std::make_shared(AndroidRenderingAPI::kSoftware); + + auto window = fml::MakeRefCounted(nullptr); + auto gr_context = GrDirectContext::MakeMock(nullptr); + auto frame_size = SkISize::Make(1000, 1000); + SurfaceFrame::FramebufferInfo framebuffer_info; + auto surface_factory = std::make_shared( + [gr_context, window, frame_size, framebuffer_info]() { + auto surface_frame_1 = std::make_unique( + SkSurfaces::Null(1000, 1000), framebuffer_info, + [](const SurfaceFrame& surface_frame, DlCanvas* canvas) { + return true; + }, + [](const SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + + auto surface_mock = std::make_unique(); + EXPECT_CALL(*surface_mock, AcquireFrame(frame_size)) + .Times(1 /* frames */) + .WillOnce(Return(ByMove(std::move(surface_frame_1)))); + + auto android_surface_mock = std::make_unique(); + EXPECT_CALL(*android_surface_mock, IsValid()).WillOnce(Return(true)); + + EXPECT_CALL(*android_surface_mock, CreateGPUSurface(gr_context.get())) + .WillOnce(Return(ByMove(std::move(surface_mock)))); + + EXPECT_CALL(*android_surface_mock, SetNativeWindow(window, _)); + return android_surface_mock; + }); + auto embedder = std::make_unique( + *android_context, jni_mock, surface_factory, GetTaskRunnersForFixture()); + + auto raster_thread_merger = GetThreadMergerFromPlatformThread(); + + EXPECT_CALL(*jni_mock, FlutterViewBeginFrame()); + embedder->BeginFrame(nullptr, raster_thread_merger); + embedder->PrepareFlutterView(frame_size, 1.5); + + { + // Add first Android view. + SkMatrix matrix = SkMatrix::Translate(100, 100); + MutatorsStack stack; + embedder->PrerollCompositeEmbeddedView( + 0, std::make_unique(matrix, SkSize::Make(100, 100), + stack)); + // The JNI call to display the Android view. + EXPECT_CALL(*jni_mock, FlutterViewOnDisplayPlatformView( + 0, 100, 100, 100, 100, 150, 150, stack)); + } + + { + // Add second Android view. + SkMatrix matrix = SkMatrix::Translate(300, 100); + MutatorsStack stack; + embedder->PrerollCompositeEmbeddedView( + 1, std::make_unique(matrix, SkSize::Make(100, 100), + stack)); + // The JNI call to display the Android view. + EXPECT_CALL(*jni_mock, FlutterViewOnDisplayPlatformView( + 1, 300, 100, 100, 100, 150, 150, stack)); + } + auto rect_paint = DlPaint(); + rect_paint.setColor(DlColor::kCyan()); + rect_paint.setDrawStyle(DlDrawStyle::kFill); + + // This simulates Flutter UI that intersects with the two Android views. + // Since we will compute the intersection for each android view in turn, and + // finally merge The final size of the overlay will be smaller than the + // width and height of the rect. + embedder->CompositeEmbeddedView(1)->DrawRect( + DlRect::MakeXYWH(150, 50, 200, 200), rect_paint); + + EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()) + .WillRepeatedly([&]() { + return std::make_unique( + 1, window); + }); + + // The JNI call to display the overlay surface. + EXPECT_CALL(*jni_mock, + FlutterViewDisplayOverlaySurface(1, 150, 100, 200, 100)) + .Times(1); + + auto surface_frame = std::make_unique( + SkSurfaces::Null(1000, 1000), framebuffer_info, + [](const SurfaceFrame& surface_frame, DlCanvas* canvas) mutable { + return true; + }, + [](const SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + + embedder->SubmitFlutterView(kImplicitViewId, gr_context.get(), nullptr, + std::move(surface_frame)); + + EXPECT_CALL(*jni_mock, FlutterViewEndFrame()); + embedder->EndFrame(/*should_resubmit_frame=*/false, raster_thread_merger); +} + +TEST(AndroidExternalViewEmbedder, SubmitFrameOverlayComposition) { + auto jni_mock = std::make_shared(); + auto android_context = + std::make_shared(AndroidRenderingAPI::kSoftware); + + auto window = fml::MakeRefCounted(nullptr); + auto gr_context = GrDirectContext::MakeMock(nullptr); + auto frame_size = SkISize::Make(1000, 1000); + SurfaceFrame::FramebufferInfo framebuffer_info; + auto surface_factory = std::make_shared( + [gr_context, window, frame_size, framebuffer_info]() { + auto surface_frame_1 = std::make_unique( + SkSurfaces::Null(1000, 1000), framebuffer_info, + [](const SurfaceFrame& surface_frame, DlCanvas* canvas) { + return true; + }, + [](const SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + + auto surface_mock = std::make_unique(); + EXPECT_CALL(*surface_mock, AcquireFrame(frame_size)) + .Times(1 /* frames */) + .WillOnce(Return(ByMove(std::move(surface_frame_1)))); + + auto android_surface_mock = std::make_unique(); + EXPECT_CALL(*android_surface_mock, IsValid()).WillOnce(Return(true)); + + EXPECT_CALL(*android_surface_mock, CreateGPUSurface(gr_context.get())) + .WillOnce(Return(ByMove(std::move(surface_mock)))); + + EXPECT_CALL(*android_surface_mock, SetNativeWindow(window, _)); + return android_surface_mock; + }); + auto embedder = std::make_unique( + *android_context, jni_mock, surface_factory, GetTaskRunnersForFixture()); + + auto raster_thread_merger = GetThreadMergerFromPlatformThread(); + + EXPECT_CALL(*jni_mock, FlutterViewBeginFrame()); + embedder->BeginFrame(nullptr, raster_thread_merger); + embedder->PrepareFlutterView(frame_size, 1.5); + + { + // Add first Android view. + SkMatrix matrix; + MutatorsStack stack; + stack.PushTransform(DlMatrix::MakeTranslation({0, 0})); + + embedder->PrerollCompositeEmbeddedView( + 0, std::make_unique(matrix, SkSize::Make(200, 200), + stack)); + EXPECT_CALL(*jni_mock, FlutterViewOnDisplayPlatformView(0, 0, 0, 200, 200, + 300, 300, stack)); + } + + auto rect_paint = DlPaint(); + rect_paint.setColor(DlColor::kCyan()); + rect_paint.setDrawStyle(DlDrawStyle::kFill); + + // This simulates Flutter UI that intersects with the first Android view. + embedder->CompositeEmbeddedView(0)->DrawRect( + DlRect::MakeXYWH(25, 25, 80, 150), rect_paint); + + { + // Add second Android view. + SkMatrix matrix; + MutatorsStack stack; + stack.PushTransform(DlMatrix::MakeTranslation({0, 100})); + + embedder->PrerollCompositeEmbeddedView( + 1, std::make_unique(matrix, SkSize::Make(100, 100), + stack)); + EXPECT_CALL(*jni_mock, FlutterViewOnDisplayPlatformView(1, 0, 0, 100, 100, + 150, 150, stack)); + } + // This simulates Flutter UI that intersects with the first and second Android + // views. + embedder->CompositeEmbeddedView(1)->DrawRect(DlRect::MakeXYWH(25, 25, 80, 50), + rect_paint); + + embedder->CompositeEmbeddedView(1)->DrawRect( + DlRect::MakeXYWH(75, 75, 30, 100), rect_paint); + + EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()) + .WillRepeatedly([&]() { + return std::make_unique( + 1, window); + }); + + EXPECT_CALL(*jni_mock, FlutterViewDisplayOverlaySurface(1, 25, 25, 80, 150)) + .Times(2); + + auto surface_frame = std::make_unique( + SkSurfaces::Null(1000, 1000), framebuffer_info, + [](const SurfaceFrame& surface_frame, DlCanvas* canvas) mutable { + return true; + }, + [](const SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + + embedder->SubmitFlutterView(kImplicitViewId, gr_context.get(), nullptr, + std::move(surface_frame)); + + EXPECT_CALL(*jni_mock, FlutterViewEndFrame()); + embedder->EndFrame(/*should_resubmit_frame=*/false, raster_thread_merger); +} + +TEST(AndroidExternalViewEmbedder, SubmitFramePlatformViewWithoutAnyOverlay) { + auto jni_mock = std::make_shared(); + auto android_context = + std::make_shared(AndroidRenderingAPI::kSoftware); + + auto window = fml::MakeRefCounted(nullptr); + auto gr_context = GrDirectContext::MakeMock(nullptr); + auto frame_size = SkISize::Make(1000, 1000); + SurfaceFrame::FramebufferInfo framebuffer_info; + auto surface_factory = std::make_shared( + [gr_context, window, frame_size, framebuffer_info]() { + auto surface_frame_1 = std::make_unique( + SkSurfaces::Null(1000, 1000), framebuffer_info, + [](const SurfaceFrame& surface_frame, DlCanvas* canvas) { + return true; + }, + [](const SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + + auto surface_mock = std::make_unique(); + EXPECT_CALL(*surface_mock, AcquireFrame(frame_size)) + .Times(1 /* frames */) + .WillOnce(Return(ByMove(std::move(surface_frame_1)))); + + auto android_surface_mock = std::make_unique(); + EXPECT_CALL(*android_surface_mock, IsValid()).WillOnce(Return(true)); + + EXPECT_CALL(*android_surface_mock, CreateGPUSurface(gr_context.get())) + .WillOnce(Return(ByMove(std::move(surface_mock)))); + + EXPECT_CALL(*android_surface_mock, SetNativeWindow(window, _)); + return android_surface_mock; + }); + auto embedder = std::make_unique( + *android_context, jni_mock, surface_factory, GetTaskRunnersForFixture()); + + auto raster_thread_merger = GetThreadMergerFromPlatformThread(); + + EXPECT_CALL(*jni_mock, FlutterViewBeginFrame()); + embedder->BeginFrame(nullptr, raster_thread_merger); + embedder->PrepareFlutterView(frame_size, 1.5); + + { + // Add Android view. + SkMatrix matrix; + MutatorsStack stack; + stack.PushTransform(DlMatrix::MakeTranslation({0, 0})); + + embedder->PrerollCompositeEmbeddedView( + 0, std::make_unique(matrix, SkSize::Make(200, 200), + stack)); + EXPECT_CALL(*jni_mock, FlutterViewOnDisplayPlatformView(0, 0, 0, 200, 200, + 300, 300, stack)); + } + + EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()).Times(0); + + auto surface_frame = std::make_unique( + SkSurfaces::Null(1000, 1000), framebuffer_info, + [](const SurfaceFrame& surface_frame, DlCanvas* canvas) mutable { + return true; + }, + [](const SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + + embedder->SubmitFlutterView(kImplicitViewId, gr_context.get(), nullptr, + std::move(surface_frame)); + + EXPECT_CALL(*jni_mock, FlutterViewEndFrame()); + embedder->EndFrame(/*should_resubmit_frame=*/false, raster_thread_merger); +} + +TEST(AndroidExternalViewEmbedder, DoesNotCallJNIPlatformThreadOnlyMethods) { + auto jni_mock = std::make_shared(); + + auto android_context = AndroidContext(AndroidRenderingAPI::kSoftware); + auto embedder = std::make_unique( + android_context, jni_mock, nullptr, GetTaskRunnersForFixture()); + + // While on the raster thread, don't make JNI calls as these methods can only + // run on the platform thread. + fml::Thread platform_thread("platform"); + auto raster_thread_merger = GetThreadMergerFromRasterThread(&platform_thread); + + EXPECT_CALL(*jni_mock, FlutterViewBeginFrame()).Times(0); + embedder->BeginFrame(nullptr, raster_thread_merger); + embedder->PrepareFlutterView(SkISize::Make(10, 20), 1.0); + + EXPECT_CALL(*jni_mock, FlutterViewEndFrame()).Times(0); + embedder->EndFrame(/*should_resubmit_frame=*/false, raster_thread_merger); +} + +TEST(AndroidExternalViewEmbedder, DestroyOverlayLayersOnSizeChange) { + auto jni_mock = std::make_shared(); + + auto android_context = + std::make_shared(AndroidRenderingAPI::kSoftware); + auto window = fml::MakeRefCounted(nullptr); + auto gr_context = GrDirectContext::MakeMock(nullptr); + auto frame_size = SkISize::Make(1000, 1000); + SurfaceFrame::FramebufferInfo framebuffer_info; + auto surface_factory = std::make_shared( + [gr_context, window, frame_size, framebuffer_info]() { + auto surface_frame_1 = std::make_unique( + SkSurfaces::Null(1000, 1000), framebuffer_info, + [](const SurfaceFrame& surface_frame, DlCanvas* canvas) { + return true; + }, + [](const SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + + auto surface_mock = std::make_unique(); + EXPECT_CALL(*surface_mock, AcquireFrame(frame_size)) + .WillOnce(Return(ByMove(std::move(surface_frame_1)))); + + auto android_surface_mock = std::make_unique(); + EXPECT_CALL(*android_surface_mock, IsValid()).WillOnce(Return(true)); + + EXPECT_CALL(*android_surface_mock, CreateGPUSurface(gr_context.get())) + .WillOnce(Return(ByMove(std::move(surface_mock)))); + + EXPECT_CALL(*android_surface_mock, SetNativeWindow(window, _)); + + return android_surface_mock; + }); + + auto embedder = std::make_unique( + *android_context, jni_mock, surface_factory, GetTaskRunnersForFixture()); + fml::Thread rasterizer_thread("rasterizer"); + auto raster_thread_merger = + GetThreadMergerFromPlatformThread(&rasterizer_thread); + + // ------------------ First frame ------------------ // + { + EXPECT_CALL(*jni_mock, FlutterViewBeginFrame()); + embedder->BeginFrame(nullptr, raster_thread_merger); + embedder->PrepareFlutterView(frame_size, 1.5); + + // Add an Android view. + MutatorsStack stack1; + // TODO(egarciad): Investigate why Flow applies the device pixel ratio to + // the offsetPixels, but not the sizePoints. + auto view_params_1 = std::make_unique( + SkMatrix(), SkSize::Make(200, 200), stack1); + + embedder->PrerollCompositeEmbeddedView(0, std::move(view_params_1)); + + // This simulates Flutter UI that intersects with the Android view. + embedder->CompositeEmbeddedView(0)->DrawRect( + DlRect::MakeXYWH(50, 50, 200, 200), DlPaint()); + + // Create a new overlay surface. + EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()) + .WillOnce(Return( + ByMove(std::make_unique( + 0, window)))); + // The JNI call to display the Android view. + EXPECT_CALL(*jni_mock, FlutterViewOnDisplayPlatformView(0, 0, 0, 200, 200, + 300, 300, stack1)); + EXPECT_CALL(*jni_mock, + FlutterViewDisplayOverlaySurface(0, 50, 50, 150, 150)); + + SurfaceFrame::FramebufferInfo framebuffer_info; + auto surface_frame = std::make_unique( + SkSurfaces::Null(1000, 1000), framebuffer_info, + [](const SurfaceFrame& surface_frame, DlCanvas* canvas) { + return true; + }, + [](const SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + embedder->SubmitFlutterView(kImplicitViewId, gr_context.get(), nullptr, + std::move(surface_frame)); + + EXPECT_CALL(*jni_mock, FlutterViewEndFrame()); + embedder->EndFrame(/*should_resubmit_frame=*/false, raster_thread_merger); + } + + EXPECT_CALL(*jni_mock, FlutterViewDestroyOverlaySurfaces()); + EXPECT_CALL(*jni_mock, FlutterViewBeginFrame()); + // Change the frame size. + embedder->BeginFrame(nullptr, raster_thread_merger); + embedder->PrepareFlutterView(SkISize::Make(30, 40), 1.0); +} + +TEST(AndroidExternalViewEmbedder, DoesNotDestroyOverlayLayersOnSizeChange) { + auto jni_mock = std::make_shared(); + auto android_context = + std::make_shared(AndroidRenderingAPI::kSoftware); + + auto window = fml::MakeRefCounted(nullptr); + auto gr_context = GrDirectContext::MakeMock(nullptr); + auto frame_size = SkISize::Make(1000, 1000); + SurfaceFrame::FramebufferInfo framebuffer_info; + auto surface_factory = std::make_shared( + [gr_context, window, frame_size, framebuffer_info]() { + auto surface_frame_1 = std::make_unique( + SkSurfaces::Null(1000, 1000), framebuffer_info, + [](const SurfaceFrame& surface_frame, DlCanvas* canvas) { + return true; + }, + [](const SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + + auto surface_mock = std::make_unique(); + EXPECT_CALL(*surface_mock, AcquireFrame(frame_size)) + .WillOnce(Return(ByMove(std::move(surface_frame_1)))); + + auto android_surface_mock = std::make_unique(); + EXPECT_CALL(*android_surface_mock, IsValid()).WillOnce(Return(true)); + + EXPECT_CALL(*android_surface_mock, CreateGPUSurface(gr_context.get())) + .WillOnce(Return(ByMove(std::move(surface_mock)))); + + EXPECT_CALL(*android_surface_mock, SetNativeWindow(window, _)); + + return android_surface_mock; + }); + + auto embedder = std::make_unique( + *android_context, jni_mock, surface_factory, GetTaskRunnersForFixture()); + + // ------------------ First frame ------------------ // + { + fml::Thread rasterizer_thread("rasterizer"); + auto raster_thread_merger = + GetThreadMergerFromPlatformThread(&rasterizer_thread); + EXPECT_CALL(*jni_mock, FlutterViewBeginFrame()); + embedder->BeginFrame(nullptr, raster_thread_merger); + embedder->PrepareFlutterView(frame_size, 1.5); + + // Add an Android view. + MutatorsStack stack1; + // TODO(egarciad): Investigate why Flow applies the device pixel ratio to + // the offsetPixels, but not the sizePoints. + auto view_params_1 = std::make_unique( + SkMatrix(), SkSize::Make(200, 200), stack1); + + embedder->PrerollCompositeEmbeddedView(0, std::move(view_params_1)); + + // This simulates Flutter UI that intersects with the Android view. + embedder->CompositeEmbeddedView(0)->DrawRect( + DlRect::MakeXYWH(50, 50, 200, 200), DlPaint()); + + // Create a new overlay surface. + EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()) + .WillOnce(Return( + ByMove(std::make_unique( + 0, window)))); + // The JNI call to display the Android view. + EXPECT_CALL(*jni_mock, FlutterViewOnDisplayPlatformView(0, 0, 0, 200, 200, + 300, 300, stack1)); + EXPECT_CALL(*jni_mock, + FlutterViewDisplayOverlaySurface(0, 50, 50, 150, 150)); + + auto surface_frame = std::make_unique( + SkSurfaces::Null(1000, 1000), framebuffer_info, + [](const SurfaceFrame& surface_frame, DlCanvas* canvas) { + return true; + }, + [](const SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + embedder->SubmitFlutterView(kImplicitViewId, gr_context.get(), nullptr, + std::move(surface_frame)); + + EXPECT_CALL(*jni_mock, FlutterViewEndFrame()); + embedder->EndFrame(/*should_resubmit_frame=*/false, raster_thread_merger); + } + + EXPECT_CALL(*jni_mock, FlutterViewDestroyOverlaySurfaces()).Times(1); + EXPECT_CALL(*jni_mock, FlutterViewBeginFrame()).Times(0); + + fml::Thread platform_thread("platform"); + embedder->BeginFrame(nullptr, + GetThreadMergerFromRasterThread(&platform_thread)); + embedder->PrepareFlutterView(SkISize::Make(30, 40), 1.0); +} + +TEST(AndroidExternalViewEmbedder, SupportsDynamicThreadMerging) { + auto jni_mock = std::make_shared(); + auto android_context = AndroidContext(AndroidRenderingAPI::kSoftware); + auto embedder = std::make_unique( + android_context, jni_mock, nullptr, GetTaskRunnersForFixture()); + ASSERT_TRUE(embedder->SupportsDynamicThreadMerging()); +} + +TEST(AndroidExternalViewEmbedder, DisableThreadMerger) { + auto jni_mock = std::make_shared(); + auto android_context = AndroidContext(AndroidRenderingAPI::kSoftware); + auto embedder = std::make_unique( + android_context, jni_mock, nullptr, GetTaskRunnersForFixture()); + + fml::Thread platform_thread("platform"); + auto raster_thread_merger = GetThreadMergerFromRasterThread(&platform_thread); + ASSERT_FALSE(raster_thread_merger->IsMerged()); + + // The shell may disable the thread merger during `OnPlatformViewDestroyed`. + raster_thread_merger->Disable(); + + EXPECT_CALL(*jni_mock, FlutterViewBeginFrame()).Times(0); + + embedder->BeginFrame(nullptr, raster_thread_merger); + embedder->PrepareFlutterView(SkISize::Make(10, 20), 1.0); + // Push a platform view. + embedder->PrerollCompositeEmbeddedView( + 0, std::make_unique()); + + auto postpreroll_result = embedder->PostPrerollAction(raster_thread_merger); + ASSERT_EQ(PostPrerollResult::kSkipAndRetryFrame, postpreroll_result); + + EXPECT_CALL(*jni_mock, FlutterViewEndFrame()).Times(0); + embedder->EndFrame(/*should_resubmit_frame=*/true, raster_thread_merger); + + ASSERT_FALSE(raster_thread_merger->IsMerged()); +} + +TEST(AndroidExternalViewEmbedder, Teardown) { + auto jni_mock = std::make_shared(); + auto android_context = + std::make_shared(AndroidRenderingAPI::kSoftware); + auto window = fml::MakeRefCounted(nullptr); + auto gr_context = GrDirectContext::MakeMock(nullptr); + auto frame_size = SkISize::Make(1000, 1000); + auto surface_factory = std::make_shared( + [gr_context, window, frame_size]() { + SurfaceFrame::FramebufferInfo framebuffer_info; + auto surface_frame_1 = std::make_unique( + SkSurfaces::Null(1000, 1000), framebuffer_info, + [](const SurfaceFrame& surface_frame, DlCanvas* canvas) { + return true; + }, + [](const SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + + auto surface_mock = std::make_unique(); + EXPECT_CALL(*surface_mock, AcquireFrame(frame_size)) + .WillOnce(Return(ByMove(std::move(surface_frame_1)))); + + auto android_surface_mock = std::make_unique(); + EXPECT_CALL(*android_surface_mock, IsValid()).WillOnce(Return(true)); + EXPECT_CALL(*android_surface_mock, CreateGPUSurface(gr_context.get())) + .WillOnce(Return(ByMove(std::move(surface_mock)))); + + return android_surface_mock; + }); + + auto embedder = std::make_unique( + *android_context, jni_mock, surface_factory, GetTaskRunnersForFixture()); + fml::Thread rasterizer_thread("rasterizer"); + auto raster_thread_merger = + GetThreadMergerFromPlatformThread(&rasterizer_thread); + + embedder->BeginFrame(nullptr, raster_thread_merger); + embedder->PrepareFlutterView(frame_size, 1.5); + + // Add an Android view. + MutatorsStack stack; + auto view_params = std::make_unique( + SkMatrix(), SkSize::Make(200, 200), stack); + + embedder->PrerollCompositeEmbeddedView(0, std::move(view_params)); + + // This simulates Flutter UI that intersects with the Android view. + embedder->CompositeEmbeddedView(0)->DrawRect( + DlRect::MakeXYWH(50, 50, 200, 200), DlPaint()); + + // Create a new overlay surface. + EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()) + .WillOnce(Return( + ByMove(std::make_unique( + 0, window)))); + + SurfaceFrame::FramebufferInfo framebuffer_info; + auto surface_frame = std::make_unique( + SkSurfaces::Null(1000, 1000), framebuffer_info, + [](const SurfaceFrame& surface_frame, DlCanvas* canvas) { return true; }, + [](const SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + embedder->SubmitFlutterView(kImplicitViewId, gr_context.get(), nullptr, + std::move(surface_frame)); + + embedder->EndFrame(/*should_resubmit_frame=*/false, raster_thread_merger); + + EXPECT_CALL(*jni_mock, FlutterViewDestroyOverlaySurfaces()); + // Teardown. + embedder->Teardown(); +} + +TEST(AndroidExternalViewEmbedder, TeardownDoesNotCallJNIMethod) { + auto jni_mock = std::make_shared(); + auto android_context = + std::make_shared(AndroidRenderingAPI::kSoftware); + auto embedder = std::make_unique( + *android_context, jni_mock, nullptr, GetTaskRunnersForFixture()); + + EXPECT_CALL(*jni_mock, FlutterViewDestroyOverlaySurfaces()).Times(0); + embedder->Teardown(); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/surface_pool.cc b/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/surface_pool.cc new file mode 100644 index 0000000000000000000000000000000000000000..f839836a747ef2f0a1cef040295cdddc679abf06 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/surface_pool.cc @@ -0,0 +1,134 @@ +// 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/shell/platform/android/external_view_embedder/surface_pool.h" + +#include + +namespace flutter { + +OverlayLayer::OverlayLayer(int id, + std::unique_ptr android_surface, + std::unique_ptr surface) + : id(id), + android_surface(std::move(android_surface)), + surface(std::move(surface)){}; + +OverlayLayer::~OverlayLayer() = default; + +SurfacePool::SurfacePool(bool use_new_surface_methods) + : use_new_surface_methods_(use_new_surface_methods) {} + +SurfacePool::~SurfacePool() = default; + +std::shared_ptr SurfacePool::GetLayer( + GrDirectContext* gr_context, + const AndroidContext& android_context, + const std::shared_ptr& jni_facade, + const std::shared_ptr& surface_factory) { + std::lock_guard lock(mutex_); + // Destroy current layers in the pool if the frame size has changed. + if (requested_frame_size_ != current_frame_size_) { + DestroyLayersLocked(jni_facade); + } + intptr_t gr_context_key = reinterpret_cast(gr_context); + // Allocate a new surface if there isn't one available. + if (available_layer_index_ >= layers_.size()) { + std::unique_ptr android_surface = + surface_factory->CreateSurface(); + + FML_CHECK(android_surface && android_surface->IsValid()) + << "Could not create an OpenGL, Vulkan or Software surface to set up " + "rendering."; + + std::unique_ptr java_metadata = + use_new_surface_methods_ + ? jni_facade->createOverlaySurface2() + : jni_facade->FlutterViewCreateOverlaySurface(); + + FML_CHECK(java_metadata->window); + android_surface->SetNativeWindow(java_metadata->window, jni_facade); + + std::unique_ptr surface = + android_surface->CreateGPUSurface(gr_context); + + std::shared_ptr layer = + std::make_shared(java_metadata->id, // + std::move(android_surface), // + std::move(surface) // + ); + layer->gr_context_key = gr_context_key; + layers_.push_back(layer); + } + + std::shared_ptr layer = layers_[available_layer_index_]; + // Since the surfaces are recycled, it's possible that the GrContext is + // different. + if (gr_context_key != layer->gr_context_key) { + layer->gr_context_key = gr_context_key; + // The overlay already exists, but the GrContext was changed so we need to + // recreate the rendering surface with the new GrContext. + std::unique_ptr surface = + layer->android_surface->CreateGPUSurface(gr_context); + layer->surface = std::move(surface); + } + available_layer_index_++; + current_frame_size_ = requested_frame_size_; + return layer; +} + +void SurfacePool::RecycleLayers() { + std::lock_guard lock(mutex_); + available_layer_index_ = 0; +} + +bool SurfacePool::HasLayers() { + std::lock_guard lock(mutex_); + return !layers_.empty(); +} + +void SurfacePool::DestroyLayers( + const std::shared_ptr& jni_facade) { + std::lock_guard lock(mutex_); + DestroyLayersLocked(jni_facade); +} + +void SurfacePool::DestroyLayersLocked( + const std::shared_ptr& jni_facade) { + if (layers_.empty()) { + return; + } + if (use_new_surface_methods_) { + jni_facade->destroyOverlaySurface2(); + } else { + jni_facade->FlutterViewDestroyOverlaySurfaces(); + } + layers_.clear(); + available_layer_index_ = 0; +} + +std::vector> SurfacePool::GetUnusedLayers() { + std::lock_guard lock(mutex_); + std::vector> results; + for (size_t i = available_layer_index_; i < layers_.size(); i++) { + results.push_back(layers_[i]); + } + return results; +} + +void SurfacePool::SetFrameSize(SkISize frame_size) { + std::lock_guard lock(mutex_); + requested_frame_size_ = frame_size; +} + +void SurfacePool::ResetLayers() { + available_layer_index_ = 0; +} + +void SurfacePool::TrimLayers() { + std::lock_guard lock(mutex_); + layers_.erase(layers_.begin() + available_layer_index_, layers_.end()); + available_layer_index_ = 0; +} +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/surface_pool.h b/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/surface_pool.h new file mode 100644 index 0000000000000000000000000000000000000000..b186bda99e1fca19bc6d755ef061c83c401e02b5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/surface_pool.h @@ -0,0 +1,118 @@ +// 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_SHELL_PLATFORM_ANDROID_EXTERNAL_VIEW_EMBEDDER_SURFACE_POOL_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_EXTERNAL_VIEW_EMBEDDER_SURFACE_POOL_H_ + +#include + +#include "flutter/flow/surface.h" +#include "flutter/shell/platform/android/context/android_context.h" +#include "flutter/shell/platform/android/surface/android_surface.h" + +namespace flutter { + +//------------------------------------------------------------------------------ +/// An Overlay layer represents an `android.view.View` in the C side. +/// +/// The `id` is used to uniquely identify the layer and recycle it between +/// frames. +/// +struct OverlayLayer { + OverlayLayer(int id, + std::unique_ptr android_surface, + std::unique_ptr surface); + + ~OverlayLayer(); + + // A unique id to identify the overlay when it gets recycled. + const int id; + + // A GPU surface. + const std::unique_ptr android_surface; + + // A GPU surface. This may change when the overlay is recycled. + std::unique_ptr surface; + + // The `GrContext` that is currently used by the overlay surfaces. + // We track this to know when the GrContext for the Flutter app has changed + // so we can update the overlay with the new context. + // + // This may change when the overlay is recycled. + intptr_t gr_context_key; +}; + +class SurfacePool { + public: + explicit SurfacePool(bool use_new_surface_methods); + + ~SurfacePool(); + + // Gets a layer from the pool if available, or allocates a new one. + // Finally, it marks the layer as used. That is, it increments + // `available_layer_index_`. + std::shared_ptr GetLayer( + GrDirectContext* gr_context, + const AndroidContext& android_context, + const std::shared_ptr& jni_facade, + const std::shared_ptr& surface_factory); + + // Gets the layers in the pool that aren't currently used. + // This method doesn't mark the layers as unused. + std::vector> GetUnusedLayers(); + + // Marks the layers in the pool as available for reuse. + void RecycleLayers(); + + // Destroys all the layers in the pool. + void DestroyLayers(const std::shared_ptr& jni_facade); + + // Sets the frame size used by the layers in the pool. + // If the current layers in the pool have a different frame size, + // then they are deallocated as soon as |GetLayer| is called. + void SetFrameSize(SkISize frame_size); + + // Returns true if the current pool has layers in use. + bool HasLayers(); + + // Reset the layer index but do not release any layers. + void ResetLayers(); + + void TrimLayers(); + + private: + // The index of the entry in the layers_ vector that determines the beginning + // of the unused layers. For example, consider the following vector: + // _____ + // | 0 | + // |---| + // | 1 | <-- `available_layer_index_` + // |---| + // | 2 | + // |---| + // + // This indicates that entries starting from 1 can be reused meanwhile the + // entry at position 0 cannot be reused. + size_t available_layer_index_ = 0; + + // The layers in the pool. + std::vector> layers_; + + // The frame size of the layers in the pool. + SkISize current_frame_size_; + + // The frame size to be used by future layers. + SkISize requested_frame_size_; + + // Used to guard public methods. + std::mutex mutex_; + bool use_new_surface_methods_ = false; + + void DestroyLayersLocked( + const std::shared_ptr& jni_facade); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_EXTERNAL_VIEW_EMBEDDER_SURFACE_POOL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/surface_pool_unittests.cc b/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/surface_pool_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..98df5f0cb9beacecf0e31677ed38a0c117fcfcf0 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/external_view_embedder/surface_pool_unittests.cc @@ -0,0 +1,353 @@ +// 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 +#include "flutter/shell/platform/android/external_view_embedder/surface_pool.h" + +#include "flutter/fml/make_copyable.h" +#include "flutter/shell/platform/android/jni/jni_mock.h" +#include "flutter/shell/platform/android/surface/android_surface_mock.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" +#include "third_party/skia/include/gpu/ganesh/GrDirectContext.h" + +namespace flutter { +namespace testing { + +using ::testing::_; +using ::testing::ByMove; +using ::testing::Return; + +class TestAndroidSurfaceFactory : public AndroidSurfaceFactory { + public: + using TestSurfaceProducer = + std::function(void)>; + explicit TestAndroidSurfaceFactory(TestSurfaceProducer&& surface_producer) { + surface_producer_ = surface_producer; + } + + ~TestAndroidSurfaceFactory() override = default; + + std::unique_ptr CreateSurface() override { + return surface_producer_(); + } + + private: + TestSurfaceProducer surface_producer_; +}; + +TEST(SurfacePool, GetLayerAllocateOneLayer) { + auto pool = std::make_unique(/*use_new_surface_methods=*/false); + + auto gr_context = GrDirectContext::MakeMock(nullptr); + auto android_context = + std::make_shared(AndroidRenderingAPI::kSoftware); + + auto jni_mock = std::make_shared(); + auto window = fml::MakeRefCounted(nullptr); + EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()) + .WillOnce(Return( + ByMove(std::make_unique( + 0, window)))); + + auto surface_factory = + std::make_shared([gr_context, window]() { + auto android_surface_mock = std::make_unique(); + EXPECT_CALL(*android_surface_mock, CreateGPUSurface(gr_context.get())); + EXPECT_CALL(*android_surface_mock, SetNativeWindow(window, _)); + EXPECT_CALL(*android_surface_mock, IsValid()).WillOnce(Return(true)); + return android_surface_mock; + }); + auto layer = pool->GetLayer(gr_context.get(), *android_context, jni_mock, + surface_factory); + + ASSERT_TRUE(pool->HasLayers()); + ASSERT_NE(nullptr, layer); + ASSERT_EQ(reinterpret_cast(gr_context.get()), + layer->gr_context_key); +} + +TEST(SurfacePool, GetUnusedLayers) { + auto pool = std::make_unique(/*use_new_surface_methods=*/false); + + auto gr_context = GrDirectContext::MakeMock(nullptr); + auto android_context = + std::make_shared(AndroidRenderingAPI::kSoftware); + + auto jni_mock = std::make_shared(); + auto window = fml::MakeRefCounted(nullptr); + EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()) + .WillOnce(Return( + ByMove(std::make_unique( + 0, window)))); + + auto surface_factory = + std::make_shared([gr_context, window]() { + auto android_surface_mock = std::make_unique(); + EXPECT_CALL(*android_surface_mock, CreateGPUSurface(gr_context.get())); + EXPECT_CALL(*android_surface_mock, SetNativeWindow(window, _)); + EXPECT_CALL(*android_surface_mock, IsValid()).WillOnce(Return(true)); + return android_surface_mock; + }); + auto layer = pool->GetLayer(gr_context.get(), *android_context, jni_mock, + surface_factory); + ASSERT_EQ(0UL, pool->GetUnusedLayers().size()); + + pool->RecycleLayers(); + + ASSERT_TRUE(pool->HasLayers()); + ASSERT_EQ(1UL, pool->GetUnusedLayers().size()); + ASSERT_EQ(layer, pool->GetUnusedLayers()[0]); +} + +TEST(SurfacePool, GetLayerRecycle) { + auto pool = std::make_unique(/*use_new_surface_methods=*/false); + + auto gr_context_1 = GrDirectContext::MakeMock(nullptr); + auto jni_mock = std::make_shared(); + auto window = fml::MakeRefCounted(nullptr); + EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()) + .WillOnce(Return( + ByMove(std::make_unique( + 0, window)))); + + auto android_context = + std::make_shared(AndroidRenderingAPI::kSoftware); + + auto gr_context_2 = GrDirectContext::MakeMock(nullptr); + auto surface_factory = std::make_shared( + [gr_context_1, gr_context_2, window]() { + auto android_surface_mock = std::make_unique(); + // Allocate two GPU surfaces for each gr context. + EXPECT_CALL(*android_surface_mock, + CreateGPUSurface(gr_context_1.get())); + EXPECT_CALL(*android_surface_mock, + CreateGPUSurface(gr_context_2.get())); + // Set the native window once. + EXPECT_CALL(*android_surface_mock, SetNativeWindow(window, _)); + EXPECT_CALL(*android_surface_mock, IsValid()).WillOnce(Return(true)); + return android_surface_mock; + }); + auto layer_1 = pool->GetLayer(gr_context_1.get(), *android_context, jni_mock, + surface_factory); + + pool->RecycleLayers(); + + auto layer_2 = pool->GetLayer(gr_context_2.get(), *android_context, jni_mock, + surface_factory); + + ASSERT_TRUE(pool->HasLayers()); + ASSERT_NE(nullptr, layer_1); + ASSERT_EQ(layer_1, layer_2); + ASSERT_EQ(reinterpret_cast(gr_context_2.get()), + layer_1->gr_context_key); + ASSERT_EQ(reinterpret_cast(gr_context_2.get()), + layer_2->gr_context_key); +} + +TEST(SurfacePool, GetLayerAllocateTwoLayers) { + auto pool = std::make_unique(/*use_new_surface_methods=*/false); + + auto gr_context = GrDirectContext::MakeMock(nullptr); + auto android_context = + std::make_shared(AndroidRenderingAPI::kSoftware); + + auto jni_mock = std::make_shared(); + auto window = fml::MakeRefCounted(nullptr); + EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()) + .Times(2) + .WillOnce(Return( + ByMove(std::make_unique( + 0, window)))) + .WillOnce(Return( + ByMove(std::make_unique( + 1, window)))); + + auto surface_factory = + std::make_shared([gr_context, window]() { + auto android_surface_mock = std::make_unique(); + EXPECT_CALL(*android_surface_mock, CreateGPUSurface(gr_context.get())); + EXPECT_CALL(*android_surface_mock, SetNativeWindow(window, _)); + EXPECT_CALL(*android_surface_mock, IsValid()).WillOnce(Return(true)); + return android_surface_mock; + }); + auto layer_1 = pool->GetLayer(gr_context.get(), *android_context, jni_mock, + surface_factory); + auto layer_2 = pool->GetLayer(gr_context.get(), *android_context, jni_mock, + surface_factory); + + ASSERT_TRUE(pool->HasLayers()); + ASSERT_NE(nullptr, layer_1); + ASSERT_NE(nullptr, layer_2); + ASSERT_NE(layer_1, layer_2); + ASSERT_EQ(0, layer_1->id); + ASSERT_EQ(1, layer_2->id); +} + +TEST(SurfacePool, DestroyLayersNew) { + auto pool = std::make_unique(/*use_new_surface_methods=*/true); + auto jni_mock = std::make_shared(); + + EXPECT_CALL(*jni_mock, destroyOverlaySurface2()).Times(0); + pool->DestroyLayers(jni_mock); + + auto gr_context = GrDirectContext::MakeMock(nullptr); + auto android_context = + std::make_shared(AndroidRenderingAPI::kSoftware); + + auto window = fml::MakeRefCounted(nullptr); + EXPECT_CALL(*jni_mock, createOverlaySurface2()) + .Times(1) + .WillOnce(Return( + ByMove(std::make_unique( + 0, window)))); + + auto surface_factory = + std::make_shared([gr_context, window]() { + auto android_surface_mock = std::make_unique(); + EXPECT_CALL(*android_surface_mock, CreateGPUSurface(gr_context.get())); + EXPECT_CALL(*android_surface_mock, SetNativeWindow(window, _)); + EXPECT_CALL(*android_surface_mock, IsValid()).WillOnce(Return(true)); + return android_surface_mock; + }); + pool->GetLayer(gr_context.get(), *android_context, jni_mock, surface_factory); + + EXPECT_CALL(*jni_mock, destroyOverlaySurface2()); + + ASSERT_TRUE(pool->HasLayers()); + pool->DestroyLayers(jni_mock); + + ASSERT_FALSE(pool->HasLayers()); + ASSERT_TRUE(pool->GetUnusedLayers().empty()); +} + +TEST(SurfacePool, DestroyLayers) { + auto pool = std::make_unique(/*use_new_surface_methods=*/false); + auto jni_mock = std::make_shared(); + + EXPECT_CALL(*jni_mock, FlutterViewDestroyOverlaySurfaces()).Times(0); + pool->DestroyLayers(jni_mock); + + auto gr_context = GrDirectContext::MakeMock(nullptr); + auto android_context = + std::make_shared(AndroidRenderingAPI::kSoftware); + + auto window = fml::MakeRefCounted(nullptr); + EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()) + .Times(1) + .WillOnce(Return( + ByMove(std::make_unique( + 0, window)))); + + auto surface_factory = + std::make_shared([gr_context, window]() { + auto android_surface_mock = std::make_unique(); + EXPECT_CALL(*android_surface_mock, CreateGPUSurface(gr_context.get())); + EXPECT_CALL(*android_surface_mock, SetNativeWindow(window, _)); + EXPECT_CALL(*android_surface_mock, IsValid()).WillOnce(Return(true)); + return android_surface_mock; + }); + pool->GetLayer(gr_context.get(), *android_context, jni_mock, surface_factory); + + EXPECT_CALL(*jni_mock, FlutterViewDestroyOverlaySurfaces()); + + ASSERT_TRUE(pool->HasLayers()); + pool->DestroyLayers(jni_mock); + + ASSERT_FALSE(pool->HasLayers()); + ASSERT_TRUE(pool->GetUnusedLayers().empty()); +} + +TEST(SurfacePool, DestroyLayersFrameSizeChanged) { + auto pool = std::make_unique(/*use_new_surface_methods=*/false); + auto jni_mock = std::make_shared(); + + auto gr_context = GrDirectContext::MakeMock(nullptr); + auto android_context = + std::make_shared(AndroidRenderingAPI::kSoftware); + + auto window = fml::MakeRefCounted(nullptr); + + auto surface_factory = + std::make_shared([gr_context, window]() { + auto android_surface_mock = std::make_unique(); + EXPECT_CALL(*android_surface_mock, CreateGPUSurface(gr_context.get())); + EXPECT_CALL(*android_surface_mock, SetNativeWindow(window, _)); + EXPECT_CALL(*android_surface_mock, IsValid()).WillOnce(Return(true)); + return android_surface_mock; + }); + pool->SetFrameSize(SkISize::Make(10, 10)); + EXPECT_CALL(*jni_mock, FlutterViewDestroyOverlaySurfaces()).Times(0); + EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()) + .Times(1) + .WillOnce(Return( + ByMove(std::make_unique( + 0, window)))); + + ASSERT_FALSE(pool->HasLayers()); + + pool->GetLayer(gr_context.get(), *android_context, jni_mock, surface_factory); + + ASSERT_TRUE(pool->HasLayers()); + + pool->SetFrameSize(SkISize::Make(20, 20)); + EXPECT_CALL(*jni_mock, FlutterViewDestroyOverlaySurfaces()).Times(1); + EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()) + .Times(1) + .WillOnce(Return( + ByMove(std::make_unique( + 1, window)))); + pool->GetLayer(gr_context.get(), *android_context, jni_mock, surface_factory); + + ASSERT_TRUE(pool->GetUnusedLayers().empty()); + ASSERT_TRUE(pool->HasLayers()); +} + +TEST(SurfacePool, DestroyLayersFrameSizeChangedNew) { + auto pool = std::make_unique(/*use_new_surface_methods=*/true); + auto jni_mock = std::make_shared(); + + auto gr_context = GrDirectContext::MakeMock(nullptr); + auto android_context = + std::make_shared(AndroidRenderingAPI::kSoftware); + + auto window = fml::MakeRefCounted(nullptr); + + auto surface_factory = + std::make_shared([gr_context, window]() { + auto android_surface_mock = std::make_unique(); + EXPECT_CALL(*android_surface_mock, CreateGPUSurface(gr_context.get())); + EXPECT_CALL(*android_surface_mock, SetNativeWindow(window, _)); + EXPECT_CALL(*android_surface_mock, IsValid()).WillOnce(Return(true)); + return android_surface_mock; + }); + pool->SetFrameSize(SkISize::Make(10, 10)); + EXPECT_CALL(*jni_mock, destroyOverlaySurface2()).Times(0); + EXPECT_CALL(*jni_mock, createOverlaySurface2()) + .Times(1) + .WillOnce(Return( + ByMove(std::make_unique( + 0, window)))); + + ASSERT_FALSE(pool->HasLayers()); + + pool->GetLayer(gr_context.get(), *android_context, jni_mock, surface_factory); + + ASSERT_TRUE(pool->HasLayers()); + + pool->SetFrameSize(SkISize::Make(20, 20)); + EXPECT_CALL(*jni_mock, destroyOverlaySurface2()).Times(1); + EXPECT_CALL(*jni_mock, createOverlaySurface2()) + .Times(1) + .WillOnce(Return( + ByMove(std::make_unique( + 1, window)))); + pool->GetLayer(gr_context.get(), *android_context, jni_mock, surface_factory); + + ASSERT_TRUE(pool->GetUnusedLayers().empty()); + ASSERT_TRUE(pool->HasLayers()); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/Build.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/Build.java new file mode 100644 index 0000000000000000000000000000000000000000..519cbeff5572b42f4f7976ac27763883aa52188a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/Build.java @@ -0,0 +1,47 @@ +// 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. + +package io.flutter; + +import androidx.annotation.VisibleForTesting; + +/** A replacement of utilities from android.os.Build. */ +public class Build { + /** For use in place of the Android Build.VERSION_CODES class. */ + public static class API_LEVELS { + @VisibleForTesting public static final int FLUTTER_MIN = 21; + /** Android 5.0 (Lollipop) */ + public static final int API_21 = 21; + /** Android 5.1 (Lollipop MR1) */ + public static final int API_22 = 22; + /** Android 6.0 (Marshmallow) */ + public static final int API_23 = 23; + /** Android 7.0 (Nougat) */ + public static final int API_24 = 24; + /** Android 7.1 (Nougat MR1) */ + public static final int API_25 = 25; + /** Android 8.0 (Oreo) */ + public static final int API_26 = 26; + /** Android 8.1 (Oreo MR1) */ + public static final int API_27 = 27; + /** Android 9 (Pie) */ + public static final int API_28 = 28; + /** Android 10 (Q) */ + public static final int API_29 = 29; + /** Android 11 (R) */ + public static final int API_30 = 30; + /** Android 12 (S) */ + public static final int API_31 = 31; + /** Android 12L (Sv2) */ + public static final int API_32 = 32; + /** Android 13 (Tiramisu) */ + public static final int API_33 = 33; + /** Android 14 (Upside Down Cake) */ + public static final int API_34 = 34; + /** Android 15 (Vanilla Ice Cream) */ + public static final int API_35 = 35; + /** Android 16 */ + public static final int API_36 = 36; + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/BuildConfig.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/BuildConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..7f74134dbe1daf9878b2d685de03b4e75db50f14 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/BuildConfig.java @@ -0,0 +1,19 @@ +// 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. + +// THIS FILE IS REPLACED WITH AN AUTO_GENERATED FILE (AND EXISTS JUST FOR IDE SUPPORT). +// DO NOT EDIT THE VALUES HERE - SEE $flutter_root/tools/gen_android_buildconfig.py +package io.flutter; + +public final class BuildConfig { + private BuildConfig() { + { + } + } + + public static final boolean DEBUG = false; + public static final boolean PROFILE = false; + public static final boolean RELEASE = false; + public static final boolean JIT_RELEASE = false; +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/FlutterInjector.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/FlutterInjector.java new file mode 100644 index 0000000000000000000000000000000000000000..16cbeb3fcdda0c4eb1748003a9d50d9f0b763935 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/FlutterInjector.java @@ -0,0 +1,185 @@ +// 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. + +package io.flutter; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.VisibleForTesting; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.deferredcomponents.DeferredComponentManager; +import io.flutter.embedding.engine.loader.FlutterLoader; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; + +/** + * This class is a simple dependency injector for the relatively thin Android part of the Flutter + * engine. + * + *

This simple solution is used facilitate testability without bringing in heavier + * app-development centric dependency injection frameworks such as Guice or Dagger2 or spreading + * construction injection everywhere. + */ +public final class FlutterInjector { + + private static FlutterInjector instance; + private static boolean accessed; + + /** + * Use {@link FlutterInjector.Builder} to specify members to be injected via the static {@code + * FlutterInjector}. + * + *

This can only be called at the beginning of the program before the {@link #instance()} is + * accessed. + */ + public static void setInstance(@NonNull FlutterInjector injector) { + if (accessed) { + throw new IllegalStateException( + "Cannot change the FlutterInjector instance once it's been " + + "read. If you're trying to dependency inject, be sure to do so at the beginning of " + + "the program"); + } + instance = injector; + } + + /** + * Retrieve the static instance of the {@code FlutterInjector} to use in your program. + * + *

Once you access it, you can no longer change the values injected. + * + *

If no override is provided for the injector, reasonable defaults are provided. + */ + public static FlutterInjector instance() { + accessed = true; + if (instance == null) { + instance = new Builder().build(); + } + return instance; + } + + // This whole class is here to enable testing so to test the thing that lets you test, some degree + // of hack is needed. + @VisibleForTesting + public static void reset() { + accessed = false; + instance = null; + } + + private FlutterInjector( + @NonNull FlutterLoader flutterLoader, + @Nullable DeferredComponentManager deferredComponentManager, + @NonNull FlutterJNI.Factory flutterJniFactory, + @NonNull ExecutorService executorService) { + this.flutterLoader = flutterLoader; + this.deferredComponentManager = deferredComponentManager; + this.flutterJniFactory = flutterJniFactory; + this.executorService = executorService; + } + + private FlutterLoader flutterLoader; + private DeferredComponentManager deferredComponentManager; + private FlutterJNI.Factory flutterJniFactory; + private ExecutorService executorService; + /** + * Returns the {@link io.flutter.embedding.engine.loader.FlutterLoader} instance to use for the + * Flutter Android engine embedding. + */ + @NonNull + public FlutterLoader flutterLoader() { + return flutterLoader; + } + + /** + * Returns the {@link DeferredComponentManager} instance to use for the Flutter Android engine + * embedding. + */ + @Nullable + public DeferredComponentManager deferredComponentManager() { + return deferredComponentManager; + } + + public ExecutorService executorService() { + return executorService; + } + + @NonNull + public FlutterJNI.Factory getFlutterJNIFactory() { + return flutterJniFactory; + } + + /** + * Builder used to supply a custom FlutterInjector instance to {@link + * FlutterInjector#setInstance(FlutterInjector)}. + * + *

Non-overridden values have reasonable defaults. + */ + public static final class Builder { + private class NamedThreadFactory implements ThreadFactory { + private int threadId = 0; + + public Thread newThread(Runnable command) { + Thread thread = new Thread(command); + thread.setName("flutter-worker-" + threadId++); + return thread; + } + } + + private FlutterLoader flutterLoader; + private DeferredComponentManager deferredComponentManager; + private FlutterJNI.Factory flutterJniFactory; + private ExecutorService executorService; + /** + * Sets a {@link io.flutter.embedding.engine.loader.FlutterLoader} override. + * + *

A reasonable default will be used if unspecified. + */ + public Builder setFlutterLoader(@NonNull FlutterLoader flutterLoader) { + this.flutterLoader = flutterLoader; + return this; + } + + public Builder setDeferredComponentManager( + @Nullable DeferredComponentManager deferredComponentManager) { + this.deferredComponentManager = deferredComponentManager; + return this; + } + + public Builder setFlutterJNIFactory(@NonNull FlutterJNI.Factory factory) { + this.flutterJniFactory = factory; + return this; + } + + public Builder setExecutorService(@NonNull ExecutorService executorService) { + this.executorService = executorService; + return this; + } + + private void fillDefaults() { + if (flutterJniFactory == null) { + flutterJniFactory = new FlutterJNI.Factory(); + } + + if (executorService == null) { + executorService = Executors.newCachedThreadPool(new NamedThreadFactory()); + } + + if (flutterLoader == null) { + flutterLoader = new FlutterLoader(flutterJniFactory.provideFlutterJNI(), executorService); + } + // DeferredComponentManager's intended default is null. + } + + /** + * Builds a {@link FlutterInjector} from the builder. Unspecified properties will have + * reasonable defaults. + */ + public FlutterInjector build() { + fillDefaults(); + + return new FlutterInjector( + flutterLoader, deferredComponentManager, flutterJniFactory, executorService); + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/Log.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/Log.java new file mode 100644 index 0000000000000000000000000000000000000000..359d38bb70bfe025a3efc0a91417efa03b84f19f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/Log.java @@ -0,0 +1,104 @@ +// 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. + +package io.flutter; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; + +/** + * Port of {@link android.util.Log} that only logs in {@value io.flutter.BuildConfig#DEBUG} mode and + * internally filters logs based on a {@link #logLevel}. + */ +public class Log { + private static int logLevel = android.util.Log.DEBUG; + + public static int ASSERT = android.util.Log.ASSERT; + public static int DEBUG = android.util.Log.DEBUG; + public static int ERROR = android.util.Log.ERROR; + public static int INFO = android.util.Log.INFO; + public static int VERBOSE = android.util.Log.VERBOSE; + public static int WARN = android.util.Log.WARN; + + /** + * Sets a log cutoff such that a log level of lower priority than {@code logLevel} is filtered + * out. + * + *

See {@link android.util.Log} for log level constants. + */ + public static void setLogLevel(int logLevel) { + Log.logLevel = logLevel; + } + + public static void println(@NonNull int level, @NonNull String tag, @NonNull String message) { + if (BuildConfig.DEBUG && logLevel <= level) { + android.util.Log.println(level, tag, message); + } + } + + public static void v(@NonNull String tag, @NonNull String message) { + if (BuildConfig.DEBUG && logLevel <= android.util.Log.VERBOSE) { + android.util.Log.v(tag, message); + } + } + + public static void v(@NonNull String tag, @NonNull String message, @NonNull Throwable tr) { + if (BuildConfig.DEBUG && logLevel <= android.util.Log.VERBOSE) { + android.util.Log.v(tag, message, tr); + } + } + + public static void i(@NonNull String tag, @NonNull String message) { + if (BuildConfig.DEBUG && logLevel <= android.util.Log.INFO) { + android.util.Log.i(tag, message); + } + } + + public static void i(@NonNull String tag, @NonNull String message, @NonNull Throwable tr) { + if (BuildConfig.DEBUG && logLevel <= android.util.Log.INFO) { + android.util.Log.i(tag, message, tr); + } + } + + public static void d(@NonNull String tag, @NonNull String message) { + if (BuildConfig.DEBUG && logLevel <= android.util.Log.DEBUG) { + android.util.Log.d(tag, message); + } + } + + public static void d(@NonNull String tag, @NonNull String message, @NonNull Throwable tr) { + if (BuildConfig.DEBUG && logLevel <= android.util.Log.DEBUG) { + android.util.Log.d(tag, message, tr); + } + } + + public static void w(@NonNull String tag, @NonNull String message) { + android.util.Log.w(tag, message); + } + + public static void w(@NonNull String tag, @NonNull String message, @NonNull Throwable tr) { + android.util.Log.w(tag, message, tr); + } + + public static void e(@NonNull String tag, @NonNull String message) { + android.util.Log.e(tag, message); + } + + public static void e(@NonNull String tag, @NonNull String message, @NonNull Throwable tr) { + android.util.Log.e(tag, message, tr); + } + + public static void wtf(@NonNull String tag, @NonNull String message) { + android.util.Log.wtf(tag, message); + } + + public static void wtf(@NonNull String tag, @NonNull String message, @NonNull Throwable tr) { + android.util.Log.wtf(tag, message, tr); + } + + @NonNull + public static String getStackTraceString(@Nullable Throwable tr) { + return android.util.Log.getStackTraceString(tr); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/app/FlutterApplication.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/app/FlutterApplication.java new file mode 100644 index 0000000000000000000000000000000000000000..ed56ec2e7bc1c32621411a7dfcaef3a433123e15 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/app/FlutterApplication.java @@ -0,0 +1,18 @@ +// 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. + +package io.flutter.app; + +import android.app.Application; + +/** + * Empty implementation of the {@link Application} class, provided to avoid breaking older Flutter + * projects. Flutter projects which need to extend an Application should migrate to extending {@link + * android.app.Application} instead. + * + *

For more information on the removal of Flutter's v1 Android embedding, see: + * https://docs.flutter.dev/release/breaking-changes/v1-android-embedding. + */ +@Deprecated +public class FlutterApplication extends Application {} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/ActivityLifecycleListener.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/ActivityLifecycleListener.java new file mode 100644 index 0000000000000000000000000000000000000000..3e34c23db4b11bee30808ad5be4ab71bf05260c4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/ActivityLifecycleListener.java @@ -0,0 +1,9 @@ +// 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. + +package io.flutter.plugin.common; + +public interface ActivityLifecycleListener { + void onPostResume(); +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/BasicMessageChannel.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/BasicMessageChannel.java new file mode 100644 index 0000000000000000000000000000000000000000..ea6612d782b36469afe002adb2a800c9e8990fdd --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/BasicMessageChannel.java @@ -0,0 +1,275 @@ +// 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. + +package io.flutter.plugin.common; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.UiThread; +import io.flutter.BuildConfig; +import io.flutter.Log; +import io.flutter.plugin.common.BinaryMessenger.BinaryMessageHandler; +import io.flutter.plugin.common.BinaryMessenger.BinaryReply; +import java.nio.ByteBuffer; +import java.util.Arrays; + +/** + * A named channel for communicating with the Flutter application using basic, asynchronous message + * passing. + * + *

Messages are encoded into binary before being sent, and binary messages received are decoded + * into Java objects. The {@link MessageCodec} used must be compatible with the one used by the + * Flutter application. This can be achieved by creating a BasicMessageChannel + * counterpart of this channel on the Dart side. The static Java type of messages sent and received + * is {@code Object}, but only values supported by the specified {@link MessageCodec} can be used. + * + *

The logical identity of the channel is given by its name. Identically named channels will + * interfere with each other's communication. + */ +public final class BasicMessageChannel { + private static final String TAG = "BasicMessageChannel#"; + public static final String CHANNEL_BUFFERS_CHANNEL = "dev.flutter/channel-buffers"; + + @NonNull private final BinaryMessenger messenger; + @NonNull private final String name; + @NonNull private final MessageCodec codec; + @Nullable private final BinaryMessenger.TaskQueue taskQueue; + + /** + * Creates a new channel associated with the specified {@link BinaryMessenger} and with the + * specified name and {@link MessageCodec}. + * + * @param messenger a {@link BinaryMessenger}. + * @param name a channel name String. + * @param codec a {@link MessageCodec}. + */ + public BasicMessageChannel( + @NonNull BinaryMessenger messenger, @NonNull String name, @NonNull MessageCodec codec) { + this(messenger, name, codec, null); + } + + /** + * Creates a new channel associated with the specified {@link BinaryMessenger} and with the + * specified name and {@link MessageCodec}. + * + * @param messenger a {@link BinaryMessenger}. + * @param name a channel name String. + * @param codec a {@link MessageCodec}. + * @param taskQueue a {@link BinaryMessenger.TaskQueue} that specifies what thread will execute + * the handler. Specifying null means execute on the platform thread. See also {@link + * BinaryMessenger#makeBackgroundTaskQueue()}. + */ + public BasicMessageChannel( + @NonNull BinaryMessenger messenger, + @NonNull String name, + @NonNull MessageCodec codec, + BinaryMessenger.TaskQueue taskQueue) { + if (BuildConfig.DEBUG) { + if (messenger == null) { + Log.e(TAG, "Parameter messenger must not be null."); + } + if (name == null) { + Log.e(TAG, "Parameter name must not be null."); + } + if (codec == null) { + Log.e(TAG, "Parameter codec must not be null."); + } + } + this.messenger = messenger; + this.name = name; + this.codec = codec; + this.taskQueue = taskQueue; + } + + /** + * Sends the specified message to the Flutter application on this channel. + * + * @param message the message, possibly null. + */ + public void send(@Nullable T message) { + send(message, null); + } + + /** + * Sends the specified message to the Flutter application, optionally expecting a reply. + * + *

Any uncaught exception thrown by the reply callback will be caught and logged. + * + * @param message the message, possibly null. + * @param callback a {@link Reply} callback, possibly null. + */ + @UiThread + public void send(@Nullable T message, @Nullable final Reply callback) { + messenger.send( + name, + codec.encodeMessage(message), + callback == null ? null : new IncomingReplyHandler(callback)); + } + + /** + * Registers a message handler on this channel for receiving messages sent from the Flutter + * application. + * + *

Overrides any existing handler registration for (the name of) this channel. + * + *

If no handler has been registered, any incoming message on this channel will be handled + * silently by sending a null reply. + * + * @param handler a {@link MessageHandler}, or null to deregister. + */ + @UiThread + public void setMessageHandler(@Nullable final MessageHandler handler) { + // We call the 2 parameter variant specifically to avoid breaking changes in + // mock verify calls. + // See https://github.com/flutter/flutter/issues/92582. + if (taskQueue != null) { + messenger.setMessageHandler( + name, handler == null ? null : new IncomingMessageHandler(handler), taskQueue); + } else { + messenger.setMessageHandler( + name, handler == null ? null : new IncomingMessageHandler(handler)); + } + } + + /** + * Adjusts the number of messages that will get buffered when sending messages to channels that + * aren't fully set up yet. For example, the engine isn't running yet or the channel's message + * handler isn't set up on the Dart side yet. + */ + public void resizeChannelBuffer(int newSize) { + resizeChannelBuffer(messenger, name, newSize); + } + + /** + * Toggles whether the channel should show warning messages when discarding messages due to + * overflow. When 'warns' is false the channel is expected to overflow and warning messages will + * not be shown. + */ + public void setWarnsOnChannelOverflow(boolean warns) { + setWarnsOnChannelOverflow(messenger, name, warns); + } + + private static ByteBuffer packetFromEncodedMessage(ByteBuffer message) { + // Create a bytes array using the buffer content (messages.array() can not be used here). + message.flip(); + final byte[] bytes = new byte[message.remaining()]; + message.get(bytes); + + // The current Android Java/JNI platform message implementation assumes + // that all buffers passed to native are direct buffers. + ByteBuffer packet = ByteBuffer.allocateDirect(bytes.length); + packet.put(bytes); + + return packet; + } + + /** + * Adjusts the number of messages that will get buffered when sending messages to channels that + * aren't fully set up yet. For example, the engine isn't running yet or the channel's message + * handler isn't set up on the Dart side yet. + */ + public static void resizeChannelBuffer( + @NonNull BinaryMessenger messenger, @NonNull String channel, int newSize) { + final StandardMethodCodec codec = StandardMethodCodec.INSTANCE; + Object[] arguments = {channel, newSize}; + MethodCall methodCall = new MethodCall("resize", Arrays.asList(arguments)); + ByteBuffer message = codec.encodeMethodCall(methodCall); + ByteBuffer packet = packetFromEncodedMessage(message); + messenger.send(BasicMessageChannel.CHANNEL_BUFFERS_CHANNEL, packet); + } + + /** + * Toggles whether the channel should show warning messages when discarding messages due to + * overflow. When 'warns' is false the channel is expected to overflow and warning messages will + * not be shown. + */ + public static void setWarnsOnChannelOverflow( + @NonNull BinaryMessenger messenger, @NonNull String channel, boolean warns) { + final StandardMethodCodec codec = StandardMethodCodec.INSTANCE; + Object[] arguments = {channel, !warns}; + MethodCall methodCall = new MethodCall("overflow", Arrays.asList(arguments)); + ByteBuffer message = codec.encodeMethodCall(methodCall); + ByteBuffer packet = packetFromEncodedMessage(message); + messenger.send(BasicMessageChannel.CHANNEL_BUFFERS_CHANNEL, packet); + } + + /** A handler of incoming messages. */ + public interface MessageHandler { + + /** + * Handles the specified message received from Flutter. + * + *

Handler implementations must reply to all incoming messages, by submitting a single reply + * message to the given {@link Reply}. Failure to do so will result in lingering Flutter reply + * handlers. The reply may be submitted asynchronously and invoked on any thread. + * + *

Any uncaught exception thrown by this method, or the preceding message decoding, will be + * caught by the channel implementation and logged, and a null reply message will be sent back + * to Flutter. + * + *

Any uncaught exception thrown during encoding a reply message submitted to the {@link + * Reply} is treated similarly: the exception is logged, and a null reply is sent to Flutter. + * + * @param message the message, possibly null. + * @param reply a {@link Reply} for sending a single message reply back to Flutter. + */ + void onMessage(@Nullable T message, @NonNull Reply reply); + } + + /** + * Message reply callback. Used to submit a reply to an incoming message from Flutter. Also used + * in the dual capacity to handle a reply received from Flutter after sending a message. + */ + public interface Reply { + /** + * Handles the specified message reply. + * + * @param reply the reply, possibly null. + */ + void reply(@Nullable T reply); + } + + private final class IncomingReplyHandler implements BinaryReply { + private final Reply callback; + + private IncomingReplyHandler(@NonNull Reply callback) { + this.callback = callback; + } + + @Override + public void reply(@Nullable ByteBuffer reply) { + try { + callback.reply(codec.decodeMessage(reply)); + } catch (RuntimeException e) { + Log.e(TAG + name, "Failed to handle message reply", e); + } + } + } + + private final class IncomingMessageHandler implements BinaryMessageHandler { + private final MessageHandler handler; + + private IncomingMessageHandler(@NonNull MessageHandler handler) { + this.handler = handler; + } + + @Override + public void onMessage(@Nullable ByteBuffer message, @NonNull final BinaryReply callback) { + try { + handler.onMessage( + codec.decodeMessage(message), + new Reply() { + @Override + public void reply(T reply) { + callback.reply(codec.encodeMessage(reply)); + } + }); + } catch (RuntimeException e) { + Log.e(TAG + name, "Failed to handle message", e); + callback.reply(null); + } + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/BinaryCodec.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/BinaryCodec.java new file mode 100644 index 0000000000000000000000000000000000000000..d00311cf5256287e8bc7ab72f823a077c70195d3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/BinaryCodec.java @@ -0,0 +1,66 @@ +// 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. + +package io.flutter.plugin.common; + +import androidx.annotation.Nullable; +import java.nio.ByteBuffer; + +/** + * A {@link MessageCodec} using unencoded binary messages, represented as {@link ByteBuffer}s. + * + *

This codec is guaranteed to be compatible with the corresponding BinaryCodec on the + * Dart side. These parts of the Flutter SDK are evolved synchronously. + * + *

On the Dart side, messages are represented using {@code ByteData}. + */ +public final class BinaryCodec implements MessageCodec { + // This codec must match the Dart codec of the same name in package flutter/services. + public static final BinaryCodec INSTANCE = new BinaryCodec(); + /** + * A BinaryCodec that returns direct ByteBuffers from `decodeMessage` for better performance. + * + * @see BinaryCodec#BinaryCodec(boolean) + */ + public static final BinaryCodec INSTANCE_DIRECT = new BinaryCodec(true); + + private final boolean returnsDirectByteBufferFromDecoding; + + private BinaryCodec() { + this.returnsDirectByteBufferFromDecoding = false; + } + + /** + * A constructor for BinaryCodec. + * + * @param returnsDirectByteBufferFromDecoding `true` means that the Codec will return direct + * ByteBuffers from `decodeMessage`. Direct ByteBuffers will have better performance but will + * be invalid beyond the scope of the `decodeMessage` call. `false` means Flutter will copy + * the encoded message to Java's memory, so the ByteBuffer will be valid beyond the + * decodeMessage call, at the cost of a copy. + */ + private BinaryCodec(boolean returnsDirectByteBufferFromDecoding) { + this.returnsDirectByteBufferFromDecoding = returnsDirectByteBufferFromDecoding; + } + + @Override + public ByteBuffer encodeMessage(@Nullable ByteBuffer message) { + return message; + } + + @Override + public ByteBuffer decodeMessage(@Nullable ByteBuffer message) { + if (message == null) { + return message; + } else if (returnsDirectByteBufferFromDecoding) { + return message; + } else { + ByteBuffer result = ByteBuffer.allocate(message.capacity()); + result.put(message); + result.rewind(); + return result; + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/BinaryMessenger.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/BinaryMessenger.java new file mode 100644 index 0000000000000000000000000000000000000000..eef8e047a0afe3112d6646a88d2c1f82424555ba --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/BinaryMessenger.java @@ -0,0 +1,205 @@ +// 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. + +package io.flutter.plugin.common; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.UiThread; +import java.nio.ByteBuffer; + +/** + * Facility for communicating with Flutter using asynchronous message passing with binary messages. + * The Flutter Dart code should use BinaryMessages to + * participate. + * + *

{@code BinaryMessenger} is expected to be utilized from a single thread throughout the + * duration of its existence. If created on the main thread, then all invocations should take place + * on the main thread. If created on a background thread, then all invocations should take place on + * that background thread. + * + * @see BasicMessageChannel , which supports message passing with Strings and semi-structured + * messages. + * @see MethodChannel , which supports communication using asynchronous method invocation. + * @see EventChannel , which supports communication using event streams. + */ +public interface BinaryMessenger { + /** + * An abstraction over the threading policy used to invoke message handlers. + * + *

These are generated by calling methods like {@link + * BinaryMessenger#makeBackgroundTaskQueue(TaskQueueOptions)} and can be passed into platform + * channels' constructors to control the threading policy for handling platform channels' + * messages. + */ + public interface TaskQueue {} + + /** Options that control how a TaskQueue should operate and be created. */ + public static class TaskQueueOptions { + private boolean isSerial = true; + + public boolean getIsSerial() { + return isSerial; + } + + /** + * Setter for `isSerial` property. + * + *

When this is true all tasks performed by the TaskQueue will be forced to happen serially + * (one completes before the other begins). + */ + public TaskQueueOptions setIsSerial(boolean isSerial) { + this.isSerial = isSerial; + return this; + } + } + + /** + * Creates a TaskQueue that executes the tasks serially on a background thread. + * + *

There is no guarantee that the tasks will execute on the same thread, just that execution is + * serial. This is could be problematic if your code relies on ThreadLocal storage or + * introspection about what thread is actually executing. + */ + @UiThread + default TaskQueue makeBackgroundTaskQueue() { + return makeBackgroundTaskQueue(new TaskQueueOptions()); + } + + /** + * Creates a TaskQueue that executes the tasks serially on a background thread. + * + *

{@link TaskQueueOptions} can be used to configure the task queue to execute tasks + * concurrently. Doing so can be more performant, though users need to ensure that the task + * handlers are thread-safe. + */ + @UiThread + default TaskQueue makeBackgroundTaskQueue(TaskQueueOptions options) { + // TODO(92582): Remove default implementation when it is safe for Google Flutter users. + throw new UnsupportedOperationException("makeBackgroundTaskQueue not implemented."); + } + + /** + * Sends a binary message to the Flutter application. + * + * @param channel the name {@link String} of the logical channel used for the message. + * @param message the message payload, a direct-allocated {@link ByteBuffer} with the message + * bytes between position zero and current position, or null. + */ + @UiThread + void send(@NonNull String channel, @Nullable ByteBuffer message); + + /** + * Sends a binary message to the Flutter application, optionally expecting a reply. + * + *

Any uncaught exception thrown by the reply callback will be caught and logged. + * + * @param channel the name {@link String} of the logical channel used for the message. + * @param message the message payload, a direct-allocated {@link ByteBuffer} with the message + * bytes between position zero and current position, or null. + * @param callback a {@link BinaryReply} callback invoked when the Flutter application responds to + * the message, possibly null. + */ + @UiThread + void send(@NonNull String channel, @Nullable ByteBuffer message, @Nullable BinaryReply callback); + + /** + * Registers a handler to be invoked when the Flutter application sends a message to its host + * platform. + * + *

Registration overwrites any previous registration for the same channel name. Use a null + * handler to deregister. + * + *

If no handler has been registered for a particular channel, any incoming message on that + * channel will be handled silently by sending a null reply. + * + * @param channel the name {@link String} of the channel. + * @param handler a {@link BinaryMessageHandler} to be invoked on incoming messages, or null. + */ + @UiThread + void setMessageHandler(@NonNull String channel, @Nullable BinaryMessageHandler handler); + + /** + * Registers a handler to be invoked when the Flutter application sends a message to its host + * platform. + * + *

Registration overwrites any previous registration for the same channel name. Use a null + * handler to deregister. + * + *

If no handler has been registered for a particular channel, any incoming message on that + * channel will be handled silently by sending a null reply. + * + * @param channel the name {@link String} of the channel. + * @param handler a {@link BinaryMessageHandler} to be invoked on incoming messages, or null. + * @param taskQueue a {@link BinaryMessenger.TaskQueue} that specifies what thread will execute + * the handler. Specifying null means execute on the platform thread. + */ + @UiThread + default void setMessageHandler( + @NonNull String channel, + @Nullable BinaryMessageHandler handler, + @Nullable TaskQueue taskQueue) { + // TODO(92582): Remove default implementation when it is safe for Google Flutter users. + if (taskQueue != null) { + throw new UnsupportedOperationException( + "setMessageHandler called with nonnull taskQueue is not supported."); + } + setMessageHandler(channel, handler); + } + + /** + * Enables the ability to queue messages received from Dart. + * + *

This is useful when there are pending channel handler registrations. For example, Dart may + * be initialized concurrently, and prior to the registration of the channel handlers. This + * implies that Dart may start sending messages while plugins are being registered. + */ + default void enableBufferingIncomingMessages() { + throw new UnsupportedOperationException("enableBufferingIncomingMessages not implemented."); + } + + /** + * Disables the ability to queue messages received from Dart. + * + *

This can be used after all pending channel handlers have been registered. + */ + default void disableBufferingIncomingMessages() { + throw new UnsupportedOperationException("disableBufferingIncomingMessages not implemented."); + } + + /** Handler for incoming binary messages from Flutter. */ + interface BinaryMessageHandler { + /** + * Handles the specified message. + * + *

Handler implementations must reply to all incoming messages, by submitting a single reply + * message to the given {@link BinaryReply}. Failure to do so will result in lingering Flutter + * reply handlers. The reply may be submitted asynchronously. + * + *

Any uncaught exception thrown by this method will be caught by the messenger + * implementation and logged, and a null reply message will be sent back to Flutter. + * + * @param message the message {@link ByteBuffer} payload, possibly null. + * @param reply A {@link BinaryReply} used for submitting a reply back to Flutter. + */ + @UiThread + void onMessage(@Nullable ByteBuffer message, @NonNull BinaryReply reply); + } + + /** + * Binary message reply callback. Used to submit a reply to an incoming message from Flutter. Also + * used in the dual capacity to handle a reply received from Flutter after sending a message. + */ + interface BinaryReply { + /** + * Handles the specified reply. + * + * @param reply the reply payload, a direct-allocated {@link ByteBuffer} or null. Senders of + * outgoing replies must place the reply bytes between position zero and current position. + * Reply receivers can read from the buffer directly. + */ + void reply(@Nullable ByteBuffer reply); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/ErrorLogResult.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/ErrorLogResult.java new file mode 100644 index 0000000000000000000000000000000000000000..90b1c541df39c2b66d2a9edbc98e4a4be4a06f27 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/ErrorLogResult.java @@ -0,0 +1,45 @@ +// 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. + +package io.flutter.plugin.common; + +import androidx.annotation.Nullable; +import io.flutter.BuildConfig; +import io.flutter.Log; + +/** + * An implementation of {@link MethodChannel.Result} that writes error results to the Android log. + */ +public class ErrorLogResult implements MethodChannel.Result { + private String tag; + private int level; + + public ErrorLogResult(String tag) { + this(tag, Log.WARN); + } + + public ErrorLogResult(String tag, int level) { + this.tag = tag; + this.level = level; + } + + @Override + public void success(@Nullable Object result) {} + + @Override + public void error( + String errorCode, @Nullable String errorMessage, @Nullable Object errorDetails) { + String details = (errorDetails != null) ? " details: " + errorDetails : ""; + if (level >= Log.WARN || BuildConfig.DEBUG) { + Log.println(level, tag, errorMessage + details); + } + } + + @Override + public void notImplemented() { + if (level >= Log.WARN || BuildConfig.DEBUG) { + Log.println(level, tag, "method not implemented"); + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/EventChannel.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/EventChannel.java new file mode 100644 index 0000000000000000000000000000000000000000..f8835f90904c4820122b5cfe2ffcfe27d88fc531 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/EventChannel.java @@ -0,0 +1,274 @@ +// 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. + +package io.flutter.plugin.common; + +import androidx.annotation.Nullable; +import androidx.annotation.UiThread; +import io.flutter.BuildConfig; +import io.flutter.Log; +import io.flutter.plugin.common.BinaryMessenger.BinaryMessageHandler; +import io.flutter.plugin.common.BinaryMessenger.BinaryReply; +import java.nio.ByteBuffer; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; + +/** + * A named channel for communicating with the Flutter application using asynchronous event streams. + * + *

Incoming requests for event stream setup are decoded from binary on receipt, and Java + * responses and events are encoded into binary before being transmitted back to Flutter. The {@link + * MethodCodec} used must be compatible with the one used by the Flutter application. This can be + * achieved by creating an EventChannel + * counterpart of this channel on the Dart side. The Java type of stream configuration arguments, + * events, and error details is {@code Object}, but only values supported by the specified {@link + * MethodCodec} can be used. + * + *

The logical identity of the channel is given by its name. Identically named channels will + * interfere with each other's communication. + */ +public final class EventChannel { + private static final String TAG = "EventChannel#"; + + private final BinaryMessenger messenger; + private final String name; + private final MethodCodec codec; + @Nullable private final BinaryMessenger.TaskQueue taskQueue; + + /** + * Creates a new channel associated with the specified {@link BinaryMessenger} and with the + * specified name and the standard {@link MethodCodec}. + * + * @param messenger a {@link BinaryMessenger}. + * @param name a channel name String. + */ + public EventChannel(BinaryMessenger messenger, String name) { + this(messenger, name, StandardMethodCodec.INSTANCE); + } + + /** + * Creates a new channel associated with the specified {@link BinaryMessenger} and with the + * specified name and {@link MethodCodec}. + * + * @param messenger a {@link BinaryMessenger}. + * @param name a channel name String. + * @param codec a {@link MessageCodec}. + */ + public EventChannel(BinaryMessenger messenger, String name, MethodCodec codec) { + this(messenger, name, codec, null); + } + + /** + * Creates a new channel associated with the specified {@link BinaryMessenger} and with the + * specified name and {@link MethodCodec}. + * + * @param messenger a {@link BinaryMessenger}. + * @param name a channel name String. + * @param codec a {@link MessageCodec}. + * @param taskQueue a {@link BinaryMessenger.TaskQueue} that specifies what thread will execute + * the handler. Specifying null means execute on the platform thread. See also {@link + * BinaryMessenger#makeBackgroundTaskQueue()}. + */ + public EventChannel( + BinaryMessenger messenger, + String name, + MethodCodec codec, + BinaryMessenger.TaskQueue taskQueue) { + if (BuildConfig.DEBUG) { + if (messenger == null) { + Log.e(TAG, "Parameter messenger must not be null."); + } + if (name == null) { + Log.e(TAG, "Parameter name must not be null."); + } + if (codec == null) { + Log.e(TAG, "Parameter codec must not be null."); + } + } + this.messenger = messenger; + this.name = name; + this.codec = codec; + this.taskQueue = taskQueue; + } + + /** + * Registers a stream handler on this channel. + * + *

Overrides any existing handler registration for (the name of) this channel. + * + *

If no handler has been registered, any incoming stream setup requests will be handled + * silently by providing an empty stream. + * + * @param handler a {@link StreamHandler}, or null to deregister. + */ + @UiThread + public void setStreamHandler(final StreamHandler handler) { + // We call the 2 parameter variant specifically to avoid breaking changes in + // mock verify calls. + // See https://github.com/flutter/flutter/issues/92582. + if (taskQueue != null) { + messenger.setMessageHandler( + name, handler == null ? null : new IncomingStreamRequestHandler(handler), taskQueue); + } else { + messenger.setMessageHandler( + name, handler == null ? null : new IncomingStreamRequestHandler(handler)); + } + } + + /** + * Handler of stream setup and teardown requests. + * + *

Implementations must be prepared to accept sequences of alternating calls to {@link + * #onListen(Object, EventChannel.EventSink)} and {@link #onCancel(Object)}. Implementations + * should ideally consume no resources when the last such call is not {@code onListen}. In typical + * situations, this means that the implementation should register itself with platform-specific + * event sources {@code onListen} and deregister again {@code onCancel}. + */ + public interface StreamHandler { + /** + * Handles a request to set up an event stream. + * + *

Any uncaught exception thrown by this method will be caught by the channel implementation + * and logged. An error result message will be sent back to Flutter. + * + * @param arguments stream configuration arguments, possibly null. + * @param events an {@link EventSink} for emitting events to the Flutter receiver. + */ + void onListen(Object arguments, EventSink events); + + /** + * Handles a request to tear down the most recently created event stream. + * + *

Any uncaught exception thrown by this method will be caught by the channel implementation + * and logged. An error result message will be sent back to Flutter. + * + *

The channel implementation may call this method with null arguments to separate a pair of + * two consecutive set up requests. Such request pairs may occur during Flutter hot restart. Any + * uncaught exception thrown in this situation will be logged without notifying Flutter. + * + * @param arguments stream configuration arguments, possibly null. + */ + void onCancel(Object arguments); + } + + /** + * Event callback. Supports dual use: Producers of events to be sent to Flutter act as clients of + * this interface for sending events. Consumers of events sent from Flutter implement this + * interface for handling received events (the latter facility has not been implemented yet). + */ + public interface EventSink { + /** + * Consumes a successful event. + * + * @param event the event, possibly null. + */ + void success(Object event); + + /** + * Consumes an error event. + * + * @param errorCode an error code String. + * @param errorMessage a human-readable error message String, possibly null. + * @param errorDetails error details, possibly null + */ + void error(String errorCode, String errorMessage, Object errorDetails); + + /** + * Consumes end of stream. Ensuing calls to {@link #success(Object)} or {@link #error(String, + * String, Object)}, if any, are ignored. + */ + void endOfStream(); + } + + private final class IncomingStreamRequestHandler implements BinaryMessageHandler { + private final StreamHandler handler; + private final AtomicReference activeSink = new AtomicReference<>(null); + + IncomingStreamRequestHandler(StreamHandler handler) { + this.handler = handler; + } + + @Override + public void onMessage(ByteBuffer message, final BinaryReply reply) { + final MethodCall call = codec.decodeMethodCall(message); + if (call.method.equals("listen")) { + onListen(call.arguments, reply); + } else if (call.method.equals("cancel")) { + onCancel(call.arguments, reply); + } else { + reply.reply(null); + } + } + + private void onListen(Object arguments, BinaryReply callback) { + final EventSink eventSink = new EventSinkImplementation(); + final EventSink oldSink = activeSink.getAndSet(eventSink); + if (oldSink != null) { + // Repeated calls to onListen may happen during hot restart. + // We separate them with a call to onCancel. + try { + handler.onCancel(null); + } catch (RuntimeException e) { + Log.e(TAG + name, "Failed to close existing event stream", e); + } + } + try { + handler.onListen(arguments, eventSink); + callback.reply(codec.encodeSuccessEnvelope(null)); + } catch (RuntimeException e) { + activeSink.set(null); + Log.e(TAG + name, "Failed to open event stream", e); + callback.reply(codec.encodeErrorEnvelope("error", e.getMessage(), null)); + } + } + + private void onCancel(Object arguments, BinaryReply callback) { + final EventSink oldSink = activeSink.getAndSet(null); + if (oldSink != null) { + try { + handler.onCancel(arguments); + callback.reply(codec.encodeSuccessEnvelope(null)); + } catch (RuntimeException e) { + Log.e(TAG + name, "Failed to close event stream", e); + callback.reply(codec.encodeErrorEnvelope("error", e.getMessage(), null)); + } + } else { + callback.reply(codec.encodeErrorEnvelope("error", "No active stream to cancel", null)); + } + } + + private final class EventSinkImplementation implements EventSink { + final AtomicBoolean hasEnded = new AtomicBoolean(false); + + @Override + @UiThread + public void success(Object event) { + if (hasEnded.get() || activeSink.get() != this) { + return; + } + EventChannel.this.messenger.send(name, codec.encodeSuccessEnvelope(event)); + } + + @Override + @UiThread + public void error(String errorCode, String errorMessage, Object errorDetails) { + if (hasEnded.get() || activeSink.get() != this) { + return; + } + EventChannel.this.messenger.send( + name, codec.encodeErrorEnvelope(errorCode, errorMessage, errorDetails)); + } + + @Override + @UiThread + public void endOfStream() { + if (hasEnded.getAndSet(true) || activeSink.get() != this) { + return; + } + EventChannel.this.messenger.send(name, null); + } + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/FlutterException.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/FlutterException.java new file mode 100644 index 0000000000000000000000000000000000000000..ffcce9eb046b5ec16a7770d3609a703c2fa077c0 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/FlutterException.java @@ -0,0 +1,25 @@ +// 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. + +package io.flutter.plugin.common; + +import io.flutter.BuildConfig; +import io.flutter.Log; + +/** Thrown to indicate that a Flutter method invocation failed on the Flutter side. */ +public class FlutterException extends RuntimeException { + private static final String TAG = "FlutterException#"; + + public final String code; + public final Object details; + + FlutterException(String code, String message, Object details) { + super(message); + if (BuildConfig.DEBUG && code == null) { + Log.e(TAG, "Parameter code must not be null."); + } + this.code = code; + this.details = details; + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONMessageCodec.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONMessageCodec.java new file mode 100644 index 0000000000000000000000000000000000000000..b2b57a452d4f83e3876fac735df53da93f204587 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONMessageCodec.java @@ -0,0 +1,63 @@ +// 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. + +package io.flutter.plugin.common; + +import androidx.annotation.Nullable; +import java.nio.ByteBuffer; +import org.json.JSONException; +import org.json.JSONObject; +import org.json.JSONTokener; + +/** + * A {@link MessageCodec} using UTF-8 encoded JSON messages. + * + *

This codec is guaranteed to be compatible with the corresponding JSONMessageCodec + * on the Dart side. These parts of the Flutter SDK are evolved synchronously. + * + *

Supports the same Java values as {@link JSONObject#wrap(Object)}. + * + *

On the Dart side, JSON messages are handled by the JSON facilities of the dart:convert package. + */ +public final class JSONMessageCodec implements MessageCodec { + // This codec must match the Dart codec of the same name in package flutter/services. + public static final JSONMessageCodec INSTANCE = new JSONMessageCodec(); + + private JSONMessageCodec() {} + + @Override + @Nullable + public ByteBuffer encodeMessage(@Nullable Object message) { + if (message == null) { + return null; + } + final Object wrapped = JSONUtil.wrap(message); + if (wrapped instanceof String) { + return StringCodec.INSTANCE.encodeMessage(JSONObject.quote((String) wrapped)); + } else { + return StringCodec.INSTANCE.encodeMessage(wrapped.toString()); + } + } + + @Override + @Nullable + public Object decodeMessage(@Nullable ByteBuffer message) { + if (message == null) { + return null; + } + try { + final String json = StringCodec.INSTANCE.decodeMessage(message); + final JSONTokener tokener = new JSONTokener(json); + final Object value = tokener.nextValue(); + if (tokener.more()) { + throw new IllegalArgumentException("Invalid JSON"); + } + return value; + } catch (JSONException e) { + throw new IllegalArgumentException("Invalid JSON", e); + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONMethodCodec.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONMethodCodec.java new file mode 100644 index 0000000000000000000000000000000000000000..3869bd5169c5076b3833452da0b1472b503e2e79 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONMethodCodec.java @@ -0,0 +1,122 @@ +// 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. + +package io.flutter.plugin.common; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import java.nio.ByteBuffer; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +/** + * A {@link MethodCodec} using UTF-8 encoded JSON method calls and result envelopes. + * + *

This codec is guaranteed to be compatible with the corresponding JSONMethodCodec on + * the Dart side. These parts of the Flutter SDK are evolved synchronously. + * + *

Values supported as methods arguments and result payloads are those supported by {@link + * JSONMessageCodec}. + */ +public final class JSONMethodCodec implements MethodCodec { + // This codec must match the Dart codec of the same name in package flutter/services. + public static final JSONMethodCodec INSTANCE = new JSONMethodCodec(); + + private JSONMethodCodec() {} + + @Override + @NonNull + public ByteBuffer encodeMethodCall(@NonNull MethodCall methodCall) { + try { + final JSONObject map = new JSONObject(); + map.put("method", methodCall.method); + map.put("args", JSONUtil.wrap(methodCall.arguments)); + return JSONMessageCodec.INSTANCE.encodeMessage(map); + } catch (JSONException e) { + throw new IllegalArgumentException("Invalid JSON", e); + } + } + + @Override + @NonNull + public MethodCall decodeMethodCall(@NonNull ByteBuffer message) { + try { + final Object json = JSONMessageCodec.INSTANCE.decodeMessage(message); + if (json instanceof JSONObject) { + final JSONObject map = (JSONObject) json; + final Object method = map.get("method"); + final Object arguments = unwrapNull(map.opt("args")); + if (method instanceof String) { + return new MethodCall((String) method, arguments); + } + } + throw new IllegalArgumentException("Invalid method call: " + json); + } catch (JSONException e) { + throw new IllegalArgumentException("Invalid JSON", e); + } + } + + @Override + @NonNull + public ByteBuffer encodeSuccessEnvelope(@Nullable Object result) { + return JSONMessageCodec.INSTANCE.encodeMessage(new JSONArray().put(JSONUtil.wrap(result))); + } + + @Override + @NonNull + public ByteBuffer encodeErrorEnvelope( + @NonNull String errorCode, @Nullable String errorMessage, @Nullable Object errorDetails) { + return JSONMessageCodec.INSTANCE.encodeMessage( + new JSONArray() + .put(errorCode) + .put(JSONUtil.wrap(errorMessage)) + .put(JSONUtil.wrap(errorDetails))); + } + + @Override + @NonNull + public ByteBuffer encodeErrorEnvelopeWithStacktrace( + @NonNull String errorCode, + @Nullable String errorMessage, + @Nullable Object errorDetails, + @Nullable String errorStacktrace) { + return JSONMessageCodec.INSTANCE.encodeMessage( + new JSONArray() + .put(errorCode) + .put(JSONUtil.wrap(errorMessage)) + .put(JSONUtil.wrap(errorDetails)) + .put(JSONUtil.wrap(errorStacktrace))); + } + + @Override + @NonNull + public Object decodeEnvelope(@NonNull ByteBuffer envelope) { + try { + final Object json = JSONMessageCodec.INSTANCE.decodeMessage(envelope); + if (json instanceof JSONArray) { + final JSONArray array = (JSONArray) json; + if (array.length() == 1) { + return unwrapNull(array.opt(0)); + } + if (array.length() == 3) { + final Object code = array.get(0); + final Object message = unwrapNull(array.opt(1)); + final Object details = unwrapNull(array.opt(2)); + if (code instanceof String && (message == null || message instanceof String)) { + throw new FlutterException((String) code, (String) message, details); + } + } + } + throw new IllegalArgumentException("Invalid envelope: " + json); + } catch (JSONException e) { + throw new IllegalArgumentException("Invalid JSON", e); + } + } + + Object unwrapNull(Object value) { + return (value == JSONObject.NULL) ? null : value; + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONUtil.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..1ee87f6fc397fb62df31edbc7a6da69f190f672e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONUtil.java @@ -0,0 +1,108 @@ +package io.flutter.plugin.common; + +import androidx.annotation.Nullable; +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import org.json.JSONArray; +import org.json.JSONObject; + +public class JSONUtil { + private JSONUtil() {} + + /** + * Convert the Json java representation to Java objects. Particularly used for converting + * JSONArray and JSONObject to Lists and Maps. + */ + @Nullable + public static Object unwrap(@Nullable Object o) { + if (JSONObject.NULL.equals(o) || o == null) { + return null; + } + if (o instanceof Boolean + || o instanceof Byte + || o instanceof Character + || o instanceof Double + || o instanceof Float + || o instanceof Integer + || o instanceof Long + || o instanceof Short + || o instanceof String) { + return o; + } + try { + if (o instanceof JSONArray) { + List list = new ArrayList<>(); + JSONArray array = (JSONArray) o; + for (int i = 0; i < array.length(); i++) { + list.add(unwrap(array.get(i))); + } + return list; + } + if (o instanceof JSONObject) { + Map map = new HashMap<>(); + JSONObject jsonObject = (JSONObject) o; + Iterator keyIterator = jsonObject.keys(); + while (keyIterator.hasNext()) { + String key = keyIterator.next(); + map.put(key, unwrap(jsonObject.get(key))); + } + return map; + } + } catch (Exception ignored) { + } + return null; + } + + /** Backport of {@link JSONObject#wrap(Object)} for use on pre-KitKat systems. */ + @Nullable + public static Object wrap(@Nullable Object o) { + if (o == null) { + return JSONObject.NULL; + } + if (o instanceof JSONArray || o instanceof JSONObject) { + return o; + } + if (o.equals(JSONObject.NULL)) { + return o; + } + try { + if (o instanceof Collection) { + JSONArray result = new JSONArray(); + for (Object e : (Collection) o) result.put(wrap(e)); + return result; + } else if (o.getClass().isArray()) { + JSONArray result = new JSONArray(); + int length = Array.getLength(o); + for (int i = 0; i < length; i++) result.put(wrap(Array.get(o, i))); + return result; + } + if (o instanceof Map) { + JSONObject result = new JSONObject(); + for (Map.Entry entry : ((Map) o).entrySet()) + result.put((String) entry.getKey(), wrap(entry.getValue())); + return result; + } + if (o instanceof Boolean + || o instanceof Byte + || o instanceof Character + || o instanceof Double + || o instanceof Float + || o instanceof Integer + || o instanceof Long + || o instanceof Short + || o instanceof String) { + return o; + } + if (o.getClass().getPackage().getName().startsWith("java.")) { + return o.toString(); + } + } catch (Exception ignored) { + } + return null; + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MessageCodec.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MessageCodec.java new file mode 100644 index 0000000000000000000000000000000000000000..a87214a14f38e016d983035cbc46f5b6b68ca83c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MessageCodec.java @@ -0,0 +1,39 @@ +// 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. + +package io.flutter.plugin.common; + +import androidx.annotation.Nullable; +import java.nio.ByteBuffer; + +/** + * A message encoding/decoding mechanism. + * + *

Both operations throw {@link IllegalArgumentException}, if conversion fails. + */ +public interface MessageCodec { + /** + * Encodes the specified message into binary. + * + * @param message the T message, possibly null. + * @return a ByteBuffer containing the encoding between position 0 and the current position, or + * null, if message is null. + */ + @Nullable + ByteBuffer encodeMessage(@Nullable T message); + + /** + * Decodes the specified message from binary. + * + *

Warning: The ByteBuffer is "direct" and it won't be valid beyond this call. Storing + * the ByteBuffer and using it later and will lead to a {@code java.nio.BufferUnderflowException}. + * If you want to retain the data you'll need to copy it. + * + * @param message the {@link ByteBuffer} message, possibly null. + * @return a T value representation of the bytes between the given buffer's current position and + * its limit, or null, if message is null. + */ + @Nullable + T decodeMessage(@Nullable ByteBuffer message); +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MethodCall.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MethodCall.java new file mode 100644 index 0000000000000000000000000000000000000000..7181a548e713abb1bc2eab92434545c02b0cd79f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MethodCall.java @@ -0,0 +1,102 @@ +// 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. + +package io.flutter.plugin.common; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import io.flutter.BuildConfig; +import java.util.Map; +import org.json.JSONObject; + +/** Command object representing a method call on a {@link MethodChannel}. */ +public final class MethodCall { + /** The name of the called method. */ + public final String method; + + /** + * Arguments for the call. + * + *

Consider using {@link #arguments()} for cases where a particular run-time type is expected. + * Consider using {@link #argument(String)} when that run-time type is {@link Map} or {@link + * JSONObject}. + */ + public final Object arguments; + + /** + * Creates a {@link MethodCall} with the specified method name and arguments. + * + * @param method the method name String, not null. + * @param arguments the arguments, a value supported by the channel's message codec. Possibly, + * null. + */ + public MethodCall(@NonNull String method, @Nullable Object arguments) { + if (BuildConfig.DEBUG && method == null) { + throw new AssertionError("Parameter method must not be null."); + } + this.method = method; + this.arguments = arguments; + } + + /** + * Returns the arguments of this method call with a static type determined by the call-site. + * + * @param the intended type of the arguments. + * @return the arguments with static type T + */ + @SuppressWarnings("unchecked") + @Nullable + public T arguments() { + return (T) arguments; + } + + /** + * Returns a String-keyed argument of this method call, assuming {@link #arguments} is a {@link + * Map} or a {@link JSONObject}. The static type of the returned result is determined by the + * call-site. + * + * @param the intended type of the argument. + * @param key the String key. + * @return the argument value at the specified key, with static type T, or {@code null}, if such + * an entry is not present. + * @throws ClassCastException if {@link #arguments} can be cast to neither {@link Map} nor {@link + * JSONObject}. + */ + @SuppressWarnings("unchecked") + @Nullable + public T argument(@NonNull String key) { + if (arguments == null) { + return null; + } else if (arguments instanceof Map) { + return (T) ((Map) arguments).get(key); + } else if (arguments instanceof JSONObject) { + return (T) ((JSONObject) arguments).opt(key); + } else { + throw new ClassCastException(); + } + } + + /** + * Returns whether this method call involves a mapping for the given argument key, assuming {@link + * #arguments} is a {@link Map} or a {@link JSONObject}. The value associated with the key, as + * returned by {@link #argument(String)}, is not considered, and may be {@code null}. + * + * @param key the String key. + * @return {@code true}, if {@link #arguments} is a {@link Map} containing key, or a {@link + * JSONObject} with a mapping for key. + * @throws ClassCastException if {@link #arguments} can be cast to neither {@link Map} nor {@link + * JSONObject}. + */ + public boolean hasArgument(@NonNull String key) { + if (arguments == null) { + return false; + } else if (arguments instanceof Map) { + return ((Map) arguments).containsKey(key); + } else if (arguments instanceof JSONObject) { + return ((JSONObject) arguments).has(key); + } else { + throw new ClassCastException(); + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MethodChannel.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MethodChannel.java new file mode 100644 index 0000000000000000000000000000000000000000..3191aa4e3ad66cc7affde3c1a69ad75507816de0 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MethodChannel.java @@ -0,0 +1,293 @@ +// 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. + +package io.flutter.plugin.common; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.UiThread; +import io.flutter.BuildConfig; +import io.flutter.Log; +import io.flutter.plugin.common.BinaryMessenger.BinaryMessageHandler; +import io.flutter.plugin.common.BinaryMessenger.BinaryReply; +import java.nio.ByteBuffer; + +/** + * A named channel for communicating with the Flutter application using asynchronous method calls. + * + *

Incoming method calls are decoded from binary on receipt, and Java results are encoded into + * binary before being transmitted back to Flutter. The {@link MethodCodec} used must be compatible + * with the one used by the Flutter application. This can be achieved by creating a MethodChannel + * counterpart of this channel on the Dart side. The Java type of method call arguments and results + * is {@code Object}, but only values supported by the specified {@link MethodCodec} can be used. + * + *

The logical identity of the channel is given by its name. Identically named channels will + * interfere with each other's communication. + */ +public class MethodChannel { + private static final String TAG = "MethodChannel#"; + + private final BinaryMessenger messenger; + private final String name; + private final MethodCodec codec; + private final BinaryMessenger.TaskQueue taskQueue; + + /** + * Creates a new channel associated with the specified {@link BinaryMessenger} and with the + * specified name and the standard {@link MethodCodec}. + * + * @param messenger a {@link BinaryMessenger}. + * @param name a channel name String. + */ + public MethodChannel(@NonNull BinaryMessenger messenger, @NonNull String name) { + this(messenger, name, StandardMethodCodec.INSTANCE); + } + + /** + * Creates a new channel associated with the specified {@link BinaryMessenger} and with the + * specified name and {@link MethodCodec}. + * + * @param messenger a {@link BinaryMessenger}. + * @param name a channel name String. + * @param codec a {@link MessageCodec}. + */ + public MethodChannel( + @NonNull BinaryMessenger messenger, @NonNull String name, @NonNull MethodCodec codec) { + this(messenger, name, codec, null); + } + + /** + * Creates a new channel associated with the specified {@link BinaryMessenger} and with the + * specified name and {@link MethodCodec}. + * + * @param messenger a {@link BinaryMessenger}. + * @param name a channel name String. + * @param codec a {@link MessageCodec}. + * @param taskQueue a {@link BinaryMessenger.TaskQueue} that specifies what thread will execute + * the handler. Specifying null means execute on the platform thread. See also {@link + * BinaryMessenger#makeBackgroundTaskQueue()}. + */ + public MethodChannel( + @NonNull BinaryMessenger messenger, + @NonNull String name, + @NonNull MethodCodec codec, + @Nullable BinaryMessenger.TaskQueue taskQueue) { + if (BuildConfig.DEBUG) { + if (messenger == null) { + Log.e(TAG, "Parameter messenger must not be null."); + } + if (name == null) { + Log.e(TAG, "Parameter name must not be null."); + } + if (codec == null) { + Log.e(TAG, "Parameter codec must not be null."); + } + } + this.messenger = messenger; + this.name = name; + this.codec = codec; + this.taskQueue = taskQueue; + } + + /** + * Invokes a method on this channel, expecting no result. + * + * @param method the name String of the method. + * @param arguments the arguments for the invocation, possibly null. + */ + @UiThread + public void invokeMethod(@NonNull String method, @Nullable Object arguments) { + invokeMethod(method, arguments, null); + } + + /** + * Invokes a method on this channel, optionally expecting a result. + * + *

Any uncaught exception thrown by the result callback will be caught and logged. + * + * @param method the name String of the method. + * @param arguments the arguments for the invocation, possibly null. + * @param callback a {@link Result} callback for the invocation result, or null. + */ + @UiThread + public void invokeMethod( + @NonNull String method, @Nullable Object arguments, @Nullable Result callback) { + messenger.send( + name, + codec.encodeMethodCall(new MethodCall(method, arguments)), + callback == null ? null : new IncomingResultHandler(callback)); + } + + /** + * Registers a method call handler on this channel. + * + *

Overrides any existing handler registration for (the name of) this channel. + * + *

If no handler has been registered, any incoming method call on this channel will be handled + * silently by sending a null reply. This results in a MissingPluginException + * on the Dart side, unless an OptionalMethodChannel + * is used. + * + * @param handler a {@link MethodCallHandler}, or null to deregister. + */ + @UiThread + public void setMethodCallHandler(final @Nullable MethodCallHandler handler) { + // We call the 2 parameter variant specifically to avoid breaking changes in + // mock verify calls. + // See https://github.com/flutter/flutter/issues/92582. + if (taskQueue != null) { + messenger.setMessageHandler( + name, handler == null ? null : new IncomingMethodCallHandler(handler), taskQueue); + } else { + messenger.setMessageHandler( + name, handler == null ? null : new IncomingMethodCallHandler(handler)); + } + } + + /** + * Adjusts the number of messages that will get buffered when sending messages to channels that + * aren't fully set up yet. For example, the engine isn't running yet or the channel's message + * handler isn't set up on the Dart side yet. + */ + public void resizeChannelBuffer(int newSize) { + BasicMessageChannel.resizeChannelBuffer(messenger, name, newSize); + } + + /** + * Toggles whether the channel should show warning messages when discarding messages due to + * overflow. When 'warns' is false the channel is expected to overflow and warning messages will + * not be shown. + */ + public void setWarnsOnChannelOverflow(boolean warns) { + BasicMessageChannel.setWarnsOnChannelOverflow(messenger, name, warns); + } + + /** A handler of incoming method calls. */ + public interface MethodCallHandler { + /** + * Handles the specified method call received from Flutter. + * + *

Handler implementations must submit a result for all incoming calls, by making a single + * call on the given {@link Result} callback. Failure to do so will result in lingering Flutter + * result handlers. The result may be submitted asynchronously and on any thread. Calls to + * unknown or unimplemented methods should be handled using {@link Result#notImplemented()}. + * + *

Any uncaught exception thrown by this method will be caught by the channel implementation + * and logged, and an error result will be sent back to Flutter. + * + *

The handler is called on the platform thread (Android main thread) by default, or + * otherwise on the thread specified by the {@link BinaryMessenger.TaskQueue} provided to the + * associated {@link MethodChannel} when it was created. See also Threading in + * the Flutter Engine. + * + * @param call A {@link MethodCall}. + * @param result A {@link Result} used for submitting the result of the call. + */ + @UiThread + void onMethodCall(@NonNull MethodCall call, @NonNull Result result); + } + + /** + * Method call result callback. Supports dual use: Implementations of methods to be invoked by + * Flutter act as clients of this interface for sending results back to Flutter. Invokers of + * Flutter methods provide implementations of this interface for handling results received from + * Flutter. + * + *

All methods of this class can be invoked on any thread. + */ + public interface Result { + /** + * Handles a successful result. + * + * @param result The result, possibly null. The result must be an Object type supported by the + * codec. For instance, if you are using {@link StandardMessageCodec} (default), please see + * its documentation on what types are supported. + */ + void success(@Nullable Object result); + + /** + * Handles an error result. + * + * @param errorCode An error code String. + * @param errorMessage A human-readable error message String, possibly null. + * @param errorDetails Error details, possibly null. The details must be an Object type + * supported by the codec. For instance, if you are using {@link StandardMessageCodec} + * (default), please see its documentation on what types are supported. + */ + void error( + @NonNull String errorCode, @Nullable String errorMessage, @Nullable Object errorDetails); + + /** Handles a call to an unimplemented method. */ + void notImplemented(); + } + + private final class IncomingResultHandler implements BinaryReply { + private final Result callback; + + IncomingResultHandler(Result callback) { + this.callback = callback; + } + + @Override + @UiThread + public void reply(ByteBuffer reply) { + try { + if (reply == null) { + callback.notImplemented(); + } else { + try { + callback.success(codec.decodeEnvelope(reply)); + } catch (FlutterException e) { + callback.error(e.code, e.getMessage(), e.details); + } + } + } catch (RuntimeException e) { + Log.e(TAG + name, "Failed to handle method call result", e); + } + } + } + + private final class IncomingMethodCallHandler implements BinaryMessageHandler { + private final MethodCallHandler handler; + + IncomingMethodCallHandler(MethodCallHandler handler) { + this.handler = handler; + } + + @Override + @UiThread + public void onMessage(ByteBuffer message, final BinaryReply reply) { + final MethodCall call = codec.decodeMethodCall(message); + try { + handler.onMethodCall( + call, + new Result() { + @Override + public void success(Object result) { + reply.reply(codec.encodeSuccessEnvelope(result)); + } + + @Override + public void error(String errorCode, String errorMessage, Object errorDetails) { + reply.reply(codec.encodeErrorEnvelope(errorCode, errorMessage, errorDetails)); + } + + @Override + public void notImplemented() { + reply.reply(null); + } + }); + } catch (RuntimeException e) { + Log.e(TAG + name, "Failed to handle method call", e); + reply.reply( + codec.encodeErrorEnvelopeWithStacktrace( + "error", e.getMessage(), null, Log.getStackTraceString(e))); + } + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MethodCodec.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MethodCodec.java new file mode 100644 index 0000000000000000000000000000000000000000..74594ad1e69a8f9a0fe7c5e8fddf89a85e0930d5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MethodCodec.java @@ -0,0 +1,92 @@ +// 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. + +package io.flutter.plugin.common; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import java.nio.ByteBuffer; + +/** + * A codec for method calls and enveloped results. + * + *

Method calls are encoded as binary messages with enough structure that the codec can extract a + * method name String and an arguments Object. These data items are used to populate a {@link + * MethodCall}. + * + *

All operations throw {@link IllegalArgumentException}, if conversion fails. + */ +public interface MethodCodec { + /** + * Encodes a message call into binary. + * + * @param methodCall a {@link MethodCall}. + * @return a {@link ByteBuffer} containing the encoding between position 0 and the current + * position. + */ + @NonNull + ByteBuffer encodeMethodCall(@NonNull MethodCall methodCall); + + /** + * Decodes a message call from binary. + * + * @param methodCall the binary encoding of the method call as a {@link ByteBuffer}. + * @return a {@link MethodCall} representation of the bytes between the given buffer's current + * position and its limit. + */ + @NonNull + MethodCall decodeMethodCall(@NonNull ByteBuffer methodCall); + + /** + * Encodes a successful result into a binary envelope message. + * + * @param result The result value, possibly null. + * @return a {@link ByteBuffer} containing the encoding between position 0 and the current + * position. + */ + @NonNull + ByteBuffer encodeSuccessEnvelope(@Nullable Object result); + + /** + * Encodes an error result into a binary envelope message. + * + * @param errorCode An error code String. + * @param errorMessage An error message String, possibly null. + * @param errorDetails Error details, possibly null. Consider supporting {@link Throwable} in your + * codec. This is the most common value passed to this field. + * @return a {@link ByteBuffer} containing the encoding between position 0 and the current + * position. + */ + @NonNull + ByteBuffer encodeErrorEnvelope( + @NonNull String errorCode, @Nullable String errorMessage, @Nullable Object errorDetails); + + /** + * Encodes an error result into a binary envelope message with the native stacktrace. + * + * @param errorCode An error code String. + * @param errorMessage An error message String, possibly null. + * @param errorDetails Error details, possibly null. Consider supporting {@link Throwable} in your + * codec. This is the most common value passed to this field. + * @param errorStacktrace Platform stacktrace for the error. possibly null. + * @return a {@link ByteBuffer} containing the encoding between position 0 and the current + * position. + */ + @NonNull + ByteBuffer encodeErrorEnvelopeWithStacktrace( + @NonNull String errorCode, + @Nullable String errorMessage, + @Nullable Object errorDetails, + @Nullable String errorStacktrace); + + /** + * Decodes a result envelope from binary. + * + * @param envelope the binary encoding of a result envelope as a {@link ByteBuffer}. + * @return the enveloped result Object. + * @throws FlutterException if the envelope was an error envelope. + */ + @NonNull + Object decodeEnvelope(@NonNull ByteBuffer envelope); +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/PluginRegistry.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/PluginRegistry.java new file mode 100644 index 0000000000000000000000000000000000000000..977b995ecf63af5859c6e79614dafdd382ad29c8 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/PluginRegistry.java @@ -0,0 +1,75 @@ +// 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. + +package io.flutter.plugin.common; + +import android.app.Activity; +import android.content.Intent; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; + +/** Container class for Android API listeners used by {@link ActivityPluginBinding}. */ +public interface PluginRegistry { + /** + * Delegate interface for handling result of permissions requests on behalf of the main {@link + * Activity}. + */ + interface RequestPermissionsResultListener { + /** + * @param requestCode The request code passed in {@code + * ActivityCompat.requestPermissions(android.app.Activity, String[], int)}. + * @param permissions The requested permissions. + * @param grantResults The grant results for the corresponding permissions which is either + * {@code PackageManager.PERMISSION_GRANTED} or {@code PackageManager.PERMISSION_DENIED}. + * @return true if the result has been handled. + */ + boolean onRequestPermissionsResult( + int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults); + } + + /** + * Delegate interface for handling activity results on behalf of the main {@link + * android.app.Activity}. + */ + interface ActivityResultListener { + /** + * @param requestCode The integer request code originally supplied to {@code + * startActivityForResult()}, allowing you to identify who this result came from. + * @param resultCode The integer result code returned by the child activity through its {@code + * setResult()}. + * @param data An Intent, which can return result data to the caller (various data can be + * attached to Intent "extras"). + * @return true if the result has been handled. + */ + boolean onActivityResult(int requestCode, int resultCode, @Nullable Intent data); + } + + /** + * Delegate interface for handling new intents on behalf of the main {@link android.app.Activity}. + */ + interface NewIntentListener { + /** + * @param intent The new intent that was started for the activity. + * @return true if the new intent has been handled. + */ + boolean onNewIntent(@NonNull Intent intent); + } + + /** + * Delegate interface for handling user leave hints on behalf of the main {@link + * android.app.Activity}. + */ + interface UserLeaveHintListener { + void onUserLeaveHint(); + } + + /** + * Delegate interface for handling window focus changes on behalf of the main {@link + * android.app.Activity}. + */ + interface WindowFocusChangedListener { + void onWindowFocusChanged(boolean hasFocus); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/StandardMessageCodec.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/StandardMessageCodec.java new file mode 100644 index 0000000000000000000000000000000000000000..c13b5681c8e0dbadf6422761a13a5a256d85fff7 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/StandardMessageCodec.java @@ -0,0 +1,460 @@ +// 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. + +package io.flutter.plugin.common; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import io.flutter.BuildConfig; +import io.flutter.Log; +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +/** + * MessageCodec using the Flutter standard binary encoding. + * + *

This codec is guaranteed to be compatible with the corresponding StandardMessageCodec + * on the Dart side. These parts of the Flutter SDK are evolved synchronously. + * + *

Supported messages are acyclic values of these forms: + * + *

    + *
  • null + *
  • Booleans + *
  • Bytes, Shorts, Integers, Longs + *
  • BigIntegers (see below) + *
  • Floats, Doubles + *
  • Strings + *
  • byte[], int[], long[], float[], double[] + *
  • Lists of supported values + *
  • Maps with supported keys and values + *
+ * + *

On the Dart side, these values are represented as follows: + * + *

    + *
  • null: null + *
  • Boolean: bool + *
  • Byte, Short, Integer, Long: int + *
  • Float, Double: double + *
  • String: String + *
  • byte[]: Uint8List + *
  • int[]: Int32List + *
  • long[]: Int64List + *
  • float[]: Float32List + *
  • double[]: Float64List + *
  • List: List + *
  • Map: Map + *
+ * + *

BigIntegers are represented in Dart as strings with the hexadecimal representation of the + * integer's value. + * + *

To extend the codec, overwrite the writeValue and readValueOfType methods. + */ +public class StandardMessageCodec implements MessageCodec { + private static final String TAG = "StandardMessageCodec#"; + public static final StandardMessageCodec INSTANCE = new StandardMessageCodec(); + + @Override + @Nullable + public ByteBuffer encodeMessage(@Nullable Object message) { + if (message == null) { + return null; + } + final ExposedByteArrayOutputStream stream = new ExposedByteArrayOutputStream(); + writeValue(stream, message); + final ByteBuffer buffer = ByteBuffer.allocateDirect(stream.size()); + buffer.put(stream.buffer(), 0, stream.size()); + return buffer; + } + + @Override + @Nullable + public Object decodeMessage(@Nullable ByteBuffer message) { + if (message == null) { + return null; + } + message.order(ByteOrder.nativeOrder()); + final Object value = readValue(message); + if (message.hasRemaining()) { + throw new IllegalArgumentException("Message corrupted"); + } + return value; + } + + private static final boolean LITTLE_ENDIAN = ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN; + private static final Charset UTF8 = Charset.forName("UTF8"); + private static final byte NULL = 0; + private static final byte TRUE = 1; + private static final byte FALSE = 2; + private static final byte INT = 3; + private static final byte LONG = 4; + private static final byte BIGINT = 5; + private static final byte DOUBLE = 6; + private static final byte STRING = 7; + private static final byte BYTE_ARRAY = 8; + private static final byte INT_ARRAY = 9; + private static final byte LONG_ARRAY = 10; + private static final byte DOUBLE_ARRAY = 11; + private static final byte LIST = 12; + private static final byte MAP = 13; + private static final byte FLOAT_ARRAY = 14; + + /** + * Writes an int representing a size to the specified stream. Uses an expanding code of 1 to 5 + * bytes to optimize for small values. + */ + protected static final void writeSize(@NonNull ByteArrayOutputStream stream, int value) { + if (BuildConfig.DEBUG && 0 > value) { + Log.e(TAG, "Attempted to write a negative size."); + } + if (value < 254) { + stream.write(value); + } else if (value <= 0xffff) { + stream.write(254); + writeChar(stream, value); + } else { + stream.write(255); + writeInt(stream, value); + } + } + + /** Writes the least significant two bytes of the specified int to the specified stream. */ + protected static final void writeChar(@NonNull ByteArrayOutputStream stream, int value) { + if (LITTLE_ENDIAN) { + stream.write(value); + stream.write(value >>> 8); + } else { + stream.write(value >>> 8); + stream.write(value); + } + } + + /** Writes the specified int as 4 bytes to the specified stream. */ + protected static final void writeInt(@NonNull ByteArrayOutputStream stream, int value) { + if (LITTLE_ENDIAN) { + stream.write(value); + stream.write(value >>> 8); + stream.write(value >>> 16); + stream.write(value >>> 24); + } else { + stream.write(value >>> 24); + stream.write(value >>> 16); + stream.write(value >>> 8); + stream.write(value); + } + } + + /** Writes the specified long as 8 bytes to the specified stream. */ + protected static final void writeLong(@NonNull ByteArrayOutputStream stream, long value) { + if (LITTLE_ENDIAN) { + stream.write((byte) value); + stream.write((byte) (value >>> 8)); + stream.write((byte) (value >>> 16)); + stream.write((byte) (value >>> 24)); + stream.write((byte) (value >>> 32)); + stream.write((byte) (value >>> 40)); + stream.write((byte) (value >>> 48)); + stream.write((byte) (value >>> 56)); + } else { + stream.write((byte) (value >>> 56)); + stream.write((byte) (value >>> 48)); + stream.write((byte) (value >>> 40)); + stream.write((byte) (value >>> 32)); + stream.write((byte) (value >>> 24)); + stream.write((byte) (value >>> 16)); + stream.write((byte) (value >>> 8)); + stream.write((byte) value); + } + } + + /** Writes the specified double as 4 bytes to the specified stream */ + protected static final void writeFloat(@NonNull ByteArrayOutputStream stream, float value) { + writeInt(stream, Float.floatToIntBits(value)); + } + + /** Writes the specified double as 8 bytes to the specified stream. */ + protected static final void writeDouble(@NonNull ByteArrayOutputStream stream, double value) { + writeLong(stream, Double.doubleToLongBits(value)); + } + + /** Writes the length and then the actual bytes of the specified array to the specified stream. */ + protected static final void writeBytes( + @NonNull ByteArrayOutputStream stream, @NonNull byte[] bytes) { + writeSize(stream, bytes.length); + stream.write(bytes, 0, bytes.length); + } + + /** + * Writes a number of padding bytes to the specified stream to ensure that the next value is + * aligned to a whole multiple of the specified alignment. An example usage with alignment = 8 is + * to ensure doubles are word-aligned in the stream. + */ + protected static final void writeAlignment(@NonNull ByteArrayOutputStream stream, int alignment) { + final int mod = stream.size() % alignment; + if (mod != 0) { + for (int i = 0; i < alignment - mod; i++) { + stream.write(0); + } + } + } + + /** + * Writes a type discriminator byte and then a byte serialization of the specified value to the + * specified stream. + * + *

Subclasses can extend the codec by overriding this method, calling super for values that the + * extension does not handle. + */ + protected void writeValue(@NonNull ByteArrayOutputStream stream, @Nullable Object value) { + if (value == null || value.equals(null)) { + stream.write(NULL); + } else if (value instanceof Boolean) { + stream.write(((Boolean) value).booleanValue() ? TRUE : FALSE); + } else if (value instanceof Number) { + if (value instanceof Integer || value instanceof Short || value instanceof Byte) { + stream.write(INT); + writeInt(stream, ((Number) value).intValue()); + } else if (value instanceof Long) { + stream.write(LONG); + writeLong(stream, (long) value); + } else if (value instanceof Float || value instanceof Double) { + stream.write(DOUBLE); + writeAlignment(stream, 8); + writeDouble(stream, ((Number) value).doubleValue()); + } else if (value instanceof BigInteger) { + stream.write(BIGINT); + writeBytes(stream, ((BigInteger) value).toString(16).getBytes(UTF8)); + } else { + throw new IllegalArgumentException("Unsupported Number type: " + value.getClass()); + } + } else if (value instanceof CharSequence) { + stream.write(STRING); + writeBytes(stream, value.toString().getBytes(UTF8)); + } else if (value instanceof byte[]) { + stream.write(BYTE_ARRAY); + writeBytes(stream, (byte[]) value); + } else if (value instanceof int[]) { + stream.write(INT_ARRAY); + final int[] array = (int[]) value; + writeSize(stream, array.length); + writeAlignment(stream, 4); + for (final int n : array) { + writeInt(stream, n); + } + } else if (value instanceof long[]) { + stream.write(LONG_ARRAY); + final long[] array = (long[]) value; + writeSize(stream, array.length); + writeAlignment(stream, 8); + for (final long n : array) { + writeLong(stream, n); + } + } else if (value instanceof double[]) { + stream.write(DOUBLE_ARRAY); + final double[] array = (double[]) value; + writeSize(stream, array.length); + writeAlignment(stream, 8); + for (final double d : array) { + writeDouble(stream, d); + } + } else if (value instanceof List) { + stream.write(LIST); + final List list = (List) value; + writeSize(stream, list.size()); + for (final Object o : list) { + writeValue(stream, o); + } + } else if (value instanceof Map) { + stream.write(MAP); + final Map map = (Map) value; + writeSize(stream, map.size()); + for (final Entry entry : map.entrySet()) { + writeValue(stream, entry.getKey()); + writeValue(stream, entry.getValue()); + } + } else if (value instanceof float[]) { + stream.write(FLOAT_ARRAY); + final float[] array = (float[]) value; + writeSize(stream, array.length); + writeAlignment(stream, 4); + for (final float f : array) { + writeFloat(stream, f); + } + } else { + throw new IllegalArgumentException( + "Unsupported value: '" + value + "' of type '" + value.getClass() + "'"); + } + } + + /** Reads an int representing a size as written by writeSize. */ + protected static final int readSize(@NonNull ByteBuffer buffer) { + if (!buffer.hasRemaining()) { + throw new IllegalArgumentException("Message corrupted"); + } + final int value = buffer.get() & 0xff; + if (value < 254) { + return value; + } else if (value == 254) { + return buffer.getChar(); + } else { + return buffer.getInt(); + } + } + + /** Reads a byte array as written by writeBytes. */ + @NonNull + protected static final byte[] readBytes(@NonNull ByteBuffer buffer) { + final int length = readSize(buffer); + final byte[] bytes = new byte[length]; + buffer.get(bytes); + return bytes; + } + + /** Reads alignment padding bytes as written by writeAlignment. */ + protected static final void readAlignment(@NonNull ByteBuffer buffer, int alignment) { + final int mod = buffer.position() % alignment; + if (mod != 0) { + buffer.position(buffer.position() + alignment - mod); + } + } + + /** Reads a value as written by writeValue. */ + @Nullable + protected final Object readValue(@NonNull ByteBuffer buffer) { + if (!buffer.hasRemaining()) { + throw new IllegalArgumentException("Message corrupted"); + } + final byte type = buffer.get(); + return readValueOfType(type, buffer); + } + + /** + * Reads a value of the specified type. + * + *

Subclasses may extend the codec by overriding this method, calling super for types that the + * extension does not handle. + */ + @Nullable + protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer) { + final Object result; + switch (type) { + case NULL: + result = null; + break; + case TRUE: + result = true; + break; + case FALSE: + result = false; + break; + case INT: + result = buffer.getInt(); + break; + case LONG: + result = buffer.getLong(); + break; + case BIGINT: + { + final byte[] hex = readBytes(buffer); + result = new BigInteger(new String(hex, UTF8), 16); + break; + } + case DOUBLE: + readAlignment(buffer, 8); + result = buffer.getDouble(); + break; + case STRING: + { + final byte[] bytes = readBytes(buffer); + result = new String(bytes, UTF8); + break; + } + case BYTE_ARRAY: + { + result = readBytes(buffer); + break; + } + case INT_ARRAY: + { + final int length = readSize(buffer); + final int[] array = new int[length]; + readAlignment(buffer, 4); + buffer.asIntBuffer().get(array); + result = array; + buffer.position(buffer.position() + 4 * length); + break; + } + case LONG_ARRAY: + { + final int length = readSize(buffer); + final long[] array = new long[length]; + readAlignment(buffer, 8); + buffer.asLongBuffer().get(array); + result = array; + buffer.position(buffer.position() + 8 * length); + break; + } + case DOUBLE_ARRAY: + { + final int length = readSize(buffer); + final double[] array = new double[length]; + readAlignment(buffer, 8); + buffer.asDoubleBuffer().get(array); + result = array; + buffer.position(buffer.position() + 8 * length); + break; + } + case LIST: + { + final int size = readSize(buffer); + final List list = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + list.add(readValue(buffer)); + } + result = list; + break; + } + case MAP: + { + final int size = readSize(buffer); + final Map map = new HashMap<>(); + for (int i = 0; i < size; i++) { + map.put(readValue(buffer), readValue(buffer)); + } + result = map; + break; + } + case FLOAT_ARRAY: + { + final int length = readSize(buffer); + final float[] array = new float[length]; + readAlignment(buffer, 4); + buffer.asFloatBuffer().get(array); + result = array; + buffer.position(buffer.position() + 4 * length); + break; + } + default: + throw new IllegalArgumentException("Message corrupted"); + } + return result; + } + + static final class ExposedByteArrayOutputStream extends ByteArrayOutputStream { + byte[] buffer() { + return buf; + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/StandardMethodCodec.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/StandardMethodCodec.java new file mode 100644 index 0000000000000000000000000000000000000000..5a8db8b25b67740f1e51b72fee8bac4e1cdc41fe --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/StandardMethodCodec.java @@ -0,0 +1,135 @@ +// 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. + +package io.flutter.plugin.common; + +import androidx.annotation.NonNull; +import io.flutter.Log; +import io.flutter.plugin.common.StandardMessageCodec.ExposedByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +/** + * A {@link MethodCodec} using the Flutter standard binary encoding. + * + *

This codec is guaranteed to be compatible with the corresponding StandardMethodCodec + * on the Dart side. These parts of the Flutter SDK are evolved synchronously. + * + *

Values supported as method arguments and result payloads are those supported by {@link + * StandardMessageCodec}. + */ +public final class StandardMethodCodec implements MethodCodec { + public static final StandardMethodCodec INSTANCE = + new StandardMethodCodec(StandardMessageCodec.INSTANCE); + private final StandardMessageCodec messageCodec; + + /** Creates a new method codec based on the specified message codec. */ + public StandardMethodCodec(@NonNull StandardMessageCodec messageCodec) { + this.messageCodec = messageCodec; + } + + @Override + @NonNull + public ByteBuffer encodeMethodCall(@NonNull MethodCall methodCall) { + final ExposedByteArrayOutputStream stream = new ExposedByteArrayOutputStream(); + messageCodec.writeValue(stream, methodCall.method); + messageCodec.writeValue(stream, methodCall.arguments); + final ByteBuffer buffer = ByteBuffer.allocateDirect(stream.size()); + buffer.put(stream.buffer(), 0, stream.size()); + return buffer; + } + + @Override + @NonNull + public MethodCall decodeMethodCall(@NonNull ByteBuffer methodCall) { + methodCall.order(ByteOrder.nativeOrder()); + final Object method = messageCodec.readValue(methodCall); + final Object arguments = messageCodec.readValue(methodCall); + if (method instanceof String && !methodCall.hasRemaining()) { + return new MethodCall((String) method, arguments); + } + throw new IllegalArgumentException("Method call corrupted"); + } + + @Override + @NonNull + public ByteBuffer encodeSuccessEnvelope(@NonNull Object result) { + final ExposedByteArrayOutputStream stream = new ExposedByteArrayOutputStream(); + stream.write(0); + messageCodec.writeValue(stream, result); + final ByteBuffer buffer = ByteBuffer.allocateDirect(stream.size()); + buffer.put(stream.buffer(), 0, stream.size()); + return buffer; + } + + @Override + @NonNull + public ByteBuffer encodeErrorEnvelope( + @NonNull String errorCode, @NonNull String errorMessage, @NonNull Object errorDetails) { + final ExposedByteArrayOutputStream stream = new ExposedByteArrayOutputStream(); + stream.write(1); + messageCodec.writeValue(stream, errorCode); + messageCodec.writeValue(stream, errorMessage); + if (errorDetails instanceof Throwable) { + messageCodec.writeValue(stream, Log.getStackTraceString((Throwable) errorDetails)); + } else { + messageCodec.writeValue(stream, errorDetails); + } + final ByteBuffer buffer = ByteBuffer.allocateDirect(stream.size()); + buffer.put(stream.buffer(), 0, stream.size()); + return buffer; + } + + @Override + @NonNull + public ByteBuffer encodeErrorEnvelopeWithStacktrace( + @NonNull String errorCode, + @NonNull String errorMessage, + @NonNull Object errorDetails, + @NonNull String errorStacktrace) { + final ExposedByteArrayOutputStream stream = new ExposedByteArrayOutputStream(); + stream.write(1); + messageCodec.writeValue(stream, errorCode); + messageCodec.writeValue(stream, errorMessage); + if (errorDetails instanceof Throwable) { + messageCodec.writeValue(stream, Log.getStackTraceString((Throwable) errorDetails)); + } else { + messageCodec.writeValue(stream, errorDetails); + } + messageCodec.writeValue(stream, errorStacktrace); + final ByteBuffer buffer = ByteBuffer.allocateDirect(stream.size()); + buffer.put(stream.buffer(), 0, stream.size()); + return buffer; + } + + @Override + @NonNull + public Object decodeEnvelope(@NonNull ByteBuffer envelope) { + envelope.order(ByteOrder.nativeOrder()); + final byte flag = envelope.get(); + switch (flag) { + case 0: + { + final Object result = messageCodec.readValue(envelope); + if (!envelope.hasRemaining()) { + return result; + } + } + // Falls through intentionally. + case 1: + { + final Object code = messageCodec.readValue(envelope); + final Object message = messageCodec.readValue(envelope); + final Object details = messageCodec.readValue(envelope); + if (code instanceof String + && (message == null || message instanceof String) + && !envelope.hasRemaining()) { + throw new FlutterException((String) code, (String) message, details); + } + } + } + throw new IllegalArgumentException("Envelope corrupted"); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/StringCodec.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/StringCodec.java new file mode 100644 index 0000000000000000000000000000000000000000..3cf17793949ba4c222b4f42c249e2e38078e84a9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/StringCodec.java @@ -0,0 +1,57 @@ +// 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. + +package io.flutter.plugin.common; + +import androidx.annotation.Nullable; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; + +/** + * A {@link MessageCodec} using UTF-8 encoded String messages. + * + *

This codec is guaranteed to be compatible with the corresponding StringCodec on the + * Dart side. These parts of the Flutter SDK are evolved synchronously. + */ +public final class StringCodec implements MessageCodec { + private static final Charset UTF8 = Charset.forName("UTF8"); + public static final StringCodec INSTANCE = new StringCodec(); + + private StringCodec() {} + + @Override + @Nullable + public ByteBuffer encodeMessage(@Nullable String message) { + if (message == null) { + return null; + } + // TODO(mravn): Avoid the extra copy below. + final byte[] bytes = message.getBytes(UTF8); + final ByteBuffer buffer = ByteBuffer.allocateDirect(bytes.length); + buffer.put(bytes); + return buffer; + } + + @Override + @Nullable + public String decodeMessage(@Nullable ByteBuffer message) { + if (message == null) { + return null; + } + final byte[] bytes; + final int offset; + final int length = message.remaining(); + if (message.hasArray()) { + bytes = message.array(); + offset = message.arrayOffset(); + } else { + // TODO(mravn): Avoid the extra copy below. + bytes = new byte[length]; + message.get(bytes); + offset = 0; + } + return new String(bytes, offset, length, UTF8); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/FlutterTextUtils.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/FlutterTextUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..ea0dc96b913de6b6b3e84e09735c6b953d8eacce --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/FlutterTextUtils.java @@ -0,0 +1,319 @@ +// 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. + +package io.flutter.plugin.editing; + +import io.flutter.embedding.engine.FlutterJNI; + +class FlutterTextUtils { + public static final int LINE_FEED = 0x0A; + public static final int CARRIAGE_RETURN = 0x0D; + public static final int COMBINING_ENCLOSING_KEYCAP = 0x20E3; + public static final int CANCEL_TAG = 0xE007F; + public static final int ZERO_WIDTH_JOINER = 0x200D; + private final FlutterJNI flutterJNI; + + public FlutterTextUtils(FlutterJNI flutterJNI) { + this.flutterJNI = flutterJNI; + } + + public boolean isEmoji(int codePoint) { + return flutterJNI.isCodePointEmoji(codePoint); + } + + public boolean isEmojiModifier(int codePoint) { + return flutterJNI.isCodePointEmojiModifier(codePoint); + } + + public boolean isEmojiModifierBase(int codePoint) { + return flutterJNI.isCodePointEmojiModifierBase(codePoint); + } + + public boolean isVariationSelector(int codePoint) { + return flutterJNI.isCodePointVariantSelector(codePoint); + } + + public boolean isRegionalIndicatorSymbol(int codePoint) { + return flutterJNI.isCodePointRegionalIndicator(codePoint); + } + + public boolean isTagSpecChar(int codePoint) { + return 0xE0020 <= codePoint && codePoint <= 0xE007E; + } + + public boolean isKeycapBase(int codePoint) { + return ('0' <= codePoint && codePoint <= '9') || codePoint == '#' || codePoint == '*'; + } + + /** + * Start offset for backspace key or moving left from the current offset. Same methods are also + * included in Android APIs but they don't work as expected in API Levels lower than 24. Reference + * for the logic in this code is the Android source code. + * + * @see https://android.googlesource.com/platform/frameworks/base/+/refs/heads/android10-s3-release/core/java/android/text/method/BaseKeyListener.java#111 + */ + public int getOffsetBefore(CharSequence text, int offset) { + if (offset <= 1) { + return 0; + } + + int codePoint = Character.codePointBefore(text, offset); + int deleteCharCount = Character.charCount(codePoint); + int lastOffset = offset - deleteCharCount; + + if (lastOffset == 0) { + return 0; + } + + // Line Feed + if (codePoint == LINE_FEED) { + codePoint = Character.codePointBefore(text, lastOffset); + if (codePoint == CARRIAGE_RETURN) { + ++deleteCharCount; + } + return offset - deleteCharCount; + } + + // Flags + if (isRegionalIndicatorSymbol(codePoint)) { + codePoint = Character.codePointBefore(text, lastOffset); + lastOffset -= Character.charCount(codePoint); + int regionalIndicatorSymbolCount = 1; + while (lastOffset > 0 && isRegionalIndicatorSymbol(codePoint)) { + codePoint = Character.codePointBefore(text, lastOffset); + lastOffset -= Character.charCount(codePoint); + regionalIndicatorSymbolCount++; + } + if (regionalIndicatorSymbolCount % 2 == 0) { + deleteCharCount += 2; + } + return offset - deleteCharCount; + } + + // Keycaps + if (codePoint == COMBINING_ENCLOSING_KEYCAP) { + codePoint = Character.codePointBefore(text, lastOffset); + lastOffset -= Character.charCount(codePoint); + if (lastOffset > 0 && isVariationSelector(codePoint)) { + int tmpCodePoint = Character.codePointBefore(text, lastOffset); + if (isKeycapBase(tmpCodePoint)) { + deleteCharCount += Character.charCount(codePoint) + Character.charCount(tmpCodePoint); + } + } else if (isKeycapBase(codePoint)) { + deleteCharCount += Character.charCount(codePoint); + } + return offset - deleteCharCount; + } + + /** + * Following if statements for Emoji tag sequence and Variation selector are skipping these + * modifiers for going through the last statement that is for handling emojis. They return the + * offset if they don't find proper base characters + */ + // Emoji Tag Sequence + if (codePoint == CANCEL_TAG) { // tag_end + codePoint = Character.codePointBefore(text, lastOffset); + lastOffset -= Character.charCount(codePoint); + while (lastOffset > 0 && isTagSpecChar(codePoint)) { // tag_spec + deleteCharCount += Character.charCount(codePoint); + codePoint = Character.codePointBefore(text, lastOffset); + lastOffset -= Character.charCount(codePoint); + } + if (!isEmoji(codePoint)) { // tag_base not found. Just delete the end. + return offset - 2; + } + deleteCharCount += Character.charCount(codePoint); + } + + if (isVariationSelector(codePoint)) { + codePoint = Character.codePointBefore(text, lastOffset); + if (!isEmoji(codePoint)) { + return offset - deleteCharCount; + } + deleteCharCount += Character.charCount(codePoint); + + lastOffset -= deleteCharCount; + } + + if (isEmoji(codePoint)) { + boolean isZwj = false; + int lastSeenVariantSelectorCharCount = 0; + do { + if (isZwj) { + deleteCharCount += Character.charCount(codePoint) + lastSeenVariantSelectorCharCount + 1; + isZwj = false; + } + lastSeenVariantSelectorCharCount = 0; + if (isEmojiModifier(codePoint)) { + codePoint = Character.codePointBefore(text, lastOffset); + lastOffset -= Character.charCount(codePoint); + if (lastOffset > 0 && isVariationSelector(codePoint)) { + codePoint = Character.codePointBefore(text, lastOffset); + if (!isEmoji(codePoint)) { + return offset - deleteCharCount; + } + lastSeenVariantSelectorCharCount = Character.charCount(codePoint); + lastOffset -= Character.charCount(codePoint); + } + if (isEmojiModifierBase(codePoint)) { + deleteCharCount += lastSeenVariantSelectorCharCount + Character.charCount(codePoint); + } + break; + } + + if (lastOffset > 0) { + codePoint = Character.codePointBefore(text, lastOffset); + lastOffset -= Character.charCount(codePoint); + if (codePoint == ZERO_WIDTH_JOINER) { + isZwj = true; + codePoint = Character.codePointBefore(text, lastOffset); + lastOffset -= Character.charCount(codePoint); + if (lastOffset > 0 && isVariationSelector(codePoint)) { + codePoint = Character.codePointBefore(text, lastOffset); + lastSeenVariantSelectorCharCount = Character.charCount(codePoint); + lastOffset -= Character.charCount(codePoint); + } + } + } + + if (lastOffset == 0) { + break; + } + } while (isZwj && isEmoji(codePoint)); + } + + return offset - deleteCharCount; + } + + /** + * Gets the offset of the next character following the given offset, with consideration for + * multi-byte characters. + * + * @see https://android.googlesource.com/platform/frameworks/base/+/refs/heads/android10-s3-release/core/java/android/text/method/BaseKeyListener.java#111 + */ + public int getOffsetAfter(CharSequence text, int offset) { + final int len = text.length(); + + if (offset >= len - 1) { + return len; + } + + int codePoint = Character.codePointAt(text, offset); + int nextCharCount = Character.charCount(codePoint); + int nextOffset = offset + nextCharCount; + + if (nextOffset == 0) { + return 0; + } + + // Line Feed + if (codePoint == LINE_FEED) { + codePoint = Character.codePointAt(text, nextOffset); + if (codePoint == CARRIAGE_RETURN) { + ++nextCharCount; + } + return offset + nextCharCount; + } + + // Flags + if (isRegionalIndicatorSymbol(codePoint)) { + if (nextOffset >= len - 1 + || !isRegionalIndicatorSymbol(Character.codePointAt(text, nextOffset))) { + return offset + nextCharCount; + } + // In this case there are at least two regional indicator symbols ahead of + // offset. If those two regional indicator symbols are a pair that + // represent a region together, the next offset should be after both of + // them. + int regionalIndicatorSymbolCount = 0; + int regionOffset = offset; + while (regionOffset > 0 + && isRegionalIndicatorSymbol(Character.codePointBefore(text, offset))) { + regionOffset -= Character.charCount(Character.codePointBefore(text, offset)); + regionalIndicatorSymbolCount++; + } + if (regionalIndicatorSymbolCount % 2 == 0) { + nextCharCount += 2; + } + return offset + nextCharCount; + } + + // Keycaps + if (isKeycapBase(codePoint)) { + nextCharCount += Character.charCount(codePoint); + } + if (codePoint == COMBINING_ENCLOSING_KEYCAP) { + codePoint = Character.codePointBefore(text, nextOffset); + nextOffset += Character.charCount(codePoint); + if (nextOffset < len && isVariationSelector(codePoint)) { + int tmpCodePoint = Character.codePointAt(text, nextOffset); + if (isKeycapBase(tmpCodePoint)) { + nextCharCount += Character.charCount(codePoint) + Character.charCount(tmpCodePoint); + } + } else if (isKeycapBase(codePoint)) { + nextCharCount += Character.charCount(codePoint); + } + return offset + nextCharCount; + } + + if (isEmoji(codePoint)) { + boolean isZwj = false; + int lastSeenVariantSelectorCharCount = 0; + do { + if (isZwj) { + nextCharCount += Character.charCount(codePoint) + lastSeenVariantSelectorCharCount + 1; + isZwj = false; + } + lastSeenVariantSelectorCharCount = 0; + if (isEmojiModifier(codePoint)) { + break; + } + + if (nextOffset < len) { + codePoint = Character.codePointAt(text, nextOffset); + nextOffset += Character.charCount(codePoint); + if (codePoint == COMBINING_ENCLOSING_KEYCAP) { + codePoint = Character.codePointBefore(text, nextOffset); + nextOffset += Character.charCount(codePoint); + if (nextOffset < len && isVariationSelector(codePoint)) { + int tmpCodePoint = Character.codePointAt(text, nextOffset); + if (isKeycapBase(tmpCodePoint)) { + nextCharCount += Character.charCount(codePoint) + Character.charCount(tmpCodePoint); + } + } else if (isKeycapBase(codePoint)) { + nextCharCount += Character.charCount(codePoint); + } + return offset + nextCharCount; + } + if (isEmojiModifier(codePoint)) { + nextCharCount += lastSeenVariantSelectorCharCount + Character.charCount(codePoint); + break; + } + if (isVariationSelector(codePoint)) { + nextCharCount += lastSeenVariantSelectorCharCount + Character.charCount(codePoint); + break; + } + if (codePoint == ZERO_WIDTH_JOINER) { + isZwj = true; + codePoint = Character.codePointAt(text, nextOffset); + nextOffset += Character.charCount(codePoint); + if (nextOffset < len && isVariationSelector(codePoint)) { + codePoint = Character.codePointAt(text, nextOffset); + lastSeenVariantSelectorCharCount = Character.charCount(codePoint); + nextOffset += Character.charCount(codePoint); + } + } + } + + if (nextOffset >= len) { + break; + } + } while (isZwj && isEmoji(codePoint)); + } + + return offset + nextCharCount; + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/ImeSyncDeferringInsetsCallback.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/ImeSyncDeferringInsetsCallback.java new file mode 100644 index 0000000000000000000000000000000000000000..9aec85d1e1e5e56d3d7a7aa3d67c05fe473a0287 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/ImeSyncDeferringInsetsCallback.java @@ -0,0 +1,205 @@ +// 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. + +package io.flutter.plugin.editing; + +import static io.flutter.Build.API_LEVELS; + +import android.annotation.SuppressLint; +import android.annotation.TargetApi; +import android.graphics.Insets; +import android.view.View; +import android.view.WindowInsets; +import android.view.WindowInsetsAnimation; +import androidx.annotation.Keep; +import androidx.annotation.NonNull; +import androidx.annotation.RequiresApi; +import androidx.annotation.VisibleForTesting; +import java.util.List; + +// Loosely based off of +// https://github.com/android/user-interface-samples/blob/main/WindowInsetsAnimation/app/src/main/java/com/google/android/samples/insetsanimation/RootViewDeferringInsetsCallback.kt +// +// When the IME is shown or hidden, it immediately sends an onApplyWindowInsets call +// with the final state of the IME. This initial call disrupts the animation, which +// causes a flicker in the beginning. +// +// To fix this, this class extends WindowInsetsAnimation.Callback and implements +// OnApplyWindowInsetsListener. We capture and defer the initial call to +// onApplyWindowInsets while the animation completes. When the animation +// finishes, we can then release the call by invoking it in the onEnd callback +// +// The WindowInsetsAnimation.Callback extension forwards the new state of the +// IME inset from onProgress() to the framework. We also make use of the +// onStart callback to detect which calls to onApplyWindowInsets would +// interrupt the animation and defer it. +// +// By implementing OnApplyWindowInsetsListener, we are able to capture Android's +// attempts to call the FlutterView's onApplyWindowInsets. When a call to onStart +// occurs, we can mark any non-animation calls to onApplyWindowInsets() that +// occurs between prepare and start as deferred by using this class' wrapper +// implementation to cache the WindowInsets passed in and turn the current call into +// a no-op. When onEnd indicates the end of the animation, the deferred call is +// dispatched again, this time avoiding any flicker since the animation is now +// complete. +@VisibleForTesting +@TargetApi(API_LEVELS.API_30) +@RequiresApi(API_LEVELS.API_30) +@SuppressLint({"NewApi", "Override"}) +@Keep +class ImeSyncDeferringInsetsCallback { + private final int deferredInsetTypes = WindowInsets.Type.ime(); + private View view; + private WindowInsets lastWindowInsets; + private AnimationCallback animationCallback; + private InsetsListener insetsListener; + + // True when an animation that matches deferredInsetTypes is active. + // + // While this is active, this class will capture the initial window inset + // sent into lastWindowInsets by flagging needsSave to true, and will hold + // onto the intitial inset until the animation is completed, when it will + // re-dispatch the inset change. + private boolean animating = false; + // When an animation begins, android sends a WindowInset with the final + // state of the animation. When needsSave is true, we know to capture this + // initial WindowInset. + // + // Certain actions, like dismissing the keyboard, can trigger multiple + // animations that are slightly offset in start time. To capture the + // correct final insets in these situations we update needsSave to true + // in each onPrepare callback, so that we save the latest final state + // to apply in onEnd. + private boolean needsSave = false; + + ImeSyncDeferringInsetsCallback(@NonNull View view) { + this.view = view; + this.animationCallback = new AnimationCallback(); + this.insetsListener = new InsetsListener(); + } + + // Add this object's event listeners to its view. + void install() { + view.setWindowInsetsAnimationCallback(animationCallback); + view.setOnApplyWindowInsetsListener(insetsListener); + } + + // Remove this object's event listeners from its view. + void remove() { + view.setWindowInsetsAnimationCallback(null); + view.setOnApplyWindowInsetsListener(null); + } + + @VisibleForTesting + View.OnApplyWindowInsetsListener getInsetsListener() { + return insetsListener; + } + + @VisibleForTesting + WindowInsetsAnimation.Callback getAnimationCallback() { + return animationCallback; + } + + // WindowInsetsAnimation.Callback was introduced in API level 30. The callback + // subclass is separated into an inner class in order to avoid warnings from + // the Android class loader on older platforms. + @Keep + private class AnimationCallback extends WindowInsetsAnimation.Callback { + AnimationCallback() { + super(WindowInsetsAnimation.Callback.DISPATCH_MODE_CONTINUE_ON_SUBTREE); + } + + @Override + public void onPrepare(WindowInsetsAnimation animation) { + needsSave = true; + if ((animation.getTypeMask() & deferredInsetTypes) != 0) { + animating = true; + } + } + + @Override + public WindowInsets onProgress( + WindowInsets insets, List runningAnimations) { + if (!animating || needsSave) { + return insets; + } + boolean matching = false; + for (WindowInsetsAnimation animation : runningAnimations) { + if ((animation.getTypeMask() & deferredInsetTypes) != 0) { + matching = true; + continue; + } + } + if (!matching) { + return insets; + } + + // The IME insets include the height of the navigation bar. If the app isn't laid out behind + // the navigation bar, this causes the IME insets to be too large during the animation. + // To fix this, we subtract the navigationBars bottom inset if the system UI flags for laying + // out behind the navigation bar aren't present. + int excludedInsets = 0; + int systemUiFlags = view.getWindowSystemUiVisibility(); + if ((systemUiFlags & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) == 0 + && (systemUiFlags & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) { + excludedInsets = insets.getInsets(WindowInsets.Type.navigationBars()).bottom; + } + + WindowInsets.Builder builder = new WindowInsets.Builder(lastWindowInsets); + Insets newImeInsets = + Insets.of( + 0, 0, 0, Math.max(insets.getInsets(deferredInsetTypes).bottom - excludedInsets, 0)); + builder.setInsets(deferredInsetTypes, newImeInsets); + + // Directly call onApplyWindowInsets of the view as we do not want to pass through + // the onApplyWindowInsets defined in this class, which would consume the insets + // as if they were a non-animation inset change and cache it for re-dispatch in + // onEnd instead. + view.onApplyWindowInsets(builder.build()); + return insets; + } + + @Override + public void onEnd(WindowInsetsAnimation animation) { + if (animating && (animation.getTypeMask() & deferredInsetTypes) != 0) { + // If we deferred the IME insets and an IME animation has finished, we need to reset + // the flags + animating = false; + + // And finally dispatch the deferred insets to the view now. + // Ideally we would just call view.requestApplyInsets() and let the normal dispatch + // cycle happen, but this happens too late resulting in a visual flicker. + // Instead we manually dispatch the most recent WindowInsets to the view. + if (lastWindowInsets != null && view != null) { + view.dispatchApplyWindowInsets(lastWindowInsets); + } + } + } + } + + private class InsetsListener implements View.OnApplyWindowInsetsListener { + @Override + public WindowInsets onApplyWindowInsets(View view, WindowInsets windowInsets) { + ImeSyncDeferringInsetsCallback.this.view = view; + if (needsSave) { + // Store the view and insets for us in onEnd() below. This captured inset + // is not part of the animation and instead, represents the final state + // of the inset after the animation is completed. Thus, we defer the processing + // of this WindowInset until the animation completes. + lastWindowInsets = windowInsets; + needsSave = false; + } + if (animating) { + // While animation is running, we consume the insets to prevent disrupting + // the animation, which skips this implementation and calls the view's + // onApplyWindowInsets directly to avoid being consumed here. + return WindowInsets.CONSUMED; + } + + // If no animation is happening, pass the insets on to the view's own + // inset handling. + return view.onApplyWindowInsets(windowInsets); + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/InputConnectionAdaptor.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/InputConnectionAdaptor.java new file mode 100644 index 0000000000000000000000000000000000000000..aa96ea02645c9aabf4630da754da2a5a3094d448 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/InputConnectionAdaptor.java @@ -0,0 +1,595 @@ +// 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. + +package io.flutter.plugin.editing; + +import static io.flutter.Build.API_LEVELS; + +import android.annotation.TargetApi; +import android.content.ClipData; +import android.content.ClipboardManager; +import android.content.Context; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import android.text.DynamicLayout; +import android.text.Editable; +import android.text.InputType; +import android.text.Layout; +import android.text.Selection; +import android.text.TextPaint; +import android.view.KeyEvent; +import android.view.View; +import android.view.inputmethod.BaseInputConnection; +import android.view.inputmethod.CursorAnchorInfo; +import android.view.inputmethod.EditorInfo; +import android.view.inputmethod.ExtractedText; +import android.view.inputmethod.ExtractedTextRequest; +import android.view.inputmethod.InputContentInfo; +import android.view.inputmethod.InputMethodManager; +import androidx.annotation.NonNull; +import androidx.annotation.RequiresApi; +import androidx.core.view.inputmethod.InputConnectionCompat; +import io.flutter.Log; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.systemchannels.ScribeChannel; +import io.flutter.embedding.engine.systemchannels.TextInputChannel; +import java.io.ByteArrayOutputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; + +public class InputConnectionAdaptor extends BaseInputConnection + implements ListenableEditingState.EditingStateWatcher { + private static final String TAG = "InputConnectionAdaptor"; + + public interface KeyboardDelegate { + public boolean handleEvent(@NonNull KeyEvent keyEvent); + } + + private final View mFlutterView; + private final int mClient; + private final ScribeChannel scribeChannel; + private final TextInputChannel textInputChannel; + private final ListenableEditingState mEditable; + private final EditorInfo mEditorInfo; + private ExtractedTextRequest mExtractRequest; + private boolean mMonitorCursorUpdate = false; + private CursorAnchorInfo.Builder mCursorAnchorInfoBuilder; + private ExtractedText mExtractedText = new ExtractedText(); + private InputMethodManager mImm; + private final Layout mLayout; + private FlutterTextUtils flutterTextUtils; + private final KeyboardDelegate keyboardDelegate; + private int batchEditNestDepth = 0; + + @SuppressWarnings("deprecation") + public InputConnectionAdaptor( + View view, + int client, + TextInputChannel textInputChannel, + ScribeChannel scribeChannel, + KeyboardDelegate keyboardDelegate, + ListenableEditingState editable, + EditorInfo editorInfo, + FlutterJNI flutterJNI) { + super(view, true); + mFlutterView = view; + mClient = client; + this.textInputChannel = textInputChannel; + this.scribeChannel = scribeChannel; + mEditable = editable; + mEditable.addEditingStateListener(this); + mEditorInfo = editorInfo; + this.keyboardDelegate = keyboardDelegate; + this.flutterTextUtils = new FlutterTextUtils(flutterJNI); + // We create a dummy Layout with max width so that the selection + // shifting acts as if all text were in one line. + mLayout = + new DynamicLayout( + mEditable, + new TextPaint(), + Integer.MAX_VALUE, + Layout.Alignment.ALIGN_NORMAL, + 1.0f, + 0.0f, + false); + mImm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + } + + public InputConnectionAdaptor( + View view, + int client, + TextInputChannel textInputChannel, + ScribeChannel scribeChannel, + KeyboardDelegate keyboardDelegate, + ListenableEditingState editable, + EditorInfo editorInfo) { + this( + view, + client, + textInputChannel, + scribeChannel, + keyboardDelegate, + editable, + editorInfo, + new FlutterJNI()); + } + + private ExtractedText getExtractedText(ExtractedTextRequest request) { + mExtractedText.startOffset = 0; + mExtractedText.partialStartOffset = -1; + mExtractedText.partialEndOffset = -1; + mExtractedText.selectionStart = mEditable.getSelectionStart(); + mExtractedText.selectionEnd = mEditable.getSelectionEnd(); + mExtractedText.text = + request == null || (request.flags & GET_TEXT_WITH_STYLES) == 0 + ? mEditable.toString() + : mEditable; + return mExtractedText; + } + + private CursorAnchorInfo getCursorAnchorInfo() { + if (mCursorAnchorInfoBuilder == null) { + mCursorAnchorInfoBuilder = new CursorAnchorInfo.Builder(); + } else { + mCursorAnchorInfoBuilder.reset(); + } + + mCursorAnchorInfoBuilder.setSelectionRange( + mEditable.getSelectionStart(), mEditable.getSelectionEnd()); + final int composingStart = mEditable.getComposingStart(); + final int composingEnd = mEditable.getComposingEnd(); + if (composingStart >= 0 && composingEnd > composingStart) { + mCursorAnchorInfoBuilder.setComposingText( + composingStart, mEditable.toString().subSequence(composingStart, composingEnd)); + } else { + mCursorAnchorInfoBuilder.setComposingText(-1, ""); + } + return mCursorAnchorInfoBuilder.build(); + } + + @Override + public Editable getEditable() { + return mEditable; + } + + @Override + public boolean beginBatchEdit() { + mEditable.beginBatchEdit(); + batchEditNestDepth += 1; + return super.beginBatchEdit(); + } + + @Override + public boolean endBatchEdit() { + boolean result = super.endBatchEdit(); + batchEditNestDepth -= 1; + mEditable.endBatchEdit(); + return result; + } + + @Override + public boolean commitText(CharSequence text, int newCursorPosition) { + final boolean result = super.commitText(text, newCursorPosition); + return result; + } + + @Override + public boolean deleteSurroundingText(int beforeLength, int afterLength) { + if (mEditable.getSelectionStart() == -1) { + return true; + } + + final boolean result = super.deleteSurroundingText(beforeLength, afterLength); + return result; + } + + @Override + public boolean deleteSurroundingTextInCodePoints(int beforeLength, int afterLength) { + boolean result = super.deleteSurroundingTextInCodePoints(beforeLength, afterLength); + return result; + } + + @Override + public boolean setComposingRegion(int start, int end) { + final boolean result = super.setComposingRegion(start, end); + return result; + } + + @Override + public boolean setComposingText(CharSequence text, int newCursorPosition) { + boolean result; + beginBatchEdit(); + if (text.length() == 0) { + result = super.commitText(text, newCursorPosition); + } else { + result = super.setComposingText(text, newCursorPosition); + } + endBatchEdit(); + return result; + } + + @Override + public boolean finishComposingText() { + final boolean result = super.finishComposingText(); + return result; + } + + // When there's not enough vertical screen space, the IME may enter fullscreen mode and this + // method will be used to get (a portion of) the currently edited text. Samsung keyboard seems + // to use this method instead of InputConnection#getText{Before,After}Cursor. + // See https://github.com/flutter/engine/pull/17426. + // TODO(garyq): Implement a more feature complete version of getExtractedText + @Override + public ExtractedText getExtractedText(ExtractedTextRequest request, int flags) { + final boolean textMonitor = (flags & GET_EXTRACTED_TEXT_MONITOR) != 0; + if (textMonitor == (mExtractRequest == null)) { + Log.d(TAG, "The input method toggled text monitoring " + (textMonitor ? "on" : "off")); + } + // Enables text monitoring if the relevant flag is set. See + // InputConnectionAdaptor#didChangeEditingState. + mExtractRequest = textMonitor ? request : null; + return getExtractedText(request); + } + + @Override + public boolean requestCursorUpdates(int cursorUpdateMode) { + if ((cursorUpdateMode & CURSOR_UPDATE_IMMEDIATE) != 0) { + mImm.updateCursorAnchorInfo(mFlutterView, getCursorAnchorInfo()); + } + + final boolean updated = (cursorUpdateMode & CURSOR_UPDATE_MONITOR) != 0; + if (updated != mMonitorCursorUpdate) { + Log.d(TAG, "The input method toggled cursor monitoring " + (updated ? "on" : "off")); + } + + // Enables cursor monitoring. See InputConnectionAdaptor#didChangeEditingState. + mMonitorCursorUpdate = updated; + return true; + } + + @Override + public boolean clearMetaKeyStates(int states) { + boolean result = super.clearMetaKeyStates(states); + return result; + } + + @Override + public void closeConnection() { + super.closeConnection(); + mEditable.removeEditingStateListener(this); + for (; batchEditNestDepth > 0; batchEditNestDepth--) { + endBatchEdit(); + } + } + + @Override + public boolean setSelection(int start, int end) { + beginBatchEdit(); + boolean result = super.setSelection(start, end); + endBatchEdit(); + return result; + } + + // TODO(justinmc): Scribe stylus gestures should be supported here via + // performHandwritingGesture. + // https://github.com/flutter/flutter/issues/156018 + + // Sanitizes the index to ensure the index is within the range of the + // contents of editable. + private static int clampIndexToEditable(int index, Editable editable) { + int clamped = Math.max(0, Math.min(editable.length(), index)); + if (clamped != index) { + Log.d( + "flutter", + "Text selection index was clamped (" + + index + + "->" + + clamped + + ") to remain in bounds. This may not be your fault, as some keyboards may select outside of bounds."); + } + return clamped; + } + + // This function is called both when hardware key events occur and aren't + // handled by the framework, as well as when soft keyboard editing events + // occur, and need a chance to be handled by the framework. + @Override + public boolean sendKeyEvent(KeyEvent event) { + return keyboardDelegate.handleEvent(event); + } + + public boolean handleKeyEvent(KeyEvent event) { + if (event.getAction() == KeyEvent.ACTION_DOWN) { + if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_LEFT) { + return handleHorizontalMovement(true, event.isShiftPressed()); + } else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT) { + return handleHorizontalMovement(false, event.isShiftPressed()); + } else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_UP) { + return handleVerticalMovement(true, event.isShiftPressed()); + } else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_DOWN) { + return handleVerticalMovement(false, event.isShiftPressed()); + // When the enter key is pressed on a non-multiline field, consider it a + // submit instead of a newline. + } else if ((event.getKeyCode() == KeyEvent.KEYCODE_ENTER + || event.getKeyCode() == KeyEvent.KEYCODE_NUMPAD_ENTER) + && (InputType.TYPE_TEXT_FLAG_MULTI_LINE & mEditorInfo.inputType) == 0) { + performEditorAction(mEditorInfo.imeOptions & EditorInfo.IME_MASK_ACTION); + return true; + } else { + // Enter a character. + final int selStart = Selection.getSelectionStart(mEditable); + final int selEnd = Selection.getSelectionEnd(mEditable); + final int character = event.getUnicodeChar(); + if (selStart < 0 || selEnd < 0 || character == 0) { + return false; + } + + final int selMin = Math.min(selStart, selEnd); + final int selMax = Math.max(selStart, selEnd); + beginBatchEdit(); + if (selMin != selMax) mEditable.delete(selMin, selMax); + mEditable.insert(selMin, String.valueOf((char) character)); + setSelection(selMin + 1, selMin + 1); + endBatchEdit(); + return true; + } + } + return false; + } + + private boolean handleHorizontalMovement(boolean isLeft, boolean isShiftPressed) { + final int selStart = Selection.getSelectionStart(mEditable); + final int selEnd = Selection.getSelectionEnd(mEditable); + + if (selStart < 0 || selEnd < 0) { + return false; + } + + final int newSelectionEnd = + isLeft + ? Math.max(flutterTextUtils.getOffsetBefore(mEditable, selEnd), 0) + : Math.min(flutterTextUtils.getOffsetAfter(mEditable, selEnd), mEditable.length()); + + final boolean shouldCollapse = selStart == selEnd && !isShiftPressed; + + if (shouldCollapse) { + setSelection(newSelectionEnd, newSelectionEnd); + } else { + setSelection(selStart, newSelectionEnd); + } + return true; + }; + + private boolean handleVerticalMovement(boolean isUp, boolean isShiftPressed) { + final int selStart = Selection.getSelectionStart(mEditable); + final int selEnd = Selection.getSelectionEnd(mEditable); + + if (selStart < 0 || selEnd < 0) { + return false; + } + + final boolean shouldCollapse = selStart == selEnd && !isShiftPressed; + + beginBatchEdit(); + if (shouldCollapse) { + if (isUp) { + Selection.moveUp(mEditable, mLayout); + } else { + Selection.moveDown(mEditable, mLayout); + } + final int newSelection = Selection.getSelectionStart(mEditable); + setSelection(newSelection, newSelection); + } else { + if (isUp) { + Selection.extendUp(mEditable, mLayout); + } else { + Selection.extendDown(mEditable, mLayout); + } + setSelection(Selection.getSelectionStart(mEditable), Selection.getSelectionEnd(mEditable)); + } + endBatchEdit(); + return true; + } + + @Override + public boolean performContextMenuAction(int id) { + beginBatchEdit(); + final boolean result = doPerformContextMenuAction(id); + endBatchEdit(); + return result; + } + + private boolean doPerformContextMenuAction(int id) { + if (id == android.R.id.selectAll) { + setSelection(0, mEditable.length()); + return true; + } else if (id == android.R.id.cut) { + int selStart = Selection.getSelectionStart(mEditable); + int selEnd = Selection.getSelectionEnd(mEditable); + if (selStart != selEnd) { + int selMin = Math.min(selStart, selEnd); + int selMax = Math.max(selStart, selEnd); + CharSequence textToCut = mEditable.subSequence(selMin, selMax); + ClipboardManager clipboard = + (ClipboardManager) + mFlutterView.getContext().getSystemService(Context.CLIPBOARD_SERVICE); + ClipData clip = ClipData.newPlainText("text label?", textToCut); + clipboard.setPrimaryClip(clip); + mEditable.delete(selMin, selMax); + setSelection(selMin, selMin); + } + return true; + } else if (id == android.R.id.copy) { + int selStart = Selection.getSelectionStart(mEditable); + int selEnd = Selection.getSelectionEnd(mEditable); + if (selStart != selEnd) { + CharSequence textToCopy = + mEditable.subSequence(Math.min(selStart, selEnd), Math.max(selStart, selEnd)); + ClipboardManager clipboard = + (ClipboardManager) + mFlutterView.getContext().getSystemService(Context.CLIPBOARD_SERVICE); + clipboard.setPrimaryClip(ClipData.newPlainText("text label?", textToCopy)); + } + return true; + } else if (id == android.R.id.paste) { + ClipboardManager clipboard = + (ClipboardManager) mFlutterView.getContext().getSystemService(Context.CLIPBOARD_SERVICE); + ClipData clip = clipboard.getPrimaryClip(); + if (clip != null) { + CharSequence textToPaste = clip.getItemAt(0).coerceToText(mFlutterView.getContext()); + int selStart = Math.max(0, Selection.getSelectionStart(mEditable)); + int selEnd = Math.max(0, Selection.getSelectionEnd(mEditable)); + int selMin = Math.min(selStart, selEnd); + int selMax = Math.max(selStart, selEnd); + if (selMin != selMax) mEditable.delete(selMin, selMax); + mEditable.insert(selMin, textToPaste); + int newSelStart = selMin + textToPaste.length(); + setSelection(newSelStart, newSelStart); + } + return true; + } + return false; + } + + @Override + public boolean performPrivateCommand(String action, Bundle data) { + textInputChannel.performPrivateCommand(mClient, action, data); + return true; + } + + @Override + public boolean performEditorAction(int actionCode) { + switch (actionCode) { + case EditorInfo.IME_ACTION_NONE: + textInputChannel.newline(mClient); + break; + case EditorInfo.IME_ACTION_UNSPECIFIED: + textInputChannel.unspecifiedAction(mClient); + break; + case EditorInfo.IME_ACTION_GO: + textInputChannel.go(mClient); + break; + case EditorInfo.IME_ACTION_SEARCH: + textInputChannel.search(mClient); + break; + case EditorInfo.IME_ACTION_SEND: + textInputChannel.send(mClient); + break; + case EditorInfo.IME_ACTION_NEXT: + textInputChannel.next(mClient); + break; + case EditorInfo.IME_ACTION_PREVIOUS: + textInputChannel.previous(mClient); + break; + default: + case EditorInfo.IME_ACTION_DONE: + textInputChannel.done(mClient); + break; + } + return true; + } + + @Override + @TargetApi(API_LEVELS.API_25) + @RequiresApi(API_LEVELS.API_25) + public boolean commitContent(InputContentInfo inputContentInfo, int flags, Bundle opts) { + // Ensure permission is granted. + if (Build.VERSION.SDK_INT >= API_LEVELS.API_25 + && (flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION) != 0) { + try { + inputContentInfo.requestPermission(); + } catch (Exception e) { + return false; + } + } else { + return false; + } + + if (inputContentInfo.getDescription().getMimeTypeCount() > 0) { + inputContentInfo.requestPermission(); + + final Uri uri = inputContentInfo.getContentUri(); + final String mimeType = inputContentInfo.getDescription().getMimeType(0); + Context context = mFlutterView.getContext(); + + if (uri != null) { + InputStream is; + try { + // Extract byte data from the given URI. + is = context.getContentResolver().openInputStream(uri); + } catch (FileNotFoundException ex) { + inputContentInfo.releasePermission(); + return false; + } + + if (is != null) { + final byte[] data = this.readStreamFully(is, 64 * 1024); + + final Map obj = new HashMap<>(); + obj.put("mimeType", mimeType); + obj.put("data", data); + obj.put("uri", uri.toString()); + + // Commit the content to the text input channel and release the permission. + textInputChannel.commitContent(mClient, obj); + inputContentInfo.releasePermission(); + return true; + } + } + + inputContentInfo.releasePermission(); + } + return false; + } + + private byte[] readStreamFully(InputStream is, int blocksize) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + byte[] buffer = new byte[blocksize]; + while (true) { + int len = -1; + try { + len = is.read(buffer); + } catch (IOException ex) { + } + if (len == -1) break; + baos.write(buffer, 0, len); + } + return baos.toByteArray(); + } + + // -------- Start: ListenableEditingState watcher implementation ------- + @Override + public void didChangeEditingState( + boolean textChanged, boolean selectionChanged, boolean composingRegionChanged) { + // This method notifies the input method that the editing state has changed. + // updateSelection is mandatory. updateExtractedText and updateCursorAnchorInfo + // are on demand (if the input method set the correspoinding monitoring + // flags). See getExtractedText and requestCursorUpdates. + + // Always send selection update. InputMethodManager#updateSelection skips + // sending the message if none of the parameters have changed since the last + // time we called it. + mImm.updateSelection( + mFlutterView, + mEditable.getSelectionStart(), + mEditable.getSelectionEnd(), + mEditable.getComposingStart(), + mEditable.getComposingEnd()); + + if (mExtractRequest != null) { + mImm.updateExtractedText( + mFlutterView, mExtractRequest.token, getExtractedText(mExtractRequest)); + } + if (mMonitorCursorUpdate) { + final CursorAnchorInfo info = getCursorAnchorInfo(); + mImm.updateCursorAnchorInfo(mFlutterView, info); + } + } + // -------- End: ListenableEditingState watcher implementation ------- +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/ListenableEditingState.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/ListenableEditingState.java new file mode 100644 index 0000000000000000000000000000000000000000..ea1d75a6a173c0b5468d441e94e8c82b8d877418 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/ListenableEditingState.java @@ -0,0 +1,296 @@ +// 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. + +package io.flutter.plugin.editing; + +import android.text.Editable; +import android.text.Selection; +import android.text.SpannableStringBuilder; +import android.view.View; +import android.view.inputmethod.BaseInputConnection; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import io.flutter.Log; +import io.flutter.embedding.engine.systemchannels.TextInputChannel; +import java.util.ArrayList; + +/// The current editing state (text, selection range, composing range) the text input plugin holds. +/// +/// As the name implies, this class also notifies its listeners when the editing state changes. When +/// there are ongoing batch edits, change notifications will be deferred until all batch edits end +/// (i.e. when the outermost batch edit ends). Listeners added during a batch edit will always be +/// notified when all batch edits end, even if there's no real change. +/// +/// Adding/removing listeners or changing the editing state in a didChangeEditingState callback may +/// cause unexpected behavior. +// +// Currently this class does not notify its listeners on spans-only changes (e.g., +// Selection.setSelection). Wrap them in a batch edit to trigger a change notification. +class ListenableEditingState extends SpannableStringBuilder { + interface EditingStateWatcher { + // Changing the editing state in a didChangeEditingState callback may cause unexpected + // behavior. + void didChangeEditingState( + boolean textChanged, boolean selectionChanged, boolean composingRegionChanged); + } + + private static final String TAG = "ListenableEditingState"; + + private int mBatchEditNestDepth = 0; + // We don't support adding/removing listeners, or changing the editing state in a listener + // callback for now. + private int mChangeNotificationDepth = 0; + private ArrayList mListeners = new ArrayList<>(); + private ArrayList mPendingListeners = new ArrayList<>(); + private ArrayList mBatchTextEditingDeltas = new ArrayList<>(); + + private String mToStringCache; + + private String mTextWhenBeginBatchEdit; + private int mSelectionStartWhenBeginBatchEdit; + private int mSelectionEndWhenBeginBatchEdit; + private int mComposingStartWhenBeginBatchEdit; + private int mComposingEndWhenBeginBatchEdit; + + private BaseInputConnection mDummyConnection; + + // The View is only used for creating a dummy BaseInputConnection for setComposingRegion. The View + // needs to have a non-null Context. + public ListenableEditingState( + @Nullable TextInputChannel.TextEditState initialState, @NonNull View view) { + super(); + + Editable self = this; + mDummyConnection = + new BaseInputConnection(view, true) { + @Override + public Editable getEditable() { + return self; + } + }; + + if (initialState != null) { + setEditingState(initialState); + } + } + + public ArrayList extractBatchTextEditingDeltas() { + ArrayList currentBatchDeltas = + new ArrayList(mBatchTextEditingDeltas); + mBatchTextEditingDeltas.clear(); + return currentBatchDeltas; + } + + public void clearBatchDeltas() { + mBatchTextEditingDeltas.clear(); + } + + /// Starts a new batch edit during which change notifications will be put on hold until all batch + /// edits end. + /// + /// Batch edits nest. + public void beginBatchEdit() { + mBatchEditNestDepth++; + if (mChangeNotificationDepth > 0) { + Log.e(TAG, "editing state should not be changed in a listener callback"); + } + if (mBatchEditNestDepth == 1 && !mListeners.isEmpty()) { + mTextWhenBeginBatchEdit = toString(); + mSelectionStartWhenBeginBatchEdit = getSelectionStart(); + mSelectionEndWhenBeginBatchEdit = getSelectionEnd(); + mComposingStartWhenBeginBatchEdit = getComposingStart(); + mComposingEndWhenBeginBatchEdit = getComposingEnd(); + } + } + + /// Ends the current batch edit and flush pending change notifications if the current batch edit + /// is not nested (i.e. it is the last ongoing batch edit). + public void endBatchEdit() { + if (mBatchEditNestDepth == 0) { + Log.e(TAG, "endBatchEdit called without a matching beginBatchEdit"); + return; + } + if (mBatchEditNestDepth == 1) { + for (final EditingStateWatcher listener : mPendingListeners) { + notifyListener(listener, true, true, true); + } + + if (!mListeners.isEmpty()) { + Log.v(TAG, "didFinishBatchEdit with " + String.valueOf(mListeners.size()) + " listener(s)"); + final boolean textChanged = !toString().equals(mTextWhenBeginBatchEdit); + final boolean selectionChanged = + mSelectionStartWhenBeginBatchEdit != getSelectionStart() + || mSelectionEndWhenBeginBatchEdit != getSelectionEnd(); + final boolean composingRegionChanged = + mComposingStartWhenBeginBatchEdit != getComposingStart() + || mComposingEndWhenBeginBatchEdit != getComposingEnd(); + + notifyListenersIfNeeded(textChanged, selectionChanged, composingRegionChanged); + } + } + + mListeners.addAll(mPendingListeners); + mPendingListeners.clear(); + mBatchEditNestDepth--; + } + + /// Update the composing region of the current editing state. + /// + /// If the range is invalid or empty, the current composing region will be removed. + public void setComposingRange(int composingStart, int composingEnd) { + if (composingStart < 0 || composingStart >= composingEnd) { + BaseInputConnection.removeComposingSpans(this); + } else { + mDummyConnection.setComposingRegion(composingStart, composingEnd); + } + } + + /// Called when the framework sends updates to the text input plugin. + /// + /// This method will also update the composing region if it has changed. + public void setEditingState(TextInputChannel.TextEditState newState) { + beginBatchEdit(); + replace(0, length(), newState.text); + + if (newState.hasSelection()) { + Selection.setSelection(this, newState.selectionStart, newState.selectionEnd); + } else { + Selection.removeSelection(this); + } + + setComposingRange(newState.composingStart, newState.composingEnd); + + // Updates from the framework should not have a delta created for it as they have already been + // applied on the framework side. + clearBatchDeltas(); + + endBatchEdit(); + } + + public void addEditingStateListener(EditingStateWatcher listener) { + if (mChangeNotificationDepth > 0) { + Log.e(TAG, "adding a listener " + listener.toString() + " in a listener callback"); + } + // It is possible for a listener to get added during a batch edit. When that happens we always + // notify the new listeners. + // This does not check if the listener is already in the list of existing listeners. + if (mBatchEditNestDepth > 0) { + Log.w(TAG, "a listener was added to EditingState while a batch edit was in progress"); + mPendingListeners.add(listener); + } else { + mListeners.add(listener); + } + } + + public void removeEditingStateListener(EditingStateWatcher listener) { + if (mChangeNotificationDepth > 0) { + Log.e(TAG, "removing a listener " + listener.toString() + " in a listener callback"); + } + mListeners.remove(listener); + if (mBatchEditNestDepth > 0) { + mPendingListeners.remove(listener); + } + } + + @Override + public SpannableStringBuilder replace( + int start, int end, CharSequence tb, int tbstart, int tbend) { + + if (mChangeNotificationDepth > 0) { + Log.e(TAG, "editing state should not be changed in a listener callback"); + } + + final CharSequence oldText = toString(); + + boolean textChanged = end - start != tbend - tbstart; + for (int i = 0; i < end - start && !textChanged; i++) { + textChanged |= charAt(start + i) != tb.charAt(tbstart + i); + } + if (textChanged) { + mToStringCache = null; + } + + final int selectionStart = getSelectionStart(); + final int selectionEnd = getSelectionEnd(); + final int composingStart = getComposingStart(); + final int composingEnd = getComposingEnd(); + + final SpannableStringBuilder editable = super.replace(start, end, tb, tbstart, tbend); + mBatchTextEditingDeltas.add( + new TextEditingDelta( + oldText, + start, + end, + tb, + getSelectionStart(), + getSelectionEnd(), + getComposingStart(), + getComposingEnd())); + + if (mBatchEditNestDepth > 0) { + return editable; + } + + final boolean selectionChanged = + getSelectionStart() != selectionStart || getSelectionEnd() != selectionEnd; + final boolean composingRegionChanged = + getComposingStart() != composingStart || getComposingEnd() != composingEnd; + notifyListenersIfNeeded(textChanged, selectionChanged, composingRegionChanged); + return editable; + } + + private void notifyListener( + EditingStateWatcher listener, + boolean textChanged, + boolean selectionChanged, + boolean composingChanged) { + mChangeNotificationDepth++; + listener.didChangeEditingState(textChanged, selectionChanged, composingChanged); + mChangeNotificationDepth--; + } + + private void notifyListenersIfNeeded( + boolean textChanged, boolean selectionChanged, boolean composingChanged) { + if (textChanged || selectionChanged || composingChanged) { + for (final EditingStateWatcher listener : mListeners) { + notifyListener(listener, textChanged, selectionChanged, composingChanged); + } + } + } + + public final int getSelectionStart() { + return Selection.getSelectionStart(this); + } + + public final int getSelectionEnd() { + return Selection.getSelectionEnd(this); + } + + public final int getComposingStart() { + return BaseInputConnection.getComposingSpanStart(this); + } + + public final int getComposingEnd() { + return BaseInputConnection.getComposingSpanEnd(this); + } + + @Override + public void setSpan(Object what, int start, int end, int flags) { + super.setSpan(what, start, end, flags); + // Setting a span does not involve mutating the text value in the editing state. Here we create + // a non text update delta with any updated selection and composing regions. + mBatchTextEditingDeltas.add( + new TextEditingDelta( + toString(), + getSelectionStart(), + getSelectionEnd(), + getComposingStart(), + getComposingEnd())); + } + + @Override + public String toString() { + return mToStringCache != null ? mToStringCache : (mToStringCache = super.toString()); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/ScribePlugin.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/ScribePlugin.java new file mode 100644 index 0000000000000000000000000000000000000000..35fb2ff0d0dfd9711e32b917875de53c8430506d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/ScribePlugin.java @@ -0,0 +1,106 @@ +// 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. + +package io.flutter.plugin.editing; + +import static io.flutter.Build.API_LEVELS; + +import android.annotation.TargetApi; +import android.os.Build; +import android.view.View; +import android.view.inputmethod.InputMethodManager; +import androidx.annotation.NonNull; +import androidx.annotation.RequiresApi; +import io.flutter.embedding.engine.systemchannels.ScribeChannel; + +/** + * {@link ScribePlugin} is the implementation of all functionality needed for handwriting stylus + * text input. + * + *

The plugin handles requests for scribe sent by the {@link + * io.flutter.embedding.engine.systemchannels.ScribeChannel}. + * + *

On API versions below 33, the plugin does nothing. + */ +public class ScribePlugin implements ScribeChannel.ScribeMethodHandler { + + @NonNull private final ScribeChannel mScribeChannel; + @NonNull private final InputMethodManager mInputMethodManager; + @NonNull private View mView; + + public ScribePlugin( + @NonNull View view, @NonNull InputMethodManager imm, @NonNull ScribeChannel scribeChannel) { + if (Build.VERSION.SDK_INT >= API_LEVELS.API_33) { + view.setAutoHandwritingEnabled(false); + } + + mView = view; + mInputMethodManager = imm; + mScribeChannel = scribeChannel; + + mScribeChannel.setScribeMethodHandler(this); + } + + /** + * Sets the View in which Scribe input is handled. + * + *

Only one View can be set at any given time. + */ + public void setView(@NonNull View view) { + if (view == mView) { + return; + } + mView = view; + } + + /** + * Unregisters this {@code ScribePlugin} as the {@code ScribeChannel.ScribeMethodHandler}, for the + * {@link io.flutter.embedding.engine.systemchannels.ScribeChannel}. + * + *

Do not invoke any methods on a {@code ScribePlugin} after invoking this method. + */ + public void destroy() { + mScribeChannel.setScribeMethodHandler(null); + } + + /** + * Returns true if the InputMethodManager supports Scribe stylus handwriting input. + * + *

Call this or isFeatureAvailable before calling startStylusHandwriting to make sure it's + * available. + */ + @TargetApi(API_LEVELS.API_34) + @RequiresApi(API_LEVELS.API_34) + @Override + public boolean isStylusHandwritingAvailable() { + return mInputMethodManager.isStylusHandwritingAvailable(); + } + + /** + * Starts stylus handwriting input. + * + *

Typically isStylusHandwritingAvailable should be called first to determine whether this is + * supported by the IME. + */ + @TargetApi(API_LEVELS.API_33) + @RequiresApi(API_LEVELS.API_33) + @Override + public void startStylusHandwriting() { + mInputMethodManager.startStylusHandwriting(mView); + } + + /** + * A convenience method to check if Scribe is available. + * + *

Differs from isStylusHandwritingAvailable in that it can be called from any API level + * without throwing an error. + * + *

Call this or isStylusHandwritingAvailable before calling startStylusHandwriting to make sure + * it's available. + */ + @Override + public boolean isFeatureAvailable() { + return Build.VERSION.SDK_INT >= API_LEVELS.API_34 && isStylusHandwritingAvailable(); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/SpellCheckPlugin.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/SpellCheckPlugin.java new file mode 100644 index 0000000000000000000000000000000000000000..37ee23cfe6f2030cdca67791781af1110b18ad4c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/SpellCheckPlugin.java @@ -0,0 +1,183 @@ +// 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. + +package io.flutter.plugin.editing; + +import android.view.textservice.SentenceSuggestionsInfo; +import android.view.textservice.SpellCheckerSession; +import android.view.textservice.SuggestionsInfo; +import android.view.textservice.TextInfo; +import android.view.textservice.TextServicesManager; +import androidx.annotation.NonNull; +import androidx.annotation.VisibleForTesting; +import io.flutter.embedding.engine.systemchannels.SpellCheckChannel; +import io.flutter.plugin.common.MethodChannel; +import io.flutter.plugin.localization.LocalizationPlugin; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Locale; + +/** + * {@link SpellCheckPlugin} is the implementation of all functionality needed for spell check for + * text input. + * + *

The plugin handles requests for spell check sent by the {@link + * io.flutter.embedding.engine.systemchannels.SpellCheckChannel} via sending requests to the Android + * spell checker. It also receives the spell check results from the service and sends them back to + * the framework through the {@link io.flutter.embedding.engine.systemchannels.SpellCheckChannel}. + */ +public class SpellCheckPlugin + implements SpellCheckChannel.SpellCheckMethodHandler, + SpellCheckerSession.SpellCheckerSessionListener { + + private final SpellCheckChannel mSpellCheckChannel; + private final TextServicesManager mTextServicesManager; + private SpellCheckerSession mSpellCheckerSession; + + public static final String START_INDEX_KEY = "startIndex"; + public static final String END_INDEX_KEY = "endIndex"; + public static final String SUGGESTIONS_KEY = "suggestions"; + + @VisibleForTesting MethodChannel.Result pendingResult; + + // The maximum number of suggestions that the Android spell check service is allowed to provide + // per word. Same number that is used by default for Android's TextViews. + private static final int MAX_SPELL_CHECK_SUGGESTIONS = 5; + + public SpellCheckPlugin( + @NonNull TextServicesManager textServicesManager, + @NonNull SpellCheckChannel spellCheckChannel) { + mTextServicesManager = textServicesManager; + mSpellCheckChannel = spellCheckChannel; + + mSpellCheckChannel.setSpellCheckMethodHandler(this); + } + + /** + * Unregisters this {@code SpellCheckPlugin} as the {@code + * SpellCheckChannel.SpellCheckMethodHandler}, for the {@link + * io.flutter.embedding.engine.systemchannels.SpellCheckChannel}, and closes the most recently + * opened {@code SpellCheckerSession}. + * + *

Do not invoke any methods on a {@code SpellCheckPlugin} after invoking this method. + */ + public void destroy() { + mSpellCheckChannel.setSpellCheckMethodHandler(null); + + if (mSpellCheckerSession != null) { + mSpellCheckerSession.close(); + } + } + + /** + * Initiates call to native spell checker to spell check specified text if there is no result + * awaiting a response. + */ + @Override + public void initiateSpellCheck( + @NonNull String locale, @NonNull String text, @NonNull MethodChannel.Result result) { + if (pendingResult != null) { + result.error("error", "Previous spell check request still pending.", null); + return; + } + + pendingResult = result; + + performSpellCheck(locale, text); + } + + /** Calls on the Android spell check API to spell check specified text. */ + public void performSpellCheck(@NonNull String locale, @NonNull String text) { + Locale localeFromString = LocalizationPlugin.localeFromString(locale); + + if (mSpellCheckerSession == null) { + mSpellCheckerSession = + mTextServicesManager.newSpellCheckerSession( + null, + localeFromString, + this, + /** referToSpellCheckerLanguageSettings= */ + true); + } + + TextInfo[] textInfos = new TextInfo[] {new TextInfo(text)}; + mSpellCheckerSession.getSentenceSuggestions(textInfos, MAX_SPELL_CHECK_SUGGESTIONS); + } + + /** + * Callback for Android spell check API that decomposes results and send results through the + * {@link SpellCheckChannel}. + * + *

Spell check results are encoded as dictionaries with a format that looks like + * + *

{@code
+   * {
+   *   startIndex: 0,
+   *   endIndex: 5,
+   *   suggestions: [hello, ...]
+   * }
+   * }
+ * + * where there may be up to 5 suggestions. + */ + @Override + public void onGetSentenceSuggestions(SentenceSuggestionsInfo[] results) { + if (results.length == 0) { + pendingResult.success(new ArrayList>()); + pendingResult = null; + return; + } + + ArrayList> spellCheckerSuggestionSpans = + new ArrayList>(); + SentenceSuggestionsInfo spellCheckResults = results[0]; + if (spellCheckResults == null) { + pendingResult.success(new ArrayList>()); + pendingResult = null; + return; + } + + for (int i = 0; i < spellCheckResults.getSuggestionsCount(); i++) { + SuggestionsInfo suggestionsInfo = spellCheckResults.getSuggestionsInfoAt(i); + int suggestionsCount = suggestionsInfo.getSuggestionsCount(); + + if (suggestionsCount <= 0) { + continue; + } + + HashMap spellCheckerSuggestionSpan = new HashMap(); + int start = spellCheckResults.getOffsetAt(i); + int end = start + spellCheckResults.getLengthAt(i); + + spellCheckerSuggestionSpan.put(START_INDEX_KEY, start); + spellCheckerSuggestionSpan.put(END_INDEX_KEY, end); + + ArrayList suggestions = new ArrayList(); + boolean validSuggestionsFound = false; + for (int j = 0; j < suggestionsCount; j++) { + String suggestion = suggestionsInfo.getSuggestionAt(j); + // TODO(camsim99): Support spell check on Samsung by retrieving accurate spell check + // results, then remove this check: https://github.com/flutter/flutter/issues/120608. + if (!suggestion.equals("")) { + validSuggestionsFound = true; + suggestions.add(suggestion); + } + } + + if (!validSuggestionsFound) { + continue; + } + spellCheckerSuggestionSpan.put(SUGGESTIONS_KEY, suggestions); + spellCheckerSuggestionSpans.add(spellCheckerSuggestionSpan); + } + + pendingResult.success(spellCheckerSuggestionSpans); + pendingResult = null; + } + + @Override + public void onGetSuggestions(SuggestionsInfo[] results) { + // Deprecated callback for Android spell check API; will not use. + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/TextEditingDelta.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/TextEditingDelta.java new file mode 100644 index 0000000000000000000000000000000000000000..8681e23c80678162dfb9ac351319c66765db2a55 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/TextEditingDelta.java @@ -0,0 +1,132 @@ +// 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. + +package io.flutter.plugin.editing; + +import androidx.annotation.NonNull; +import androidx.annotation.VisibleForTesting; +import io.flutter.Log; +import org.json.JSONException; +import org.json.JSONObject; + +/// A representation of the change that occured to an editing state, along with the resulting +/// composing and selection regions. +public final class TextEditingDelta { + private @NonNull CharSequence oldText; + private @NonNull CharSequence deltaText; + private int deltaStart; + private int deltaEnd; + private int newSelectionStart; + private int newSelectionEnd; + private int newComposingStart; + private int newComposingEnd; + + private static final String TAG = "TextEditingDelta"; + + public TextEditingDelta( + @NonNull CharSequence oldEditable, + int replacementDestinationStart, + int replacementDestinationEnd, + @NonNull CharSequence replacementSource, + int selectionStart, + int selectionEnd, + int composingStart, + int composingEnd) { + newSelectionStart = selectionStart; + newSelectionEnd = selectionEnd; + newComposingStart = composingStart; + newComposingEnd = composingEnd; + + setDeltas( + oldEditable, + replacementSource.toString(), + replacementDestinationStart, + replacementDestinationEnd); + } + + // Non text update delta constructor. + public TextEditingDelta( + @NonNull CharSequence oldText, + int selectionStart, + int selectionEnd, + int composingStart, + int composingEnd) { + newSelectionStart = selectionStart; + newSelectionEnd = selectionEnd; + newComposingStart = composingStart; + newComposingEnd = composingEnd; + + setDeltas(oldText, "", -1, -1); + } + + @VisibleForTesting + @NonNull + public CharSequence getOldText() { + return oldText; + } + + @VisibleForTesting + @NonNull + public CharSequence getDeltaText() { + return deltaText; + } + + @VisibleForTesting + public int getDeltaStart() { + return deltaStart; + } + + @VisibleForTesting + public int getDeltaEnd() { + return deltaEnd; + } + + @VisibleForTesting + public int getNewSelectionStart() { + return newSelectionStart; + } + + @VisibleForTesting + public int getNewSelectionEnd() { + return newSelectionEnd; + } + + @VisibleForTesting + public int getNewComposingStart() { + return newComposingStart; + } + + @VisibleForTesting + public int getNewComposingEnd() { + return newComposingEnd; + } + + private void setDeltas( + @NonNull CharSequence oldText, @NonNull CharSequence newText, int newStart, int newExtent) { + this.oldText = oldText; + deltaText = newText; + deltaStart = newStart; + deltaEnd = newExtent; + } + + @NonNull + public JSONObject toJSON() { + JSONObject delta = new JSONObject(); + + try { + delta.put("oldText", oldText.toString()); + delta.put("deltaText", deltaText.toString()); + delta.put("deltaStart", deltaStart); + delta.put("deltaEnd", deltaEnd); + delta.put("selectionBase", newSelectionStart); + delta.put("selectionExtent", newSelectionEnd); + delta.put("composingBase", newComposingStart); + delta.put("composingExtent", newComposingEnd); + } catch (JSONException e) { + Log.e(TAG, "unable to create JSONObject: " + e); + } + + return delta; + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/TextInputPlugin.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/TextInputPlugin.java new file mode 100644 index 0000000000000000000000000000000000000000..064ea52fb97081ba709294441ff1e3e22780ab27 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/TextInputPlugin.java @@ -0,0 +1,852 @@ +// 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. + +package io.flutter.plugin.editing; + +import static io.flutter.Build.API_LEVELS; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.graphics.Rect; +import android.os.Build; +import android.os.Bundle; +import android.text.Editable; +import android.text.InputType; +import android.util.SparseArray; +import android.view.KeyEvent; +import android.view.View; +import android.view.ViewStructure; +import android.view.autofill.AutofillId; +import android.view.autofill.AutofillManager; +import android.view.autofill.AutofillValue; +import android.view.inputmethod.EditorInfo; +import android.view.inputmethod.InputConnection; +import android.view.inputmethod.InputMethodManager; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.VisibleForTesting; +import androidx.core.view.inputmethod.EditorInfoCompat; +import io.flutter.Log; +import io.flutter.embedding.android.KeyboardManager; +import io.flutter.embedding.engine.systemchannels.ScribeChannel; +import io.flutter.embedding.engine.systemchannels.TextInputChannel; +import io.flutter.embedding.engine.systemchannels.TextInputChannel.TextEditState; +import io.flutter.plugin.platform.PlatformViewsController; +import io.flutter.plugin.platform.PlatformViewsController2; +import java.util.ArrayList; +import java.util.HashMap; + +/** Android implementation of the text input plugin. */ +public class TextInputPlugin implements ListenableEditingState.EditingStateWatcher { + private static final String TAG = "TextInputPlugin"; + + @NonNull private final View mView; + @NonNull private final InputMethodManager mImm; + @NonNull private final AutofillManager afm; + @NonNull private final ScribeChannel scribeChannel; + @NonNull private final TextInputChannel textInputChannel; + @NonNull private InputTarget inputTarget = new InputTarget(InputTarget.Type.NO_TARGET, 0); + @Nullable private TextInputChannel.Configuration configuration; + @Nullable private SparseArray autofillConfiguration; + @NonNull private ListenableEditingState mEditable; + private boolean mRestartInputPending; + @Nullable private InputConnection lastInputConnection; + @NonNull private PlatformViewsController platformViewsController; + @NonNull private PlatformViewsController2 platformViewsController2; + @Nullable private Rect lastClientRect; + private ImeSyncDeferringInsetsCallback imeSyncCallback; + + // Initialize the "last seen" text editing values to a non-null value. + private TextEditState mLastKnownFrameworkTextEditingState; + + // When true following calls to createInputConnection will return the cached lastInputConnection + // if the input + // target is a platform view. See the comments on lockPlatformViewInputConnection for more + // details. + private boolean isInputConnectionLocked; + + @SuppressLint("NewApi") + public TextInputPlugin( + @NonNull View view, + @NonNull TextInputChannel textInputChannel, + @NonNull ScribeChannel scribeChannel, + @NonNull PlatformViewsController platformViewsController, + @NonNull PlatformViewsController2 platformViewsController2) { + mView = view; + // Create a default object. + mEditable = new ListenableEditingState(null, mView); + mImm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + if (Build.VERSION.SDK_INT >= API_LEVELS.API_26) { + afm = view.getContext().getSystemService(AutofillManager.class); + } else { + afm = null; + } + + // Sets up syncing ime insets with the framework, allowing + // the Flutter view to grow and shrink to accommodate Android + // controlled keyboard animations. + if (Build.VERSION.SDK_INT >= API_LEVELS.API_30) { + imeSyncCallback = new ImeSyncDeferringInsetsCallback(view); + imeSyncCallback.install(); + } + + this.textInputChannel = textInputChannel; + textInputChannel.setTextInputMethodHandler( + new TextInputChannel.TextInputMethodHandler() { + @Override + public void show() { + showTextInput(mView); + } + + @Override + public void hide() { + if (inputTarget.type == InputTarget.Type.PHYSICAL_DISPLAY_PLATFORM_VIEW) { + notifyViewExited(); + } else { + hideTextInput(mView); + } + } + + @Override + public void requestAutofill() { + notifyViewEntered(); + } + + @Override + public void finishAutofillContext(boolean shouldSave) { + if (Build.VERSION.SDK_INT < API_LEVELS.API_26 || afm == null) { + return; + } + if (shouldSave) { + afm.commit(); + } else { + afm.cancel(); + } + } + + @Override + public void setClient( + int textInputClientId, TextInputChannel.Configuration configuration) { + setTextInputClient(textInputClientId, configuration); + } + + @Override + public void setPlatformViewClient(int platformViewId, boolean usesVirtualDisplay) { + setPlatformViewTextInputClient(platformViewId, usesVirtualDisplay); + } + + @Override + public void setEditingState(TextInputChannel.TextEditState editingState) { + setTextInputEditingState(mView, editingState); + } + + @Override + public void setEditableSizeAndTransform(double width, double height, double[] transform) { + saveEditableSizeAndTransform(width, height, transform); + } + + @Override + public void clearClient() { + clearTextInputClient(); + } + + @Override + public void sendAppPrivateCommand(String action, Bundle data) { + sendTextInputAppPrivateCommand(action, data); + } + }); + + textInputChannel.requestExistingInputState(); + + this.scribeChannel = scribeChannel; + + this.platformViewsController = platformViewsController; + this.platformViewsController.attachTextInputPlugin(this); + this.platformViewsController2 = platformViewsController2; + this.platformViewsController2.attachTextInputPlugin(this); + } + + @NonNull + public InputMethodManager getInputMethodManager() { + return mImm; + } + + @VisibleForTesting + Editable getEditable() { + return mEditable; + } + + @VisibleForTesting + ImeSyncDeferringInsetsCallback getImeSyncCallback() { + return imeSyncCallback; + } + + /** + * Use the current platform view input connection until unlockPlatformViewInputConnection is + * called. + * + *

The current input connection instance is cached and any following call to @{link + * createInputConnection} returns the cached connection until unlockPlatformViewInputConnection is + * called. + * + *

This is a no-op if the current input target isn't a platform view. + * + *

This is used to preserve an input connection when moving a platform view from one virtual + * display to another. + */ + public void lockPlatformViewInputConnection() { + if (inputTarget.type == InputTarget.Type.VIRTUAL_DISPLAY_PLATFORM_VIEW) { + isInputConnectionLocked = true; + } + } + + /** + * Unlocks the input connection. + * + *

See also: @{link lockPlatformViewInputConnection}. + */ + public void unlockPlatformViewInputConnection() { + if (inputTarget.type == InputTarget.Type.VIRTUAL_DISPLAY_PLATFORM_VIEW) { + isInputConnectionLocked = false; + } + } + + /** + * Detaches the text input plugin from the platform views controller. + * + *

The TextInputPlugin instance should not be used after calling this. + */ + @SuppressLint("NewApi") + public void destroy() { + platformViewsController.detachTextInputPlugin(); + platformViewsController2.detachTextInputPlugin(); + textInputChannel.setTextInputMethodHandler(null); + notifyViewExited(); + mEditable.removeEditingStateListener(this); + if (imeSyncCallback != null) { + imeSyncCallback.remove(); + } + } + + private static int inputTypeFromTextInputType( + TextInputChannel.InputType type, + boolean obscureText, + boolean autocorrect, + boolean enableSuggestions, + boolean enableIMEPersonalizedLearning, + TextInputChannel.TextCapitalization textCapitalization) { + if (type.type == TextInputChannel.TextInputType.DATETIME) { + return InputType.TYPE_CLASS_DATETIME; + } else if (type.type == TextInputChannel.TextInputType.NUMBER) { + int textType = InputType.TYPE_CLASS_NUMBER; + if (type.isSigned) { + textType |= InputType.TYPE_NUMBER_FLAG_SIGNED; + } + if (type.isDecimal) { + textType |= InputType.TYPE_NUMBER_FLAG_DECIMAL; + } + return textType; + } else if (type.type == TextInputChannel.TextInputType.PHONE) { + return InputType.TYPE_CLASS_PHONE; + } else if (type.type == TextInputChannel.TextInputType.NONE) { + return InputType.TYPE_NULL; + } + + int textType = InputType.TYPE_CLASS_TEXT; + if (type.type == TextInputChannel.TextInputType.MULTILINE) { + textType |= InputType.TYPE_TEXT_FLAG_MULTI_LINE; + } else if (type.type == TextInputChannel.TextInputType.EMAIL_ADDRESS + || type.type == TextInputChannel.TextInputType.TWITTER) { + textType |= InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS; + } else if (type.type == TextInputChannel.TextInputType.URL + || type.type == TextInputChannel.TextInputType.WEB_SEARCH) { + textType |= InputType.TYPE_TEXT_VARIATION_URI; + } else if (type.type == TextInputChannel.TextInputType.VISIBLE_PASSWORD) { + textType |= InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD; + } else if (type.type == TextInputChannel.TextInputType.NAME) { + textType |= InputType.TYPE_TEXT_VARIATION_PERSON_NAME; + } else if (type.type == TextInputChannel.TextInputType.POSTAL_ADDRESS) { + textType |= InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS; + } + + if (obscureText) { + // Note: both required. Some devices ignore TYPE_TEXT_FLAG_NO_SUGGESTIONS. + textType |= InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS; + textType |= InputType.TYPE_TEXT_VARIATION_PASSWORD; + } else { + if (autocorrect) textType |= InputType.TYPE_TEXT_FLAG_AUTO_CORRECT; + if (!enableSuggestions) { + // Note: both required. Some devices ignore TYPE_TEXT_FLAG_NO_SUGGESTIONS. + textType |= InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS; + textType |= InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD; + } + } + + if (textCapitalization == TextInputChannel.TextCapitalization.CHARACTERS) { + textType |= InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS; + } else if (textCapitalization == TextInputChannel.TextCapitalization.WORDS) { + textType |= InputType.TYPE_TEXT_FLAG_CAP_WORDS; + } else if (textCapitalization == TextInputChannel.TextCapitalization.SENTENCES) { + textType |= InputType.TYPE_TEXT_FLAG_CAP_SENTENCES; + } + + return textType; + } + + @Nullable + public InputConnection createInputConnection( + @NonNull View view, @NonNull KeyboardManager keyboardManager, @NonNull EditorInfo outAttrs) { + if (inputTarget.type == InputTarget.Type.NO_TARGET) { + lastInputConnection = null; + return null; + } + + if (inputTarget.type == InputTarget.Type.PHYSICAL_DISPLAY_PLATFORM_VIEW) { + return null; + } + + if (inputTarget.type == InputTarget.Type.VIRTUAL_DISPLAY_PLATFORM_VIEW) { + if (isInputConnectionLocked) { + return lastInputConnection; + } + lastInputConnection = + platformViewsController + .getPlatformViewById(inputTarget.id) + .onCreateInputConnection(outAttrs); + return lastInputConnection; + } + + outAttrs.inputType = + inputTypeFromTextInputType( + configuration.inputType, + configuration.obscureText, + configuration.autocorrect, + configuration.enableSuggestions, + configuration.enableIMEPersonalizedLearning, + configuration.textCapitalization); + outAttrs.imeOptions = EditorInfo.IME_FLAG_NO_FULLSCREEN; + + if (Build.VERSION.SDK_INT >= API_LEVELS.API_26 + && !configuration.enableIMEPersonalizedLearning) { + outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING; + } + + int enterAction; + if (configuration.inputAction == null) { + // If an explicit input action isn't set, then default to none for multi-line fields + // and done for single line fields. + enterAction = + (InputType.TYPE_TEXT_FLAG_MULTI_LINE & outAttrs.inputType) != 0 + ? EditorInfo.IME_ACTION_NONE + : EditorInfo.IME_ACTION_DONE; + } else { + enterAction = configuration.inputAction; + } + if (configuration.actionLabel != null) { + outAttrs.actionLabel = configuration.actionLabel; + outAttrs.actionId = enterAction; + } + outAttrs.imeOptions |= enterAction; + + if (configuration.contentCommitMimeTypes != null) { + String[] imgTypeString = configuration.contentCommitMimeTypes; + EditorInfoCompat.setContentMimeTypes(outAttrs, imgTypeString); + } + + if (Build.VERSION.SDK_INT >= API_LEVELS.API_34) { + EditorInfoCompat.setStylusHandwritingEnabled(outAttrs, true); + } + // TODO(justinmc): Scribe stylus gestures should be supported here via + // outAttrs.setSupportedHandwritingGestures and + // outAttrs.setSupportedHandwritingGesturePreviews. + // https://github.com/flutter/flutter/issues/156018 + + InputConnectionAdaptor connection = + new InputConnectionAdaptor( + view, + inputTarget.id, + textInputChannel, + scribeChannel, + keyboardManager, + mEditable, + outAttrs); + outAttrs.initialSelStart = mEditable.getSelectionStart(); + outAttrs.initialSelEnd = mEditable.getSelectionEnd(); + + lastInputConnection = connection; + return lastInputConnection; + } + + @Nullable + public InputConnection getLastInputConnection() { + return lastInputConnection; + } + + /** + * Clears a platform view text input client if it is the current input target. + * + *

This is called when a platform view is disposed to make sure we're not hanging to a stale + * input connection. + */ + public void clearPlatformViewClient(int platformViewId) { + if ((inputTarget.type == InputTarget.Type.VIRTUAL_DISPLAY_PLATFORM_VIEW + || inputTarget.type == InputTarget.Type.PHYSICAL_DISPLAY_PLATFORM_VIEW) + && inputTarget.id == platformViewId) { + inputTarget = new InputTarget(InputTarget.Type.NO_TARGET, 0); + notifyViewExited(); + mImm.hideSoftInputFromWindow(mView.getApplicationWindowToken(), 0); + mImm.restartInput(mView); + mRestartInputPending = false; + } + } + + public void sendTextInputAppPrivateCommand(@NonNull String action, @NonNull Bundle data) { + mImm.sendAppPrivateCommand(mView, action, data); + } + + @VisibleForTesting + void showTextInput(View view) { + if (configuration == null + || configuration.inputType == null + || configuration.inputType.type != TextInputChannel.TextInputType.NONE) { + view.requestFocus(); + mImm.showSoftInput(view, 0); + } else { + hideTextInput(view); + } + } + + private void hideTextInput(View view) { + notifyViewExited(); + // Note: when a virtual display is used, a race condition may lead to us hiding the keyboard + // here just after a platform view has shown it. + // This can only potentially happen when switching focus from a Flutter text field to a platform + // view's text + // field(by text field here I mean anything that keeps the keyboard open). + // See: https://github.com/flutter/flutter/issues/34169 + mImm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0); + } + + @VisibleForTesting + void setTextInputClient(int client, TextInputChannel.Configuration configuration) { + // Call notifyViewExited on the previous field. + notifyViewExited(); + this.configuration = configuration; + inputTarget = new InputTarget(InputTarget.Type.FRAMEWORK_CLIENT, client); + + mEditable.removeEditingStateListener(this); + mEditable = + new ListenableEditingState( + configuration.autofill != null ? configuration.autofill.editState : null, mView); + updateAutofillConfigurationIfNeeded(configuration); + + // setTextInputClient will be followed by a call to setTextInputEditingState. + // Do a restartInput at that time. + mRestartInputPending = true; + unlockPlatformViewInputConnection(); + lastClientRect = null; + mEditable.addEditingStateListener(this); + } + + private void setPlatformViewTextInputClient(int platformViewId, boolean usesVirtualDisplay) { + if (usesVirtualDisplay) { + // We need to make sure that the Flutter view is focused so that no imm operations get short + // circuited. + // Not asking for focus here specifically manifested in a bug on API 28 devices where the + // platform view's request to show a keyboard was ignored. + mView.requestFocus(); + inputTarget = new InputTarget(InputTarget.Type.VIRTUAL_DISPLAY_PLATFORM_VIEW, platformViewId); + mImm.restartInput(mView); + mRestartInputPending = false; + } else { + inputTarget = + new InputTarget(InputTarget.Type.PHYSICAL_DISPLAY_PLATFORM_VIEW, platformViewId); + lastInputConnection = null; + } + } + + private static boolean composingChanged( + TextInputChannel.TextEditState before, TextInputChannel.TextEditState after) { + final int composingRegionLength = before.composingEnd - before.composingStart; + if (composingRegionLength != after.composingEnd - after.composingStart) { + return true; + } + for (int index = 0; index < composingRegionLength; index++) { + if (before.text.charAt(index + before.composingStart) + != after.text.charAt(index + after.composingStart)) { + return true; + } + } + return false; + } + + // Called by the text input channel to update the text input plugin with the + // latest TextEditState from the framework. + @VisibleForTesting + void setTextInputEditingState(View view, TextInputChannel.TextEditState state) { + if (!mRestartInputPending + && mLastKnownFrameworkTextEditingState != null + && mLastKnownFrameworkTextEditingState.hasComposing()) { + // Also restart input if the framework (or the developer) decides to + // change the composing region by itself (which is discouraged). Many IMEs + // don't expect editors to commit composing text, so a restart is needed + // to reset their internal states. + mRestartInputPending = composingChanged(mLastKnownFrameworkTextEditingState, state); + if (mRestartInputPending) { + Log.i(TAG, "Composing region changed by the framework. Restarting the input method."); + } + } + + mLastKnownFrameworkTextEditingState = state; + mEditable.setEditingState(state); + + // Restart if needed. Restarting will also update the selection. + if (mRestartInputPending) { + mImm.restartInput(view); + mRestartInputPending = false; + } + } + + private interface MinMax { + void inspect(double x, double y); + } + + private void saveEditableSizeAndTransform(double width, double height, double[] matrix) { + final double[] minMax = new double[4]; // minX, maxX, minY, maxY. + final boolean isAffine = matrix[3] == 0 && matrix[7] == 0 && matrix[15] == 1; + minMax[0] = minMax[1] = matrix[12] / matrix[15]; // minX and maxX. + minMax[2] = minMax[3] = matrix[13] / matrix[15]; // minY and maxY. + + final MinMax finder = + new MinMax() { + @Override + public void inspect(double x, double y) { + final double w = isAffine ? 1 : 1 / (matrix[3] * x + matrix[7] * y + matrix[15]); + final double tx = (matrix[0] * x + matrix[4] * y + matrix[12]) * w; + final double ty = (matrix[1] * x + matrix[5] * y + matrix[13]) * w; + + if (tx < minMax[0]) { + minMax[0] = tx; + } else if (tx > minMax[1]) { + minMax[1] = tx; + } + + if (ty < minMax[2]) { + minMax[2] = ty; + } else if (ty > minMax[3]) { + minMax[3] = ty; + } + } + }; + + finder.inspect(width, 0); + finder.inspect(width, height); + finder.inspect(0, height); + final Float density = mView.getContext().getResources().getDisplayMetrics().density; + lastClientRect = + new Rect( + (int) (minMax[0] * density), + (int) (minMax[2] * density), + (int) Math.ceil(minMax[1] * density), + (int) Math.ceil(minMax[3] * density)); + } + + @VisibleForTesting + void clearTextInputClient() { + if (inputTarget.type == InputTarget.Type.VIRTUAL_DISPLAY_PLATFORM_VIEW) { + // This only applies to platform views that use a virtual display. + // Focus changes in the framework tree have no guarantees on the order focus nodes are + // notified. A node that lost focus may be notified before or after a node that gained focus. + // When moving the focus from a Flutter text field to an AndroidView, it is possible that the + // Flutter text field's focus node will be notified that it lost focus after the AndroidView + // was notified that it gained focus. When this happens the text field will send a + // clearTextInput command which we ignore. + // By doing this we prevent the framework from clearing a platform view input client (the only + // way to do so is to set a new framework text client). I don't see an obvious use case for + // "clearing" a platform view's text input client, and it may be error prone as we don't know + // how the platform view manages the input connection and we probably shouldn't interfere. + // If we ever want to allow the framework to clear a platform view text client we should + // probably consider changing the focus manager such that focus nodes that lost focus are + // notified before focus nodes that gained focus as part of the same focus event. + return; + } + mEditable.removeEditingStateListener(this); + notifyViewExited(); + configuration = null; + updateAutofillConfigurationIfNeeded(null); + inputTarget = new InputTarget(InputTarget.Type.NO_TARGET, 0); + unlockPlatformViewInputConnection(); + lastClientRect = null; + } + + private static class InputTarget { + enum Type { + NO_TARGET, + // InputConnection is managed by the TextInputPlugin, and events are forwarded to the Flutter + // framework. + FRAMEWORK_CLIENT, + // InputConnection is managed by a platform view that is presented on a virtual display. + VIRTUAL_DISPLAY_PLATFORM_VIEW, + // InputConnection is managed by a platform view that is embedded in the activity's view + // hierarchy. This view hierarchy is displayed in a physical display within the aplication + // display area. + PHYSICAL_DISPLAY_PLATFORM_VIEW, + } + + public InputTarget(@NonNull Type type, int id) { + this.type = type; + this.id = id; + } + + @NonNull Type type; + // The ID of the input target. + // + // For framework clients this is the framework input connection client ID. + // For platform views this is the platform view's ID. + int id; + } + + // -------- Start: KeyboardManager Synchronous Responder ------- + public boolean handleKeyEvent(@NonNull KeyEvent keyEvent) { + if (!getInputMethodManager().isAcceptingText() || lastInputConnection == null) { + return false; + } + + // Send the KeyEvent as an IME KeyEvent. If the input connection is an + // InputConnectionAdaptor then call its handleKeyEvent method (because + // this method will be called by the keyboard manager, and + // InputConnectionAdaptor#sendKeyEvent forwards the key event back to the + // keyboard manager). + return (lastInputConnection instanceof InputConnectionAdaptor) + ? ((InputConnectionAdaptor) lastInputConnection).handleKeyEvent(keyEvent) + : lastInputConnection.sendKeyEvent(keyEvent); + } + // -------- End: KeyboardManager Synchronous Responder ------- + + // -------- Start: ListenableEditingState watcher implementation ------- + + @Override + public void didChangeEditingState( + boolean textChanged, boolean selectionChanged, boolean composingRegionChanged) { + if (textChanged) { + // Notify the autofill manager of the value change. + notifyValueChanged(mEditable.toString()); + } + + final int selectionStart = mEditable.getSelectionStart(); + final int selectionEnd = mEditable.getSelectionEnd(); + final int composingStart = mEditable.getComposingStart(); + final int composingEnd = mEditable.getComposingEnd(); + + final ArrayList batchTextEditingDeltas = + mEditable.extractBatchTextEditingDeltas(); + final boolean skipFrameworkUpdate = + // The framework needs to send its editing state first. + mLastKnownFrameworkTextEditingState == null + || (mEditable.toString().equals(mLastKnownFrameworkTextEditingState.text) + && selectionStart == mLastKnownFrameworkTextEditingState.selectionStart + && selectionEnd == mLastKnownFrameworkTextEditingState.selectionEnd + && composingStart == mLastKnownFrameworkTextEditingState.composingStart + && composingEnd == mLastKnownFrameworkTextEditingState.composingEnd); + if (!skipFrameworkUpdate) { + Log.v(TAG, "send EditingState to flutter: " + mEditable.toString()); + + if (configuration.enableDeltaModel) { + textInputChannel.updateEditingStateWithDeltas(inputTarget.id, batchTextEditingDeltas); + mEditable.clearBatchDeltas(); + } else { + textInputChannel.updateEditingState( + inputTarget.id, + mEditable.toString(), + selectionStart, + selectionEnd, + composingStart, + composingEnd); + } + mLastKnownFrameworkTextEditingState = + new TextEditState( + mEditable.toString(), selectionStart, selectionEnd, composingStart, composingEnd); + } else { + // Don't accumulate deltas if they are not sent to the framework. + mEditable.clearBatchDeltas(); + } + } + + // -------- End: ListenableEditingState watcher implementation ------- + + // -------- Start: Autofill ------- + // ### Setup and provide the initial text values and hints. + // + // The TextInputConfiguration used to set up the current client is also used for populating + // "AutofillVirtualStructure" when requested by the autofill manager (AFM), See + // #onProvideAutofillVirtualStructure. + // + // ### Keep the AFM updated + // + // The autofill session connected to the AFM keeps a copy of the current state for each reported + // field in "AutofillVirtualStructure" (instead of holding a reference to those fields), so the + // AFM needs to be notified when text changes if the client was part of the + // "AutofillVirtualStructure" previously reported to the AFM. This step is essential for + // triggering autofill save. This is done in #didChangeEditingState by calling + // #notifyValueChanged. + // + // Additionally when the text input plugin receives a new TextInputConfiguration, + // AutofillManager#notifyValueChanged will be called on all the autofillable fields contained in + // the TextInputConfiguration, in case some of them are tracked by the session and their values + // have changed. However if the value of an unfocused EditableText is changed in the framework, + // such change will not be sent to the text input plugin until the next TextInput.attach call. + private boolean needsAutofill() { + return autofillConfiguration != null; + } + + private void notifyViewEntered() { + if (Build.VERSION.SDK_INT < API_LEVELS.API_26 || afm == null || !needsAutofill()) { + return; + } + + final String triggerIdentifier = configuration.autofill.uniqueIdentifier; + final int[] offset = new int[2]; + mView.getLocationOnScreen(offset); + Rect rect = new Rect(lastClientRect); + rect.offset(offset[0], offset[1]); + afm.notifyViewEntered(mView, triggerIdentifier.hashCode(), rect); + } + + private void notifyViewExited() { + if (Build.VERSION.SDK_INT < API_LEVELS.API_26 + || afm == null + || configuration == null + || configuration.autofill == null + || !needsAutofill()) { + return; + } + + final String triggerIdentifier = configuration.autofill.uniqueIdentifier; + afm.notifyViewExited(mView, triggerIdentifier.hashCode()); + } + + private void notifyValueChanged(String newValue) { + if (Build.VERSION.SDK_INT < API_LEVELS.API_26 || afm == null || !needsAutofill()) { + return; + } + + final String triggerIdentifier = configuration.autofill.uniqueIdentifier; + afm.notifyValueChanged(mView, triggerIdentifier.hashCode(), AutofillValue.forText(newValue)); + } + + private void updateAutofillConfigurationIfNeeded(TextInputChannel.Configuration configuration) { + if (Build.VERSION.SDK_INT < API_LEVELS.API_26) { + return; + } + + if (configuration == null || configuration.autofill == null) { + // Disables autofill if the configuration doesn't have an autofill field. + autofillConfiguration = null; + return; + } + + final TextInputChannel.Configuration[] configurations = configuration.fields; + autofillConfiguration = new SparseArray<>(); + + if (configurations == null) { + autofillConfiguration.put(configuration.autofill.uniqueIdentifier.hashCode(), configuration); + } else { + for (TextInputChannel.Configuration config : configurations) { + TextInputChannel.Configuration.Autofill autofill = config.autofill; + if (autofill != null) { + autofillConfiguration.put(autofill.uniqueIdentifier.hashCode(), config); + afm.notifyValueChanged( + mView, + autofill.uniqueIdentifier.hashCode(), + AutofillValue.forText(autofill.editState.text)); + } + } + } + } + + public void onProvideAutofillVirtualStructure(@NonNull ViewStructure structure, int flags) { + if (Build.VERSION.SDK_INT < API_LEVELS.API_26 || !needsAutofill()) { + return; + } + + final String triggerIdentifier = configuration.autofill.uniqueIdentifier; + final AutofillId parentId = structure.getAutofillId(); + for (int i = 0; i < autofillConfiguration.size(); i++) { + final int autofillId = autofillConfiguration.keyAt(i); + final TextInputChannel.Configuration config = autofillConfiguration.valueAt(i); + final TextInputChannel.Configuration.Autofill autofill = config.autofill; + if (autofill == null) { + continue; + } + + structure.addChildCount(1); + final ViewStructure child = structure.newChild(i); + child.setAutofillId(parentId, autofillId); + // Don't set hints when there's none. + // See https://github.com/flutter/flutter/issues/98505. + if (autofill.hints.length > 0) { + child.setAutofillHints(autofill.hints); + } + child.setAutofillType(View.AUTOFILL_TYPE_TEXT); + child.setVisibility(View.VISIBLE); + if (autofill.hintText != null) { + child.setHint(autofill.hintText); + } + + // For some autofill services, only visible input fields are eligible for autofill. + // Reports the real size of the child if it's the current client, or 1x1 if we don't + // know the real dimensions of the child. + if (triggerIdentifier.hashCode() == autofillId && lastClientRect != null) { + child.setDimens( + lastClientRect.left, + lastClientRect.top, + 0, + 0, + lastClientRect.width(), + lastClientRect.height()); + child.setAutofillValue(AutofillValue.forText(mEditable)); + } else { + child.setDimens(0, 0, 0, 0, 1, 1); + child.setAutofillValue(AutofillValue.forText(autofill.editState.text)); + } + } + } + + public void autofill(@NonNull SparseArray values) { + if (Build.VERSION.SDK_INT < API_LEVELS.API_26) { + return; + } + + if (configuration == null || autofillConfiguration == null || configuration.autofill == null) { + return; + } + + final TextInputChannel.Configuration.Autofill currentAutofill = configuration.autofill; + final HashMap editingValues = new HashMap<>(); + for (int i = 0; i < values.size(); i++) { + int virtualId = values.keyAt(i); + + final TextInputChannel.Configuration config = autofillConfiguration.get(virtualId); + if (config == null || config.autofill == null) { + continue; + } + + final TextInputChannel.Configuration.Autofill autofill = config.autofill; + final String value = values.valueAt(i).getTextValue().toString(); + final TextInputChannel.TextEditState newState = + new TextInputChannel.TextEditState(value, value.length(), value.length(), -1, -1); + + if (autofill.uniqueIdentifier.equals(currentAutofill.uniqueIdentifier)) { + // Autofilling the current client is the same as handling user input + // from the virtual keyboard. Setting the editable to newState and an + // update will be sent to the framework. + mEditable.setEditingState(newState); + } else { + editingValues.put(autofill.uniqueIdentifier, newState); + } + } + textInputChannel.updateEditingStateWithTag(inputTarget.id, editingValues); + } + // -------- End: Autofill ------- +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/localization/LocalizationPlugin.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/localization/LocalizationPlugin.java new file mode 100644 index 0000000000000000000000000000000000000000..1b5d398a98231aaf2e2711d9fa5189cc732f37d4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/localization/LocalizationPlugin.java @@ -0,0 +1,208 @@ +// 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. + +package io.flutter.plugin.localization; + +import static io.flutter.Build.API_LEVELS; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.res.Configuration; +import android.os.Build; +import android.os.LocaleList; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.VisibleForTesting; +import io.flutter.embedding.engine.systemchannels.LocalizationChannel; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +/** Android implementation of the localization plugin. */ +public class LocalizationPlugin { + @NonNull private final LocalizationChannel localizationChannel; + @NonNull private final Context context; + + @SuppressLint({ + "AppBundleLocaleChanges", + "DiscouragedApi" + }) // This is optionally turned on by apps. + @VisibleForTesting + final LocalizationChannel.LocalizationMessageHandler localizationMessageHandler = + new LocalizationChannel.LocalizationMessageHandler() { + @Override + public String getStringResource(@NonNull String key, @Nullable String localeString) { + Context localContext = context; + String stringToReturn = null; + Locale savedLocale = null; + + if (localeString != null) { + Locale locale = localeFromString(localeString); + + Configuration config = new Configuration(context.getResources().getConfiguration()); + config.setLocale(locale); + localContext = context.createConfigurationContext(config); + } + + String packageName = context.getPackageName(); + int resId = localContext.getResources().getIdentifier(key, "string", packageName); + if (resId != 0) { + // 0 means the resource is not found. + stringToReturn = localContext.getResources().getString(resId); + } + + return stringToReturn; + } + }; + + public LocalizationPlugin( + @NonNull Context context, @NonNull LocalizationChannel localizationChannel) { + + this.context = context; + this.localizationChannel = localizationChannel; + this.localizationChannel.setLocalizationMessageHandler(localizationMessageHandler); + } + + /** + * Computes the {@link Locale} in supportedLocales that best matches the user's preferred locales. + * + *

FlutterEngine must be non-null when this method is invoked. + */ + @SuppressWarnings("deprecation") + @Nullable + public Locale resolveNativeLocale(@Nullable List supportedLocales) { + if (supportedLocales == null || supportedLocales.isEmpty()) { + return null; + } + + // Android improved the localization resolution algorithms after API 24 (7.0, Nougat). + // See https://developer.android.com/guide/topics/resources/multilingual-support + // + // LanguageRange and Locale.lookup was added in API 26 and is the preferred way to + // select a locale. Pre-API 26, we implement a manual locale resolution. + if (Build.VERSION.SDK_INT >= API_LEVELS.API_26) { + // Modern locale resolution using LanguageRange + // https://developer.android.com/guide/topics/resources/multilingual-support#postN + List languageRanges = new ArrayList<>(); + LocaleList localeList = context.getResources().getConfiguration().getLocales(); + int localeCount = localeList.size(); + for (int index = 0; index < localeCount; ++index) { + Locale locale = localeList.get(index); + // Convert locale string into language range format. + String fullRange = locale.getLanguage(); + if (!locale.getScript().isEmpty()) { + fullRange += "-" + locale.getScript(); + } + if (!locale.getCountry().isEmpty()) { + fullRange += "-" + locale.getCountry(); + } + languageRanges.add(new Locale.LanguageRange(fullRange)); + languageRanges.add(new Locale.LanguageRange(locale.getLanguage())); + languageRanges.add(new Locale.LanguageRange(locale.getLanguage() + "-*")); + } + Locale platformResolvedLocale = Locale.lookup(languageRanges, supportedLocales); + if (platformResolvedLocale != null) { + return platformResolvedLocale; + } + return supportedLocales.get(0); + } else if (Build.VERSION.SDK_INT >= API_LEVELS.API_24) { + // Modern locale resolution without languageRange + // https://developer.android.com/guide/topics/resources/multilingual-support#postN + LocaleList localeList = context.getResources().getConfiguration().getLocales(); + for (int index = 0; index < localeList.size(); ++index) { + Locale preferredLocale = localeList.get(index); + // Look for exact match. + for (Locale locale : supportedLocales) { + if (preferredLocale.equals(locale)) { + return locale; + } + } + // Look for exact language only match. + for (Locale locale : supportedLocales) { + if (preferredLocale.getLanguage().equals(locale.toLanguageTag())) { + return locale; + } + } + // Look for any locale with matching language. + for (Locale locale : supportedLocales) { + if (preferredLocale.getLanguage().equals(locale.getLanguage())) { + return locale; + } + } + } + return supportedLocales.get(0); + } + + // Legacy locale resolution + // https://developer.android.com/guide/topics/resources/multilingual-support#preN + Locale preferredLocale = context.getResources().getConfiguration().locale; + if (preferredLocale != null) { + // Look for exact match. + for (Locale locale : supportedLocales) { + if (preferredLocale.equals(locale)) { + return locale; + } + } + // Look for exact language only match. + for (Locale locale : supportedLocales) { + if (preferredLocale.getLanguage().equals(locale.toString())) { + return locale; + } + } + } + return supportedLocales.get(0); + } + + /** + * Send the current {@link Locale} configuration to Flutter. + * + *

FlutterEngine must be non-null when this method is invoked. + */ + @SuppressWarnings("deprecation") + public void sendLocalesToFlutter(@NonNull Configuration config) { + List locales = new ArrayList<>(); + if (Build.VERSION.SDK_INT >= API_LEVELS.API_24) { + LocaleList localeList = config.getLocales(); + int localeCount = localeList.size(); + for (int index = 0; index < localeCount; ++index) { + Locale locale = localeList.get(index); + locales.add(locale); + } + } else { + locales.add(config.locale); + } + + localizationChannel.sendLocales(locales); + } + + /** + * Computes the {@link Locale} from the provided {@code String} with format + * language[-script][-region][-...], where script is an alphabet string of length 4, and region is + * either an alphabet string of length 2 or a digit string of length 3. + */ + @NonNull + public static Locale localeFromString(@NonNull String localeString) { + // Normalize the locale string, replace all underscores with hyphens. + localeString = localeString.replace('_', '-'); + + // Pre-API 21, we fall back to manually parsing the locale tag. + String parts[] = localeString.split("-", -1); + + // Assume the first part is always the language code. + String languageCode = parts[0]; + String scriptCode = ""; + String countryCode = ""; + int index = 1; + if (parts.length > index && parts[index].length() == 4) { + scriptCode = parts[index]; + index++; + } + if (parts.length > index && parts[index].length() >= 2 && parts[index].length() <= 3) { + countryCode = parts[index]; + index++; + } + // Ignore the rest of the locale for this purpose. + return new Locale(languageCode, countryCode, scriptCode); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/mouse/MouseCursorPlugin.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/mouse/MouseCursorPlugin.java new file mode 100644 index 0000000000000000000000000000000000000000..e6a4f7083bfe162920cfd8be8e588aa7ffe1b4b5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/mouse/MouseCursorPlugin.java @@ -0,0 +1,136 @@ +// 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. + +package io.flutter.plugin.mouse; + +import static io.flutter.Build.API_LEVELS; + +import android.annotation.TargetApi; +import android.view.PointerIcon; +import androidx.annotation.NonNull; +import androidx.annotation.RequiresApi; +import io.flutter.embedding.engine.systemchannels.MouseCursorChannel; +import java.util.HashMap; + +/** A mandatory plugin that handles mouse cursor requests. */ +@TargetApi(API_LEVELS.API_24) +@RequiresApi(API_LEVELS.API_24) +public class MouseCursorPlugin { + @NonNull private final MouseCursorViewDelegate mView; + @NonNull private final MouseCursorChannel mouseCursorChannel; + + public MouseCursorPlugin( + @NonNull MouseCursorViewDelegate view, @NonNull MouseCursorChannel mouseCursorChannel) { + mView = view; + + this.mouseCursorChannel = mouseCursorChannel; + mouseCursorChannel.setMethodHandler( + new MouseCursorChannel.MouseCursorMethodHandler() { + @Override + public void activateSystemCursor(@NonNull String kind) { + mView.setPointerIcon(resolveSystemCursor(kind)); + } + }); + } + + /** + * Return a pointer icon object for a system cursor. + * + *

This method guarantees to return a non-null object. + */ + private PointerIcon resolveSystemCursor(@NonNull String kind) { + if (MouseCursorPlugin.systemCursorConstants == null) { + // Initialize the map when first used, because the map can grow big in the future (~70) + // and most mobile devices will not use them. + MouseCursorPlugin.systemCursorConstants = + new HashMap() { + private static final long serialVersionUID = 1L; + + { + put("alias", PointerIcon.TYPE_ALIAS); + put("allScroll", PointerIcon.TYPE_ALL_SCROLL); + put("basic", PointerIcon.TYPE_ARROW); + put("cell", PointerIcon.TYPE_CELL); + put("click", PointerIcon.TYPE_HAND); + put("contextMenu", PointerIcon.TYPE_CONTEXT_MENU); + put("copy", PointerIcon.TYPE_COPY); + put("forbidden", PointerIcon.TYPE_NO_DROP); + put("grab", PointerIcon.TYPE_GRAB); + put("grabbing", PointerIcon.TYPE_GRABBING); + put("help", PointerIcon.TYPE_HELP); + put("move", PointerIcon.TYPE_ALL_SCROLL); + put("none", PointerIcon.TYPE_NULL); + put("noDrop", PointerIcon.TYPE_NO_DROP); + put("precise", PointerIcon.TYPE_CROSSHAIR); + put("text", PointerIcon.TYPE_TEXT); + put("resizeColumn", PointerIcon.TYPE_HORIZONTAL_DOUBLE_ARROW); + put("resizeDown", PointerIcon.TYPE_VERTICAL_DOUBLE_ARROW); + put("resizeUpLeft", PointerIcon.TYPE_TOP_RIGHT_DIAGONAL_DOUBLE_ARROW); + put("resizeDownRight", PointerIcon.TYPE_TOP_LEFT_DIAGONAL_DOUBLE_ARROW); + put("resizeLeft", PointerIcon.TYPE_HORIZONTAL_DOUBLE_ARROW); + put("resizeLeftRight", PointerIcon.TYPE_HORIZONTAL_DOUBLE_ARROW); + put("resizeRight", PointerIcon.TYPE_HORIZONTAL_DOUBLE_ARROW); + put("resizeRow", PointerIcon.TYPE_VERTICAL_DOUBLE_ARROW); + put("resizeUp", PointerIcon.TYPE_VERTICAL_DOUBLE_ARROW); + put("resizeUpDown", PointerIcon.TYPE_VERTICAL_DOUBLE_ARROW); + put("resizeUpLeft", PointerIcon.TYPE_TOP_LEFT_DIAGONAL_DOUBLE_ARROW); + put("resizeUpRight", PointerIcon.TYPE_TOP_RIGHT_DIAGONAL_DOUBLE_ARROW); + put("resizeUpLeftDownRight", PointerIcon.TYPE_TOP_LEFT_DIAGONAL_DOUBLE_ARROW); + put("resizeUpRightDownLeft", PointerIcon.TYPE_TOP_RIGHT_DIAGONAL_DOUBLE_ARROW); + put("verticalText", PointerIcon.TYPE_VERTICAL_TEXT); + put("wait", PointerIcon.TYPE_WAIT); + put("zoomIn", PointerIcon.TYPE_ZOOM_IN); + put("zoomOut", PointerIcon.TYPE_ZOOM_OUT); + } + }; + } + + final int cursorConstant = + MouseCursorPlugin.systemCursorConstants.getOrDefault(kind, PointerIcon.TYPE_ARROW); + return mView.getSystemPointerIcon(cursorConstant); + } + + /** + * Detaches the text input plugin from the platform views controller. + * + *

The MouseCursorPlugin instance should not be used after calling this. + */ + public void destroy() { + mouseCursorChannel.setMethodHandler(null); + } + + /** + * A map from Flutter's system cursor {@code kind} to Android's pointer icon constants. + * + *

It is null until the first time a system cursor is requested, at which time it is filled + * with the entire mapping. + */ + @NonNull private static HashMap systemCursorConstants; + + /** + * Delegate interface for requesting the system to display a pointer icon object. + * + *

Typically implemented by an {@link android.view.View}, such as a {@code FlutterView}. + */ + public interface MouseCursorViewDelegate { + /** + * Gets a system pointer icon object for the given {@code type}. + * + *

If typeis not recognized, returns the default pointer icon. + * + *

This is typically implemented by calling {@link android.view.PointerIcon#getSystemIcon} + * with the context associated with this view. + */ + @NonNull + public PointerIcon getSystemPointerIcon(int type); + + /** + * Request the pointer to display the specified icon object. + * + *

If the delegate is implemented by a {@link android.view.View}, then this method is + * automatically implemented by View. + */ + public void setPointerIcon(@NonNull PointerIcon icon); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/AccessibilityEventsDelegate.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/AccessibilityEventsDelegate.java new file mode 100644 index 0000000000000000000000000000000000000000..808274efc94c972aeaf5fe92b1314c077f344f50 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/AccessibilityEventsDelegate.java @@ -0,0 +1,61 @@ +// 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. + +package io.flutter.plugin.platform; + +import android.view.MotionEvent; +import android.view.View; +import android.view.accessibility.AccessibilityEvent; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import io.flutter.view.AccessibilityBridge; + +/** + * Delegates accessibility events to the currently attached accessibility bridge if one is attached. + */ +class AccessibilityEventsDelegate { + private AccessibilityBridge accessibilityBridge; + + /** + * Delegates handling of {@link android.view.ViewParent#requestSendAccessibilityEvent} to the + * accessibility bridge. + * + *

This is a no-op if there is no accessibility delegate set. + * + *

This is used by embedded platform views to propagate accessibility events from their view + * hierarchy to the accessibility bridge. + * + *

As the embedded view doesn't have to be the only View in the embedded hierarchy (it can have + * child views) and the event might have been originated from any view in this hierarchy, this + * method gets both a reference to the embedded platform view, and a reference to the view from + * its hierarchy that sent the event. + * + * @param embeddedView the embedded platform view for which the event is delegated + * @param eventOrigin the view in the embedded view's hierarchy that sent the event. + * @return True if the event was sent. + */ + public boolean requestSendAccessibilityEvent( + @NonNull View embeddedView, @NonNull View eventOrigin, @NonNull AccessibilityEvent event) { + if (accessibilityBridge == null) { + return false; + } + return accessibilityBridge.externalViewRequestSendAccessibilityEvent( + embeddedView, eventOrigin, event); + } + + public boolean onAccessibilityHoverEvent(MotionEvent event, boolean ignorePlatformViews) { + if (accessibilityBridge == null) { + return false; + } + return accessibilityBridge.onAccessibilityHoverEvent(event, ignorePlatformViews); + } + + /* + * This setter should only be used directly in PlatformViewsController when attached/detached to an accessibility + * bridge. + */ + void setAccessibilityBridge(@Nullable AccessibilityBridge accessibilityBridge) { + this.accessibilityBridge = accessibilityBridge; + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/ImageReaderPlatformViewRenderTarget.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/ImageReaderPlatformViewRenderTarget.java new file mode 100644 index 0000000000000000000000000000000000000000..4cf0cd01ed9b35e6fe6d8fb9f26e2cdea2dea1c5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/ImageReaderPlatformViewRenderTarget.java @@ -0,0 +1,139 @@ +package io.flutter.plugin.platform; + +import static io.flutter.Build.API_LEVELS; + +import android.annotation.TargetApi; +import android.graphics.ImageFormat; +import android.hardware.HardwareBuffer; +import android.media.Image; +import android.media.ImageReader; +import android.os.Build; +import android.os.Handler; +import android.view.Surface; +import io.flutter.Log; +import io.flutter.view.TextureRegistry.ImageTextureEntry; + +@TargetApi(API_LEVELS.API_29) +public class ImageReaderPlatformViewRenderTarget implements PlatformViewRenderTarget { + private ImageTextureEntry textureEntry; + private ImageReader reader; + private int bufferWidth = 0; + private int bufferHeight = 0; + private static final String TAG = "ImageReaderPlatformViewRenderTarget"; + private static final int MAX_IMAGES = 4; + + private void closeReader() { + if (this.reader != null) { + // Push a null image, forcing the texture entry to close any cached images. + textureEntry.pushImage(null); + // Close the reader, which also closes any produced images. + this.reader.close(); + this.reader = null; + } + } + + private final Handler onImageAvailableHandler = new Handler(); + private final ImageReader.OnImageAvailableListener onImageAvailableListener = + new ImageReader.OnImageAvailableListener() { + @Override + public void onImageAvailable(ImageReader reader) { + Image image = null; + try { + image = reader.acquireLatestImage(); + } catch (IllegalStateException e) { + Log.e(TAG, "onImageAvailable acquireLatestImage failed: " + e.toString()); + } + if (image == null) { + return; + } + textureEntry.pushImage(image); + } + }; + + @TargetApi(API_LEVELS.API_33) + protected ImageReader createImageReader33() { + final ImageReader.Builder builder = new ImageReader.Builder(bufferWidth, bufferHeight); + // Allow for double buffering. + builder.setMaxImages(MAX_IMAGES); + // Use PRIVATE image format so that we can support video decoding. + // TODO(johnmccutchan): Should we always use PRIVATE here? It may impact our ability to read + // back texture data. If we don't always want to use it, how do we decide when to use it or not? + // Perhaps PlatformViews can indicate if they may contain DRM'd content. I need to investigate + // how PRIVATE impacts our ability to take screenshots or capture the output of Flutter + // application. + builder.setImageFormat(ImageFormat.PRIVATE); + // Hint that consumed images will only be read by GPU. + builder.setUsage(HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE); + final ImageReader reader = builder.build(); + reader.setOnImageAvailableListener(this.onImageAvailableListener, onImageAvailableHandler); + return reader; + } + + @TargetApi(API_LEVELS.API_29) + protected ImageReader createImageReader29() { + final ImageReader reader = + ImageReader.newInstance( + bufferWidth, + bufferHeight, + ImageFormat.PRIVATE, + MAX_IMAGES, + HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE); + reader.setOnImageAvailableListener(this.onImageAvailableListener, onImageAvailableHandler); + return reader; + } + + protected ImageReader createImageReader() { + if (Build.VERSION.SDK_INT >= API_LEVELS.API_33) { + return createImageReader33(); + } else if (Build.VERSION.SDK_INT >= API_LEVELS.API_29) { + return createImageReader29(); + } + throw new UnsupportedOperationException( + "ImageReaderPlatformViewRenderTarget requires API version 29+"); + } + + public ImageReaderPlatformViewRenderTarget(ImageTextureEntry textureEntry) { + if (Build.VERSION.SDK_INT < API_LEVELS.API_29) { + throw new UnsupportedOperationException( + "ImageReaderPlatformViewRenderTarget requires API version 29+"); + } + this.textureEntry = textureEntry; + } + + public void resize(int width, int height) { + if (this.reader != null && bufferWidth == width && bufferHeight == height) { + // No size change. + return; + } + closeReader(); + bufferWidth = width; + bufferHeight = height; + this.reader = createImageReader(); + } + + public int getWidth() { + return this.bufferWidth; + } + + public int getHeight() { + return this.bufferHeight; + } + + public long getId() { + return this.textureEntry.id(); + } + + public void release() { + closeReader(); + // textureEntry has a finalizer attached. + textureEntry = null; + } + + public boolean isReleased() { + return this.textureEntry == null; + } + + public Surface getSurface() { + return this.reader.getSurface(); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformOverlayView.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformOverlayView.java new file mode 100644 index 0000000000000000000000000000000000000000..228f081e843bb685e6380ae062d6b8b0a1d6f937 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformOverlayView.java @@ -0,0 +1,49 @@ +// 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. + +package io.flutter.plugin.platform; + +import android.content.Context; +import android.util.AttributeSet; +import android.view.MotionEvent; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import io.flutter.embedding.android.FlutterImageView; + +/** A host view for Flutter content displayed over a platform view. */ +public class PlatformOverlayView extends FlutterImageView { + @Nullable private AccessibilityEventsDelegate accessibilityDelegate; + + public PlatformOverlayView( + @NonNull Context context, + int width, + int height, + @NonNull AccessibilityEventsDelegate accessibilityDelegate) { + super(context, width, height, FlutterImageView.SurfaceKind.overlay); + this.accessibilityDelegate = accessibilityDelegate; + } + + public PlatformOverlayView(@NonNull Context context) { + this(context, 1, 1, null); + } + + public PlatformOverlayView(@NonNull Context context, @NonNull AttributeSet attrs) { + this(context, 1, 1, null); + } + + @Override + public boolean onHoverEvent(@NonNull MotionEvent event) { + // This view doesn't have any accessibility information of its own, but anything drawn in + // this view is visible above the platform view it is overlaying, so should respond to + // accessibility exploration events. Forward those events to the accessibility delegate in + // a special mode that will stop as soon as it reaches a platform view, so that it will not + // find widgets that behind the platform view. If no such widget is found, treat the event + // as unhandled so that it can fall through to the platform view. + if (accessibilityDelegate != null + && accessibilityDelegate.onAccessibilityHoverEvent(event, true)) { + return true; + } + return super.onHoverEvent(event); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformPlugin.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformPlugin.java new file mode 100644 index 0000000000000000000000000000000000000000..e798d76c7bea2deb353201dcee54ba74c8fae069 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformPlugin.java @@ -0,0 +1,626 @@ +// 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. + +package io.flutter.plugin.platform; + +import static io.flutter.Build.API_LEVELS; + +import android.app.Activity; +import android.app.ActivityManager.TaskDescription; +import android.content.ClipData; +import android.content.ClipDescription; +import android.content.ClipboardManager; +import android.content.Context; +import android.content.Intent; +import android.content.res.AssetFileDescriptor; +import android.net.Uri; +import android.os.Build; +import android.view.HapticFeedbackConstants; +import android.view.SoundEffectConstants; +import android.view.View; +import android.view.Window; +import android.view.WindowManager; +import androidx.activity.OnBackPressedDispatcherOwner; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.VisibleForTesting; +import androidx.core.view.WindowInsetsControllerCompat; +import io.flutter.Log; +import io.flutter.embedding.engine.systemchannels.PlatformChannel; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.List; + +/** Android implementation of the platform plugin. */ +public class PlatformPlugin { + public static final int DEFAULT_SYSTEM_UI = + View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; + + private final Activity activity; + private final PlatformChannel platformChannel; + @Nullable private final PlatformPluginDelegate platformPluginDelegate; + private PlatformChannel.SystemChromeStyle currentTheme; + private int mEnabledOverlays; + private static final String TAG = "PlatformPlugin"; + + /** + * The {@link PlatformPlugin} generally has default behaviors implemented for platform + * functionalities requested by the Flutter framework. However, functionalities exposed through + * this interface could be customized by the more public-facing APIs that implement this interface + * such as the {@link io.flutter.embedding.android.FlutterActivity} or the {@link + * io.flutter.embedding.android.FlutterFragment}. + */ + public interface PlatformPluginDelegate { + /** + * Allow implementer to customize the behavior needed when the Flutter framework calls to pop + * the Android-side navigation stack. + * + * @return true if the implementation consumed the pop signal. If false, a default behavior of + * finishing the activity or sending the signal to {@link + * androidx.activity.OnBackPressedDispatcher} will be executed. + */ + boolean popSystemNavigator(); + + /** + * The Flutter application would or would not like to handle navigation pop events itself. + * + *

Relevant for registering and unregistering the app's OnBackInvokedCallback for the + * Predictive Back feature, for example as in {@link + * io.flutter.embedding.android.FlutterActivity}. + */ + default void setFrameworkHandlesBack(boolean frameworkHandlesBack) {} + } + + @VisibleForTesting + final PlatformChannel.PlatformMessageHandler mPlatformMessageHandler = + new PlatformChannel.PlatformMessageHandler() { + @Override + public void playSystemSound(@NonNull PlatformChannel.SoundType soundType) { + PlatformPlugin.this.playSystemSound(soundType); + } + + @Override + public void vibrateHapticFeedback( + @NonNull PlatformChannel.HapticFeedbackType feedbackType) { + PlatformPlugin.this.vibrateHapticFeedback(feedbackType); + } + + @Override + public void setPreferredOrientations(int androidOrientation) { + setSystemChromePreferredOrientations(androidOrientation); + } + + @Override + public void setApplicationSwitcherDescription( + @NonNull PlatformChannel.AppSwitcherDescription description) { + setSystemChromeApplicationSwitcherDescription(description); + } + + @Override + public void showSystemOverlays(@NonNull List overlays) { + setSystemChromeEnabledSystemUIOverlays(overlays); + } + + @Override + public void showSystemUiMode(@NonNull PlatformChannel.SystemUiMode mode) { + setSystemChromeEnabledSystemUIMode(mode); + } + + @Override + public void setSystemUiChangeListener() { + setSystemChromeChangeListener(); + } + + @Override + public void restoreSystemUiOverlays() { + restoreSystemChromeSystemUIOverlays(); + } + + @Override + public void setSystemUiOverlayStyle( + @NonNull PlatformChannel.SystemChromeStyle systemUiOverlayStyle) { + setSystemChromeSystemUIOverlayStyle(systemUiOverlayStyle); + } + + @Override + public void setFrameworkHandlesBack(boolean frameworkHandlesBack) { + PlatformPlugin.this.setFrameworkHandlesBack(frameworkHandlesBack); + } + + @Override + public void popSystemNavigator() { + PlatformPlugin.this.popSystemNavigator(); + } + + @Override + public CharSequence getClipboardData( + @Nullable PlatformChannel.ClipboardContentFormat format) { + return PlatformPlugin.this.getClipboardData(format); + } + + @Override + public void setClipboardData(@NonNull String text) { + PlatformPlugin.this.setClipboardData(text); + } + + @Override + public boolean clipboardHasStrings() { + return PlatformPlugin.this.clipboardHasStrings(); + } + + @Override + public void share(@NonNull String text) { + PlatformPlugin.this.share(text); + } + }; + + public PlatformPlugin(@NonNull Activity activity, @NonNull PlatformChannel platformChannel) { + this(activity, platformChannel, null); + } + + public PlatformPlugin( + @NonNull Activity activity, + @NonNull PlatformChannel platformChannel, + @Nullable PlatformPluginDelegate delegate) { + this.activity = activity; + this.platformChannel = platformChannel; + this.platformChannel.setPlatformMessageHandler(mPlatformMessageHandler); + this.platformPluginDelegate = delegate; + + mEnabledOverlays = DEFAULT_SYSTEM_UI; + } + + /** + * Releases all resources held by this {@code PlatformPlugin}. + * + *

Do not invoke any methods on a {@code PlatformPlugin} after invoking this method. + */ + public void destroy() { + this.platformChannel.setPlatformMessageHandler(null); + } + + private void playSystemSound(@NonNull PlatformChannel.SoundType soundType) { + if (soundType == PlatformChannel.SoundType.CLICK) { + View view = activity.getWindow().getDecorView(); + view.playSoundEffect(SoundEffectConstants.CLICK); + } + } + + @VisibleForTesting + /* package */ void vibrateHapticFeedback( + @NonNull PlatformChannel.HapticFeedbackType feedbackType) { + View view = activity.getWindow().getDecorView(); + switch (feedbackType) { + case STANDARD: + view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); + break; + case LIGHT_IMPACT: + view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY); + break; + case MEDIUM_IMPACT: + view.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP); + break; + case HEAVY_IMPACT: + if (Build.VERSION.SDK_INT >= API_LEVELS.API_23) { + view.performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK); + } + break; + case SELECTION_CLICK: + view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK); + break; + } + } + + private void setSystemChromePreferredOrientations(int androidOrientation) { + activity.setRequestedOrientation(androidOrientation); + } + + @SuppressWarnings("deprecation") + private void setSystemChromeApplicationSwitcherDescription( + PlatformChannel.AppSwitcherDescription description) { + if (Build.VERSION.SDK_INT < API_LEVELS.API_28) { + activity.setTaskDescription( + new TaskDescription(description.label, /* icon= */ null, description.color)); + } else { + TaskDescription taskDescription = + new TaskDescription(description.label, 0, description.color); + activity.setTaskDescription(taskDescription); + } + } + + private void setSystemChromeChangeListener() { + // Set up a listener to notify the framework when the system ui has changed. + View decorView = activity.getWindow().getDecorView(); + decorView.setOnSystemUiVisibilityChangeListener( + new View.OnSystemUiVisibilityChangeListener() { + @Override + public void onSystemUiVisibilityChange(int visibility) { + // `platformChannel.systemChromeChanged` may trigger a callback that eventually results + // in a call to `setSystemUiVisibility`. + // `setSystemUiVisibility` must not be called in the same frame as when + // `onSystemUiVisibilityChange` is received though. + // + // As such, post `platformChannel.systemChromeChanged` to the view handler to ensure + // that downstream callbacks are trigged on the next frame. + decorView.post( + () -> { + if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) { + // The system bars are visible. Make any desired adjustments to + // your UI, such as showing the action bar or other navigational + // controls. Another common action is to set a timer to dismiss + // the system bars and restore the fullscreen mode that was + // previously enabled. + platformChannel.systemChromeChanged(true); + } else { + // The system bars are NOT visible. Make any desired adjustments + // to your UI, such as hiding the action bar or other + // navigational controls. + platformChannel.systemChromeChanged(false); + } + }); + } + }); + } + + private void setSystemChromeEnabledSystemUIMode(PlatformChannel.SystemUiMode systemUiMode) { + int enabledOverlays; + + if (systemUiMode == PlatformChannel.SystemUiMode.LEAN_BACK) { + // LEAN BACK + // Available starting at Android SDK 4.1 (API 16). + // + // If the Flutter Android app targets Android SDK 15 (API 35) or later then the Android + // system will ignore this value unless the app also follows the opt out + // instructions found in + // https://docs.flutter.dev/release/breaking-changes/default-systemuimode-edge-to-edge. + // + // Should not show overlays, tap to reveal overlays, needs onChange callback + // When the overlays come in on tap, the app does not receive the gesture and does not know + // the system overlay has changed. The overlays cannot be dismissed, so adding the callback + // support will allow users to restore the system ui and dismiss the overlays. + // Not compatible with top/bottom overlays enabled. + enabledOverlays = + View.SYSTEM_UI_FLAG_LAYOUT_STABLE + | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN + | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_FULLSCREEN; + } else if (systemUiMode == PlatformChannel.SystemUiMode.IMMERSIVE) { + // IMMERSIVE + // Available starting at Android SDK 4.4 (API 19). + // + // If the Flutter Android app targets Android SDK 15 (API 35) or later then the Android + // system will ignore this value unless the app also follows the opt out + // instructions found in + // https://docs.flutter.dev/release/breaking-changes/default-systemuimode-edge-to-edge. + // + // Should not show overlays, swipe from edges to reveal overlays, needs onChange callback + // When the overlays come in on swipe, the app does not receive the gesture and does not know + // the system overlay has changed. The overlays cannot be dismissed, so adding callback + // support will allow users to restore the system ui and dismiss the overlays. + // Not compatible with top/bottom overlays enabled. + enabledOverlays = + View.SYSTEM_UI_FLAG_IMMERSIVE + | View.SYSTEM_UI_FLAG_LAYOUT_STABLE + | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN + | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_FULLSCREEN; + } else if (systemUiMode == PlatformChannel.SystemUiMode.IMMERSIVE_STICKY) { + // STICKY IMMERSIVE + // Available starting at Android SDK 4.4 (API 19). + // + // If the Flutter Android app targets Android SDK 15 (API 35) or later then the Android + // system will ignore this value unless the app also follows the opt out + // instructions found in + // https://docs.flutter.dev/release/breaking-changes/default-systemuimode-edge-to-edge. + // + // Should not show overlays, swipe from edges to reveal overlays. The app will also receive + // the swipe gesture. The overlays cannot be dismissed, so adding callback support will + // allow users to restore the system ui and dismiss the overlays. + // Not compatible with top/bottom overlays enabled. + enabledOverlays = + View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY + | View.SYSTEM_UI_FLAG_LAYOUT_STABLE + | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN + | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_FULLSCREEN; + } else if (systemUiMode == PlatformChannel.SystemUiMode.EDGE_TO_EDGE + && Build.VERSION.SDK_INT >= API_LEVELS.API_29) { + // EDGE TO EDGE + // + // Available starting at Android SDK 10 (API 29). + // + // If the Flutter app targets Android SDK 15 (API 35) or later (Flutter does this by default), + // then this mode is used by default. + // + // SDK 29 and up will apply a translucent body scrim behind 2/3 button navigation bars + // to ensure contrast with buttons on the nav and status bars, unless the contrast is not + // enforced in the overlay styling. + enabledOverlays = + View.SYSTEM_UI_FLAG_LAYOUT_STABLE + | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; + } else { + // When none of the conditions are matched, return without updating the system UI overlays. + return; + } + + mEnabledOverlays = enabledOverlays; + updateSystemUiOverlays(); + } + + private void setSystemChromeEnabledSystemUIOverlays( + List overlaysToShow) { + // Start by assuming we want to hide all system overlays (like an immersive + // game). + int enabledOverlays = + DEFAULT_SYSTEM_UI + | View.SYSTEM_UI_FLAG_FULLSCREEN + | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; + + if (overlaysToShow.size() == 0) { + enabledOverlays |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; + } + + // Re-add any desired system overlays. + for (int i = 0; i < overlaysToShow.size(); ++i) { + PlatformChannel.SystemUiOverlay overlayToShow = overlaysToShow.get(i); + switch (overlayToShow) { + case TOP_OVERLAYS: + enabledOverlays &= ~View.SYSTEM_UI_FLAG_FULLSCREEN; + break; + case BOTTOM_OVERLAYS: + enabledOverlays &= ~View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION; + enabledOverlays &= ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; + break; + } + } + + mEnabledOverlays = enabledOverlays; + updateSystemUiOverlays(); + } + + /** + * Refreshes Android's window system UI (AKA system chrome) to match Flutter's desired {@link + * PlatformChannel.SystemChromeStyle}. + * + *

Updating the system UI Overlays is accomplished by altering the decor view of the {@link + * Window} associated with the {@link android.app.Activity} that was provided to this {@code + * PlatformPlugin}. + */ + public void updateSystemUiOverlays() { + activity.getWindow().getDecorView().setSystemUiVisibility(mEnabledOverlays); + if (currentTheme != null) { + setSystemChromeSystemUIOverlayStyle(currentTheme); + } + } + + private void restoreSystemChromeSystemUIOverlays() { + updateSystemUiOverlays(); + } + + @SuppressWarnings("deprecation") + private void setSystemChromeSystemUIOverlayStyle( + PlatformChannel.SystemChromeStyle systemChromeStyle) { + Window window = activity.getWindow(); + View view = window.getDecorView(); + WindowInsetsControllerCompat windowInsetsControllerCompat = + new WindowInsetsControllerCompat(window, view); + + if (Build.VERSION.SDK_INT < API_LEVELS.API_30) { + // Flag set to specify that this window is responsible for drawing the background for the + // system bars. Must be set for all operations on API < 30 (Android SDK < 11) excluding + // enforcing + // system bar contrasts. Deprecated in API 30. + window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); + + // Flag set to dismiss any requests for translucent system bars to be provided in lieu of what + // is specified by systemChromeStyle. Must be set for all operations on API < 30 operations + // excluding enforcing system bar contrasts. Deprecated in API 30. + window.clearFlags( + WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS + | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); + } + + // SYSTEM STATUS BAR ------------------------------------------------------------------- + // You can't change the color of the system status bar until SDK 21, and you can't change the + // color of the status icons until SDK 23. We only allow both starting at 23 to ensure buttons + // and icons can be visible when changing the background color. + // If transparent, SDK 29 and higher may apply a translucent scrim behind the bar to ensure + // proper contrast. This can be overridden with + // SystemChromeStyle.systemStatusBarContrastEnforced. + if (Build.VERSION.SDK_INT >= API_LEVELS.API_23) { + if (systemChromeStyle.statusBarIconBrightness != null) { + switch (systemChromeStyle.statusBarIconBrightness) { + case DARK: + // Dark status bar icon brightness. + // Light status bar appearance. + windowInsetsControllerCompat.setAppearanceLightStatusBars(true); + break; + case LIGHT: + // Light status bar icon brightness. + // Dark status bar appearance. + windowInsetsControllerCompat.setAppearanceLightStatusBars(false); + break; + } + } + + if (systemChromeStyle.statusBarColor != null) { + window.setStatusBarColor(systemChromeStyle.statusBarColor); + } + } + // You can't override the enforced contrast for a transparent status bar until SDK 29. + // This overrides the translucent scrim that may be placed behind the bar on SDK 29+ to ensure + // contrast is appropriate when using full screen layout modes like Edge to Edge. + if (systemChromeStyle.systemStatusBarContrastEnforced != null + && Build.VERSION.SDK_INT >= API_LEVELS.API_29) { + window.setStatusBarContrastEnforced(systemChromeStyle.systemStatusBarContrastEnforced); + } + + // SYSTEM NAVIGATION BAR -------------------------------------------------------------- + // You can't change the color of the system navigation bar until SDK 21, and you can't change + // the color of the navigation buttons until SDK 26. We only allow both starting at 26 to + // ensure buttons can be visible when changing the background color. + // If transparent, SDK 29 and higher may apply a translucent scrim behind 2/3 button navigation + // bars to ensure proper contrast. This can be overridden with + // SystemChromeStyle.systemNavigationBarContrastEnforced. + if (Build.VERSION.SDK_INT >= API_LEVELS.API_26) { + if (systemChromeStyle.systemNavigationBarIconBrightness != null) { + switch (systemChromeStyle.systemNavigationBarIconBrightness) { + case DARK: + // Dark navigation bar icon brightness. + // Light navigation bar appearance. + windowInsetsControllerCompat.setAppearanceLightNavigationBars(true); + break; + case LIGHT: + // Light navigation bar icon brightness. + // Dark navigation bar appearance. + windowInsetsControllerCompat.setAppearanceLightNavigationBars(false); + break; + } + } + + if (systemChromeStyle.systemNavigationBarColor != null) { + window.setNavigationBarColor(systemChromeStyle.systemNavigationBarColor); + } + } + // You can't change the color of the navigation bar divider color until SDK 28. + if (systemChromeStyle.systemNavigationBarDividerColor != null + && Build.VERSION.SDK_INT >= API_LEVELS.API_28) { + window.setNavigationBarDividerColor(systemChromeStyle.systemNavigationBarDividerColor); + } + + // You can't override the enforced contrast for a transparent navigation bar until SDK 29. + // This overrides the translucent scrim that may be placed behind 2/3 button navigation bars on + // SDK 29+ to ensure contrast is appropriate when using full screen layout modes like + // Edge to Edge. + if (systemChromeStyle.systemNavigationBarContrastEnforced != null + && Build.VERSION.SDK_INT >= API_LEVELS.API_29) { + window.setNavigationBarContrastEnforced( + systemChromeStyle.systemNavigationBarContrastEnforced); + } + + currentTheme = systemChromeStyle; + } + + private void setFrameworkHandlesBack(boolean frameworkHandlesBack) { + if (platformPluginDelegate != null) { + platformPluginDelegate.setFrameworkHandlesBack(frameworkHandlesBack); + } + } + + private void popSystemNavigator() { + if (platformPluginDelegate != null && platformPluginDelegate.popSystemNavigator()) { + // A custom behavior was executed by the delegate. Don't execute default behavior. + return; + } + + if (activity instanceof OnBackPressedDispatcherOwner) { + ((OnBackPressedDispatcherOwner) activity).getOnBackPressedDispatcher().onBackPressed(); + } else { + activity.finish(); + } + } + + private CharSequence getClipboardData(PlatformChannel.ClipboardContentFormat format) { + ClipboardManager clipboard = + (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE); + + if (!clipboard.hasPrimaryClip()) return null; + + CharSequence itemText = null; + try { + ClipData clip = clipboard.getPrimaryClip(); + if (clip == null) return null; + if (format == null || format == PlatformChannel.ClipboardContentFormat.PLAIN_TEXT) { + ClipData.Item item = clip.getItemAt(0); + // First, try getting clipboard data as text; no further processing + // required if so. + itemText = item.getText(); + if (itemText == null) { + // Clipboard data does not contain text, so check whether or not it + // contains a URI to extract text from. + Uri itemUri = item.getUri(); + + if (itemUri == null) { + Log.w( + TAG, "Clipboard item contained no textual content nor a URI to retrieve it from."); + return null; + } + + // Will only try to extract text from URI if it has the content scheme. + String uriScheme = itemUri.getScheme(); + + if (!uriScheme.equals("content")) { + Log.w( + TAG, + "Clipboard item contains a Uri with scheme '" + uriScheme + "'that is unhandled."); + return null; + } + + AssetFileDescriptor assetFileDescriptor = + activity.getContentResolver().openTypedAssetFileDescriptor(itemUri, "text/*", null); + + // Safely return clipboard data coerced into text; will return either + // itemText or text retrieved from its URI. + itemText = item.coerceToText(activity); + if (assetFileDescriptor != null) assetFileDescriptor.close(); + } + + return itemText; + } + } catch (SecurityException e) { + Log.w( + TAG, + "Attempted to get clipboard data that requires additional permission(s).\n" + + "See the exception details for which permission(s) are required, and consider adding them to your Android Manifest as described in:\n" + + "https://developer.android.com/guide/topics/permissions/overview", + e); + return null; + } catch (FileNotFoundException e) { + Log.w(TAG, "Clipboard text was unable to be received from content URI."); + return null; + } catch (IOException e) { + Log.w(TAG, "Failed to close AssetFileDescriptor while trying to read text from URI.", e); + return itemText; + } + + return null; + } + + private void setClipboardData(String text) { + ClipboardManager clipboard = + (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE); + ClipData clip = ClipData.newPlainText("text label?", text); + clipboard.setPrimaryClip(clip); + } + + private boolean clipboardHasStrings() { + ClipboardManager clipboard = + (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE); + // Android 12 introduces a toast message that appears when an app reads the clipboard. To avoid + // unintended access, call the appropriate APIs to receive information about the current content + // that's on the clipboard (rather than the actual content itself). + if (!clipboard.hasPrimaryClip()) { + return false; + } + ClipDescription description = clipboard.getPrimaryClipDescription(); + if (description == null) { + return false; + } + return description.hasMimeType("text/*"); + } + + private void share(@NonNull String text) { + Intent intent = new Intent(); + intent.setAction(Intent.ACTION_SEND); + intent.setType("text/plain"); + intent.putExtra(Intent.EXTRA_TEXT, text); + + activity.startActivity(Intent.createChooser(intent, null)); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformView.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformView.java new file mode 100644 index 0000000000000000000000000000000000000000..d7b3cf52aba91148242234e5d6e42a51db4e8414 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformView.java @@ -0,0 +1,81 @@ +// 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. + +package io.flutter.plugin.platform; + +import android.annotation.SuppressLint; +import android.view.View; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; + +/** A handle to an Android view to be embedded in the Flutter hierarchy. */ +public interface PlatformView { + /** Returns the Android view to be embedded in the Flutter hierarchy. */ + @Nullable + View getView(); + + /** + * Called by the {@link io.flutter.embedding.engine.FlutterEngine} that owns this {@code + * PlatformView} when the Android {@link View} responsible for rendering a Flutter UI is + * associated with the {@link io.flutter.embedding.engine.FlutterEngine}. + * + *

This means that our associated {@link io.flutter.embedding.engine.FlutterEngine} can now + * render a UI and interact with the user. + * + *

Some platform views may have unusual dependencies on the {@link View} that renders Flutter + * UIs, such as unique keyboard interactions. That {@link View} is provided here for those + * purposes. Use of this {@link View} should be avoided if it is not absolutely necessary, because + * depending on this {@link View} will tend to make platform view code more brittle to future + * changes. + */ + // Default interface methods are supported on all min SDK versions of Android. + @SuppressLint("NewApi") + default void onFlutterViewAttached(@NonNull View flutterView) {} + + /** + * Called by the {@link io.flutter.embedding.engine.FlutterEngine} that owns this {@code + * PlatformView} when the Android {@link View} responsible for rendering a Flutter UI is detached + * and disassociated from the {@link io.flutter.embedding.engine.FlutterEngine}. + * + *

This means that our associated {@link io.flutter.embedding.engine.FlutterEngine} no longer + * has a rendering surface, or a user interaction surface of any kind. + * + *

This platform view must release any references related to the Android {@link View} that was + * provided in {@link #onFlutterViewAttached(View)}. + */ + // Default interface methods are supported on all min SDK versions of Android. + @SuppressLint("NewApi") + default void onFlutterViewDetached() {} + + /** + * Dispose this platform view. + * + *

The {@link PlatformView} object is unusable after this method is called. + * + *

Plugins implementing {@link PlatformView} must clear all references to the View object and + * the PlatformView after this method is called. Failing to do so will result in a memory leak. + * + *

References related to the Android {@link View} attached in {@link + * #onFlutterViewAttached(View)} must be released in {@code dispose()} to avoid memory leaks. + */ + void dispose(); + + /** + * Callback fired when the platform's input connection is locked, or should be used. + * + *

This hook only exists for rare cases where the plugin relies on the state of the input + * connection. This probably doesn't need to be implemented. + */ + @SuppressLint("NewApi") + default void onInputConnectionLocked() {} + + /** + * Callback fired when the platform input connection has been unlocked. + * + *

This hook only exists for rare cases where the plugin relies on the state of the input + * connection. This probably doesn't need to be implemented. + */ + @SuppressLint("NewApi") + default void onInputConnectionUnlocked() {} +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewFactory.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..e21ee3897f5558db6e6b25f63467c0786a9bddb2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewFactory.java @@ -0,0 +1,38 @@ +// 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. + +package io.flutter.plugin.platform; + +import android.content.Context; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import io.flutter.plugin.common.MessageCodec; + +public abstract class PlatformViewFactory { + private final MessageCodec createArgsCodec; + + /** @param createArgsCodec the codec used to decode the args parameter of {@link #create}. */ + public PlatformViewFactory(@Nullable MessageCodec createArgsCodec) { + this.createArgsCodec = createArgsCodec; + } + + /** + * Creates a new Android view to be embedded in the Flutter hierarchy. + * + * @param context the context to be used when creating the view, this is different than + * FlutterView's context. + * @param viewId unique identifier for the created instance, this value is known on the Dart side. + * @param args arguments sent from the Flutter app. The bytes for this value are decoded using the + * createArgsCodec argument passed to the constructor. This is null if createArgsCodec was + * null, or no arguments were sent from the Flutter app. + */ + @NonNull + public abstract PlatformView create(Context context, int viewId, @Nullable Object args); + + /** Returns the codec to be used for decoding the args parameter of {@link #create}. */ + @Nullable + public final MessageCodec getCreateArgsCodec() { + return createArgsCodec; + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewRegistry.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewRegistry.java new file mode 100644 index 0000000000000000000000000000000000000000..028b3b1d2eb3f1dfaf9127889637724b7c1cac12 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewRegistry.java @@ -0,0 +1,24 @@ +// 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. + +package io.flutter.plugin.platform; + +import androidx.annotation.NonNull; + +/** + * Registry for platform view factories. + * + *

Plugins can register factories for specific view types. + */ +public interface PlatformViewRegistry { + + /** + * Registers a factory for a platform view. + * + * @param viewTypeId unique identifier for the platform view's type. + * @param factory factory for creating platform views of the specified type. + * @return true if succeeded, false if a factory is already registered for viewTypeId. + */ + boolean registerViewFactory(@NonNull String viewTypeId, @NonNull PlatformViewFactory factory); +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewRegistryImpl.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewRegistryImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..724853998ed4465c4a7cd4ede629b439d473c26e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewRegistryImpl.java @@ -0,0 +1,29 @@ +// 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. + +package io.flutter.plugin.platform; + +import java.util.HashMap; +import java.util.Map; + +public class PlatformViewRegistryImpl implements PlatformViewRegistry { + + PlatformViewRegistryImpl() { + viewFactories = new HashMap<>(); + } + + // Maps a platform view type id to its factory. + private final Map viewFactories; + + @Override + public boolean registerViewFactory(String viewTypeId, PlatformViewFactory factory) { + if (viewFactories.containsKey(viewTypeId)) return false; + viewFactories.put(viewTypeId, factory); + return true; + } + + PlatformViewFactory getFactory(String viewTypeId) { + return viewFactories.get(viewTypeId); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewRenderTarget.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewRenderTarget.java new file mode 100644 index 0000000000000000000000000000000000000000..7cb6c7a784065b4a2a190a445ee7ce7f50ad081a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewRenderTarget.java @@ -0,0 +1,38 @@ +// 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. + +package io.flutter.plugin.platform; + +import android.view.Surface; + +/** + * A PlatformViewRenderTarget interface allows an Android Platform View to be rendered into an + * offscreen buffer (usually a texture is involved) that the engine can compose into the + * FlutterView. + */ +public interface PlatformViewRenderTarget { + // Called when the render target should be resized. + public void resize(int width, int height); + + // Returns the currently specified width. + public int getWidth(); + + // Returns the currently specified height. + public int getHeight(); + + // The id of this render target. + public long getId(); + + // Releases backing resources. + public void release(); + + // Returns true in the case that backing resource have been released. + public boolean isReleased(); + + // Returns the Surface to be rendered on to. + public Surface getSurface(); + + // Schedules a frame to be drawn. + public default void scheduleFrame() {} +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewWrapper.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewWrapper.java new file mode 100644 index 0000000000000000000000000000000000000000..1bce76fd09bbe6b68d3854f1656db9d75d267117 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewWrapper.java @@ -0,0 +1,251 @@ +// 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. + +package io.flutter.plugin.platform; + +import static io.flutter.Build.API_LEVELS; + +import android.annotation.SuppressLint; +import android.annotation.TargetApi; +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Matrix; +import android.graphics.PorterDuff; +import android.graphics.Rect; +import android.view.MotionEvent; +import android.view.Surface; +import android.view.View; +import android.view.ViewParent; +import android.view.ViewTreeObserver; +import android.view.accessibility.AccessibilityEvent; +import android.widget.FrameLayout; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.VisibleForTesting; +import io.flutter.Log; +import io.flutter.embedding.android.AndroidTouchProcessor; +import io.flutter.embedding.engine.renderer.FlutterRenderer; +import io.flutter.util.ViewUtils; + +/** + * Wraps a platform view to intercept gestures and project this view onto a {@link + * PlatformViewRenderTarget}. + * + *

An Android platform view is composed by the engine using a {@code TextureLayer}. The view is + * embeded to the Android view hierarchy like a normal view, but it's projected onto a {@link + * PlatformViewRenderTarget}, so it can be efficiently composed by the engine. + * + *

Since the view is in the Android view hierarchy, keyboard and accessibility interactions + * behave normally. + */ +@TargetApi(API_LEVELS.API_23) +public class PlatformViewWrapper extends FrameLayout { + private static final String TAG = "PlatformViewWrapper"; + + private int prevLeft; + private int prevTop; + private int left; + private int top; + private AndroidTouchProcessor touchProcessor; + private PlatformViewRenderTarget renderTarget; + + private ViewTreeObserver.OnGlobalFocusChangeListener activeFocusListener; + + public PlatformViewWrapper(@NonNull Context context) { + super(context); + setWillNotDraw(false); + } + + public PlatformViewWrapper( + @NonNull Context context, @NonNull PlatformViewRenderTarget renderTarget) { + this(context); + this.renderTarget = renderTarget; + + Surface surface = renderTarget.getSurface(); + if (surface != null && !FlutterRenderer.debugDisableSurfaceClear) { + final Canvas canvas = surface.lockHardwareCanvas(); + try { + canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); + } finally { + surface.unlockCanvasAndPost(canvas); + } + } + } + + /** + * Sets the touch processor that allows to intercept gestures. + * + * @param newTouchProcessor The touch processor. + */ + public void setTouchProcessor(@Nullable AndroidTouchProcessor newTouchProcessor) { + touchProcessor = newTouchProcessor; + } + + /** + * Sets the layout parameters for this view. + * + * @param params The new parameters. + */ + public void setLayoutParams(@NonNull FrameLayout.LayoutParams params) { + super.setLayoutParams(params); + + left = params.leftMargin; + top = params.topMargin; + } + + public void resizeRenderTarget(int width, int height) { + if (renderTarget != null) { + renderTarget.resize(width, height); + } + } + + public int getRenderTargetWidth() { + if (renderTarget != null) { + return renderTarget.getWidth(); + } + return 0; + } + + public int getRenderTargetHeight() { + if (renderTarget != null) { + return renderTarget.getHeight(); + } + return 0; + } + + /** Releases resources. */ + public void release() { + if (renderTarget != null) { + renderTarget.release(); + renderTarget = null; + } + } + + @Override + public boolean onInterceptTouchEvent(@NonNull MotionEvent event) { + return true; + } + + @Override + public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { + final View embeddedView = getChildAt(0); + if (embeddedView != null + && embeddedView.getImportantForAccessibility() + == View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { + return false; + } + // Forward the request only if the embedded view is in the Flutter accessibility tree. + // The embedded view may be ignored when the framework doesn't populate a SemanticNode + // for the current platform view. + // See AccessibilityBridge for more. + return super.requestSendAccessibilityEvent(child, event); + } + + /** Used on Android O+, {@link invalidateChildInParent} used for previous versions. */ + @SuppressLint("NewApi") + @Override + public void onDescendantInvalidated(@NonNull View child, @NonNull View target) { + super.onDescendantInvalidated(child, target); + invalidate(); + } + + @Override + public ViewParent invalidateChildInParent(int[] location, Rect dirty) { + invalidate(); + return super.invalidateChildInParent(location, dirty); + } + + @Override + @SuppressLint("NewApi") + public void draw(Canvas canvas) { + if (renderTarget == null) { + super.draw(canvas); + Log.e(TAG, "Platform view cannot be composed without a RenderTarget."); + return; + } + + final Surface targetSurface = renderTarget.getSurface(); + if (!targetSurface.isValid()) { + Log.e(TAG, "Platform view cannot be composed without a valid RenderTarget surface."); + return; + } + + final Canvas targetCanvas = targetSurface.lockHardwareCanvas(); + if (targetCanvas == null) { + // Cannot render right now. + invalidate(); + return; + } + + try { + // Fill the render target with transparent pixels. This is needed for platform views that + // expect a transparent background. + targetCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); + // Override the canvas that this subtree of views will use to draw. + super.draw(targetCanvas); + } finally { + renderTarget.scheduleFrame(); + targetSurface.unlockCanvasAndPost(targetCanvas); + } + } + + @Override + @SuppressLint("ClickableViewAccessibility") + public boolean onTouchEvent(@NonNull MotionEvent event) { + if (touchProcessor == null) { + return super.onTouchEvent(event); + } + final Matrix screenMatrix = new Matrix(); + switch (event.getAction()) { + case MotionEvent.ACTION_DOWN: + prevLeft = left; + prevTop = top; + screenMatrix.postTranslate(left, top); + break; + case MotionEvent.ACTION_MOVE: + // While the view is dragged, use the left and top positions as + // they were at the moment the touch event fired. + screenMatrix.postTranslate(prevLeft, prevTop); + prevLeft = left; + prevTop = top; + break; + case MotionEvent.ACTION_UP: + default: + screenMatrix.postTranslate(left, top); + break; + } + return touchProcessor.onTouchEvent(event, screenMatrix); + } + + @VisibleForTesting + public ViewTreeObserver.OnGlobalFocusChangeListener getActiveFocusListener() { + return this.activeFocusListener; + } + + public void setOnDescendantFocusChangeListener(@NonNull OnFocusChangeListener userFocusListener) { + unsetOnDescendantFocusChangeListener(); + final ViewTreeObserver observer = getViewTreeObserver(); + if (observer.isAlive() && activeFocusListener == null) { + activeFocusListener = + new ViewTreeObserver.OnGlobalFocusChangeListener() { + @Override + public void onGlobalFocusChanged(View oldFocus, View newFocus) { + userFocusListener.onFocusChange( + PlatformViewWrapper.this, ViewUtils.childHasFocus(PlatformViewWrapper.this)); + } + }; + observer.addOnGlobalFocusChangeListener(activeFocusListener); + } + } + + public void unsetOnDescendantFocusChangeListener() { + final ViewTreeObserver observer = getViewTreeObserver(); + if (observer.isAlive() && activeFocusListener != null) { + final ViewTreeObserver.OnGlobalFocusChangeListener currFocusListener = activeFocusListener; + activeFocusListener = null; + observer.removeOnGlobalFocusChangeListener(currFocusListener); + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewsAccessibilityDelegate.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewsAccessibilityDelegate.java new file mode 100644 index 0000000000000000000000000000000000000000..f1f91ddaa305503f36f04323c569f7ff79f53321 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewsAccessibilityDelegate.java @@ -0,0 +1,39 @@ +// 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. + +package io.flutter.plugin.platform; + +import android.view.View; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import io.flutter.view.AccessibilityBridge; + +/** Facilitates interaction between the accessibility bridge and embedded platform views. */ +public interface PlatformViewsAccessibilityDelegate { + /** + * Returns the root of the view hierarchy for the platform view with the requested id, or null if + * there is no corresponding view. + */ + @Nullable + View getPlatformViewById(int viewId); + + /** Returns true if the platform view uses virtual displays. */ + boolean usesVirtualDisplay(int id); + + /** + * Attaches an accessibility bridge for this platform views accessibility delegate. + * + *

Accessibility events originating in platform views belonging to this delegate will be + * delegated to this accessibility bridge. + */ + void attachAccessibilityBridge(@NonNull AccessibilityBridge accessibilityBridge); + + /** + * Detaches the current accessibility bridge. + * + *

Any accessibility events sent by platform views belonging to this delegate will be ignored + * until a new accessibility bridge is attached. + */ + void detachAccessibilityBridge(); +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewsController.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewsController.java new file mode 100644 index 0000000000000000000000000000000000000000..a8ec08ff5b84c8a152e1a0c980b650a7045b9e78 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewsController.java @@ -0,0 +1,1389 @@ +// 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. + +package io.flutter.plugin.platform; + +import static io.flutter.Build.API_LEVELS; + +import android.annotation.TargetApi; +import android.content.ComponentCallbacks2; +import android.content.Context; +import android.content.MutableContextWrapper; +import android.os.Build; +import android.util.SparseArray; +import android.view.MotionEvent; +import android.view.MotionEvent.PointerCoords; +import android.view.MotionEvent.PointerProperties; +import android.view.SurfaceView; +import android.view.View; +import android.view.ViewGroup; +import android.widget.FrameLayout; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.UiThread; +import androidx.annotation.VisibleForTesting; +import io.flutter.Log; +import io.flutter.embedding.android.AndroidTouchProcessor; +import io.flutter.embedding.android.FlutterView; +import io.flutter.embedding.android.MotionEventTracker; +import io.flutter.embedding.engine.FlutterOverlaySurface; +import io.flutter.embedding.engine.dart.DartExecutor; +import io.flutter.embedding.engine.mutatorsstack.*; +import io.flutter.embedding.engine.renderer.FlutterRenderer; +import io.flutter.embedding.engine.systemchannels.PlatformViewsChannel; +import io.flutter.plugin.editing.TextInputPlugin; +import io.flutter.util.ViewUtils; +import io.flutter.view.AccessibilityBridge; +import io.flutter.view.TextureRegistry; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; + +/** + * Manages platform views. + * + *

Each {@link io.flutter.embedding.engine.FlutterEngine} has a single platform views controller. + * A platform views controller can be attached to at most one Flutter view. + */ +public class PlatformViewsController implements PlatformViewsAccessibilityDelegate { + private static final String TAG = "PlatformViewsController"; + + // These view types allow out-of-band drawing commands that don't notify the Android view + // hierarchy. + // To support these cases, Flutter hosts the embedded view in a VirtualDisplay, + // and binds the VirtualDisplay to a GL texture that is then composed by the engine. + // However, there are a few issues with Virtual Displays. For example, they don't fully support + // accessibility due to https://github.com/flutter/flutter/issues/29717, + // and keyboard interactions may have non-deterministic behavior. + // Views that issue out-of-band drawing commands that aren't included in this array are + // required to call `View#invalidate()` to notify Flutter about the update. + // This isn't ideal, but given all the other limitations it's a reasonable tradeoff. + // Related issue: https://github.com/flutter/flutter/issues/103630 + private static Class[] VIEW_TYPES_REQUIRE_VIRTUAL_DISPLAY = {SurfaceView.class}; + + private final PlatformViewRegistryImpl registry; + + private AndroidTouchProcessor androidTouchProcessor; + + // The context of the Activity or Fragment hosting the render target for the Flutter engine. + private Context context; + + // The View currently rendering the Flutter UI associated with these platform views. + private FlutterView flutterView; + + // The texture registry maintaining the textures into which the embedded views will be rendered. + @VisibleForTesting @Nullable TextureRegistry textureRegistry; + + @Nullable private TextInputPlugin textInputPlugin; + + // The system channel used to communicate with the framework about platform views. + private PlatformViewsChannel platformViewsChannel; + + // The accessibility bridge to which accessibility events form the platform views will be + // dispatched. + private final AccessibilityEventsDelegate accessibilityEventsDelegate; + + // TODO(mattcarroll): Refactor overall platform views to facilitate testing and then make + // this private. This is visible as a hack to facilitate testing. This was deemed the least + // bad option at the time of writing. + @VisibleForTesting /* package */ final HashMap vdControllers; + + // Maps a virtual display's context to the embedded view hosted in this virtual display. + // Since each virtual display has it's unique context this allows associating any view with the + // platform view that + // it is associated with(e.g if a platform view creates other views in the same virtual display. + @VisibleForTesting /* package */ final HashMap contextToEmbeddedView; + + // The platform views. + private final SparseArray platformViews; + + // The platform view wrappers that are appended to FlutterView. + // + // These platform views use a PlatformViewLayer in the framework. This is different than + // the platform views that use a TextureLayer. + // + // This distinction is necessary because a PlatformViewLayer allows to embed Android's + // SurfaceViews in a Flutter app whereas the texture layer is unable to support such native views. + // + // If an entry in `platformViews` doesn't have an entry in this array, the platform view isn't + // in the view hierarchy. + // + // This view provides a wrapper that applies scene builder operations to the platform view. + // For example, a transform matrix, or setting opacity on the platform view layer. + private final SparseArray platformViewParent; + + // Map of unique IDs to views that render overlay layers. + private final SparseArray overlayLayerViews; + + // The platform view wrappers that are appended to FlutterView. + // + // These platform views use a TextureLayer in the framework. This is different than + // the platform views that use a PlatformViewLayer. + // + // This is the default mode, and recommended for better performance. + private final SparseArray viewWrappers; + + // Next available unique ID for use in overlayLayerViews. + private int nextOverlayLayerId = 0; + + // Tracks whether the flutterView has been converted to use a FlutterImageView. + private boolean flutterViewConvertedToImageView = false; + + // When adding platform views using Hybrid Composition, the engine converts the render surface + // to a FlutterImageView to help improve animation synchronization on Android. This flag allows + // disabling this conversion through the PlatformView platform channel. + private boolean synchronizeToNativeViewHierarchy = true; + + // Overlay layer IDs that were displayed since the start of the current frame. + private final HashSet currentFrameUsedOverlayLayerIds; + + // Platform view IDs that were displayed since the start of the current frame. + private final HashSet currentFrameUsedPlatformViewIds; + + // Used to acquire the original motion events using the motionEventIds. + private final MotionEventTracker motionEventTracker; + + // Whether software rendering is used. + private boolean usesSoftwareRendering = false; + + private static boolean enableImageRenderTarget = true; + + private static boolean enableSurfaceProducerRenderTarget = true; + + private final PlatformViewsChannel.PlatformViewsHandler channelHandler = + new PlatformViewsChannel.PlatformViewsHandler() { + + @Override + // TODO(egarciad): Remove the need for this. + // https://github.com/flutter/flutter/issues/96679 + public void createForPlatformViewLayer( + @NonNull PlatformViewsChannel.PlatformViewCreationRequest request) { + // API level 19 is required for `android.graphics.ImageReader`. + enforceMinimumAndroidApiVersion(19); + ensureValidRequest(request); + + final PlatformView platformView = createPlatformView(request, false); + + configureForHybridComposition(platformView, request); + // New code should be added to configureForHybridComposition, not here, unless it is + // not applicable to fallback from TLHC to HC. + } + + @Override + public long createForTextureLayer( + @NonNull PlatformViewsChannel.PlatformViewCreationRequest request) { + ensureValidRequest(request); + final int viewId = request.viewId; + if (viewWrappers.get(viewId) != null) { + throw new IllegalStateException( + "Trying to create an already created platform view, view id: " + viewId); + } + if (textureRegistry == null) { + throw new IllegalStateException( + "Texture registry is null. This means that platform views controller was detached," + + " view id: " + + viewId); + } + if (flutterView == null) { + throw new IllegalStateException( + "Flutter view is null. This means the platform views controller doesn't have an" + + " attached view, view id: " + + viewId); + } + + final PlatformView platformView = createPlatformView(request, true); + + final View embeddedView = platformView.getView(); + if (embeddedView.getParent() != null) { + throw new IllegalStateException( + "The Android view returned from PlatformView#getView() was already added to a" + + " parent view."); + } + + // The newer Texture Layer Hybrid Composition mode isn't suppported if any of the + // following are true: + // - The embedded view contains any of the VIEW_TYPES_REQUIRE_VIRTUAL_DISPLAY view types. + // These views allow out-of-band graphics operations that aren't notified to the Android + // view hierarchy via callbacks such as ViewParent#onDescendantInvalidated(). + // - The API level is <23, due to TLHC implementation API requirements. + final boolean supportsTextureLayerMode = + Build.VERSION.SDK_INT >= API_LEVELS.API_23 + && !ViewUtils.hasChildViewOfType( + embeddedView, VIEW_TYPES_REQUIRE_VIRTUAL_DISPLAY); + + // Fall back to Hybrid Composition or Virtual Display when necessary, depending on which + // fallback mode is requested. + if (!supportsTextureLayerMode) { + if (request.displayMode + == PlatformViewsChannel.PlatformViewCreationRequest.RequestedDisplayMode + .TEXTURE_WITH_HYBRID_FALLBACK) { + configureForHybridComposition(platformView, request); + return PlatformViewsChannel.PlatformViewsHandler.NON_TEXTURE_FALLBACK; + } else if (!usesSoftwareRendering) { // Virtual Display doesn't support software mode. + return configureForVirtualDisplay(platformView, request); + } + // TODO(stuartmorgan): Consider throwing a specific exception here as a breaking change. + // For now, preserve the 3.0 behavior of falling through to Texture Layer mode even + // though it won't work correctly. + } + return configureForTextureLayerComposition(platformView, request); + } + + @Override + public void dispose(int viewId) { + final PlatformView platformView = platformViews.get(viewId); + if (platformView == null) { + Log.e(TAG, "Disposing unknown platform view with id: " + viewId); + return; + } + if (platformView.getView() != null) { + final View embeddedView = platformView.getView(); + final ViewGroup pvParent = (ViewGroup) embeddedView.getParent(); + if (pvParent != null) { + // Eagerly remove the embedded view from the PlatformViewWrapper. + // Without this call, we see some crashes because removing the view + // is used as a signal to stop processing. + pvParent.removeView(embeddedView); + } + } + platformViews.remove(viewId); + try { + platformView.dispose(); + } catch (RuntimeException exception) { + Log.e(TAG, "Disposing platform view threw an exception", exception); + } + if (usesVirtualDisplay(viewId)) { + final VirtualDisplayController vdController = vdControllers.get(viewId); + final View embeddedView = vdController.getView(); + if (embeddedView != null) { + contextToEmbeddedView.remove(embeddedView.getContext()); + } + vdController.dispose(); + vdControllers.remove(viewId); + return; + } + // The platform view is displayed using a TextureLayer and is inserted in the view + // hierarchy. + final PlatformViewWrapper viewWrapper = viewWrappers.get(viewId); + if (viewWrapper != null) { + viewWrapper.removeAllViews(); + viewWrapper.release(); + viewWrapper.unsetOnDescendantFocusChangeListener(); + + final ViewGroup wrapperParent = (ViewGroup) viewWrapper.getParent(); + if (wrapperParent != null) { + wrapperParent.removeView(viewWrapper); + } + viewWrappers.remove(viewId); + return; + } + // The platform view is displayed using a PlatformViewLayer. + final FlutterMutatorView parentView = platformViewParent.get(viewId); + if (parentView != null) { + parentView.removeAllViews(); + parentView.unsetOnDescendantFocusChangeListener(); + + final ViewGroup mutatorViewParent = (ViewGroup) parentView.getParent(); + if (mutatorViewParent != null) { + mutatorViewParent.removeView(parentView); + } + platformViewParent.remove(viewId); + } + } + + @Override + public void offset(int viewId, double top, double left) { + if (usesVirtualDisplay(viewId)) { + // Virtual displays don't need an accessibility offset. + return; + } + // For platform views that use TextureView and are in the view hierarchy, set + // an offset to the wrapper view. + // This ensures that the accessibility highlights are drawn in the expected position on + // screen. + // This offset doesn't affect the position of the embeded view by itself since the GL + // texture is positioned by the Flutter engine, which knows where to position different + // types of layers. + final PlatformViewWrapper viewWrapper = viewWrappers.get(viewId); + if (viewWrapper == null) { + Log.e(TAG, "Setting offset for unknown platform view with id: " + viewId); + return; + } + final int physicalTop = toPhysicalPixels(top); + final int physicalLeft = toPhysicalPixels(left); + final FrameLayout.LayoutParams layoutParams = + (FrameLayout.LayoutParams) viewWrapper.getLayoutParams(); + layoutParams.topMargin = physicalTop; + layoutParams.leftMargin = physicalLeft; + viewWrapper.setLayoutParams(layoutParams); + } + + @Override + public void resize( + @NonNull PlatformViewsChannel.PlatformViewResizeRequest request, + @NonNull PlatformViewsChannel.PlatformViewBufferResized onComplete) { + final int physicalWidth = toPhysicalPixels(request.newLogicalWidth); + final int physicalHeight = toPhysicalPixels(request.newLogicalHeight); + final int viewId = request.viewId; + + if (usesVirtualDisplay(viewId)) { + final float originalDisplayDensity = getDisplayDensity(); + final VirtualDisplayController vdController = vdControllers.get(viewId); + // Resizing involved moving the platform view to a new virtual display. Doing so + // potentially results in losing an active input connection. To make sure we preserve + // the input connection when resizing we lock it here and unlock after the resize is + // complete. + lockInputConnection(vdController); + vdController.resize( + physicalWidth, + physicalHeight, + () -> { + unlockInputConnection(vdController); + // Converting back to logic pixels requires a context, which may no longer be + // available. If that happens, assume the same logic/physical relationship as + // was present when the request arrived. + final float displayDensity = + context == null ? originalDisplayDensity : getDisplayDensity(); + onComplete.run( + new PlatformViewsChannel.PlatformViewBufferSize( + toLogicalPixels(vdController.getRenderTargetWidth(), displayDensity), + toLogicalPixels(vdController.getRenderTargetHeight(), displayDensity))); + }); + return; + } + + final PlatformView platformView = platformViews.get(viewId); + final PlatformViewWrapper viewWrapper = viewWrappers.get(viewId); + if (platformView == null || viewWrapper == null) { + Log.e(TAG, "Resizing unknown platform view with id: " + viewId); + return; + } + // Resize the buffer only when the current buffer size is smaller than the new size. + // This is required to prevent a situation when smooth keyboard animation + // resizes the texture too often, such that the GPU and the platform thread don't agree on + // the timing of the new size. + // Resizing the texture causes pixel stretching since the size of the GL texture used in + // the engine is set by the framework, but the texture buffer size is set by the + // platform down below. + if (physicalWidth > viewWrapper.getRenderTargetWidth() + || physicalHeight > viewWrapper.getRenderTargetHeight()) { + viewWrapper.resizeRenderTarget(physicalWidth, physicalHeight); + } + + final ViewGroup.LayoutParams viewWrapperLayoutParams = viewWrapper.getLayoutParams(); + viewWrapperLayoutParams.width = physicalWidth; + viewWrapperLayoutParams.height = physicalHeight; + viewWrapper.setLayoutParams(viewWrapperLayoutParams); + + final View embeddedView = platformView.getView(); + if (embeddedView != null) { + final ViewGroup.LayoutParams embeddedViewLayoutParams = embeddedView.getLayoutParams(); + embeddedViewLayoutParams.width = physicalWidth; + embeddedViewLayoutParams.height = physicalHeight; + embeddedView.setLayoutParams(embeddedViewLayoutParams); + } + onComplete.run( + new PlatformViewsChannel.PlatformViewBufferSize( + toLogicalPixels(viewWrapper.getRenderTargetWidth()), + toLogicalPixels(viewWrapper.getRenderTargetHeight()))); + } + + @Override + public void onTouch(@NonNull PlatformViewsChannel.PlatformViewTouch touch) { + final int viewId = touch.viewId; + final float density = context.getResources().getDisplayMetrics().density; + + if (usesVirtualDisplay(viewId)) { + final VirtualDisplayController vdController = vdControllers.get(viewId); + final MotionEvent event = toMotionEvent(density, touch, true); + vdController.dispatchTouchEvent(event); + return; + } + + final PlatformView platformView = platformViews.get(viewId); + if (platformView == null) { + Log.e(TAG, "Sending touch to an unknown view with id: " + viewId); + return; + } + final View view = platformView.getView(); + if (view == null) { + Log.e(TAG, "Sending touch to a null view with id: " + viewId); + return; + } + final MotionEvent event = toMotionEvent(density, touch, false); + view.dispatchTouchEvent(event); + } + + @Override + public void setDirection(int viewId, int direction) { + if (!validateDirection(direction)) { + throw new IllegalStateException( + "Trying to set unknown direction value: " + + direction + + "(view id: " + + viewId + + ")"); + } + + View embeddedView; + + if (usesVirtualDisplay(viewId)) { + final VirtualDisplayController controller = vdControllers.get(viewId); + embeddedView = controller.getView(); + } else { + final PlatformView platformView = platformViews.get(viewId); + if (platformView == null) { + Log.e(TAG, "Setting direction to an unknown view with id: " + viewId); + return; + } + embeddedView = platformView.getView(); + } + if (embeddedView == null) { + Log.e(TAG, "Setting direction to a null view with id: " + viewId); + return; + } + embeddedView.setLayoutDirection(direction); + } + + @Override + public void clearFocus(int viewId) { + View embeddedView; + + if (usesVirtualDisplay(viewId)) { + final VirtualDisplayController controller = vdControllers.get(viewId); + embeddedView = controller.getView(); + } else { + final PlatformView platformView = platformViews.get(viewId); + if (platformView == null) { + Log.e(TAG, "Clearing focus on an unknown view with id: " + viewId); + return; + } + embeddedView = platformView.getView(); + } + if (embeddedView == null) { + Log.e(TAG, "Clearing focus on a null view with id: " + viewId); + return; + } + embeddedView.clearFocus(); + } + + @Override + public void synchronizeToNativeViewHierarchy(boolean yes) { + synchronizeToNativeViewHierarchy = yes; + } + }; + + /// Throws an exception if the SDK version is below minSdkVersion. + private void enforceMinimumAndroidApiVersion(int minSdkVersion) { + if (Build.VERSION.SDK_INT < minSdkVersion) { + throw new IllegalStateException( + "Trying to use platform views with API " + + Build.VERSION.SDK_INT + + ", required API level is: " + + minSdkVersion); + } + } + + private void ensureValidRequest( + @NonNull PlatformViewsChannel.PlatformViewCreationRequest request) { + if (!validateDirection(request.direction)) { + throw new IllegalStateException( + "Trying to create a view with unknown direction value: " + + request.direction + + "(view id: " + + request.viewId + + ")"); + } + } + + // Creates a platform view based on `request`, performs configuration that's common to + // all display modes, and adds it to `platformViews`. + @VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE) + public PlatformView createPlatformView( + @NonNull PlatformViewsChannel.PlatformViewCreationRequest request, boolean wrapContext) { + final PlatformViewFactory viewFactory = registry.getFactory(request.viewType); + if (viewFactory == null) { + throw new IllegalStateException( + "Trying to create a platform view of unregistered type: " + request.viewType); + } + + Object createParams = null; + if (request.params != null) { + createParams = viewFactory.getCreateArgsCodec().decodeMessage(request.params); + } + + // In some display modes, the context needs to be modified during display. + // TODO(stuartmorgan): Make this wrapping unconditional if possible; for context see + // https://github.com/flutter/flutter/issues/113449 + final Context mutableContext = wrapContext ? new MutableContextWrapper(context) : context; + final PlatformView platformView = + viewFactory.create(mutableContext, request.viewId, createParams); + + // Configure the view to match the requested layout direction. + final View embeddedView = platformView.getView(); + if (embeddedView == null) { + throw new IllegalStateException( + "PlatformView#getView() returned null, but an Android view reference was expected."); + } + embeddedView.setLayoutDirection(request.direction); + platformViews.put(request.viewId, platformView); + maybeInvokeOnFlutterViewAttached(platformView); + return platformView; + } + + // Configures the view for Hybrid Composition mode. + private void configureForHybridComposition( + @NonNull PlatformView platformView, + @NonNull PlatformViewsChannel.PlatformViewCreationRequest request) { + enforceMinimumAndroidApiVersion(19); + Log.i(TAG, "Using hybrid composition for platform view: " + request.viewId); + } + + // Configures the view for Virtual Display mode, returning the associated texture ID. + private long configureForVirtualDisplay( + @NonNull PlatformView platformView, + @NonNull PlatformViewsChannel.PlatformViewCreationRequest request) { + // This mode adds the view to a virtual display, which is wired up to a GL texture that + // is composed by the Flutter engine. + + // API level 20 is required to use VirtualDisplay#setSurface. + enforceMinimumAndroidApiVersion(20); + + Log.i(TAG, "Hosting view in a virtual display for platform view: " + request.viewId); + + final PlatformViewRenderTarget renderTarget = makePlatformViewRenderTarget(textureRegistry); + final int physicalWidth = toPhysicalPixels(request.logicalWidth); + final int physicalHeight = toPhysicalPixels(request.logicalHeight); + final VirtualDisplayController vdController = + VirtualDisplayController.create( + context, + accessibilityEventsDelegate, + platformView, + renderTarget, + physicalWidth, + physicalHeight, + request.viewId, + null, + (view, hasFocus) -> { + if (hasFocus) { + platformViewsChannel.invokeViewFocused(request.viewId); + } + }); + + if (vdController == null) { + throw new IllegalStateException( + "Failed creating virtual display for a " + + request.viewType + + " with id: " + + request.viewId); + } + + // The embedded view doesn't need to be sized in Virtual Display mode because the + // virtual display itself is sized. + + vdControllers.put(request.viewId, vdController); + final View embeddedView = platformView.getView(); + contextToEmbeddedView.put(embeddedView.getContext(), embeddedView); + + return renderTarget.getId(); + } + + // Configures the view for Texture Layer Hybrid Composition mode, returning the associated + // texture ID. + @TargetApi(API_LEVELS.API_23) + @VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE) + public long configureForTextureLayerComposition( + @NonNull PlatformView platformView, + @NonNull PlatformViewsChannel.PlatformViewCreationRequest request) { + // This mode attaches the view to the Android view hierarchy and record its drawing + // operations, so they can be forwarded to a GL texture that is composed by the + // Flutter engine. + + // API level 23 is required to use Surface#lockHardwareCanvas(). + enforceMinimumAndroidApiVersion(23); + Log.i(TAG, "Hosting view in view hierarchy for platform view: " + request.viewId); + + final int physicalWidth = toPhysicalPixels(request.logicalWidth); + final int physicalHeight = toPhysicalPixels(request.logicalHeight); + PlatformViewWrapper viewWrapper; + long textureId; + if (usesSoftwareRendering) { + viewWrapper = new PlatformViewWrapper(context); + textureId = -1; + } else { + final PlatformViewRenderTarget renderTarget = makePlatformViewRenderTarget(textureRegistry); + viewWrapper = new PlatformViewWrapper(context, renderTarget); + textureId = renderTarget.getId(); + } + viewWrapper.setTouchProcessor(androidTouchProcessor); + viewWrapper.resizeRenderTarget(physicalWidth, physicalHeight); + + final FrameLayout.LayoutParams viewWrapperLayoutParams = + new FrameLayout.LayoutParams(physicalWidth, physicalHeight); + + // Size and position the view wrapper. + final int physicalTop = toPhysicalPixels(request.logicalTop); + final int physicalLeft = toPhysicalPixels(request.logicalLeft); + viewWrapperLayoutParams.topMargin = physicalTop; + viewWrapperLayoutParams.leftMargin = physicalLeft; + viewWrapper.setLayoutParams(viewWrapperLayoutParams); + + // Size the embedded view. + final View embeddedView = platformView.getView(); + embeddedView.setLayoutParams(new FrameLayout.LayoutParams(physicalWidth, physicalHeight)); + + // Accessibility in the embedded view is initially disabled because if a Flutter app + // disabled accessibility in the first frame, the embedding won't receive an update to + // disable accessibility since the embedding never received an update to enable it. + // The AccessibilityBridge keeps track of the accessibility nodes, and handles the deltas + // when the framework sends a new a11y tree to the embedding. + // To prevent races, the framework populate the SemanticsNode after the platform view has + // been created. + embeddedView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); + + // Add the embedded view to the wrapper. + viewWrapper.addView(embeddedView); + + // Listen for focus changed in any subview, so the framework is notified when the platform + // view is focused. + viewWrapper.setOnDescendantFocusChangeListener( + (v, hasFocus) -> { + if (hasFocus) { + platformViewsChannel.invokeViewFocused(request.viewId); + } else if (textInputPlugin != null) { + textInputPlugin.clearPlatformViewClient(request.viewId); + } + }); + + flutterView.addView(viewWrapper); + viewWrappers.append(request.viewId, viewWrapper); + + maybeInvokeOnFlutterViewAttached(platformView); + + return textureId; + } + + /** + * Translates an original touch event to have the same locations as the ones that Flutter + * calculates (because original + flutter's - original = flutter's). + * + * @param originalEvent The saved original input event. + * @param pointerCoords The coordinates that Flutter thinks the touch is happening at. + */ + private static void translateMotionEvent( + MotionEvent originalEvent, PointerCoords[] pointerCoords) { + if (pointerCoords.length < 1) { + return; + } + + float xOffset = pointerCoords[0].x - originalEvent.getX(); + float yOffset = pointerCoords[0].y - originalEvent.getY(); + + originalEvent.offsetLocation(xOffset, yOffset); + } + + @VisibleForTesting + public MotionEvent toMotionEvent( + float density, PlatformViewsChannel.PlatformViewTouch touch, boolean usingVirtualDiplay) { + MotionEventTracker.MotionEventId motionEventId = + MotionEventTracker.MotionEventId.from(touch.motionEventId); + MotionEvent trackedEvent = motionEventTracker.pop(motionEventId); + + // Pointer coordinates in the tracked events are global to FlutterView + // The framework converts them to be local to a widget, given that + // motion events operate on local coords, we need to replace these in the tracked + // event with their local counterparts. + // Compute this early so it can be used as input to translateNonVirtualDisplayMotionEvent. + PointerCoords[] pointerCoords = + parsePointerCoordsList(touch.rawPointerCoords, density) + .toArray(new PointerCoords[touch.pointerCount]); + + if (!usingVirtualDiplay && trackedEvent != null) { + // We have the original event, deliver it after offsetting as it will pass the verifiable + // input check. + translateMotionEvent(trackedEvent, pointerCoords); + return trackedEvent; + } + // We are in virtual display mode or don't have a reference to the original MotionEvent. + // In this case we manually recreate a MotionEvent to be delivered. This MotionEvent + // will fail the verifiable input check. + PointerProperties[] pointerProperties = + parsePointerPropertiesList(touch.rawPointerPropertiesList) + .toArray(new PointerProperties[touch.pointerCount]); + + // TODO (kaushikiska) : warn that we are potentially using an untracked + // event in the platform views. + return MotionEvent.obtain( + touch.downTime.longValue(), + touch.eventTime.longValue(), + touch.action, + touch.pointerCount, + pointerProperties, + pointerCoords, + touch.metaState, + touch.buttonState, + touch.xPrecision, + touch.yPrecision, + touch.deviceId, + touch.edgeFlags, + touch.source, + touch.flags); + } + + public PlatformViewsController() { + registry = new PlatformViewRegistryImpl(); + vdControllers = new HashMap<>(); + accessibilityEventsDelegate = new AccessibilityEventsDelegate(); + contextToEmbeddedView = new HashMap<>(); + overlayLayerViews = new SparseArray<>(); + currentFrameUsedOverlayLayerIds = new HashSet<>(); + currentFrameUsedPlatformViewIds = new HashSet<>(); + viewWrappers = new SparseArray<>(); + platformViews = new SparseArray<>(); + platformViewParent = new SparseArray<>(); + + motionEventTracker = MotionEventTracker.getInstance(); + } + + /** + * Attaches this platform views controller to its input and output channels. + * + * @param context The base context that will be passed to embedded views created by this + * controller. This should be the context of the Activity hosting the Flutter application. + * @param textureRegistry The texture registry which provides the output textures into which the + * embedded views will be rendered. + * @param dartExecutor The dart execution context, which is used to set up a system channel. + */ + public void attach( + @Nullable Context context, + @NonNull TextureRegistry textureRegistry, + @NonNull DartExecutor dartExecutor) { + if (this.context != null) { + throw new AssertionError( + "A PlatformViewsController can only be attached to a single output target.\n" + + "attach was called while the PlatformViewsController was already attached."); + } + this.context = context; + this.textureRegistry = textureRegistry; + platformViewsChannel = new PlatformViewsChannel(dartExecutor); + platformViewsChannel.setPlatformViewsHandler(channelHandler); + } + + /** + * Sets whether Flutter uses software rendering. + * + *

When software rendering is used, no GL context is available on the raster thread. When this + * is set to true, there's no Flutter composition of Android views and Flutter widgets since GL + * textures cannot be used. + * + *

Software rendering is only used for testing in emulators, and it should never be set to true + * in a production environment. + * + * @param useSoftwareRendering Whether software rendering is used. + */ + public void setSoftwareRendering(boolean useSoftwareRendering) { + usesSoftwareRendering = useSoftwareRendering; + } + + /** + * Detaches this platform views controller. + * + *

This is typically called when a Flutter applications moves to run in the background, or is + * destroyed. After calling this the platform views controller will no longer listen to it's + * previous messenger, and will not maintain references to the texture registry, context, and + * messenger passed to the previous attach call. + */ + @UiThread + public void detach() { + if (platformViewsChannel != null) { + platformViewsChannel.setPlatformViewsHandler(null); + } + destroyOverlaySurfaces(); + platformViewsChannel = null; + context = null; + textureRegistry = null; + } + + /** + * Attaches the controller to a {@link FlutterView}. + * + *

When {@link io.flutter.embedding.android.FlutterFragment} is used, this method is called + * after the device rotates since the FlutterView is recreated after a rotation. + */ + public void attachToView(@NonNull FlutterView newFlutterView) { + flutterView = newFlutterView; + // Add wrapper for platform views that use GL texture. + for (int index = 0; index < viewWrappers.size(); index++) { + final PlatformViewWrapper view = viewWrappers.valueAt(index); + flutterView.addView(view); + } + // Add wrapper for platform views that are composed at the view hierarchy level. + for (int index = 0; index < platformViewParent.size(); index++) { + final FlutterMutatorView view = platformViewParent.valueAt(index); + flutterView.addView(view); + } + // Notify platform views that they are now attached to a FlutterView. + for (int index = 0; index < platformViews.size(); index++) { + final PlatformView view = platformViews.valueAt(index); + view.onFlutterViewAttached(flutterView); + } + } + + /** + * Detaches the controller from {@link FlutterView}. + * + *

When {@link io.flutter.embedding.android.FlutterFragment} is used, this method is called + * when the device rotates since the FlutterView is detached from the fragment. The next time the + * fragment needs to be displayed, a new Flutter view is created, so attachToView is called again. + */ + public void detachFromView() { + // Remove wrapper for platform views that use GL texture. + for (int index = 0; index < viewWrappers.size(); index++) { + final PlatformViewWrapper view = viewWrappers.valueAt(index); + flutterView.removeView(view); + } + // Remove wrapper for platform views that are composed at the view hierarchy level. + for (int index = 0; index < platformViewParent.size(); index++) { + final FlutterMutatorView view = platformViewParent.valueAt(index); + flutterView.removeView(view); + } + + destroyOverlaySurfaces(); + removeOverlaySurfaces(); + flutterView = null; + flutterViewConvertedToImageView = false; + + // Notify that the platform view have been detached from FlutterView. + for (int index = 0; index < platformViews.size(); index++) { + final PlatformView view = platformViews.valueAt(index); + view.onFlutterViewDetached(); + } + } + + private void maybeInvokeOnFlutterViewAttached(PlatformView view) { + if (flutterView == null) { + Log.i(TAG, "null flutterView"); + // There is currently no FlutterView that we are attached to. + return; + } + view.onFlutterViewAttached(flutterView); + } + + @Override + public void attachAccessibilityBridge(@NonNull AccessibilityBridge accessibilityBridge) { + accessibilityEventsDelegate.setAccessibilityBridge(accessibilityBridge); + } + + @Override + public void detachAccessibilityBridge() { + accessibilityEventsDelegate.setAccessibilityBridge(null); + } + + /** + * Attaches this controller to a text input plugin. + * + *

While a text input plugin is available, the platform views controller interacts with it to + * facilitate delegation of text input connections to platform views. + * + *

A platform views controller should be attached to a text input plugin whenever it is + * possible for the Flutter framework to receive text input. + */ + public void attachTextInputPlugin(@NonNull TextInputPlugin textInputPlugin) { + this.textInputPlugin = textInputPlugin; + } + + /** Detaches this controller from the currently attached text input plugin. */ + public void detachTextInputPlugin() { + textInputPlugin = null; + } + + /** + * Returns true if Flutter should perform input connection proxying for the view. + * + *

If the view is a platform view managed by this platform views controller returns true. Else + * if the view was created in a platform view's VD, delegates the decision to the platform view's + * {@link View#checkInputConnectionProxy(View)} method. Else returns false. + */ + public boolean checkInputConnectionProxy(@Nullable View view) { + // View can be null on some devices + // See: https://github.com/flutter/flutter/issues/36517 + if (view == null) { + return false; + } + if (!contextToEmbeddedView.containsKey(view.getContext())) { + return false; + } + View platformView = contextToEmbeddedView.get(view.getContext()); + if (platformView == view) { + return true; + } + return platformView.checkInputConnectionProxy(view); + } + + public PlatformViewRegistry getRegistry() { + return registry; + } + + /** + * Invoked when the {@link io.flutter.embedding.engine.FlutterEngine} that owns this {@link + * PlatformViewsController} detaches from JNI. + */ + public void onDetachedFromJNI() { + diposeAllViews(); + } + + public void onPreEngineRestart() { + diposeAllViews(); + } + + @Override + @Nullable + public View getPlatformViewById(int viewId) { + if (usesVirtualDisplay(viewId)) { + final VirtualDisplayController controller = vdControllers.get(viewId); + return controller.getView(); + } + + final PlatformView platformView = platformViews.get(viewId); + if (platformView == null) { + return null; + } + return platformView.getView(); + } + + @Override + public boolean usesVirtualDisplay(int id) { + return vdControllers.containsKey(id); + } + + private void lockInputConnection(@NonNull VirtualDisplayController controller) { + if (textInputPlugin == null) { + return; + } + textInputPlugin.lockPlatformViewInputConnection(); + controller.onInputConnectionLocked(); + } + + private void unlockInputConnection(@NonNull VirtualDisplayController controller) { + if (textInputPlugin == null) { + return; + } + textInputPlugin.unlockPlatformViewInputConnection(); + controller.onInputConnectionUnlocked(); + } + + private static PlatformViewRenderTarget makePlatformViewRenderTarget( + TextureRegistry textureRegistry) { + if (enableSurfaceProducerRenderTarget && Build.VERSION.SDK_INT >= API_LEVELS.API_29) { + TextureRegistry.SurfaceLifecycle lifecycle = + Build.VERSION.SDK_INT <= API_LEVELS.API_34 + ? TextureRegistry.SurfaceLifecycle.resetInBackground + : TextureRegistry.SurfaceLifecycle.manual; + final TextureRegistry.SurfaceProducer textureEntry = + textureRegistry.createSurfaceProducer(lifecycle); + Log.i(TAG, "PlatformView is using SurfaceProducer backend"); + return new SurfaceProducerPlatformViewRenderTarget(textureEntry); + } + if (enableImageRenderTarget && Build.VERSION.SDK_INT >= API_LEVELS.API_29) { + final TextureRegistry.ImageTextureEntry textureEntry = textureRegistry.createImageTexture(); + Log.i(TAG, "PlatformView is using ImageReader backend"); + return new ImageReaderPlatformViewRenderTarget(textureEntry); + } + final TextureRegistry.SurfaceTextureEntry textureEntry = textureRegistry.createSurfaceTexture(); + Log.i(TAG, "PlatformView is using SurfaceTexture backend"); + return new SurfaceTexturePlatformViewRenderTarget(textureEntry); + } + + private static boolean validateDirection(int direction) { + return direction == View.LAYOUT_DIRECTION_LTR || direction == View.LAYOUT_DIRECTION_RTL; + } + + @SuppressWarnings("unchecked") + private static List parsePointerPropertiesList(Object rawPropertiesList) { + List rawProperties = (List) rawPropertiesList; + List pointerProperties = new ArrayList<>(); + for (Object o : rawProperties) { + pointerProperties.add(parsePointerProperties(o)); + } + return pointerProperties; + } + + @SuppressWarnings("unchecked") + private static PointerProperties parsePointerProperties(Object rawProperties) { + List propertiesList = (List) rawProperties; + PointerProperties properties = new MotionEvent.PointerProperties(); + properties.id = (int) propertiesList.get(0); + properties.toolType = (int) propertiesList.get(1); + return properties; + } + + @SuppressWarnings("unchecked") + private static List parsePointerCoordsList(Object rawCoordsList, float density) { + List rawCoords = (List) rawCoordsList; + List pointerCoords = new ArrayList<>(); + for (Object o : rawCoords) { + pointerCoords.add(parsePointerCoords(o, density)); + } + return pointerCoords; + } + + @SuppressWarnings("unchecked") + private static PointerCoords parsePointerCoords(Object rawCoords, float density) { + List coordsList = (List) rawCoords; + PointerCoords coords = new MotionEvent.PointerCoords(); + coords.orientation = (float) (double) coordsList.get(0); + coords.pressure = (float) (double) coordsList.get(1); + coords.size = (float) (double) coordsList.get(2); + coords.toolMajor = (float) ((double) coordsList.get(3) * density); + coords.toolMinor = (float) ((double) coordsList.get(4) * density); + coords.touchMajor = (float) ((double) coordsList.get(5) * density); + coords.touchMinor = (float) ((double) coordsList.get(6) * density); + coords.x = (float) ((double) coordsList.get(7) * density); + coords.y = (float) ((double) coordsList.get(8) * density); + return coords; + } + + private float getDisplayDensity() { + return context.getResources().getDisplayMetrics().density; + } + + private int toPhysicalPixels(double logicalPixels) { + return (int) Math.round(logicalPixels * getDisplayDensity()); + } + + private int toLogicalPixels(double physicalPixels, float displayDensity) { + return (int) Math.round(physicalPixels / displayDensity); + } + + private int toLogicalPixels(double physicalPixels) { + return toLogicalPixels(physicalPixels, getDisplayDensity()); + } + + private void diposeAllViews() { + while (platformViews.size() > 0) { + final int viewId = platformViews.keyAt(0); + // Dispose deletes the entry from platformViews and clears associated resources. + channelHandler.dispose(viewId); + } + } + + // Invoked when the Android system is requesting we reduce memory usage. + public void onTrimMemory(int level) { + if (level < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND) { + return; + } + for (VirtualDisplayController vdc : vdControllers.values()) { + vdc.clearSurface(); + } + } + + // Called after the application has been resumed. + // This is where we undo whatever may have been done in onTrimMemory. + public void onResume() { + for (VirtualDisplayController vdc : vdControllers.values()) { + vdc.resetSurface(); + } + } + + /** + * Disposes a single + * + * @param viewId the PlatformView ID. + */ + @VisibleForTesting + public void disposePlatformView(int viewId) { + channelHandler.dispose(viewId); + } + + private void initializeRootImageViewIfNeeded() { + if (synchronizeToNativeViewHierarchy && !flutterViewConvertedToImageView) { + flutterView.convertToImageView(); + flutterViewConvertedToImageView = true; + } + } + + /** + * Initializes a platform view and adds it to the view hierarchy. + * + * @param viewId The view ID. This member is not intended for public use, and is only visible for + * testing. + */ + @VisibleForTesting + boolean initializePlatformViewIfNeeded(int viewId) { + final PlatformView platformView = platformViews.get(viewId); + if (platformView == null) { + return false; + } + if (platformViewParent.get(viewId) != null) { + return true; + } + final View embeddedView = platformView.getView(); + if (embeddedView == null) { + throw new IllegalStateException( + "PlatformView#getView() returned null, but an Android view reference was expected."); + } + if (embeddedView.getParent() != null) { + throw new IllegalStateException( + "The Android view returned from PlatformView#getView() was already added to a parent" + + " view."); + } + final FlutterMutatorView parentView = + new FlutterMutatorView( + context, context.getResources().getDisplayMetrics().density, androidTouchProcessor); + + parentView.setOnDescendantFocusChangeListener( + (view, hasFocus) -> { + if (hasFocus) { + platformViewsChannel.invokeViewFocused(viewId); + } else if (textInputPlugin != null) { + textInputPlugin.clearPlatformViewClient(viewId); + } + }); + + platformViewParent.put(viewId, parentView); + + // Accessibility in the embedded view is initially disabled because if a Flutter app disabled + // accessibility in the first frame, the embedding won't receive an update to disable + // accessibility since the embedding never received an update to enable it. + // The AccessibilityBridge keeps track of the accessibility nodes, and handles the deltas when + // the framework sends a new a11y tree to the embedding. + // To prevent races, the framework populate the SemanticsNode after the platform view has been + // created. + embeddedView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); + + parentView.addView(embeddedView); + flutterView.addView(parentView); + return true; + } + + public void attachToFlutterRenderer(@NonNull FlutterRenderer flutterRenderer) { + androidTouchProcessor = new AndroidTouchProcessor(flutterRenderer, /*trackMotionEvents=*/ true); + } + + /** + * Called when a platform view id displayed in the current frame. + * + * @param viewId The ID of the platform view. + * @param x The left position relative to {@code FlutterView}. + * @param y The top position relative to {@code FlutterView}. + * @param width The width of the platform view. + * @param height The height of the platform view. + * @param viewWidth The original width of the platform view before applying the mutator stack. + * @param viewHeight The original height of the platform view before applying the mutator stack. + * @param mutatorsStack The mutator stack. This member is not intended for public use, and is only + * visible for testing. + */ + public void onDisplayPlatformView( + int viewId, + int x, + int y, + int width, + int height, + int viewWidth, + int viewHeight, + @NonNull FlutterMutatorsStack mutatorsStack) { + initializeRootImageViewIfNeeded(); + if (!initializePlatformViewIfNeeded(viewId)) { + return; + } + + final FlutterMutatorView parentView = platformViewParent.get(viewId); + parentView.readyToDisplay(mutatorsStack, x, y, width, height); + parentView.setVisibility(View.VISIBLE); + parentView.bringToFront(); + + final FrameLayout.LayoutParams layoutParams = + new FrameLayout.LayoutParams(viewWidth, viewHeight); + final View view = platformViews.get(viewId).getView(); + if (view != null) { + view.setLayoutParams(layoutParams); + view.bringToFront(); + } + currentFrameUsedPlatformViewIds.add(viewId); + } + + /** + * Called when an overlay surface is displayed in the current frame. + * + * @param id The ID of the surface. + * @param x The left position relative to {@code FlutterView}. + * @param y The top position relative to {@code FlutterView}. + * @param width The width of the surface. + * @param height The height of the surface. This member is not intended for public use, and is + * only visible for testing. + */ + public void onDisplayOverlaySurface(int id, int x, int y, int width, int height) { + if (overlayLayerViews.get(id) == null) { + throw new IllegalStateException("The overlay surface (id:" + id + ") doesn't exist"); + } + initializeRootImageViewIfNeeded(); + + final PlatformOverlayView overlayView = overlayLayerViews.get(id); + if (overlayView.getParent() == null) { + flutterView.addView(overlayView); + } + + FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams((int) width, (int) height); + layoutParams.leftMargin = (int) x; + layoutParams.topMargin = (int) y; + overlayView.setLayoutParams(layoutParams); + overlayView.setVisibility(View.VISIBLE); + overlayView.bringToFront(); + currentFrameUsedOverlayLayerIds.add(id); + } + + public void onBeginFrame() { + currentFrameUsedOverlayLayerIds.clear(); + currentFrameUsedPlatformViewIds.clear(); + } + + /** + * Called by {@code FlutterJNI} when the Flutter frame was submitted. + * + *

This member is not intended for public use, and is only visible for testing. + */ + public void onEndFrame() { + // If there are no platform views in the current frame, + // then revert the image view surface and use the previous surface. + // + // Otherwise, acquire the latest image. + if (flutterViewConvertedToImageView && currentFrameUsedPlatformViewIds.isEmpty()) { + flutterViewConvertedToImageView = false; + flutterView.revertImageView( + () -> { + // Destroy overlay surfaces once the surface reversion is completed. + finishFrame(false); + }); + return; + } + // Whether the current frame was rendered using ImageReaders. + // + // Since the image readers may not have images available at this point, + // this becomes true if all the required surfaces have images available. + // + // This is used to decide if the platform views can be rendered in the current frame. + // If one of the surfaces doesn't have an image, the frame may be incomplete and must be + // dropped. + // For example, a toolbar widget painted by Flutter may not be rendered. + final boolean isFrameRenderedUsingImageReaders = + flutterViewConvertedToImageView && flutterView.acquireLatestImageViewFrame(); + finishFrame(isFrameRenderedUsingImageReaders); + } + + private void finishFrame(boolean isFrameRenderedUsingImageReaders) { + for (int i = 0; i < overlayLayerViews.size(); i++) { + final int overlayId = overlayLayerViews.keyAt(i); + final PlatformOverlayView overlayView = overlayLayerViews.valueAt(i); + + if (currentFrameUsedOverlayLayerIds.contains(overlayId)) { + flutterView.attachOverlaySurfaceToRender(overlayView); + final boolean didAcquireOverlaySurfaceImage = overlayView.acquireLatestImage(); + isFrameRenderedUsingImageReaders &= didAcquireOverlaySurfaceImage; + } else { + // If the background surface isn't rendered by the image view, then the + // overlay surfaces can be detached from the rendered. + // This releases resources used by the ImageReader. + if (!flutterViewConvertedToImageView) { + overlayView.detachFromRenderer(); + } + // Hide overlay surfaces that aren't rendered in the current frame. + overlayView.setVisibility(View.GONE); + flutterView.removeView(overlayView); + } + } + + for (int i = 0; i < platformViewParent.size(); i++) { + final int viewId = platformViewParent.keyAt(i); + final View parentView = platformViewParent.get(viewId); + + // This should only show platform views that are rendered in this frame and either: + // 1. Surface has images available in this frame or, + // 2. Surface does not have images available in this frame because the render surface should + // not be an ImageView. + // + // The platform view is appended to a mutator view. + // + // Otherwise, hide the platform view, but don't remove it from the view hierarchy yet as + // they are removed when the framework disposes the platform view widget. + if (currentFrameUsedPlatformViewIds.contains(viewId) + && (isFrameRenderedUsingImageReaders || !synchronizeToNativeViewHierarchy)) { + parentView.setVisibility(View.VISIBLE); + } else { + parentView.setVisibility(View.GONE); + } + } + } + + /** + * Creates and tracks the overlay surface. + * + * @param imageView The surface that displays the overlay. + * @return Wrapper object that provides the layer id and the surface. This member is not intended + * for public use, and is only visible for testing. + */ + @VisibleForTesting + @NonNull + public FlutterOverlaySurface createOverlaySurface(@NonNull PlatformOverlayView imageView) { + final int id = nextOverlayLayerId++; + overlayLayerViews.put(id, imageView); + return new FlutterOverlaySurface(id, imageView.getSurface()); + } + + /** + * Creates an overlay surface while the Flutter view is rendered by {@code PlatformOverlayView}. + * + *

This method is invoked by {@code FlutterJNI} only. + * + *

This member is not intended for public use, and is only visible for testing. + */ + @NonNull + public FlutterOverlaySurface createOverlaySurface() { + // Overlay surfaces have the same size as the background surface. + // + // This allows to reuse these surfaces in consecutive frames even + // if the drawings they contain have a different tight bound. + // + // The final view size is determined when its frame is set. + return createOverlaySurface( + new PlatformOverlayView( + flutterView.getContext(), + flutterView.getWidth(), + flutterView.getHeight(), + accessibilityEventsDelegate)); + } + + /** + * Destroys the overlay surfaces and removes them from the view hierarchy. + * + *

This method is used only internally by {@code FlutterJNI}. + */ + public void destroyOverlaySurfaces() { + for (int viewId = 0; viewId < overlayLayerViews.size(); viewId++) { + final PlatformOverlayView overlayView = overlayLayerViews.valueAt(viewId); + overlayView.detachFromRenderer(); + overlayView.closeImageReader(); + // Don't remove overlayView from the view hierarchy since this method can + // be called while the Android framework is iterating over the array of views. + // See ViewGroup#dispatchDetachedFromWindow(), and + // https://github.com/flutter/flutter/issues/97679. + } + } + + private void removeOverlaySurfaces() { + if (flutterView == null) { + Log.e(TAG, "removeOverlaySurfaces called while flutter view is null"); + return; + } + for (int viewId = 0; viewId < overlayLayerViews.size(); viewId++) { + flutterView.removeView(overlayLayerViews.valueAt(viewId)); + } + overlayLayerViews.clear(); + } + + @VisibleForTesting + public SparseArray getOverlayLayerViews() { + return overlayLayerViews; + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewsController2.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewsController2.java new file mode 100644 index 0000000000000000000000000000000000000000..0410141191ddf2f8e7ef24e7ebbdbbba1ddcaf7b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewsController2.java @@ -0,0 +1,723 @@ +// 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. + +package io.flutter.plugin.platform; + +import static io.flutter.Build.API_LEVELS; + +import android.annotation.TargetApi; +import android.content.Context; +import android.graphics.PixelFormat; +import android.util.SparseArray; +import android.view.MotionEvent; +import android.view.MotionEvent.PointerCoords; +import android.view.MotionEvent.PointerProperties; +import android.view.Surface; +import android.view.SurfaceControl; +import android.view.View; +import android.view.ViewGroup; +import android.widget.FrameLayout; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.RequiresApi; +import androidx.annotation.UiThread; +import androidx.annotation.VisibleForTesting; +import io.flutter.Log; +import io.flutter.embedding.android.AndroidTouchProcessor; +import io.flutter.embedding.android.FlutterView; +import io.flutter.embedding.android.MotionEventTracker; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.FlutterOverlaySurface; +import io.flutter.embedding.engine.dart.DartExecutor; +import io.flutter.embedding.engine.mutatorsstack.*; +import io.flutter.embedding.engine.renderer.FlutterRenderer; +import io.flutter.embedding.engine.systemchannels.PlatformViewsChannel2; +import io.flutter.plugin.editing.TextInputPlugin; +import io.flutter.view.AccessibilityBridge; +import java.util.ArrayList; +import java.util.List; + +/** + * Manages platform views. + * + *

Each {@link io.flutter.embedding.engine.FlutterEngine} has a single platform views controller. + * A platform views controller can be attached to at most one Flutter view. + */ +public class PlatformViewsController2 implements PlatformViewsAccessibilityDelegate { + private static final String TAG = "PlatformViewsController2"; + + private PlatformViewRegistryImpl registry; + private AndroidTouchProcessor androidTouchProcessor; + private Context context; + private FlutterView flutterView; + private FlutterJNI flutterJNI = null; + + @Nullable private TextInputPlugin textInputPlugin; + + private PlatformViewsChannel2 platformViewsChannel; + private final AccessibilityEventsDelegate accessibilityEventsDelegate; + + private final SparseArray platformViews; + private final SparseArray platformViewParent; + private final MotionEventTracker motionEventTracker; + + private final ArrayList pendingTransactions; + private final ArrayList activeTransactions; + private Surface overlayerSurface = null; + private SurfaceControl overlaySurfaceControl = null; + + public PlatformViewsController2() { + accessibilityEventsDelegate = new AccessibilityEventsDelegate(); + platformViews = new SparseArray<>(); + platformViewParent = new SparseArray<>(); + pendingTransactions = new ArrayList<>(); + activeTransactions = new ArrayList<>(); + motionEventTracker = MotionEventTracker.getInstance(); + } + + public void setRegistry(@NonNull PlatformViewRegistry registry) { + this.registry = (PlatformViewRegistryImpl) registry; + } + + /** Whether the SurfaceControl swapchain mode is enabled. */ + public void setFlutterJNI(FlutterJNI flutterJNI) { + this.flutterJNI = flutterJNI; + } + + @Override + public boolean usesVirtualDisplay(int id) { + return false; + } + + public PlatformView createFlutterPlatformView( + @NonNull PlatformViewsChannel2.PlatformViewCreationRequest request) { + final PlatformViewFactory viewFactory = registry.getFactory(request.viewType); + if (viewFactory == null) { + throw new IllegalStateException( + "Trying to create a platform view of unregistered type: " + request.viewType); + } + + Object createParams = null; + if (request.params != null) { + createParams = viewFactory.getCreateArgsCodec().decodeMessage(request.params); + } + final PlatformView platformView = viewFactory.create(context, request.viewId, createParams); + + // Configure the view to match the requested layout direction. + final View embeddedView = platformView.getView(); + if (embeddedView == null) { + throw new IllegalStateException( + "PlatformView#getView() returned null, but an Android view reference was expected."); + } + embeddedView.setLayoutDirection(request.direction); + platformViews.put(request.viewId, platformView); + maybeInvokeOnFlutterViewAttached(platformView); + return platformView; + } + + /** + * Translates an original touch event to have the same locations as the ones that Flutter + * calculates (because original + flutter's - original = flutter's). + * + * @param originalEvent The saved original input event. + * @param pointerCoords The coordinates that Flutter thinks the touch is happening at. + */ + private static void translateMotionEvent( + MotionEvent originalEvent, PointerCoords[] pointerCoords) { + if (pointerCoords.length < 1) { + return; + } + + float xOffset = pointerCoords[0].x - originalEvent.getX(); + float yOffset = pointerCoords[0].y - originalEvent.getY(); + + originalEvent.offsetLocation(xOffset, yOffset); + } + + @VisibleForTesting + public MotionEvent toMotionEvent(float density, PlatformViewsChannel2.PlatformViewTouch touch) { + MotionEventTracker.MotionEventId motionEventId = + MotionEventTracker.MotionEventId.from(touch.motionEventId); + MotionEvent trackedEvent = motionEventTracker.pop(motionEventId); + + // Pointer coordinates in the tracked events are global to FlutterView + // The framework converts them to be local to a widget, given that + // motion events operate on local coords, we need to replace these in the tracked + // event with their local counterparts. + // Compute this early so it can be used as input to translateNonVirtualDisplayMotionEvent. + PointerCoords[] pointerCoords = + parsePointerCoordsList(touch.rawPointerCoords, density) + .toArray(new PointerCoords[touch.pointerCount]); + + if (trackedEvent != null) { + // We have the original event, deliver it after offsetting as it will pass the verifiable + // input check. + translateMotionEvent(trackedEvent, pointerCoords); + return trackedEvent; + } + // We don't have a reference to the original MotionEvent. + // In this case we manually recreate a MotionEvent to be delivered. This MotionEvent + // will fail the verifiable input check. + PointerProperties[] pointerProperties = + parsePointerPropertiesList(touch.rawPointerPropertiesList) + .toArray(new PointerProperties[touch.pointerCount]); + + return MotionEvent.obtain( + touch.downTime.longValue(), + touch.eventTime.longValue(), + touch.action, + touch.pointerCount, + pointerProperties, + pointerCoords, + touch.metaState, + touch.buttonState, + touch.xPrecision, + touch.yPrecision, + touch.deviceId, + touch.edgeFlags, + touch.source, + touch.flags); + } + + /** + * Attaches this platform views controller to its input and output channels. + * + * @param context The base context that will be passed to embedded views created by this + * controller. This should be the context of the Activity hosting the Flutter application. + * @param dartExecutor The dart execution context, which is used to set up a system channel. + */ + public void attach(@Nullable Context context, @NonNull DartExecutor dartExecutor) { + if (this.context != null) { + throw new AssertionError( + "A PlatformViewsController can only be attached to a single output target.\n" + + "attach was called while the PlatformViewsController was already attached."); + } + this.context = context; + platformViewsChannel = new PlatformViewsChannel2(dartExecutor); + platformViewsChannel.setPlatformViewsHandler(channelHandler); + } + + /** + * Detaches this platform views controller. + * + *

This is typically called when a Flutter applications moves to run in the background, or is + * destroyed. After calling this the platform views controller will no longer listen to it's + * previous messenger, and will not maintain references to the texture registry, context, and + * messenger passed to the previous attach call. + */ + @UiThread + public void detach() { + if (platformViewsChannel != null) { + platformViewsChannel.setPlatformViewsHandler(null); + } + destroyOverlaySurface(); + platformViewsChannel = null; + context = null; + } + + /** + * Attaches the controller to a {@link FlutterView}. + * + *

When {@link io.flutter.embedding.android.FlutterFragment} is used, this method is called + * after the device rotates since the FlutterView is recreated after a rotation. + */ + public void attachToView(@NonNull FlutterView newFlutterView) { + flutterView = newFlutterView; + // Add wrapper for platform views that are composed at the view hierarchy level. + for (int index = 0; index < platformViewParent.size(); index++) { + final FlutterMutatorView view = platformViewParent.valueAt(index); + flutterView.addView(view); + } + // Notify platform views that they are now attached to a FlutterView. + for (int index = 0; index < platformViews.size(); index++) { + final PlatformView view = platformViews.valueAt(index); + view.onFlutterViewAttached(flutterView); + } + } + + /** + * Detaches the controller from {@link FlutterView}. + * + *

When {@link io.flutter.embedding.android.FlutterFragment} is used, this method is called + * when the device rotates since the FlutterView is detached from the fragment. The next time the + * fragment needs to be displayed, a new Flutter view is created, so attachToView is called again. + */ + public void detachFromView() { + // Remove wrapper for platform views that are composed at the view hierarchy level. + for (int index = 0; index < platformViewParent.size(); index++) { + final FlutterMutatorView view = platformViewParent.valueAt(index); + flutterView.removeView(view); + } + + destroyOverlaySurface(); + flutterView = null; + + // Notify that the platform view have been detached from FlutterView. + for (int index = 0; index < platformViews.size(); index++) { + final PlatformView view = platformViews.valueAt(index); + view.onFlutterViewDetached(); + } + } + + private void maybeInvokeOnFlutterViewAttached(PlatformView view) { + if (flutterView == null) { + Log.i(TAG, "null flutterView"); + // There is currently no FlutterView that we are attached to. + return; + } + view.onFlutterViewAttached(flutterView); + } + + @Override + public void attachAccessibilityBridge(@NonNull AccessibilityBridge accessibilityBridge) { + accessibilityEventsDelegate.setAccessibilityBridge(accessibilityBridge); + } + + @Override + public void detachAccessibilityBridge() { + accessibilityEventsDelegate.setAccessibilityBridge(null); + } + + /** + * Attaches this controller to a text input plugin. + * + *

While a text input plugin is available, the platform views controller interacts with it to + * facilitate delegation of text input connections to platform views. + * + *

A platform views controller should be attached to a text input plugin whenever it is + * possible for the Flutter framework to receive text input. + */ + public void attachTextInputPlugin(@NonNull TextInputPlugin textInputPlugin) { + this.textInputPlugin = textInputPlugin; + } + + /** Detaches this controller from the currently attached text input plugin. */ + public void detachTextInputPlugin() { + textInputPlugin = null; + } + + public PlatformViewRegistry getRegistry() { + return registry; + } + + /** + * Invoked when the {@link io.flutter.embedding.engine.FlutterEngine} that owns this {@link + * PlatformViewsController} detaches from JNI. + */ + public void onDetachedFromJNI() { + diposeAllViews(); + } + + public void onPreEngineRestart() { + diposeAllViews(); + } + + @Override + @Nullable + public View getPlatformViewById(int viewId) { + final PlatformView platformView = platformViews.get(viewId); + if (platformView == null) { + return null; + } + return platformView.getView(); + } + + private void lockInputConnection(@NonNull VirtualDisplayController controller) { + if (textInputPlugin == null) { + return; + } + textInputPlugin.lockPlatformViewInputConnection(); + controller.onInputConnectionLocked(); + } + + private void unlockInputConnection(@NonNull VirtualDisplayController controller) { + if (textInputPlugin == null) { + return; + } + textInputPlugin.unlockPlatformViewInputConnection(); + controller.onInputConnectionUnlocked(); + } + + private static boolean validateDirection(int direction) { + return direction == View.LAYOUT_DIRECTION_LTR || direction == View.LAYOUT_DIRECTION_RTL; + } + + @SuppressWarnings("unchecked") + private static List parsePointerPropertiesList(Object rawPropertiesList) { + List rawProperties = (List) rawPropertiesList; + List pointerProperties = new ArrayList<>(); + for (Object o : rawProperties) { + pointerProperties.add(parsePointerProperties(o)); + } + return pointerProperties; + } + + @SuppressWarnings("unchecked") + private static PointerProperties parsePointerProperties(Object rawProperties) { + List propertiesList = (List) rawProperties; + PointerProperties properties = new MotionEvent.PointerProperties(); + properties.id = (int) propertiesList.get(0); + properties.toolType = (int) propertiesList.get(1); + return properties; + } + + @SuppressWarnings("unchecked") + private static List parsePointerCoordsList(Object rawCoordsList, float density) { + List rawCoords = (List) rawCoordsList; + List pointerCoords = new ArrayList<>(); + for (Object o : rawCoords) { + pointerCoords.add(parsePointerCoords(o, density)); + } + return pointerCoords; + } + + @SuppressWarnings("unchecked") + private static PointerCoords parsePointerCoords(Object rawCoords, float density) { + List coordsList = (List) rawCoords; + PointerCoords coords = new MotionEvent.PointerCoords(); + coords.orientation = (float) (double) coordsList.get(0); + coords.pressure = (float) (double) coordsList.get(1); + coords.size = (float) (double) coordsList.get(2); + coords.toolMajor = (float) ((double) coordsList.get(3) * density); + coords.toolMinor = (float) ((double) coordsList.get(4) * density); + coords.touchMajor = (float) ((double) coordsList.get(5) * density); + coords.touchMinor = (float) ((double) coordsList.get(6) * density); + coords.x = (float) ((double) coordsList.get(7) * density); + coords.y = (float) ((double) coordsList.get(8) * density); + return coords; + } + + private float getDisplayDensity() { + return context.getResources().getDisplayMetrics().density; + } + + private int toPhysicalPixels(double logicalPixels) { + return (int) Math.round(logicalPixels * getDisplayDensity()); + } + + private int toLogicalPixels(double physicalPixels, float displayDensity) { + return (int) Math.round(physicalPixels / displayDensity); + } + + private int toLogicalPixels(double physicalPixels) { + return toLogicalPixels(physicalPixels, getDisplayDensity()); + } + + private void diposeAllViews() { + while (platformViews.size() > 0) { + final int viewId = platformViews.keyAt(0); + // Dispose deletes the entry from platformViews and clears associated resources. + channelHandler.dispose(viewId); + } + } + + /** + * Disposes a single + * + * @param viewId the PlatformView ID. + */ + @VisibleForTesting + public void disposePlatformView(int viewId) { + channelHandler.dispose(viewId); + } + + /** + * Initializes a platform view and adds it to the view hierarchy. + * + * @param viewId The view ID. This member is not intended for public use, and is only visible for + * testing. + */ + @VisibleForTesting + boolean initializePlatformViewIfNeeded(int viewId) { + final PlatformView platformView = platformViews.get(viewId); + if (platformView == null) { + return false; + } + if (platformViewParent.get(viewId) != null) { + return true; + } + final View embeddedView = platformView.getView(); + if (embeddedView == null) { + throw new IllegalStateException( + "PlatformView#getView() returned null, but an Android view reference was expected."); + } + if (embeddedView.getParent() != null) { + throw new IllegalStateException( + "The Android view returned from PlatformView#getView() was already added to a parent" + + " view."); + } + final FlutterMutatorView parentView = + new FlutterMutatorView( + context, context.getResources().getDisplayMetrics().density, androidTouchProcessor); + + parentView.setOnDescendantFocusChangeListener( + (view, hasFocus) -> { + if (hasFocus) { + platformViewsChannel.invokeViewFocused(viewId); + } else if (textInputPlugin != null) { + textInputPlugin.clearPlatformViewClient(viewId); + } + }); + + platformViewParent.put(viewId, parentView); + + // Accessibility in the embedded view is initially disabled because if a Flutter app disabled + // accessibility in the first frame, the embedding won't receive an update to disable + // accessibility since the embedding never received an update to enable it. + // The AccessibilityBridge keeps track of the accessibility nodes, and handles the deltas when + // the framework sends a new a11y tree to the embedding. + // To prevent races, the framework populate the SemanticsNode after the platform view has been + // created. + embeddedView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); + + parentView.addView(embeddedView); + flutterView.addView(parentView); + return true; + } + + public void attachToFlutterRenderer(@NonNull FlutterRenderer flutterRenderer) { + androidTouchProcessor = new AndroidTouchProcessor(flutterRenderer, /*trackMotionEvents=*/ true); + } + + /** + * Called when a platform view id displayed in the current frame. + * + * @param viewId The ID of the platform view. + * @param x The left position relative to {@code FlutterView}. + * @param y The top position relative to {@code FlutterView}. + * @param width The width of the platform view. + * @param height The height of the platform view. + * @param viewWidth The original width of the platform view before applying the mutator stack. + * @param viewHeight The original height of the platform view before applying the mutator stack. + * @param mutatorsStack The mutator stack. This member is not intended for public use, and is only + * visible for testing. + */ + public void onDisplayPlatformView( + int viewId, + int x, + int y, + int width, + int height, + int viewWidth, + int viewHeight, + @NonNull FlutterMutatorsStack mutatorsStack) { + if (!initializePlatformViewIfNeeded(viewId)) { + return; + } + + final FlutterMutatorView parentView = platformViewParent.get(viewId); + parentView.readyToDisplay(mutatorsStack, x, y, width, height); + parentView.setVisibility(View.VISIBLE); + parentView.bringToFront(); + + final FrameLayout.LayoutParams layoutParams = + new FrameLayout.LayoutParams(viewWidth, viewHeight); + final View view = platformViews.get(viewId).getView(); + if (view != null) { + view.setLayoutParams(layoutParams); + view.bringToFront(); + } + } + + @TargetApi(API_LEVELS.API_34) + @RequiresApi(API_LEVELS.API_34) + public void onEndFrame() { + SurfaceControl.Transaction tx = new SurfaceControl.Transaction(); + for (int i = 0; i < activeTransactions.size(); i++) { + tx = tx.merge(activeTransactions.get(i)); + } + activeTransactions.clear(); + flutterView.invalidate(); + flutterView.getRootSurfaceControl().applyTransactionOnDraw(tx); + } + + // NOT called from UI thread. + public synchronized void swapTransactions() { + activeTransactions.clear(); + for (int i = 0; i < pendingTransactions.size(); i++) { + activeTransactions.add(pendingTransactions.get(i)); + } + pendingTransactions.clear(); + } + + // NOT called from UI thread. + @TargetApi(API_LEVELS.API_34) + @RequiresApi(API_LEVELS.API_34) + public SurfaceControl.Transaction createTransaction() { + SurfaceControl.Transaction tx = new SurfaceControl.Transaction(); + pendingTransactions.add(tx); + return tx; + } + + // NOT called from UI thread. + @TargetApi(API_LEVELS.API_34) + @RequiresApi(API_LEVELS.API_34) + public void applyTransactions() { + SurfaceControl.Transaction tx = new SurfaceControl.Transaction(); + for (int i = 0; i < pendingTransactions.size(); i++) { + tx = tx.merge(pendingTransactions.get(i)); + } + tx.apply(); + pendingTransactions.clear(); + } + + @TargetApi(API_LEVELS.API_34) + @RequiresApi(API_LEVELS.API_34) + public FlutterOverlaySurface createOverlaySurface() { + if (overlayerSurface == null) { + final SurfaceControl.Builder surfaceControlBuilder = new SurfaceControl.Builder(); + surfaceControlBuilder.setBufferSize(flutterView.getWidth(), flutterView.getHeight()); + surfaceControlBuilder.setFormat(PixelFormat.RGBA_8888); + surfaceControlBuilder.setName("Flutter Overlay Surface"); + surfaceControlBuilder.setOpaque(false); + surfaceControlBuilder.setHidden(false); + final SurfaceControl surfaceControl = surfaceControlBuilder.build(); + final SurfaceControl.Transaction tx = + flutterView.getRootSurfaceControl().buildReparentTransaction(surfaceControl); + tx.setLayer(surfaceControl, 1000); + tx.apply(); + overlayerSurface = new Surface(surfaceControl); + overlaySurfaceControl = surfaceControl; + } + + return new FlutterOverlaySurface(0, overlayerSurface); + } + + public void destroyOverlaySurface() { + if (overlayerSurface != null) { + overlayerSurface.release(); + overlayerSurface = null; + overlaySurfaceControl = null; + } + } + + @TargetApi(API_LEVELS.API_34) + @RequiresApi(API_LEVELS.API_34) + public void showOverlaySurface() { + if (overlaySurfaceControl == null) { + return; + } + SurfaceControl.Transaction tx = new SurfaceControl.Transaction(); + tx.setVisibility(overlaySurfaceControl, /*visible=*/ true); + tx.apply(); + } + + @TargetApi(API_LEVELS.API_34) + @RequiresApi(API_LEVELS.API_34) + public void hideOverlaySurface() { + if (overlaySurfaceControl == null) { + return; + } + SurfaceControl.Transaction tx = new SurfaceControl.Transaction(); + tx.setVisibility(overlaySurfaceControl, /*visible=*/ false); + tx.apply(); + } + + //// Message Handler /////// + + private final PlatformViewsChannel2.PlatformViewsHandler channelHandler = + new PlatformViewsChannel2.PlatformViewsHandler() { + + @Override + public void createPlatformView( + @NonNull PlatformViewsChannel2.PlatformViewCreationRequest request) { + createFlutterPlatformView(request); + } + + @Override + public void dispose(int viewId) { + final PlatformView platformView = platformViews.get(viewId); + if (platformView == null) { + Log.e(TAG, "Disposing unknown platform view with id: " + viewId); + return; + } + if (platformView.getView() != null) { + final View embeddedView = platformView.getView(); + final ViewGroup pvParent = (ViewGroup) embeddedView.getParent(); + if (pvParent != null) { + // Eagerly remove the embedded view from the PlatformViewWrapper. + // Without this call, we see some crashes because removing the view + // is used as a signal to stop processing. + pvParent.removeView(embeddedView); + } + } + platformViews.remove(viewId); + try { + platformView.dispose(); + } catch (RuntimeException exception) { + Log.e(TAG, "Disposing platform view threw an exception", exception); + } + + // The platform view is displayed using a PlatformViewLayer. + final FlutterMutatorView parentView = platformViewParent.get(viewId); + if (parentView != null) { + parentView.removeAllViews(); + parentView.unsetOnDescendantFocusChangeListener(); + + final ViewGroup mutatorViewParent = (ViewGroup) parentView.getParent(); + if (mutatorViewParent != null) { + mutatorViewParent.removeView(parentView); + } + platformViewParent.remove(viewId); + } + } + + @Override + public void onTouch(@NonNull PlatformViewsChannel2.PlatformViewTouch touch) { + final int viewId = touch.viewId; + final float density = context.getResources().getDisplayMetrics().density; + + final PlatformView platformView = platformViews.get(viewId); + if (platformView == null) { + Log.e(TAG, "Sending touch to an unknown view with id: " + viewId); + return; + } + final View view = platformView.getView(); + if (view == null) { + Log.e(TAG, "Sending touch to a null view with id: " + viewId); + return; + } + final MotionEvent event = toMotionEvent(density, touch); + view.dispatchTouchEvent(event); + } + + @Override + public void setDirection(int viewId, int direction) { + final PlatformView platformView = platformViews.get(viewId); + if (platformView == null) { + Log.e(TAG, "Setting direction to an unknown view with id: " + viewId); + return; + } + View embeddedView = platformView.getView(); + if (embeddedView == null) { + Log.e(TAG, "Setting direction to a null view with id: " + viewId); + return; + } + embeddedView.setLayoutDirection(direction); + } + + @Override + public void clearFocus(int viewId) { + final PlatformView platformView = platformViews.get(viewId); + if (platformView == null) { + Log.e(TAG, "Clearing focus on an unknown view with id: " + viewId); + return; + } + View embeddedView = platformView.getView(); + if (embeddedView == null) { + Log.e(TAG, "Clearing focus on a null view with id: " + viewId); + return; + } + embeddedView.clearFocus(); + } + + @Override + public boolean isSurfaceControlEnabled() { + if (flutterJNI == null) { + return false; + } + return flutterJNI.IsSurfaceControlEnabled(); + } + }; +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/SingleViewFakeWindowViewGroup.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/SingleViewFakeWindowViewGroup.java new file mode 100644 index 0000000000000000000000000000000000000000..fa16b525435efb6c2326cb0d273841f25d064be0 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/SingleViewFakeWindowViewGroup.java @@ -0,0 +1,65 @@ +// 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. + +package io.flutter.plugin.platform; + +import android.content.Context; +import android.graphics.Rect; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.view.WindowManager; + +/* + * A view group that implements the same layout protocol that exist between the WindowManager and its direct + * children. + * + * Currently only a subset of the protocol is supported (gravity, x, and y). + */ +class SingleViewFakeWindowViewGroup extends ViewGroup { + // Used in onLayout to keep the bounds of the current view. + // We keep it as a member to avoid object allocations during onLayout which are discouraged. + private final Rect viewBounds; + + // Used in onLayout to keep the bounds of the child views. + // We keep it as a member to avoid object allocations during onLayout which are discouraged. + private final Rect childRect; + + public SingleViewFakeWindowViewGroup(Context context) { + super(context); + viewBounds = new Rect(); + childRect = new Rect(); + } + + @Override + protected void onLayout(boolean changed, int l, int t, int r, int b) { + for (int i = 0; i < getChildCount(); i++) { + View child = getChildAt(i); + WindowManager.LayoutParams params = (WindowManager.LayoutParams) child.getLayoutParams(); + viewBounds.set(l, t, r, b); + Gravity.apply( + params.gravity, + child.getMeasuredWidth(), + child.getMeasuredHeight(), + viewBounds, + params.x, + params.y, + childRect); + child.layout(childRect.left, childRect.top, childRect.right, childRect.bottom); + } + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + for (int i = 0; i < getChildCount(); i++) { + View child = getChildAt(i); + child.measure(atMost(widthMeasureSpec), atMost(heightMeasureSpec)); + } + super.onMeasure(widthMeasureSpec, heightMeasureSpec); + } + + private static int atMost(int measureSpec) { + return MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(measureSpec), MeasureSpec.AT_MOST); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/SingleViewPresentation.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/SingleViewPresentation.java new file mode 100644 index 0000000000000000000000000000000000000000..82a8013db30c413943b06da666de831c5cd6da50 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/SingleViewPresentation.java @@ -0,0 +1,332 @@ +// 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. + +package io.flutter.plugin.platform; + +import static android.content.Context.WINDOW_SERVICE; +import static android.view.View.OnFocusChangeListener; + +import android.app.AlertDialog; +import android.app.Presentation; +import android.content.Context; +import android.content.ContextWrapper; +import android.content.MutableContextWrapper; +import android.graphics.drawable.ColorDrawable; +import android.os.Bundle; +import android.view.Display; +import android.view.View; +import android.view.WindowManager; +import android.view.accessibility.AccessibilityEvent; +import android.view.inputmethod.InputMethodManager; +import android.widget.FrameLayout; +import androidx.annotation.Keep; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import io.flutter.Log; + +/* + * A presentation used for hosting a single Android view in a virtual display. + * + * This presentation overrides the WindowManager's addView/removeView/updateViewLayout methods, such that views added + * directly to the WindowManager are added as part of the presentation's view hierarchy (to fakeWindowViewGroup). + * + * The view hierarchy for the presentation is as following: + * + * rootView + * / \ + * / \ + * / \ + * container state.fakeWindowViewGroup + * | + * EmbeddedView + */ +@Keep +class SingleViewPresentation extends Presentation { + private static final String TAG = "PlatformViewsController"; + + /* + * When an embedded view is resized in Flutterverse we move the Android view to a new virtual display + * that has the new size. This class keeps the presentation state that moves with the view to the presentation of + * the new virtual display. + */ + static class PresentationState { + // The Android view we are embedding in the Flutter app. + private PlatformView platformView; + + // The InvocationHandler for a WindowManager proxy. This is essentially the custom window + // manager for the + // presentation. + private WindowManagerHandler windowManagerHandler; + + // Contains views that were added directly to the window manager (e.g + // android.widget.PopupWindow). + private SingleViewFakeWindowViewGroup fakeWindowViewGroup; + } + + // A reference to the current accessibility bridge to which accessibility events will be + // delegated. + private final AccessibilityEventsDelegate accessibilityEventsDelegate; + + private final OnFocusChangeListener focusChangeListener; + + // This is the view id assigned by the Flutter framework to the embedded view, we keep it here + // so when we create the platform view we can tell it its view id. + private int viewId; + + // The root view for the presentation, it has 2 childs: container which contains the embedded + // view, and + // fakeWindowViewGroup which contains views that were added directly to the presentation's window + // manager. + private AccessibilityDelegatingFrameLayout rootView; + + // Contains the embedded platform view (platformView.getView()) when it is attached to the + // presentation. + private FrameLayout container; + + private final PresentationState state; + + private boolean startFocused = false; + + // The context for the application window that hosts FlutterView. + private final Context outerContext; + + /** + * Creates a presentation that will use the view factory to create a new platform view in the + * presentation's onCreate, and attach it. + */ + public SingleViewPresentation( + Context outerContext, + Display display, + PlatformView view, + AccessibilityEventsDelegate accessibilityEventsDelegate, + int viewId, + OnFocusChangeListener focusChangeListener) { + super(new ImmContext(outerContext), display); + this.accessibilityEventsDelegate = accessibilityEventsDelegate; + this.viewId = viewId; + this.focusChangeListener = focusChangeListener; + this.outerContext = outerContext; + state = new PresentationState(); + state.platformView = view; + getWindow() + .setFlags( + WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, + WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE); + getWindow().setType(WindowManager.LayoutParams.TYPE_PRIVATE_PRESENTATION); + } + + /** + * Creates a presentation that will attach an already existing view as its root view. + * + *

The display's density must match the density of the context used when the view was created. + */ + public SingleViewPresentation( + Context outerContext, + Display display, + AccessibilityEventsDelegate accessibilityEventsDelegate, + PresentationState state, + OnFocusChangeListener focusChangeListener, + boolean startFocused) { + super(new ImmContext(outerContext), display); + this.accessibilityEventsDelegate = accessibilityEventsDelegate; + this.state = state; + this.focusChangeListener = focusChangeListener; + this.outerContext = outerContext; + getWindow() + .setFlags( + WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, + WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE); + this.startFocused = startFocused; + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + // This makes sure we preserve alpha for the VD's content. + getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + if (state.fakeWindowViewGroup == null) { + state.fakeWindowViewGroup = new SingleViewFakeWindowViewGroup(getContext()); + } + if (state.windowManagerHandler == null) { + WindowManager windowManagerDelegate = + (WindowManager) getContext().getSystemService(WINDOW_SERVICE); + state.windowManagerHandler = + new WindowManagerHandler(windowManagerDelegate, state.fakeWindowViewGroup); + } + + container = new FrameLayout(getContext()); + + // Our base mContext has already been wrapped with an IMM cache at instantiation time, but + // we want to wrap it again here to also return state.windowManagerHandler. + Context baseContext = + new PresentationContext(getContext(), state.windowManagerHandler, outerContext); + + View embeddedView = state.platformView.getView(); + if (embeddedView.getContext() instanceof MutableContextWrapper) { + MutableContextWrapper currentContext = (MutableContextWrapper) embeddedView.getContext(); + currentContext.setBaseContext(baseContext); + } else { + // In some cases, such as when using LayoutInflator, the original context + // may not be preserved. For backward compatibility with previous + // implementations of Virtual Display, which didn't validate the context, + // continue, but log a warning indicating that some functionality may not + // work as expected. + // See https://github.com/flutter/flutter/issues/110146 for context. + Log.w( + TAG, + "Unexpected platform view context for view ID " + + viewId + + "; some functionality may not work correctly. When constructing a platform view " + + "in the factory, ensure that the view returned from PlatformViewFactory#create " + + "returns the provided context from getContext(). If you are unable to associate " + + "the view with that context, consider using Hybrid Composition instead."); + } + + container.addView(embeddedView); + rootView = + new AccessibilityDelegatingFrameLayout( + getContext(), accessibilityEventsDelegate, embeddedView); + rootView.addView(container); + rootView.addView(state.fakeWindowViewGroup); + + embeddedView.setOnFocusChangeListener(focusChangeListener); + rootView.setFocusableInTouchMode(true); + if (startFocused) { + embeddedView.requestFocus(); + } else { + rootView.requestFocus(); + } + setContentView(rootView); + } + + public PresentationState detachState() { + // These views can be null before onCreate() is called + if (container != null) { + container.removeAllViews(); + } + if (rootView != null) { + rootView.removeAllViews(); + } + return state; + } + + @Nullable + public PlatformView getView() { + return state.platformView; + } + + /** Answers calls for {@link InputMethodManager} with an instance cached at creation time. */ + // TODO(mklim): This caches the IMM at construction time and won't pick up any changes. In rare + // cases where the FlutterView changes windows this will return an outdated instance. This + // should be fixed to instead defer returning the IMM to something that know's FlutterView's + // true Context. + private static class ImmContext extends ContextWrapper { + private @NonNull final InputMethodManager inputMethodManager; + + ImmContext(Context base) { + this(base, /*inputMethodManager=*/ null); + } + + private ImmContext(Context base, @Nullable InputMethodManager inputMethodManager) { + super(base); + this.inputMethodManager = + inputMethodManager != null + ? inputMethodManager + : (InputMethodManager) base.getSystemService(INPUT_METHOD_SERVICE); + } + + @Override + public Object getSystemService(String name) { + if (INPUT_METHOD_SERVICE.equals(name)) { + return inputMethodManager; + } + return super.getSystemService(name); + } + + @Override + public Context createDisplayContext(Display display) { + Context displayContext = super.createDisplayContext(display); + return new ImmContext(displayContext, inputMethodManager); + } + } + + /** Proxies a Context replacing the WindowManager with our custom instance. */ + // TODO(mklim): This caches the IMM at construction time and won't pick up any changes. In rare + // cases where the FlutterView changes windows this will return an outdated instance. This + // should be fixed to instead defer returning the IMM to something that know's FlutterView's + // true Context. + private static class PresentationContext extends ContextWrapper { + private @NonNull final WindowManagerHandler windowManagerHandler; + private @Nullable WindowManager windowManager; + private final Context flutterAppWindowContext; + + PresentationContext( + Context base, + @NonNull WindowManagerHandler windowManagerHandler, + Context flutterAppWindowContext) { + super(base); + this.windowManagerHandler = windowManagerHandler; + this.flutterAppWindowContext = flutterAppWindowContext; + } + + @Override + public Object getSystemService(String name) { + if (WINDOW_SERVICE.equals(name)) { + if (isCalledFromAlertDialog()) { + // Alert dialogs are showing on top of the entire application and should not be limited to + // the virtual + // display. If we detect that an android.app.AlertDialog constructor is what's fetching + // the window manager + // we return the one for the application's window. + // + // Note that if we don't do this AlertDialog will throw a ClassCastException as down the + // line it tries + // to case this instance to a WindowManagerImpl which the object returned by + // getWindowManager is not + // a subclass of. + return flutterAppWindowContext.getSystemService(name); + } + return getWindowManager(); + } + return super.getSystemService(name); + } + + private WindowManager getWindowManager() { + if (windowManager == null) { + windowManager = windowManagerHandler; + } + return windowManager; + } + + private boolean isCalledFromAlertDialog() { + StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); + for (int i = 0; i < stackTraceElements.length && i < 11; i++) { + if (stackTraceElements[i].getClassName().equals(AlertDialog.class.getCanonicalName()) + && stackTraceElements[i].getMethodName().equals("")) { + return true; + } + } + return false; + } + } + + private static class AccessibilityDelegatingFrameLayout extends FrameLayout { + private final AccessibilityEventsDelegate accessibilityEventsDelegate; + private final View embeddedView; + + public AccessibilityDelegatingFrameLayout( + Context context, + AccessibilityEventsDelegate accessibilityEventsDelegate, + View embeddedView) { + super(context); + this.accessibilityEventsDelegate = accessibilityEventsDelegate; + this.embeddedView = embeddedView; + } + + @Override + public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { + return accessibilityEventsDelegate.requestSendAccessibilityEvent(embeddedView, child, event); + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/SingleViewWindowManager.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/SingleViewWindowManager.java new file mode 100644 index 0000000000000000000000000000000000000000..ffeb3871afc475d8524ed1e89860093e3353a3f9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/SingleViewWindowManager.java @@ -0,0 +1,128 @@ +// 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. + +package io.flutter.plugin.platform; + +import static io.flutter.Build.API_LEVELS; + +import android.view.Display; +import android.view.View; +import android.view.ViewGroup; +import android.view.WindowManager; +import android.view.WindowMetrics; +import androidx.annotation.NonNull; +import androidx.annotation.RequiresApi; +import io.flutter.Log; +import java.util.concurrent.Executor; +import java.util.function.Consumer; + +/** + * A static proxy handler for a WindowManager with custom overrides. + * + *

The presentation's window manager delegates all calls to the default window manager. + * WindowManager#addView calls triggered by views that are attached to the virtual display are + * crashing (see: https://github.com/flutter/flutter/issues/20714). This was triggered when + * selecting text in an embedded WebView (as the selection handles are implemented as popup + * windows). + * + *

This static proxy overrides the addView, removeView, removeViewImmediate, and updateViewLayout + * methods to prevent these crashes, and forwards all other calls to the delegate. + * + *

This is an abstract class because some clients of Flutter compile the Android embedding with + * the Android System SDK, which has additional abstract methods that need to be overriden. + */ +abstract class SingleViewWindowManager implements WindowManager { + private static final String TAG = "PlatformViewsController"; + + final WindowManager delegate; + SingleViewFakeWindowViewGroup fakeWindowRootView; + + SingleViewWindowManager( + WindowManager delegate, SingleViewFakeWindowViewGroup fakeWindowViewGroup) { + this.delegate = delegate; + fakeWindowRootView = fakeWindowViewGroup; + } + + @Override + @Deprecated + public Display getDefaultDisplay() { + return delegate.getDefaultDisplay(); + } + + @Override + public void removeViewImmediate(View view) { + if (fakeWindowRootView == null) { + Log.w(TAG, "Embedded view called removeViewImmediate while detached from presentation"); + return; + } + view.clearAnimation(); + fakeWindowRootView.removeView(view); + } + + @Override + public void addView(View view, ViewGroup.LayoutParams params) { + if (fakeWindowRootView == null) { + Log.w(TAG, "Embedded view called addView while detached from presentation"); + return; + } + fakeWindowRootView.addView(view, params); + } + + @Override + public void updateViewLayout(View view, ViewGroup.LayoutParams params) { + if (fakeWindowRootView == null) { + Log.w(TAG, "Embedded view called updateViewLayout while detached from presentation"); + return; + } + fakeWindowRootView.updateViewLayout(view, params); + } + + @Override + public void removeView(View view) { + if (fakeWindowRootView == null) { + Log.w(TAG, "Embedded view called removeView while detached from presentation"); + return; + } + fakeWindowRootView.removeView(view); + } + + @RequiresApi(api = API_LEVELS.API_30) + @NonNull + @Override + public WindowMetrics getCurrentWindowMetrics() { + return delegate.getCurrentWindowMetrics(); + } + + @RequiresApi(api = API_LEVELS.API_30) + @NonNull + @Override + public WindowMetrics getMaximumWindowMetrics() { + return delegate.getMaximumWindowMetrics(); + } + + @RequiresApi(api = API_LEVELS.API_31) + @Override + public boolean isCrossWindowBlurEnabled() { + return delegate.isCrossWindowBlurEnabled(); + } + + @RequiresApi(api = API_LEVELS.API_31) + @Override + public void addCrossWindowBlurEnabledListener(@NonNull Consumer listener) { + delegate.addCrossWindowBlurEnabledListener(listener); + } + + @RequiresApi(api = API_LEVELS.API_31) + @Override + public void addCrossWindowBlurEnabledListener( + @NonNull Executor executor, @NonNull Consumer listener) { + delegate.addCrossWindowBlurEnabledListener(executor, listener); + } + + @RequiresApi(api = API_LEVELS.API_31) + @Override + public void removeCrossWindowBlurEnabledListener(@NonNull Consumer listener) { + delegate.removeCrossWindowBlurEnabledListener(listener); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/SurfaceProducerPlatformViewRenderTarget.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/SurfaceProducerPlatformViewRenderTarget.java new file mode 100644 index 0000000000000000000000000000000000000000..03e28d28806f4d0104ea51aa35d1df2894cf01e5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/SurfaceProducerPlatformViewRenderTarget.java @@ -0,0 +1,57 @@ +package io.flutter.plugin.platform; + +import static io.flutter.Build.API_LEVELS; + +import android.annotation.TargetApi; +import android.view.Surface; +import io.flutter.view.TextureRegistry.SurfaceProducer; + +@TargetApi(API_LEVELS.API_29) +public class SurfaceProducerPlatformViewRenderTarget implements PlatformViewRenderTarget { + private static final String TAG = "SurfaceProducerRenderTarget"; + private SurfaceProducer producer; + + public SurfaceProducerPlatformViewRenderTarget(SurfaceProducer producer) { + this.producer = producer; + } + + // Called when the render target should be resized. + public void resize(int width, int height) { + this.producer.setSize(width, height); + } + + // Returns the currently specified width. + public int getWidth() { + return this.producer.getWidth(); + } + + // Returns the currently specified height. + public int getHeight() { + return this.producer.getHeight(); + } + + // The id of this render target. + public long getId() { + return this.producer.id(); + } + + // Releases backing resources. + public void release() { + this.producer.release(); + this.producer = null; + } + + // Returns true in the case that backing resource have been released. + public boolean isReleased() { + return this.producer == null; + } + + // Returns the Surface to be rendered on to. + public Surface getSurface() { + return this.producer.getSurface(); + } + + public void scheduleFrame() { + this.producer.scheduleFrame(); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/util/HandlerCompat.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/util/HandlerCompat.java new file mode 100644 index 0000000000000000000000000000000000000000..39a7f7d6ff6102b85f1eddf20230ad71b88bf832 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/util/HandlerCompat.java @@ -0,0 +1,37 @@ +// 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. + +package io.flutter.util; + +import static io.flutter.Build.API_LEVELS; + +import android.os.Build; +import android.os.Handler; +import android.os.Looper; + +/** Compatability wrapper over {@link Handler}. */ +public final class HandlerCompat { + /** + * Create a new Handler whose posted messages and runnables are not subject to synchronization + * barriers such as display vsync. + * + *

Messages sent to an async handler are guaranteed to be ordered with respect to one another, + * but not necessarily with respect to messages from other Handlers. Compatibility behavior: + * + *

    + *
  • SDK 28 and above, this method matches platform behavior. + *
  • Otherwise, returns a synchronous handler instance. + *
+ * + * @param looper the Looper that the new Handler should be bound to + * @return a new async Handler instance + * @see Handler#createAsync(Looper) + */ + public static Handler createAsyncHandler(Looper looper) { + if (Build.VERSION.SDK_INT >= API_LEVELS.API_28) { + return Handler.createAsync(looper); + } + return new Handler(looper); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/util/PathUtils.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/util/PathUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..15b6d1e752849ff87a5b848f3e47293c61ac4f1c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/util/PathUtils.java @@ -0,0 +1,59 @@ +// 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. + +package io.flutter.util; + +import static io.flutter.Build.API_LEVELS; + +import android.content.Context; +import android.os.Build; +import androidx.annotation.NonNull; +import java.io.File; + +public final class PathUtils { + @NonNull + public static String getFilesDir(@NonNull Context applicationContext) { + File filesDir = applicationContext.getFilesDir(); + if (filesDir == null) { + filesDir = new File(getDataDirPath(applicationContext), "files"); + } + return filesDir.getPath(); + } + + @NonNull + public static String getDataDirectory(@NonNull Context applicationContext) { + final String name = "flutter"; + File flutterDir = applicationContext.getDir(name, Context.MODE_PRIVATE); + if (flutterDir == null) { + flutterDir = new File(getDataDirPath(applicationContext), "app_" + name); + } + return flutterDir.getPath(); + } + + @NonNull + public static String getCacheDirectory(@NonNull Context applicationContext) { + File cacheDir; + cacheDir = applicationContext.getCodeCacheDir(); + if (cacheDir == null) { + cacheDir = applicationContext.getCacheDir(); + } + if (cacheDir == null) { + // This can happen if the disk is full. This code path is used to set up dart:io's + // `Directory.systemTemp`. It's unknown if the application will ever try to + // use that or not, so do not throw here. In this case, this directory does + // not exist because the disk is full, and the application will later get an + // exception when it tries to actually write. + cacheDir = new File(getDataDirPath(applicationContext), "cache"); + } + return cacheDir.getPath(); + } + + private static String getDataDirPath(Context applicationContext) { + if (Build.VERSION.SDK_INT >= API_LEVELS.API_24) { + return applicationContext.getDataDir().getPath(); + } else { + return applicationContext.getApplicationInfo().dataDir; + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/util/Preconditions.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/util/Preconditions.java new file mode 100644 index 0000000000000000000000000000000000000000..83c58f202fd4d3943f8ec87c2768a87be6c638f8 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/util/Preconditions.java @@ -0,0 +1,55 @@ +// 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. + +package io.flutter.util; + +import androidx.annotation.Nullable; + +/** + * Static convenience methods that help a method or constructor check whether it was invoked + * correctly (that is, whether its preconditions were met). + */ +public final class Preconditions { + private Preconditions() {} + + /** + * Ensures that an object reference passed as a parameter to the calling method is not null. + * + * @param reference an object reference + * @return the non-null reference that was validated + * @throws NullPointerException if {@code reference} is null + */ + public static T checkNotNull(T reference) { + if (reference == null) { + throw new NullPointerException(); + } + return reference; + } + + /** + * Ensures the truth of an expression involving the state of the calling instance. + * + * @param expression a boolean expression that must be checked to be true + * @throws IllegalStateException if {@code expression} is false + */ + public static void checkState(boolean expression) { + if (!expression) { + throw new IllegalStateException(); + } + } + + /** + * Ensures the truth of an expression involving the state of the calling instance. + * + * @param expression a boolean expression that must be checked to be true + * @param errorMessage the exception message to use if the check fails; will be converted to a + * string using {@link String#valueOf(Object)} + * @throws IllegalStateException if {@code expression} is false + */ + public static void checkState(boolean expression, @Nullable Object errorMessage) { + if (!expression) { + throw new IllegalStateException(String.valueOf(errorMessage)); + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/util/Predicate.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/util/Predicate.java new file mode 100644 index 0000000000000000000000000000000000000000..074fbd6b3ecbf8aa6a6022501f1643f2b07562fd --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/util/Predicate.java @@ -0,0 +1,11 @@ +// 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. + +package io.flutter.util; + +// TODO(dnfield): remove this if/when we can use appcompat to support it. +// java.util.function.Predicate isn't available until API24 +public interface Predicate { + public abstract boolean test(T t); +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/util/TraceSection.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/util/TraceSection.java new file mode 100644 index 0000000000000000000000000000000000000000..5ea2355d4d24358e3217ec713b4dda9ac270c5a9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/util/TraceSection.java @@ -0,0 +1,68 @@ +// 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. + +package io.flutter.util; + +import androidx.annotation.NonNull; +import androidx.tracing.Trace; + +public final class TraceSection implements AutoCloseable { + /** + * Factory used to support the try-with-resource construct. + * + *

To get scoped trace events, use the try-with-resource construct, for instance: + * + *

{@code
+   * try (TraceSection e = TraceSection.scoped("MyTraceEvent")) {
+   *   // code.
+   * }
+   * }
+ */ + public static TraceSection scoped(String name) { + return new TraceSection(name); + } + + /** Constructor used to support the try-with-resource construct. */ + private TraceSection(String name) { + begin(name); + } + + @Override + public void close() { + end(); + } + + private static String cropSectionName(@NonNull String sectionName) { + return sectionName.length() < 124 ? sectionName : sectionName.substring(0, 124) + "..."; + } + + /** + * Wraps Trace.beginSection to ensure that the line length stays below 127 code units. + * + * @param sectionName The string to display as the section name in the trace. + */ + public static void begin(@NonNull String sectionName) { + Trace.beginSection(cropSectionName(sectionName)); + } + + /** Wraps Trace.endSection. */ + public static void end() throws RuntimeException { + Trace.endSection(); + } + + /** + * Wraps Trace.beginAsyncSection to ensure that the line length stays below 127 code units. + * + * @param sectionName The string to display as the section name in the trace. + * @param cookie Unique integer defining the section. + */ + public static void beginAsyncSection(String sectionName, int cookie) { + Trace.beginAsyncSection(cropSectionName(sectionName), cookie); + } + + /** Wraps Trace.endAsyncSection to ensure that the line length stays below 127 code units. */ + public static void endAsyncSection(String sectionName, int cookie) { + Trace.endAsyncSection(cropSectionName(sectionName), cookie); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/util/ViewUtils.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/util/ViewUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..d26039f814d5d7e6545db46f2281b0579652cd54 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/util/ViewUtils.java @@ -0,0 +1,126 @@ +// 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. + +package io.flutter.util; + +import android.app.Activity; +import android.content.Context; +import android.content.ContextWrapper; +import android.view.View; +import android.view.ViewGroup; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.window.layout.WindowMetrics; +import androidx.window.layout.WindowMetricsCalculator; + +public final class ViewUtils { + public interface DisplayUpdater { + /** Publishes display metrics to Dart code in Flutter. */ + public void updateDisplayMetrics(float width, float height, float density); + } + + /** + * Calculates the maximum display metrics for the given context, and pushes the metric data to the + * updater. + */ + public static void calculateMaximumDisplayMetrics( + @Nullable Context context, @NonNull DisplayUpdater updater) { + Activity activity = getActivity(context); + if (activity != null) { + WindowMetrics metrics = + WindowMetricsCalculator.getOrCreate().computeMaximumWindowMetrics(activity); + float width = metrics.getBounds().width(); + float height = metrics.getBounds().height(); + float density = context.getResources().getDisplayMetrics().density; + updater.updateDisplayMetrics(width, height, density); + } + } + + /** + * Retrieves the {@link Activity} from a given {@link Context}. + * + *

This method will recursively traverse up the context chain if it is a {@link ContextWrapper} + * until it finds the first instance of the base context that is an {@link Activity}. + */ + @Nullable + public static Activity getActivity(@Nullable Context context) { + if (context == null) { + return null; + } + if (context instanceof Activity) { + return (Activity) context; + } + if (context instanceof ContextWrapper) { + // Recurse up chain of base contexts until we find an Activity. + return getActivity(((ContextWrapper) context).getBaseContext()); + } + return null; + } + + /** + * Determines if the current view or any descendant view has focus. + * + * @param root The root view. + * @return True if the current view or any descendant view has focus. + */ + public static boolean childHasFocus(@Nullable View root) { + return traverseHierarchy(root, (View view) -> view.hasFocus()); + } + + /** + * Returns true if the root or any child view is an instance of the given types. + * + * @param root The root view. + * @param viewTypes The types of views. + * @return true if any child view is an instance of any of the given types. + */ + public static boolean hasChildViewOfType(@Nullable View root, Class[] viewTypes) { + return traverseHierarchy( + root, + (View view) -> { + for (int i = 0; i < viewTypes.length; i++) { + final Class viewType = viewTypes[i]; + if (viewType.isInstance(view)) { + return true; + } + } + return false; + }); + } + + /** Allows to visit a view. */ + public interface ViewVisitor { + boolean run(@NonNull View view); + } + + /** + * Traverses the view hierarchy in pre-order and runs the visitor for each child view including + * the root view. + * + *

If the visitor returns true, the traversal stops, and the method returns true. + * + *

If the visitor returns false, the traversal continues until all views are visited. + * + * @param root The root view. + * @param visitor The visitor. + * @return true if the visitor returned true for a given view. + */ + public static boolean traverseHierarchy(@Nullable View root, @NonNull ViewVisitor visitor) { + if (root == null) { + return false; + } + if (visitor.run(root)) { + return true; + } + if (root instanceof ViewGroup) { + final ViewGroup viewGroup = (ViewGroup) root; + for (int idx = 0; idx < viewGroup.getChildCount(); idx++) { + if (traverseHierarchy(viewGroup.getChildAt(idx), visitor)) { + return true; + } + } + } + return false; + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/view/AccessibilityBridge.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/view/AccessibilityBridge.java new file mode 100644 index 0000000000000000000000000000000000000000..3ae1d8699927406cb3a1c02668c2d6d53c488d2b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/view/AccessibilityBridge.java @@ -0,0 +1,2994 @@ +// 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. + +package io.flutter.view; + +import static io.flutter.Build.API_LEVELS; + +import android.annotation.SuppressLint; +import android.annotation.TargetApi; +import android.app.Activity; +import android.content.ContentResolver; +import android.content.Context; +import android.content.res.Configuration; +import android.database.ContentObserver; +import android.graphics.Rect; +import android.net.Uri; +import android.opengl.Matrix; +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.text.style.URLSpan; +import android.view.MotionEvent; +import android.view.View; +import android.view.WindowInsets; +import android.view.WindowManager; +import android.view.accessibility.AccessibilityEvent; +import android.view.accessibility.AccessibilityManager; +import android.view.accessibility.AccessibilityNodeInfo; +import android.view.accessibility.AccessibilityNodeProvider; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.RequiresApi; +import androidx.annotation.VisibleForTesting; +import io.flutter.BuildConfig; +import io.flutter.Log; +import io.flutter.embedding.engine.systemchannels.AccessibilityChannel; +import io.flutter.plugin.platform.PlatformViewsAccessibilityDelegate; +import io.flutter.util.Predicate; +import io.flutter.util.ViewUtils; +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; + +/** + * Bridge between Android's OS accessibility system and Flutter's accessibility system. + * + *

An {@code AccessibilityBridge} requires: + * + *

    + *
  • A real Android {@link View}, called the {@link #rootAccessibilityView}, which contains a + * Flutter UI. The {@link #rootAccessibilityView} is required at the time of {@code + * AccessibilityBridge}'s instantiation and is held for the duration of {@code + * AccessibilityBridge}'s lifespan. {@code AccessibilityBridge} invokes various accessibility + * methods on the {@link #rootAccessibilityView}, e.g., {@link + * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. The {@link + * #rootAccessibilityView} is expected to notify the {@code AccessibilityBridge} of relevant + * interactions: {@link #onAccessibilityHoverEvent(MotionEvent)}, {@link #reset()}, {@link + * #updateSemantics(ByteBuffer, String[], ByteBuffer[])}, and {@link + * #updateCustomAccessibilityActions(ByteBuffer, String[])} + *
  • An {@link AccessibilityChannel} that is connected to the running Flutter app. + *
  • Android's {@link AccessibilityManager} to query and listen for accessibility settings. + *
  • Android's {@link ContentResolver} to listen for changes to system animation settings. + *
+ * + * The {@code AccessibilityBridge} causes Android to treat Flutter {@code SemanticsNode}s as if they + * were accessible Android {@link View}s. Accessibility requests may be sent from a Flutter widget + * to the Android OS, as if it were an Android {@link View}, and accessibility events may be + * consumed by a Flutter widget, as if it were an Android {@link View}. {@code AccessibilityBridge} + * refers to Flutter's accessible widgets as "virtual views" and identifies them with "virtual view + * IDs". + */ +public class AccessibilityBridge extends AccessibilityNodeProvider { + private static final String TAG = "AccessibilityBridge"; + + // Constants from higher API levels. + // TODO(goderbauer): Get these from Android Support Library when + // https://github.com/flutter/flutter/issues/11099 is resolved. + private static final int ACTION_SHOW_ON_SCREEN = 16908342; // API level 23 + + private static final float SCROLL_EXTENT_FOR_INFINITY = 100000.0f; + private static final float SCROLL_POSITION_CAP_FOR_INFINITY = 70000.0f; + private static final int ROOT_NODE_ID = 0; + private static final int SCROLLABLE_ACTIONS = + Action.SCROLL_RIGHT.value + | Action.SCROLL_LEFT.value + | Action.SCROLL_UP.value + | Action.SCROLL_DOWN.value; + // Flags that make a node accessibilty focusable. + private static final int FOCUSABLE_FLAGS = + Flag.HAS_CHECKED_STATE.value + | Flag.IS_CHECKED.value + | Flag.IS_SELECTED.value + | Flag.IS_TEXT_FIELD.value + | Flag.IS_FOCUSED.value + | Flag.HAS_ENABLED_STATE.value + | Flag.IS_ENABLED.value + | Flag.IS_IN_MUTUALLY_EXCLUSIVE_GROUP.value + | Flag.HAS_TOGGLED_STATE.value + | Flag.IS_TOGGLED.value + | Flag.IS_FOCUSABLE.value + | Flag.IS_SLIDER.value; + + // The minimal ID for an engine generated AccessibilityNodeInfo. + // + // The AccessibilityNodeInfo node IDs are generated by the framework for most Flutter semantic + // nodes. + // When embedding platform views, the framework does not have the accessibility information for + // the embedded view; + // in this case the engine generates AccessibilityNodeInfo that mirrors the a11y information + // exposed by the platform + // view. To avoid the need of synchronizing the framework and engine mechanisms for generating the + // next ID, we split + // the 32bit range of virtual node IDs into 2. The least significant 16 bits are used for + // framework generated IDs + // and the most significant 16 bits are used for engine generated IDs. + private static final int MIN_ENGINE_GENERATED_NODE_ID = 1 << 16; + + // Font weight adjustment for bold text. FontWeight.Bold - FontWeight.Normal = w700 - w400 = 300. + private static final int BOLD_TEXT_WEIGHT_ADJUSTMENT = 300; + + // Default transition animation scale (animations enabled) + private static final float DEFAULT_TRANSITION_ANIMATION_SCALE = 1.0f; + + // Transition animation scale when animations are disabled + private static final float DISABLED_TRANSITION_ANIMATION_SCALE = 0.0f; + + /// Value is derived from ACTION_TYPE_MASK in AccessibilityNodeInfo.java + private static int FIRST_RESOURCE_ID = 267386881; + + // Real Android View, which internally holds a Flutter UI. + @NonNull private final View rootAccessibilityView; + + // The accessibility communication API between Flutter's Android embedding and + // the Flutter framework. + @NonNull private final AccessibilityChannel accessibilityChannel; + + // Android's {@link AccessibilityManager}, which we can query to see if accessibility is + // turned on, as well as listen for changes to accessibility's activation. + @NonNull private final AccessibilityManager accessibilityManager; + + @NonNull private final AccessibilityViewEmbedder accessibilityViewEmbedder; + + // The delegate for interacting with embedded platform views. Used to embed accessibility data for + // an embedded view in the accessibility tree. + @NonNull private final PlatformViewsAccessibilityDelegate platformViewsAccessibilityDelegate; + + // Android's {@link ContentResolver}, which is used to observe the global + // TRANSITION_ANIMATION_SCALE, + // which determines whether Flutter's animations should be enabled or disabled for accessibility + // purposes. + @NonNull private final ContentResolver contentResolver; + + // The entire Flutter semantics tree of the running Flutter app, stored as a Map + // from each SemanticsNode's ID to a Java representation of a Flutter SemanticsNode. + // + // Flutter's semantics tree is cached here because Android might ask for information about + // a given SemanticsNode at any moment in time. Caching the tree allows for immediate + // response to Android's request. + // + // The structure of flutterSemanticsTree may be 1 or 2 frames behind the Flutter app + // due to the time required to communicate tree changes from Flutter to Android. + // + // See the Flutter docs on SemanticsNode: + // https://api.flutter.dev/flutter/semantics/SemanticsNode-class.html + @NonNull private final Map flutterSemanticsTree = new HashMap<>(); + + // The set of all custom Flutter accessibility actions that are present in the running + // Flutter app, stored as a Map from each action's ID to the definition of the custom + // accessibility + // action. + // + // Flutter and Android support a number of built-in accessibility actions. However, these + // predefined actions are not always sufficient for a desired interaction. Android facilitates + // custom accessibility actions, + // https://developer.android.com/reference/android/view/accessibility/AccessibilityNodeInfo.AccessibilityAction. + // Flutter supports custom accessibility actions via {@code customSemanticsActions} within + // a {@code Semantics} widget, https://api.flutter.dev/flutter/widgets/Semantics-class.html. + // {@code customAccessibilityActions} are an Android-side cache of all custom accessibility + // types declared within the running Flutter app. + // + // Custom accessibility actions are comprised of only a few fields, and therefore it is likely + // that a given app may define the same custom accessibility action many times. Identical + // custom accessibility actions are de-duped such that {@code customAccessibilityActions} only + // caches unique custom accessibility actions. + // + // See the Android documentation for custom accessibility actions: + // https://developer.android.com/reference/android/view/accessibility/AccessibilityNodeInfo.AccessibilityAction + // + // See the Flutter documentation for the Semantics widget: + // https://api.flutter.dev/flutter/widgets/Semantics-class.html + @NonNull + private final Map customAccessibilityActions = + new HashMap<>(); + + // The {@code SemanticsNode} within Flutter that currently has the focus of Android's + // accessibility system. + // + // This is null when a node embedded by the AccessibilityViewEmbedder has the focus. + @Nullable private SemanticsNode accessibilityFocusedSemanticsNode; + + // The virtual ID of the currently embedded node with accessibility focus. + // + // This is the ID of a node generated by the AccessibilityViewEmbedder if an embedded node is + // focused, + // null otherwise. + private Integer embeddedAccessibilityFocusedNodeId; + + // The virtual ID of the currently embedded node with input focus. + // + // This is the ID of a node generated by the AccessibilityViewEmbedder if an embedded node is + // focused, + // null otherwise. + private Integer embeddedInputFocusedNodeId; + + // The accessibility features that should currently be active within Flutter, represented as + // a bitmask whose values comes from {@link AccessibilityFeature}. + private int accessibilityFeatureFlags = 0; + + // The {@code SemanticsNode} within Flutter that currently has the focus of Android's input + // system. + // + // Input focus is independent of accessibility focus. It is possible that accessibility focus + // and input focus target the same {@code SemanticsNode}, but it is also possible that one + // {@code SemanticsNode} has input focus while a different {@code SemanticsNode} has + // accessibility focus. For example, a user may use a D-Pad to navigate to a text field, giving + // it accessibility focus, and then enable input on that text field, giving it input focus. Then + // the user moves the accessibility focus to a nearby label to get info about the label, while + // maintaining input focus on the original text field. + @Nullable private SemanticsNode inputFocusedSemanticsNode; + + // Keeps track of the last semantics node that had the input focus. + // + // This is used to determine if the input focus has changed since the last time the + // {@code inputFocusSemanticsNode} has been set, so that we can send a {@code TYPE_VIEW_FOCUSED} + // event when it changes. + @Nullable private SemanticsNode lastInputFocusedSemanticsNode; + + // The widget within Flutter that currently sits beneath a cursor, e.g, + // beneath a stylus or mouse cursor. + @Nullable private SemanticsNode hoveredObject; + + @VisibleForTesting + public int getHoveredObjectId() { + return hoveredObject.id; + } + + // A Java/Android cached representation of the Flutter app's navigation stack. The Flutter + // navigation stack is tracked so that accessibility announcements can be made during Flutter's + // navigation changes. + // TODO(mattcarroll): take this cache into account for new routing solution so accessibility does + // not get left behind. + @NonNull private final List flutterNavigationStack = new ArrayList<>(); + + // TODO(mattcarroll): why do we need previouseRouteId if we have flutterNavigationStack + private int previousRouteId = ROOT_NODE_ID; + + // Tracks the left system inset of the screen because Flutter needs to manually adjust + // accessibility positioning when in reverse-landscape. This is an Android bug that Flutter + // is solving for itself. + @NonNull private Integer lastLeftFrameInset = 0; + + @Nullable private OnAccessibilityChangeListener onAccessibilityChangeListener; + + // Whether the users are using assistive technologies to interact with the devices. + // + // The getter returns true when at least one of the assistive technologies is running: + // TalkBack, SwitchAccess, or VoiceAccess. + @VisibleForTesting + public boolean getAccessibleNavigation() { + return accessibleNavigation; + } + + private boolean accessibleNavigation = false; + + private void setAccessibleNavigation(boolean value) { + if (accessibleNavigation == value) { + return; + } + accessibleNavigation = value; + if (accessibleNavigation) { + accessibilityFeatureFlags |= AccessibilityFeature.ACCESSIBLE_NAVIGATION.value; + } else { + accessibilityFeatureFlags &= ~AccessibilityFeature.ACCESSIBLE_NAVIGATION.value; + } + sendLatestAccessibilityFlagsToFlutter(); + } + + // Set to true after {@code release} has been invoked. + private boolean isReleased = false; + + // Handler for all messages received from Flutter via the {@code accessibilityChannel} + private final AccessibilityChannel.AccessibilityMessageHandler accessibilityMessageHandler = + new AccessibilityChannel.AccessibilityMessageHandler() { + /** The Dart application would like the given {@code message} to be announced. */ + @Override + public void announce(@NonNull String message) { + if (Build.VERSION.SDK_INT >= API_LEVELS.API_36) { + Log.w( + TAG, + "Using AnnounceSemanticsEvent for accessibility is deprecated on Android. " + + "Migrate to using semantic properties for a more robust and accessible " + + "user experience.\n" + + "Flutter: If you are unsure why you are seeing this bug, it might be because " + + "you are using a widget that calls this method. See https://github.com/flutter/flutter/issues/165510 " + + "for more details.\n" + + "Android documentation: https://developer.android.com/reference/android/view/View#announceForAccessibility(java.lang.CharSequence)"); + } + rootAccessibilityView.announceForAccessibility(message); + } + + /** The user has tapped on the widget with the given {@code nodeId}. */ + @Override + public void onTap(int nodeId) { + sendAccessibilityEvent(nodeId, AccessibilityEvent.TYPE_VIEW_CLICKED); + } + + /** The user has long pressed on the widget with the given {@code nodeId}. */ + @Override + public void onLongPress(int nodeId) { + sendAccessibilityEvent(nodeId, AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); + } + + /** The framework has requested focus on the given {@code nodeId}. */ + @Override + public void onFocus(int nodeId) { + sendAccessibilityEvent(nodeId, AccessibilityEvent.TYPE_VIEW_FOCUSED); + } + + /** The user has opened a tooltip. */ + @Override + public void onTooltip(@NonNull String message) { + // Native Android tooltip is no longer announced when it pops up after API 28 and is + // handled by + // AccessibilityNodeInfo.setTooltipText instead. + // + // To reproduce native behavior, see + // https://developer.android.com/guide/topics/ui/tooltips. + if (Build.VERSION.SDK_INT >= API_LEVELS.API_28) { + return; + } + AccessibilityEvent e = + obtainAccessibilityEvent(ROOT_NODE_ID, AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); + e.getText().add(message); + sendAccessibilityEvent(e); + } + + /** New custom accessibility actions exist in Flutter. Update our Android-side cache. */ + @Override + public void updateCustomAccessibilityActions(ByteBuffer buffer, String[] strings) { + buffer.order(ByteOrder.LITTLE_ENDIAN); + AccessibilityBridge.this.updateCustomAccessibilityActions(buffer, strings); + } + + /** Flutter's semantics tree has changed. Update our Android-side cache. */ + @Override + public void updateSemantics( + ByteBuffer buffer, String[] strings, ByteBuffer[] stringAttributeArgs) { + buffer.order(ByteOrder.LITTLE_ENDIAN); + for (ByteBuffer args : stringAttributeArgs) { + args.order(ByteOrder.LITTLE_ENDIAN); + } + AccessibilityBridge.this.updateSemantics(buffer, strings, stringAttributeArgs); + } + }; + + // Listener that is notified when accessibility is turned on/off. + private final AccessibilityManager.AccessibilityStateChangeListener + accessibilityStateChangeListener = + new AccessibilityManager.AccessibilityStateChangeListener() { + @Override + public void onAccessibilityStateChanged(boolean accessibilityEnabled) { + if (isReleased) { + return; + } + if (accessibilityEnabled) { + accessibilityChannel.setAccessibilityMessageHandler(accessibilityMessageHandler); + accessibilityChannel.onAndroidAccessibilityEnabled(); + } else { + setAccessibleNavigation(false); + accessibilityChannel.setAccessibilityMessageHandler(null); + accessibilityChannel.onAndroidAccessibilityDisabled(); + } + + if (onAccessibilityChangeListener != null) { + onAccessibilityChangeListener.onAccessibilityChanged( + accessibilityEnabled, accessibilityManager.isTouchExplorationEnabled()); + } + } + }; + + // Listener that is notified when accessibility touch exploration is turned on/off. + // This is guarded at instantiation time. + private final AccessibilityManager.TouchExplorationStateChangeListener + touchExplorationStateChangeListener; + + // Listener that is notified when the global TRANSITION_ANIMATION_SCALE. When this scale goes + // to zero, we instruct Flutter to disable animations. + private final ContentObserver animationScaleObserver = + new ContentObserver(new Handler()) { + @Override + public void onChange(boolean selfChange) { + this.onChange(selfChange, null); + } + + @Override + public void onChange(boolean selfChange, Uri uri) { + if (isReleased) { + return; + } + // Retrieve the current value of TRANSITION_ANIMATION_SCALE from the OS. + float value = + Settings.Global.getFloat( + contentResolver, + Settings.Global.TRANSITION_ANIMATION_SCALE, + DEFAULT_TRANSITION_ANIMATION_SCALE); + + boolean shouldAnimationsBeDisabled = value == DISABLED_TRANSITION_ANIMATION_SCALE; + if (shouldAnimationsBeDisabled) { + accessibilityFeatureFlags |= AccessibilityFeature.DISABLE_ANIMATIONS.value; + } else { + accessibilityFeatureFlags &= ~AccessibilityFeature.DISABLE_ANIMATIONS.value; + } + sendLatestAccessibilityFlagsToFlutter(); + } + }; + + public AccessibilityBridge( + @NonNull View rootAccessibilityView, + @NonNull AccessibilityChannel accessibilityChannel, + @NonNull AccessibilityManager accessibilityManager, + @NonNull ContentResolver contentResolver, + @NonNull PlatformViewsAccessibilityDelegate platformViewsAccessibilityDelegate) { + this( + rootAccessibilityView, + accessibilityChannel, + accessibilityManager, + contentResolver, + new AccessibilityViewEmbedder(rootAccessibilityView, MIN_ENGINE_GENERATED_NODE_ID), + platformViewsAccessibilityDelegate); + } + + @VisibleForTesting + public AccessibilityBridge( + @NonNull View rootAccessibilityView, + @NonNull AccessibilityChannel accessibilityChannel, + @NonNull AccessibilityManager accessibilityManager, + @NonNull ContentResolver contentResolver, + @NonNull AccessibilityViewEmbedder accessibilityViewEmbedder, + @NonNull PlatformViewsAccessibilityDelegate platformViewsAccessibilityDelegate) { + this.rootAccessibilityView = rootAccessibilityView; + this.accessibilityChannel = accessibilityChannel; + this.accessibilityManager = accessibilityManager; + this.contentResolver = contentResolver; + this.accessibilityViewEmbedder = accessibilityViewEmbedder; + this.platformViewsAccessibilityDelegate = platformViewsAccessibilityDelegate; + // Tell Flutter whether accessibility is initially active or not. Then register a listener + // to be notified of changes in the future. + accessibilityStateChangeListener.onAccessibilityStateChanged(accessibilityManager.isEnabled()); + this.accessibilityManager.addAccessibilityStateChangeListener(accessibilityStateChangeListener); + + // Tell Flutter whether touch exploration is initially active or not. Then register a listener + // to be notified of changes in the future. + touchExplorationStateChangeListener = + new AccessibilityManager.TouchExplorationStateChangeListener() { + @Override + public void onTouchExplorationStateChanged(boolean isTouchExplorationEnabled) { + if (isReleased) { + return; + } + if (!isTouchExplorationEnabled) { + setAccessibleNavigation(false); + onTouchExplorationExit(); + } + + if (onAccessibilityChangeListener != null) { + onAccessibilityChangeListener.onAccessibilityChanged( + accessibilityManager.isEnabled(), isTouchExplorationEnabled); + } + } + }; + touchExplorationStateChangeListener.onTouchExplorationStateChanged( + accessibilityManager.isTouchExplorationEnabled()); + this.accessibilityManager.addTouchExplorationStateChangeListener( + touchExplorationStateChangeListener); + + // Tell Flutter whether animations should initially be enabled or disabled. Then register a + // listener to be notified of changes in the future. + animationScaleObserver.onChange(false); + Uri transitionUri = Settings.Global.getUriFor(Settings.Global.TRANSITION_ANIMATION_SCALE); + this.contentResolver.registerContentObserver(transitionUri, false, animationScaleObserver); + + // Tells Flutter whether the text should be bolded or not. If the user changes bold text + // setting, the configuration will change and trigger a re-build of the accesibiltyBridge. + if (Build.VERSION.SDK_INT >= API_LEVELS.API_31) { + setBoldTextFlag(); + } + + platformViewsAccessibilityDelegate.attachAccessibilityBridge(this); + } + + /** + * Disconnects any listeners and/or delegates that were initialized in {@code + * AccessibilityBridge}'s constructor, or added after. + * + *

Do not use this instance after invoking {@code release}. The behavior of any method invoked + * on this {@code AccessibilityBridge} after invoking {@code release()} is undefined. + */ + public void release() { + isReleased = true; + platformViewsAccessibilityDelegate.detachAccessibilityBridge(); + setOnAccessibilityChangeListener(null); + accessibilityManager.removeAccessibilityStateChangeListener(accessibilityStateChangeListener); + accessibilityManager.removeTouchExplorationStateChangeListener( + touchExplorationStateChangeListener); + contentResolver.unregisterContentObserver(animationScaleObserver); + accessibilityChannel.setAccessibilityMessageHandler(null); + } + + /** Returns true if the Android OS currently has accessibility enabled, false otherwise. */ + public boolean isAccessibilityEnabled() { + return accessibilityManager.isEnabled(); + } + + /** Returns true if the Android OS currently has touch exploration enabled, false otherwise. */ + public boolean isTouchExplorationEnabled() { + return accessibilityManager.isTouchExplorationEnabled(); + } + + /** + * Sets a listener on this {@code AccessibilityBridge}, which is notified whenever accessibility + * activation, or touch exploration activation changes. + */ + public void setOnAccessibilityChangeListener(@Nullable OnAccessibilityChangeListener listener) { + this.onAccessibilityChangeListener = listener; + } + + /** Sends the current value of {@link #accessibilityFeatureFlags} to Flutter. */ + private void sendLatestAccessibilityFlagsToFlutter() { + accessibilityChannel.setAccessibilityFeatures(accessibilityFeatureFlags); + } + + private boolean shouldSetCollectionInfo(final SemanticsNode semanticsNode) { + // TalkBack expects a number of rows and/or columns greater than 0 to announce + // in list and out of list. For an infinite or growing list, you have to + // specify something > 0 to get "in list" announcements. + // TalkBack will also only track one list at a time, so we only want to set this + // for a list that contains the current a11y focused semanticsNode - otherwise, if there + // are two lists or nested lists, we may end up with announcements for only the last + // one that is currently available in the semantics tree. However, we also want + // to set it if we're exiting a list to a non-list, so that we can get the "out of list" + // announcement when A11y focus moves out of a list and not into another list. + return semanticsNode.scrollChildren > 0 + && (SemanticsNode.nullableHasAncestor( + accessibilityFocusedSemanticsNode, o -> o == semanticsNode) + || !SemanticsNode.nullableHasAncestor( + accessibilityFocusedSemanticsNode, o -> o.hasFlag(Flag.HAS_IMPLICIT_SCROLLING))); + } + + @TargetApi(API_LEVELS.API_31) + @RequiresApi(API_LEVELS.API_31) + private void setBoldTextFlag() { + if (rootAccessibilityView == null || rootAccessibilityView.getResources() == null) { + return; + } + int fontWeightAdjustment = + rootAccessibilityView.getResources().getConfiguration().fontWeightAdjustment; + boolean shouldBold = + fontWeightAdjustment != Configuration.FONT_WEIGHT_ADJUSTMENT_UNDEFINED + && fontWeightAdjustment >= BOLD_TEXT_WEIGHT_ADJUSTMENT; + + if (shouldBold) { + accessibilityFeatureFlags |= AccessibilityFeature.BOLD_TEXT.value; + } else { + accessibilityFeatureFlags &= ~AccessibilityFeature.BOLD_TEXT.value; + } + sendLatestAccessibilityFlagsToFlutter(); + } + + @VisibleForTesting + public AccessibilityNodeInfo obtainAccessibilityNodeInfo(View rootView) { + return AccessibilityNodeInfo.obtain(rootView); + } + + @VisibleForTesting + public AccessibilityNodeInfo obtainAccessibilityNodeInfo(View rootView, int virtualViewId) { + return AccessibilityNodeInfo.obtain(rootView, virtualViewId); + } + + /** + * Returns {@link AccessibilityNodeInfo} for the view corresponding to the given {@code + * virtualViewId}. + * + *

This method is invoked by Android's accessibility system when Android needs accessibility + * info for a given view. + * + *

When a {@code virtualViewId} of {@link View#NO_ID} is requested, accessibility node info is + * returned for our {@link #rootAccessibilityView}. Otherwise, Flutter's semantics tree, + * represented by {@link #flutterSemanticsTree}, is searched for a {@link SemanticsNode} with the + * given {@code virtualViewId}. If no such {@link SemanticsNode} is found, then this method + * returns null. If the desired {@link SemanticsNode} is found, then an {@link + * AccessibilityNodeInfo} is obtained from the {@link #rootAccessibilityView}, filled with + * appropriate info, and then returned. + * + *

Depending on the type of Flutter {@code SemanticsNode} that is requested, the returned + * {@link AccessibilityNodeInfo} pretends that the {@code SemanticsNode} in question comes from a + * specialize Android view, e.g., {@link Flag#IS_TEXT_FIELD} maps to {@code + * android.widget.EditText}, {@link Flag#IS_BUTTON} maps to {@code android.widget.Button}, and + * {@link Flag#IS_IMAGE} maps to {@code android.widget.ImageView}. In the case that no specialized + * view applies, the returned {@link AccessibilityNodeInfo} pretends that it represents a {@code + * android.view.View}. + */ + @Override + @SuppressWarnings("deprecation") + // Suppressing Lint warning for new API, as we are version guarding all calls to newer APIs + @SuppressLint("NewApi") + public AccessibilityNodeInfo createAccessibilityNodeInfo(int virtualViewId) { + setAccessibleNavigation(true); + if (virtualViewId >= MIN_ENGINE_GENERATED_NODE_ID) { + // The node is in the engine generated range, and is provided by the accessibility view + // embedder. + return accessibilityViewEmbedder.createAccessibilityNodeInfo(virtualViewId); + } + + if (virtualViewId == View.NO_ID) { + AccessibilityNodeInfo result = obtainAccessibilityNodeInfo(rootAccessibilityView); + rootAccessibilityView.onInitializeAccessibilityNodeInfo(result); + // TODO(mattcarroll): what does it mean for the semantics tree to contain or not contain + // the root node ID? + if (flutterSemanticsTree.containsKey(ROOT_NODE_ID)) { + result.addChild(rootAccessibilityView, ROOT_NODE_ID); + } + if (Build.VERSION.SDK_INT >= API_LEVELS.API_24) { + result.setImportantForAccessibility(false); + } + return result; + } + + SemanticsNode semanticsNode = flutterSemanticsTree.get(virtualViewId); + if (semanticsNode == null) { + return null; + } + + // Generate accessibility node for platform views using a virtual display. + // + // In this case, register the accessibility node in the view embedder, + // so the accessibility tree can be mirrored as a subtree of the Flutter accessibility tree. + // This is in constrast to hybrid composition where the embedded view is in the view hiearchy, + // so it doesn't need to be mirrored. + // + // See the case down below for how hybrid composition is handled. + if (semanticsNode.platformViewId != -1) { + if (platformViewsAccessibilityDelegate.usesVirtualDisplay(semanticsNode.platformViewId)) { + View embeddedView = + platformViewsAccessibilityDelegate.getPlatformViewById(semanticsNode.platformViewId); + if (embeddedView == null) { + return null; + } + Rect bounds = semanticsNode.getGlobalRect(); + return accessibilityViewEmbedder.getRootNode(embeddedView, semanticsNode.id, bounds); + } + } + + AccessibilityNodeInfo result = + obtainAccessibilityNodeInfo(rootAccessibilityView, virtualViewId); + + // Accessibility Scanner uses isImportantForAccessibility to decide whether to check + // or skip this node. + if (Build.VERSION.SDK_INT >= API_LEVELS.API_24) { + result.setImportantForAccessibility(isImportant(semanticsNode)); + } + + // Work around for https://github.com/flutter/flutter/issues/21030 + result.setViewIdResourceName(""); + if (semanticsNode.identifier != null) { + result.setViewIdResourceName(semanticsNode.identifier); + } + result.setPackageName(rootAccessibilityView.getContext().getPackageName()); + result.setClassName("android.view.View"); + result.setSource(rootAccessibilityView, virtualViewId); + result.setFocusable(semanticsNode.isFocusable()); + if (inputFocusedSemanticsNode != null) { + result.setFocused(inputFocusedSemanticsNode.id == virtualViewId); + } + + if (accessibilityFocusedSemanticsNode != null) { + result.setAccessibilityFocused(accessibilityFocusedSemanticsNode.id == virtualViewId); + } + + if (semanticsNode.hasFlag(Flag.IS_TEXT_FIELD)) { + result.setPassword(semanticsNode.hasFlag(Flag.IS_OBSCURED)); + if (!semanticsNode.hasFlag(Flag.IS_READ_ONLY)) { + result.setClassName("android.widget.EditText"); + } + result.setEditable(!semanticsNode.hasFlag(Flag.IS_READ_ONLY)); + if (semanticsNode.textSelectionBase != -1 && semanticsNode.textSelectionExtent != -1) { + result.setTextSelection(semanticsNode.textSelectionBase, semanticsNode.textSelectionExtent); + } + // Text fields will always be created as a live region when they have input focus, + // so that updates to the label trigger polite announcements. This makes it easy to + // follow a11y guidelines for text fields on Android. + if (accessibilityFocusedSemanticsNode != null + && accessibilityFocusedSemanticsNode.id == virtualViewId) { + result.setLiveRegion(View.ACCESSIBILITY_LIVE_REGION_POLITE); + } + + // Cursor movements + int granularities = 0; + if (semanticsNode.hasAction(Action.MOVE_CURSOR_FORWARD_BY_CHARACTER)) { + result.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); + granularities |= AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER; + } + if (semanticsNode.hasAction(Action.MOVE_CURSOR_BACKWARD_BY_CHARACTER)) { + result.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); + granularities |= AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER; + } + if (semanticsNode.hasAction(Action.MOVE_CURSOR_FORWARD_BY_WORD)) { + result.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); + granularities |= AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD; + } + if (semanticsNode.hasAction(Action.MOVE_CURSOR_BACKWARD_BY_WORD)) { + result.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); + granularities |= AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD; + } + result.setMovementGranularities(granularities); + if (semanticsNode.maxValueLength >= 0) { + // Account for the fact that Flutter is counting Unicode scalar values and Android + // is counting UTF16 words. + final int length = semanticsNode.value == null ? 0 : semanticsNode.value.length(); + int a = length - semanticsNode.currentValueLength + semanticsNode.maxValueLength; + result.setMaxTextLength( + length - semanticsNode.currentValueLength + semanticsNode.maxValueLength); + } + } + + // These are non-ops on older devices. Attempting to interact with the text will cause Talkback + // to read the contents of the text box instead. + if (semanticsNode.hasAction(Action.SET_SELECTION)) { + result.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); + } + if (semanticsNode.hasAction(Action.COPY)) { + result.addAction(AccessibilityNodeInfo.ACTION_COPY); + } + if (semanticsNode.hasAction(Action.CUT)) { + result.addAction(AccessibilityNodeInfo.ACTION_CUT); + } + if (semanticsNode.hasAction(Action.PASTE)) { + result.addAction(AccessibilityNodeInfo.ACTION_PASTE); + } + + if (semanticsNode.hasAction(Action.SET_TEXT)) { + result.addAction(AccessibilityNodeInfo.ACTION_SET_TEXT); + } + + if (semanticsNode.hasFlag(Flag.IS_BUTTON)) { + result.setClassName("android.widget.Button"); + } + if (semanticsNode.hasFlag(Flag.IS_IMAGE)) { + result.setClassName("android.widget.ImageView"); + // TODO(jonahwilliams): Figure out a way conform to the expected id from TalkBack's + // CustomLabelManager. talkback/src/main/java/labeling/CustomLabelManager.java#L525 + } + if (semanticsNode.hasAction(Action.DISMISS)) { + result.setDismissable(true); + result.addAction(AccessibilityNodeInfo.ACTION_DISMISS); + } + + if (semanticsNode.parent != null) { + if (BuildConfig.DEBUG && semanticsNode.id <= ROOT_NODE_ID) { + Log.e(TAG, "Semantics node id is not > ROOT_NODE_ID."); + } + result.setParent(rootAccessibilityView, semanticsNode.parent.id); + } else { + if (BuildConfig.DEBUG && semanticsNode.id != ROOT_NODE_ID) { + Log.e(TAG, "Semantics node id does not equal ROOT_NODE_ID."); + } + result.setParent(rootAccessibilityView); + } + + if (semanticsNode.previousNodeId != -1 && Build.VERSION.SDK_INT >= API_LEVELS.API_22) { + result.setTraversalAfter(rootAccessibilityView, semanticsNode.previousNodeId); + } + + Rect bounds = semanticsNode.getGlobalRect(); + if (semanticsNode.parent != null) { + Rect parentBounds = semanticsNode.parent.getGlobalRect(); + Rect boundsInParent = new Rect(bounds); + boundsInParent.offset(-parentBounds.left, -parentBounds.top); + result.setBoundsInParent(boundsInParent); + } else { + result.setBoundsInParent(bounds); + } + final Rect boundsInScreen = getBoundsInScreen(bounds); + result.setBoundsInScreen(boundsInScreen); + result.setVisibleToUser(true); + result.setEnabled( + !semanticsNode.hasFlag(Flag.HAS_ENABLED_STATE) || semanticsNode.hasFlag(Flag.IS_ENABLED)); + + if (semanticsNode.hasAction(Action.TAP)) { + if (semanticsNode.onTapOverride != null) { + result.addAction( + new AccessibilityNodeInfo.AccessibilityAction( + AccessibilityNodeInfo.ACTION_CLICK, semanticsNode.onTapOverride.hint)); + result.setClickable(true); + } else { + result.addAction(AccessibilityNodeInfo.ACTION_CLICK); + result.setClickable(true); + } + } else { + // Prevent Slider to receive a regular tap which will change the value. + // + // This is needed because it causes slider to select to middle if it + // doesn't have a semantics tap. + if (semanticsNode.hasFlag(Flag.IS_SLIDER)) { + result.addAction(AccessibilityNodeInfo.ACTION_CLICK); + result.setClickable(true); + } + } + if (semanticsNode.hasAction(Action.LONG_PRESS)) { + if (semanticsNode.onLongPressOverride != null) { + result.addAction( + new AccessibilityNodeInfo.AccessibilityAction( + AccessibilityNodeInfo.ACTION_LONG_CLICK, semanticsNode.onLongPressOverride.hint)); + result.setLongClickable(true); + } else { + result.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); + result.setLongClickable(true); + } + } + if (semanticsNode.hasAction(Action.SCROLL_LEFT) + || semanticsNode.hasAction(Action.SCROLL_UP) + || semanticsNode.hasAction(Action.SCROLL_RIGHT) + || semanticsNode.hasAction(Action.SCROLL_DOWN)) { + result.setScrollable(true); + + // This tells Android's a11y to send scroll events when reaching the end of + // the visible viewport of a scrollable, unless the node itself does not + // allow implicit scrolling - then we leave the className as view.View. + // + // We should prefer setCollectionInfo to the class names, as this way we get "In List" + // and "Out of list" announcements. But we don't always know the counts, so we + // can fallback to the generic scroll view class names. + // + // On older APIs, we always fall back to the generic scroll view class names here. + // + // TODO(dnfield): We should add semantics properties for rows and columns in 2 dimensional + // lists, e.g. + // GridView. Right now, we're only supporting ListViews and only if they have scroll + // children. + if (semanticsNode.hasFlag(Flag.HAS_IMPLICIT_SCROLLING)) { + if (semanticsNode.hasAction(Action.SCROLL_LEFT) + || semanticsNode.hasAction(Action.SCROLL_RIGHT)) { + if (shouldSetCollectionInfo(semanticsNode)) { + result.setCollectionInfo( + AccessibilityNodeInfo.CollectionInfo.obtain( + 0, // rows + semanticsNode.scrollChildren, // columns + false // hierarchical + )); + } else { + result.setClassName("android.widget.HorizontalScrollView"); + } + } else { + if (shouldSetCollectionInfo(semanticsNode)) { + result.setCollectionInfo( + AccessibilityNodeInfo.CollectionInfo.obtain( + semanticsNode.scrollChildren, // rows + 0, // columns + false // hierarchical + )); + } else { + result.setClassName("android.widget.ScrollView"); + } + } + } + // TODO(ianh): Once we're on SDK v23+, call addAction to + // expose AccessibilityAction.ACTION_SCROLL_LEFT, _RIGHT, + // _UP, and _DOWN when appropriate. + if (semanticsNode.hasAction(Action.SCROLL_LEFT) + || semanticsNode.hasAction(Action.SCROLL_UP)) { + result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); + } + if (semanticsNode.hasAction(Action.SCROLL_RIGHT) + || semanticsNode.hasAction(Action.SCROLL_DOWN)) { + result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD); + } + } + if (semanticsNode.hasAction(Action.INCREASE) || semanticsNode.hasAction(Action.DECREASE)) { + // TODO(jonahwilliams): support AccessibilityAction.ACTION_SET_PROGRESS once SDK is + // updated. + result.setClassName("android.widget.SeekBar"); + if (semanticsNode.hasAction(Action.INCREASE)) { + result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); + } + if (semanticsNode.hasAction(Action.DECREASE)) { + result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD); + } + } + if (semanticsNode.hasFlag(Flag.IS_LIVE_REGION)) { + result.setLiveRegion(View.ACCESSIBILITY_LIVE_REGION_POLITE); + } + + // Scopes routes are not focusable, only need to set the content + // for non-scopes-routes semantics nodes. + if (semanticsNode.hasFlag(Flag.IS_TEXT_FIELD)) { + result.setText(semanticsNode.getValue()); + if (Build.VERSION.SDK_INT >= API_LEVELS.API_28) { + result.setHintText(semanticsNode.getTextFieldHint()); + } + } else if (!semanticsNode.hasFlag(Flag.SCOPES_ROUTE)) { + CharSequence content = semanticsNode.getValueLabelHint(); + if (Build.VERSION.SDK_INT < API_LEVELS.API_28) { + if (semanticsNode.tooltip != null) { + // For backward compatibility with Flutter SDK before Android API + // level 28, the tooltip is appended at the end of content description. + content = content != null ? content : ""; + content = content + "\n" + semanticsNode.tooltip; + } + } + if (content != null) { + result.setContentDescription(content); + } + } + + if (Build.VERSION.SDK_INT >= API_LEVELS.API_28) { + if (semanticsNode.tooltip != null) { + result.setTooltipText(semanticsNode.tooltip); + } + } + + boolean hasCheckedState = semanticsNode.hasFlag(Flag.HAS_CHECKED_STATE); + boolean hasToggledState = semanticsNode.hasFlag(Flag.HAS_TOGGLED_STATE); + if (BuildConfig.DEBUG && (hasCheckedState && hasToggledState)) { + Log.e(TAG, "Expected semanticsNode to have checked state and toggled state."); + } + result.setCheckable(hasCheckedState || hasToggledState); + if (hasCheckedState) { + result.setChecked(semanticsNode.hasFlag(Flag.IS_CHECKED)); + if (semanticsNode.hasFlag(Flag.IS_IN_MUTUALLY_EXCLUSIVE_GROUP)) { + result.setClassName("android.widget.RadioButton"); + } else { + result.setClassName("android.widget.CheckBox"); + } + } else if (hasToggledState) { + result.setChecked(semanticsNode.hasFlag(Flag.IS_TOGGLED)); + result.setClassName("android.widget.Switch"); + } + result.setSelected(semanticsNode.hasFlag(Flag.IS_SELECTED)); + + // Heading support + if (Build.VERSION.SDK_INT >= API_LEVELS.API_28) { + result.setHeading(semanticsNode.hasFlag(Flag.IS_HEADER)); + } + + // Accessibility Focus + if (accessibilityFocusedSemanticsNode != null + && accessibilityFocusedSemanticsNode.id == virtualViewId) { + result.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); + } else { + result.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); + } + + // Actions on the local context menu + if (semanticsNode.customAccessibilityActions != null) { + for (CustomAccessibilityAction action : semanticsNode.customAccessibilityActions) { + result.addAction( + new AccessibilityNodeInfo.AccessibilityAction(action.resourceId, action.label)); + } + } + + for (SemanticsNode child : semanticsNode.childrenInTraversalOrder) { + if (child.hasFlag(Flag.IS_HIDDEN)) { + continue; + } + if (child.platformViewId != -1) { + View embeddedView = + platformViewsAccessibilityDelegate.getPlatformViewById(child.platformViewId); + + // Add the embedded view as a child of the current accessibility node if it's not + // using a virtual display. + // + // In this case, the view is in the Activity's view hierarchy, so it doesn't need to be + // mirrored. + // + // See the case above for how virtual displays are handled. + if (!platformViewsAccessibilityDelegate.usesVirtualDisplay(child.platformViewId)) { + result.addChild(embeddedView); + continue; + } + } + result.addChild(rootAccessibilityView, child.id); + } + return result; + } + + private boolean isImportant(SemanticsNode node) { + if (node.hasFlag(Flag.SCOPES_ROUTE)) { + return false; + } + + if (node.getValueLabelHint() != null) { + return true; + } + + // Return true if the node has had any user action (not including system actions) + return (node.actions & ~systemAction) != 0; + } + + /** + * Get the bounds in screen with root FlutterView's offset. + * + * @param bounds the bounds in FlutterView + * @return the bounds with offset + */ + private Rect getBoundsInScreen(Rect bounds) { + Rect boundsInScreen = new Rect(bounds); + int[] locationOnScreen = new int[2]; + rootAccessibilityView.getLocationOnScreen(locationOnScreen); + boundsInScreen.offset(locationOnScreen[0], locationOnScreen[1]); + return boundsInScreen; + } + + /** + * Instructs the view represented by {@code virtualViewId} to carry out the desired {@code + * accessibilityAction}, perhaps configured by additional {@code arguments}. + * + *

This method is invoked by Android's accessibility system. This method returns true if the + * desired {@code SemanticsNode} was found and was capable of performing the desired action, false + * otherwise. + * + *

In a traditional Android app, the given view ID refers to a {@link View} within an Android + * {@link View} hierarchy. Flutter does not have an Android {@link View} hierarchy, therefore the + * given view ID is a {@code virtualViewId} that refers to a {@code SemanticsNode} within a + * Flutter app. The given arguments of this method are forwarded from Android to Flutter. + */ + @Override + public boolean performAction( + int virtualViewId, int accessibilityAction, @Nullable Bundle arguments) { + if (virtualViewId >= MIN_ENGINE_GENERATED_NODE_ID) { + // The node is in the engine generated range, and is handled by the accessibility view + // embedder. + boolean didPerform = + accessibilityViewEmbedder.performAction(virtualViewId, accessibilityAction, arguments); + if (didPerform + && accessibilityAction == AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS) { + embeddedAccessibilityFocusedNodeId = null; + } + return didPerform; + } + SemanticsNode semanticsNode = flutterSemanticsTree.get(virtualViewId); + if (semanticsNode == null) { + return false; + } + switch (accessibilityAction) { + case AccessibilityNodeInfo.ACTION_CLICK: + { + // Note: TalkBack prior to Oreo doesn't use this handler and instead simulates a + // click event at the center of the SemanticsNode. Other a11y services might go + // through this handler though. + accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.TAP); + return true; + } + case AccessibilityNodeInfo.ACTION_LONG_CLICK: + { + // Note: TalkBack doesn't use this handler and instead simulates a long click event + // at the center of the SemanticsNode. Other a11y services might go through this + // handler though. + accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.LONG_PRESS); + return true; + } + case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: + { + if (semanticsNode.hasAction(Action.SCROLL_UP)) { + accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.SCROLL_UP); + } else if (semanticsNode.hasAction(Action.SCROLL_LEFT)) { + // TODO(ianh): bidi support using textDirection + 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); + } else { + return false; + } + return true; + } + case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: + { + if (semanticsNode.hasAction(Action.SCROLL_DOWN)) { + accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.SCROLL_DOWN); + } else if (semanticsNode.hasAction(Action.SCROLL_RIGHT)) { + // TODO(ianh): bidi support using textDirection + 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); + } else { + return false; + } + return true; + } + case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: + { + return performCursorMoveAction(semanticsNode, virtualViewId, arguments, false); + } + case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: + { + return performCursorMoveAction(semanticsNode, virtualViewId, arguments, true); + } + case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: + { + // Focused semantics node must be reset before sending the + // TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED event. Otherwise, + // TalkBack may think the node is still focused. + if (accessibilityFocusedSemanticsNode != null + && accessibilityFocusedSemanticsNode.id == virtualViewId) { + accessibilityFocusedSemanticsNode = null; + } + if (embeddedAccessibilityFocusedNodeId != null + && embeddedAccessibilityFocusedNodeId == virtualViewId) { + embeddedAccessibilityFocusedNodeId = null; + } + accessibilityChannel.dispatchSemanticsAction( + virtualViewId, Action.DID_LOSE_ACCESSIBILITY_FOCUS); + sendAccessibilityEvent( + virtualViewId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); + return true; + } + case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: + { + if (accessibilityFocusedSemanticsNode == null) { + // When Android focuses a node, it doesn't invalidate the view. + // (It does when it sends ACTION_CLEAR_ACCESSIBILITY_FOCUS, so + // we only have to worry about this when the focused node is null.) + rootAccessibilityView.invalidate(); + } + // Focused semantics node must be set before sending the TYPE_VIEW_ACCESSIBILITY_FOCUSED + // event. Otherwise, TalkBack may think the node is not focused yet. + accessibilityFocusedSemanticsNode = semanticsNode; + + accessibilityChannel.dispatchSemanticsAction( + virtualViewId, Action.DID_GAIN_ACCESSIBILITY_FOCUS); + + HashMap message = new HashMap<>(); + message.put("type", "didGainFocus"); + message.put("nodeId", semanticsNode.id); + accessibilityChannel.channel.send(message); + + sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); + + if (semanticsNode.hasAction(Action.INCREASE) + || semanticsNode.hasAction(Action.DECREASE)) { + // SeekBars only announce themselves after this event. + sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_SELECTED); + } + + return true; + } + case ACTION_SHOW_ON_SCREEN: + { + accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.SHOW_ON_SCREEN); + return true; + } + case AccessibilityNodeInfo.ACTION_SET_SELECTION: + { + final Map selection = new HashMap<>(); + final boolean hasSelection = + arguments != null + && arguments.containsKey( + AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT) + && arguments.containsKey(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT); + if (hasSelection) { + selection.put( + "base", + arguments.getInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT)); + selection.put( + "extent", + arguments.getInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT)); + } else { + // Clear the selection + selection.put("base", semanticsNode.textSelectionExtent); + selection.put("extent", semanticsNode.textSelectionExtent); + } + accessibilityChannel.dispatchSemanticsAction( + virtualViewId, Action.SET_SELECTION, selection); + // The voice access expects the semantics node to update immediately. We update the + // semantics node based on prediction. If the result is incorrect, it will be updated in + // the next frame. + SemanticsNode node = flutterSemanticsTree.get(virtualViewId); + node.textSelectionBase = selection.get("base"); + node.textSelectionExtent = selection.get("extent"); + return true; + } + case AccessibilityNodeInfo.ACTION_COPY: + { + accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.COPY); + return true; + } + case AccessibilityNodeInfo.ACTION_CUT: + { + accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.CUT); + return true; + } + case AccessibilityNodeInfo.ACTION_PASTE: + { + accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.PASTE); + return true; + } + case AccessibilityNodeInfo.ACTION_DISMISS: + { + accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.DISMISS); + return true; + } + case AccessibilityNodeInfo.ACTION_SET_TEXT: + { + return performSetText(semanticsNode, virtualViewId, arguments); + } + default: + // might be a custom accessibility accessibilityAction. + final int flutterId = accessibilityAction - FIRST_RESOURCE_ID; + CustomAccessibilityAction contextAction = customAccessibilityActions.get(flutterId); + if (contextAction != null) { + accessibilityChannel.dispatchSemanticsAction( + virtualViewId, Action.CUSTOM_ACTION, contextAction.id); + return true; + } + } + return false; + } + + /** + * Handles the responsibilities of {@link #performAction(int, int, Bundle)} for the specific + * scenario of cursor movement. + */ + private boolean performCursorMoveAction( + @NonNull SemanticsNode semanticsNode, + int virtualViewId, + @NonNull Bundle arguments, + boolean forward) { + final int granularity = + arguments.getInt(AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); + final boolean extendSelection = + arguments.getBoolean(AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); + // The voice access expects the semantics node to update immediately. We update the semantics + // node based on prediction. If the result is incorrect, it will be updated in the next frame. + final int previousTextSelectionBase = semanticsNode.textSelectionBase; + final int previousTextSelectionExtent = semanticsNode.textSelectionExtent; + predictCursorMovement(semanticsNode, granularity, forward, extendSelection); + + if (previousTextSelectionBase != semanticsNode.textSelectionBase + || previousTextSelectionExtent != semanticsNode.textSelectionExtent) { + final String value = semanticsNode.value != null ? semanticsNode.value : ""; + final AccessibilityEvent selectionEvent = + obtainAccessibilityEvent( + semanticsNode.id, AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); + selectionEvent.getText().add(value); + selectionEvent.setFromIndex(semanticsNode.textSelectionBase); + selectionEvent.setToIndex(semanticsNode.textSelectionExtent); + selectionEvent.setItemCount(value.length()); + sendAccessibilityEvent(selectionEvent); + } + + switch (granularity) { + case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: + { + if (forward && semanticsNode.hasAction(Action.MOVE_CURSOR_FORWARD_BY_CHARACTER)) { + accessibilityChannel.dispatchSemanticsAction( + virtualViewId, Action.MOVE_CURSOR_FORWARD_BY_CHARACTER, extendSelection); + return true; + } + if (!forward && semanticsNode.hasAction(Action.MOVE_CURSOR_BACKWARD_BY_CHARACTER)) { + accessibilityChannel.dispatchSemanticsAction( + virtualViewId, Action.MOVE_CURSOR_BACKWARD_BY_CHARACTER, extendSelection); + return true; + } + break; + } + case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: + if (forward && semanticsNode.hasAction(Action.MOVE_CURSOR_FORWARD_BY_WORD)) { + accessibilityChannel.dispatchSemanticsAction( + virtualViewId, Action.MOVE_CURSOR_FORWARD_BY_WORD, extendSelection); + return true; + } + if (!forward && semanticsNode.hasAction(Action.MOVE_CURSOR_BACKWARD_BY_WORD)) { + accessibilityChannel.dispatchSemanticsAction( + virtualViewId, Action.MOVE_CURSOR_BACKWARD_BY_WORD, extendSelection); + return true; + } + break; + case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE: + case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: + case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PAGE: + return true; + } + return false; + } + + private void predictCursorMovement( + @NonNull SemanticsNode node, int granularity, boolean forward, boolean extendSelection) { + if (node.textSelectionExtent < 0 || node.textSelectionBase < 0) { + return; + } + + switch (granularity) { + case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: + if (forward && node.textSelectionExtent < node.value.length()) { + node.textSelectionExtent += 1; + } else if (!forward && node.textSelectionExtent > 0) { + node.textSelectionExtent -= 1; + } + break; + case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: + if (forward && node.textSelectionExtent < node.value.length()) { + Pattern pattern = Pattern.compile("\\p{L}(\\b)"); + Matcher result = pattern.matcher(node.value.substring(node.textSelectionExtent)); + // we discard the first result because we want to find the "next" word + result.find(); + if (result.find()) { + node.textSelectionExtent += result.start(1); + } else { + node.textSelectionExtent = node.value.length(); + } + } else if (!forward && node.textSelectionExtent > 0) { + // Finds last beginning of the word boundary. + Pattern pattern = Pattern.compile("(?s:.*)(\\b)\\p{L}"); + Matcher result = pattern.matcher(node.value.substring(0, node.textSelectionExtent)); + if (result.find()) { + node.textSelectionExtent = result.start(1); + } + } + break; + case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE: + if (forward && node.textSelectionExtent < node.value.length()) { + // Finds the next new line. + Pattern pattern = Pattern.compile("(?!^)(\\n)"); + Matcher result = pattern.matcher(node.value.substring(node.textSelectionExtent)); + if (result.find()) { + node.textSelectionExtent += result.start(1); + } else { + node.textSelectionExtent = node.value.length(); + } + } else if (!forward && node.textSelectionExtent > 0) { + // Finds the last new line. + Pattern pattern = Pattern.compile("(?s:.*)(\\n)"); + Matcher result = pattern.matcher(node.value.substring(0, node.textSelectionExtent)); + if (result.find()) { + node.textSelectionExtent = result.start(1); + } else { + node.textSelectionExtent = 0; + } + } + break; + case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: + case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PAGE: + if (forward) { + node.textSelectionExtent = node.value.length(); + } else { + node.textSelectionExtent = 0; + } + break; + } + if (!extendSelection) { + node.textSelectionBase = node.textSelectionExtent; + } + } + + /** + * Handles the responsibilities of {@link #performAction(int, int, Bundle)} for the specific + * scenario of cursor movement. + */ + private boolean performSetText(SemanticsNode node, int virtualViewId, @NonNull Bundle arguments) { + String newText = ""; + if (arguments != null + && arguments.containsKey(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE)) { + newText = arguments.getString(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE); + } + accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.SET_TEXT, newText); + // The voice access expects the semantics node to update immediately. Update the semantics + // node based on prediction. If the result is incorrect, it will be updated in the next frame. + node.value = newText; + node.valueAttributes = null; + return true; + } + + // TODO(ianh): implement findAccessibilityNodeInfosByText() + + /** + * Finds the view in a hierarchy that currently has the given type of {@code focus}. + * + *

This method is invoked by Android's accessibility system. + * + *

Flutter does not have an Android {@link View} hierarchy. Therefore, Flutter conceptually + * handles this request by searching its semantics tree for the given {@code focus}, represented + * by {@link #flutterSemanticsTree}. In practice, this {@code AccessibilityBridge} always caches + * any active {@link #accessibilityFocusedSemanticsNode} and {@link #inputFocusedSemanticsNode}. + * Therefore, no searching is necessary. This method directly inspects the given {@code focus} + * type to return one of the cached nodes, null if the cached node is null, or null if a different + * {@code focus} type is requested. + */ + @Override + public AccessibilityNodeInfo findFocus(int focus) { + switch (focus) { + case AccessibilityNodeInfo.FOCUS_INPUT: + { + if (inputFocusedSemanticsNode != null) { + return createAccessibilityNodeInfo(inputFocusedSemanticsNode.id); + } + if (embeddedInputFocusedNodeId != null) { + return createAccessibilityNodeInfo(embeddedInputFocusedNodeId); + } + } + // Fall through to check FOCUS_ACCESSIBILITY + case AccessibilityNodeInfo.FOCUS_ACCESSIBILITY: + { + if (accessibilityFocusedSemanticsNode != null) { + return createAccessibilityNodeInfo(accessibilityFocusedSemanticsNode.id); + } + if (embeddedAccessibilityFocusedNodeId != null) { + return createAccessibilityNodeInfo(embeddedAccessibilityFocusedNodeId); + } + } + } + return null; + } + + /** Returns the {@link SemanticsNode} at the root of Flutter's semantics tree. */ + private SemanticsNode getRootSemanticsNode() { + if (BuildConfig.DEBUG && !flutterSemanticsTree.containsKey(0)) { + Log.e(TAG, "Attempted to getRootSemanticsNode without a root semantics node."); + } + return flutterSemanticsTree.get(0); + } + + /** + * Returns an existing {@link SemanticsNode} with the given {@code id}, if it exists within {@link + * #flutterSemanticsTree}, or creates and returns a new {@link SemanticsNode} with the given + * {@code id}, adding the new {@link SemanticsNode} to the {@link #flutterSemanticsTree}. + * + *

This method should only be invoked as a result of receiving new information from Flutter. + * The {@link #flutterSemanticsTree} is an Android cache of the last known state of a Flutter + * app's semantics tree, therefore, invoking this method in any other situation will result in a + * corrupt cache of Flutter's semantics tree. + */ + private SemanticsNode getOrCreateSemanticsNode(int id) { + SemanticsNode semanticsNode = flutterSemanticsTree.get(id); + if (semanticsNode == null) { + semanticsNode = new SemanticsNode(this); + semanticsNode.id = id; + flutterSemanticsTree.put(id, semanticsNode); + } + return semanticsNode; + } + + /** + * Returns an existing {@link CustomAccessibilityAction} with the given {@code id}, if it exists + * within {@link #customAccessibilityActions}, or creates and returns a new {@link + * CustomAccessibilityAction} with the given {@code id}, adding the new {@link + * CustomAccessibilityAction} to the {@link #customAccessibilityActions}. + * + *

This method should only be invoked as a result of receiving new information from Flutter. + * The {@link #customAccessibilityActions} is an Android cache of the last known state of a + * Flutter app's registered custom accessibility actions, therefore, invoking this method in any + * other situation will result in a corrupt cache of Flutter's accessibility actions. + */ + private CustomAccessibilityAction getOrCreateAccessibilityAction(int id) { + CustomAccessibilityAction action = customAccessibilityActions.get(id); + if (action == null) { + action = new CustomAccessibilityAction(); + action.id = id; + action.resourceId = id + FIRST_RESOURCE_ID; + customAccessibilityActions.put(id, action); + } + return action; + } + + /** + * A hover {@link MotionEvent} has occurred in the {@code View} that corresponds to this {@code + * AccessibilityBridge}. + * + *

This method returns true if Flutter's accessibility system handled the hover event, false + * otherwise. + * + *

This method should be invoked from the corresponding {@code View}'s {@link + * View#onHoverEvent(MotionEvent)}. + */ + public boolean onAccessibilityHoverEvent(MotionEvent event) { + return onAccessibilityHoverEvent(event, false); + } + + /** + * A hover {@link MotionEvent} has occurred in the {@code View} that corresponds to this {@code + * AccessibilityBridge}. + * + *

If {@code ignorePlatformViews} is true, if hit testing for the event finds a platform view, + * the event will not be handled. This is useful when handling accessibility events for views + * overlaying platform views. See {@code PlatformOverlayView} for details. + * + *

This method returns true if Flutter's accessibility system handled the hover event, false + * otherwise. + * + *

This method should be invoked from the corresponding {@code View}'s {@link + * View#onHoverEvent(MotionEvent)}. + */ + public boolean onAccessibilityHoverEvent(MotionEvent event, boolean ignorePlatformViews) { + if (!accessibilityManager.isTouchExplorationEnabled()) { + return false; + } + if (flutterSemanticsTree.isEmpty()) { + return false; + } + + SemanticsNode semanticsNodeUnderCursor = + getRootSemanticsNode() + .hitTest(new float[] {event.getX(), event.getY(), 0, 1}, ignorePlatformViews); + // semanticsNodeUnderCursor can be null when hovering over non-flutter UI such as + // the Android navigation bar due to hitTest() bounds checking. + if (semanticsNodeUnderCursor != null && semanticsNodeUnderCursor.platformViewId != -1) { + if (ignorePlatformViews) { + return false; + } + return accessibilityViewEmbedder.onAccessibilityHoverEvent( + semanticsNodeUnderCursor.id, event); + } + + if (event.getAction() == MotionEvent.ACTION_HOVER_ENTER + || event.getAction() == MotionEvent.ACTION_HOVER_MOVE) { + handleTouchExploration(event.getX(), event.getY(), ignorePlatformViews); + } else if (event.getAction() == MotionEvent.ACTION_HOVER_EXIT) { + onTouchExplorationExit(); + } else { + Log.d("flutter", "unexpected accessibility hover event: " + event); + return false; + } + return true; + } + + /** + * This method should be invoked when a hover interaction has the cursor move off of a {@code + * SemanticsNode}. + * + *

This method informs the Android accessibility system that a {@link + * AccessibilityEvent#TYPE_VIEW_HOVER_EXIT} has occurred. + */ + private void onTouchExplorationExit() { + if (hoveredObject != null) { + sendAccessibilityEvent(hoveredObject.id, AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); + hoveredObject = null; + } + } + + /** + * This method should be invoked when a new hover interaction begins with a {@code SemanticsNode}, + * or when an existing hover interaction sees a movement of the cursor. + * + *

This method checks to see if the cursor has moved from one {@code SemanticsNode} to another. + * If it has, this method informs the Android accessibility system of the change by first sending + * a {@link AccessibilityEvent#TYPE_VIEW_HOVER_ENTER} event for the new hover node, followed by a + * {@link AccessibilityEvent#TYPE_VIEW_HOVER_EXIT} event for the old hover node. + */ + private void handleTouchExploration(float x, float y, boolean ignorePlatformViews) { + if (flutterSemanticsTree.isEmpty()) { + return; + } + SemanticsNode semanticsNodeUnderCursor = + getRootSemanticsNode().hitTest(new float[] {x, y, 0, 1}, ignorePlatformViews); + if (semanticsNodeUnderCursor != hoveredObject) { + // sending ENTER before EXIT is how Android wants it + if (semanticsNodeUnderCursor != null) { + sendAccessibilityEvent( + semanticsNodeUnderCursor.id, AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); + } + if (hoveredObject != null) { + sendAccessibilityEvent(hoveredObject.id, AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); + } + hoveredObject = semanticsNodeUnderCursor; + } + } + + /** + * Updates the Android cache of Flutter's currently registered custom accessibility actions. + * + *

The buffer received here is encoded by PlatformViewAndroid::UpdateSemantics, and the decode + * logic here must be kept in sync with that method's encoding logic. + */ + // TODO(mattcarroll): Consider introducing ability to delete custom actions because they can + // probably come and go in Flutter, so we may want to reflect that here in + // the Android cache as well. + void updateCustomAccessibilityActions(@NonNull ByteBuffer buffer, @NonNull String[] strings) { + while (buffer.hasRemaining()) { + int id = buffer.getInt(); + CustomAccessibilityAction action = getOrCreateAccessibilityAction(id); + action.overrideId = buffer.getInt(); + int stringIndex = buffer.getInt(); + action.label = stringIndex == -1 ? null : strings[stringIndex]; + stringIndex = buffer.getInt(); + action.hint = stringIndex == -1 ? null : strings[stringIndex]; + } + } + + /** + * Updates {@link #flutterSemanticsTree} to reflect the latest state of Flutter's semantics tree. + * + *

The latest state of Flutter's semantics tree is encoded in the given {@code buffer}. The + * 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, + @NonNull ByteBuffer[] stringAttributeArgs) { + ArrayList updated = new ArrayList<>(); + while (buffer.hasRemaining()) { + int id = buffer.getInt(); + SemanticsNode semanticsNode = getOrCreateSemanticsNode(id); + semanticsNode.updateWith(buffer, strings, stringAttributeArgs); + if (semanticsNode.hasFlag(Flag.IS_HIDDEN)) { + continue; + } + if (semanticsNode.hasFlag(Flag.IS_FOCUSED)) { + inputFocusedSemanticsNode = semanticsNode; + } + if (semanticsNode.hadPreviousConfig) { + updated.add(semanticsNode); + } + if (semanticsNode.platformViewId != -1 + && !platformViewsAccessibilityDelegate.usesVirtualDisplay(semanticsNode.platformViewId)) { + View embeddedView = + platformViewsAccessibilityDelegate.getPlatformViewById(semanticsNode.platformViewId); + if (embeddedView != null) { + embeddedView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_AUTO); + } + } + } + + Set visitedObjects = new HashSet<>(); + SemanticsNode rootObject = getRootSemanticsNode(); + List newRoutes = new ArrayList<>(); + if (rootObject != null) { + final float[] identity = new float[16]; + Matrix.setIdentityM(identity, 0); + // In Android devices API 23 and above, the system nav bar can be placed on the left side + // of the screen in landscape mode. We must handle the translation ourselves for the + // a11y nodes. + if (Build.VERSION.SDK_INT >= API_LEVELS.API_23) { + boolean needsToApplyLeftCutoutInset = true; + // In Android devices API 28 and above, the `layoutInDisplayCutoutMode` window attribute + // can be set to allow overlapping content within the cutout area. Query the attribute + // to figure out whether the content overlaps with the cutout and decide whether to + // apply cutout inset. + if (Build.VERSION.SDK_INT >= API_LEVELS.API_28) { + needsToApplyLeftCutoutInset = doesLayoutInDisplayCutoutModeRequireLeftInset(); + } + + if (needsToApplyLeftCutoutInset) { + WindowInsets insets = rootAccessibilityView.getRootWindowInsets(); + if (insets != null) { + if (!lastLeftFrameInset.equals(insets.getSystemWindowInsetLeft())) { + rootObject.globalGeometryDirty = true; + rootObject.inverseTransformDirty = true; + } + lastLeftFrameInset = insets.getSystemWindowInsetLeft(); + Matrix.translateM(identity, 0, lastLeftFrameInset, 0, 0); + } + } + } + rootObject.updateRecursively(identity, visitedObjects, false); + rootObject.collectRoutes(newRoutes); + } + + // Dispatch a TYPE_WINDOW_STATE_CHANGED event if the most recent route id changed from the + // previously cached route id. + + // Finds the last route that is not in the previous routes. + SemanticsNode lastAdded = null; + for (SemanticsNode semanticsNode : newRoutes) { + if (!flutterNavigationStack.contains(semanticsNode.id)) { + lastAdded = semanticsNode; + } + } + + // If all the routes are in the previous route, get the last route. + if (lastAdded == null && newRoutes.size() > 0) { + lastAdded = newRoutes.get(newRoutes.size() - 1); + } + + // There are two cases if lastAdded != nil + // 1. lastAdded is not in previous routes. In this case, + // lastAdded.id != previousRouteId + // 2. All new routes are in previous routes and + // lastAdded = newRoutes.last. + // In the first case, we need to announce new route. In the second case, + // we need to announce if one list is shorter than the other. + if (lastAdded != null + && (lastAdded.id != previousRouteId || newRoutes.size() != flutterNavigationStack.size())) { + previousRouteId = lastAdded.id; + onWindowNameChange(lastAdded); + } + flutterNavigationStack.clear(); + for (SemanticsNode semanticsNode : newRoutes) { + flutterNavigationStack.add(semanticsNode.id); + } + + Iterator> it = flutterSemanticsTree.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry entry = it.next(); + SemanticsNode object = entry.getValue(); + if (!visitedObjects.contains(object)) { + willRemoveSemanticsNode(object); + it.remove(); + } + } + + // TODO(goderbauer): Send this event only once (!) for changed subtrees, + // see https://github.com/flutter/flutter/issues/14534 + sendWindowContentChangeEvent(0); + + for (SemanticsNode object : updated) { + if (object.didScroll()) { + AccessibilityEvent event = + obtainAccessibilityEvent(object.id, AccessibilityEvent.TYPE_VIEW_SCROLLED); + + // Android doesn't support unbound scrolling. So we pretend there is a large + // bound (SCROLL_EXTENT_FOR_INFINITY), which you can never reach. + float position = object.scrollPosition; + float max = object.scrollExtentMax; + if (Float.isInfinite(object.scrollExtentMax)) { + max = SCROLL_EXTENT_FOR_INFINITY; + if (position > SCROLL_POSITION_CAP_FOR_INFINITY) { + position = SCROLL_POSITION_CAP_FOR_INFINITY; + } + } + if (Float.isInfinite(object.scrollExtentMin)) { + max += SCROLL_EXTENT_FOR_INFINITY; + if (position < -SCROLL_POSITION_CAP_FOR_INFINITY) { + position = -SCROLL_POSITION_CAP_FOR_INFINITY; + } + position += SCROLL_EXTENT_FOR_INFINITY; + } else { + max -= object.scrollExtentMin; + position -= object.scrollExtentMin; + } + + if (object.hadAction(Action.SCROLL_UP) || object.hadAction(Action.SCROLL_DOWN)) { + event.setScrollY((int) position); + event.setMaxScrollY((int) max); + } else if (object.hadAction(Action.SCROLL_LEFT) || object.hadAction(Action.SCROLL_RIGHT)) { + event.setScrollX((int) position); + event.setMaxScrollX((int) max); + } + if (object.scrollChildren > 0) { + // We don't need to add 1 to the scroll index because TalkBack does this automagically. + event.setItemCount(object.scrollChildren); + event.setFromIndex(object.scrollIndex); + int visibleChildren = 0; + // handle hidden children at the beginning and end of the list. + for (SemanticsNode child : object.childrenInHitTestOrder) { + if (!child.hasFlag(Flag.IS_HIDDEN)) { + visibleChildren += 1; + } + } + if (BuildConfig.DEBUG) { + if (object.scrollIndex + visibleChildren > object.scrollChildren) { + Log.e(TAG, "Scroll index is out of bounds."); + } + + if (object.childrenInHitTestOrder.isEmpty()) { + Log.e(TAG, "Had scrollChildren but no childrenInHitTestOrder"); + } + } + // The setToIndex should be the index of the last visible child. Because we counted all + // children, including the first index we need to subtract one. + // + // [0, 1, 2, 3, 4, 5] + // ^ ^ + // In the example above where 0 is the first visible index and 2 is the last, we will + // count 3 total visible children. We then subtract one to get the correct last visible + // index of 2. + event.setToIndex(object.scrollIndex + visibleChildren - 1); + } + sendAccessibilityEvent(event); + } + if (object.hasFlag(Flag.IS_LIVE_REGION) && object.didChangeLabel()) { + sendWindowContentChangeEvent(object.id); + } + if (accessibilityFocusedSemanticsNode != null + && accessibilityFocusedSemanticsNode.id == object.id + && !object.hadFlag(Flag.IS_SELECTED) + && object.hasFlag(Flag.IS_SELECTED)) { + AccessibilityEvent event = + obtainAccessibilityEvent(object.id, AccessibilityEvent.TYPE_VIEW_SELECTED); + event.getText().add(object.label); + sendAccessibilityEvent(event); + } + + // If the object is the input-focused node, then tell the reader about it, but only if + // it has changed since the last update. + if (inputFocusedSemanticsNode != null + && inputFocusedSemanticsNode.id == object.id + && (lastInputFocusedSemanticsNode == null + || lastInputFocusedSemanticsNode.id != inputFocusedSemanticsNode.id)) { + lastInputFocusedSemanticsNode = inputFocusedSemanticsNode; + sendAccessibilityEvent( + obtainAccessibilityEvent(object.id, AccessibilityEvent.TYPE_VIEW_FOCUSED)); + } else if (inputFocusedSemanticsNode == null) { + // There's no TYPE_VIEW_CLEAR_FOCUSED event, so if the current input focus becomes + // null, then we just set the last one to null too, so that it sends the event again + // when something regains focus. + lastInputFocusedSemanticsNode = null; + } + + if (inputFocusedSemanticsNode != null + && inputFocusedSemanticsNode.id == object.id + && object.hadFlag(Flag.IS_TEXT_FIELD) + && object.hasFlag(Flag.IS_TEXT_FIELD) + // If we have a TextField that has InputFocus, we should avoid announcing it if something + // else we track has a11y focus. This needs to still work when, e.g., IME has a11y focus + // or the "PASTE" popup is used though. + // See more discussion at https://github.com/flutter/flutter/issues/23180 + && (accessibilityFocusedSemanticsNode == null + || (accessibilityFocusedSemanticsNode.id == inputFocusedSemanticsNode.id))) { + String oldValue = object.previousValue != null ? object.previousValue : ""; + String newValue = object.value != null ? object.value : ""; + AccessibilityEvent event = createTextChangedEvent(object.id, oldValue, newValue); + if (event != null) { + sendAccessibilityEvent(event); + } + + if (object.previousTextSelectionBase != object.textSelectionBase + || object.previousTextSelectionExtent != object.textSelectionExtent) { + AccessibilityEvent selectionEvent = + obtainAccessibilityEvent( + object.id, AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); + selectionEvent.getText().add(newValue); + selectionEvent.setFromIndex(object.textSelectionBase); + selectionEvent.setToIndex(object.textSelectionExtent); + selectionEvent.setItemCount(newValue.length()); + sendAccessibilityEvent(selectionEvent); + } + } + } + } + + private AccessibilityEvent createTextChangedEvent(int id, String oldValue, String newValue) { + AccessibilityEvent e = obtainAccessibilityEvent(id, AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED); + e.setBeforeText(oldValue); + e.getText().add(newValue); + + int i; + for (i = 0; i < oldValue.length() && i < newValue.length(); ++i) { + if (oldValue.charAt(i) != newValue.charAt(i)) { + break; + } + } + if (i >= oldValue.length() && i >= newValue.length()) { + return null; // Text did not change + } + int firstDifference = i; + e.setFromIndex(firstDifference); + + int oldIndex = oldValue.length() - 1; + int newIndex = newValue.length() - 1; + while (oldIndex >= firstDifference && newIndex >= firstDifference) { + if (oldValue.charAt(oldIndex) != newValue.charAt(newIndex)) { + break; + } + --oldIndex; + --newIndex; + } + e.setRemovedCount(oldIndex - firstDifference + 1); + e.setAddedCount(newIndex - firstDifference + 1); + + return e; + } + + /** + * Sends an accessibility event of the given {@code eventType} to Android's accessibility system + * with the given {@code viewId} represented as the source of the event. + * + *

The given {@code viewId} may either belong to {@link #rootAccessibilityView}, or any Flutter + * {@link SemanticsNode}. + */ + @VisibleForTesting + public void sendAccessibilityEvent(int viewId, int eventType) { + if (!accessibilityManager.isEnabled()) { + return; + } + sendAccessibilityEvent(obtainAccessibilityEvent(viewId, eventType)); + } + + /** + * Sends the given {@link AccessibilityEvent} to Android's accessibility system for a given + * Flutter {@link SemanticsNode}. + * + *

This method should only be called for a Flutter {@link SemanticsNode}, not a traditional + * Android {@code View}, i.e., {@link #rootAccessibilityView}. + */ + private void sendAccessibilityEvent(@NonNull AccessibilityEvent event) { + if (!accessibilityManager.isEnabled()) { + return; + } + // See + // https://developer.android.com/reference/android/view/View.html#sendAccessibilityEvent(int) + // We just want the final part at this point, since the event parameter + // has already been correctly populated. + rootAccessibilityView.getParent().requestSendAccessibilityEvent(rootAccessibilityView, event); + } + + /** + * Informs the TalkBack user about window name changes. + * + *

This method sets accessibility panel title if the API level >= 28, otherwise, it creates a + * {@link AccessibilityEvent#TYPE_WINDOW_STATE_CHANGED} and sends the event to Android's + * accessibility system. In both cases, TalkBack announces the label of the route and re-addjusts + * the accessibility focus. + * + *

The given {@code route} should be a {@link SemanticsNode} that represents a navigation route + * in the Flutter app. + */ + private void onWindowNameChange(@NonNull SemanticsNode route) { + String routeName = route.getRouteName(); + if (routeName == null) { + // The routeName will be null when there is no semantics node that represnets namesRoute in + // the scopeRoute. The TYPE_WINDOW_STATE_CHANGED only works the route name is not null and not + // empty. Gives it a whitespace will make it focus the first semantics node without + // pronouncing any word. + // + // The other way to trigger a focus change is to send a TYPE_VIEW_FOCUSED to the + // rootAccessibilityView. However, it is less predictable which semantics node it will focus + // next. + routeName = " "; + } + if (Build.VERSION.SDK_INT >= API_LEVELS.API_28) { + setAccessibilityPaneTitle(routeName); + } else { + AccessibilityEvent event = + obtainAccessibilityEvent(route.id, AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); + event.getText().add(routeName); + sendAccessibilityEvent(event); + } + } + + @TargetApi(API_LEVELS.API_28) + @RequiresApi(API_LEVELS.API_28) + private void setAccessibilityPaneTitle(String title) { + rootAccessibilityView.setAccessibilityPaneTitle(title); + } + + /** + * Creates a {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} and sends the event to + * Android's accessibility system. + * + *

It sets the content change types to {@link AccessibilityEvent#CONTENT_CHANGE_TYPE_SUBTREE} + * when supported by the API level. + * + *

The given {@code virtualViewId} should be a {@link SemanticsNode} below which the content + * has changed. + */ + private void sendWindowContentChangeEvent(int virtualViewId) { + AccessibilityEvent event = + obtainAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); + event.setContentChangeTypes(AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); + sendAccessibilityEvent(event); + } + + /** + * Factory method that creates a new {@link AccessibilityEvent} that is configured to represent + * the Flutter {@link SemanticsNode} represented by the given {@code virtualViewId}, categorized + * as the given {@code eventType}. + * + *

This method should *only* be called for Flutter {@link SemanticsNode}s. It should *not* be + * invoked to create an {@link AccessibilityEvent} for the {@link #rootAccessibilityView}. + */ + private AccessibilityEvent obtainAccessibilityEvent(int virtualViewId, int eventType) { + AccessibilityEvent event = obtainAccessibilityEvent(eventType); + event.setPackageName(rootAccessibilityView.getContext().getPackageName()); + event.setSource(rootAccessibilityView, virtualViewId); + return event; + } + + @VisibleForTesting + public AccessibilityEvent obtainAccessibilityEvent(int eventType) { + return AccessibilityEvent.obtain(eventType); + } + + /** + * Reads the {@code layoutInDisplayCutoutMode} value from the window attribute and returns whether + * a left cutout inset is required. + * + *

The {@code layoutInDisplayCutoutMode} is added after API level 28. + */ + @TargetApi(API_LEVELS.API_28) + @RequiresApi(API_LEVELS.API_28) + private boolean doesLayoutInDisplayCutoutModeRequireLeftInset() { + Context context = rootAccessibilityView.getContext(); + Activity activity = ViewUtils.getActivity(context); + if (activity == null || activity.getWindow() == null) { + // The activity is not visible, it does not matter whether to apply left inset + // or not. + return false; + } + int layoutInDisplayCutoutMode = activity.getWindow().getAttributes().layoutInDisplayCutoutMode; + return layoutInDisplayCutoutMode + == WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER + || layoutInDisplayCutoutMode + == WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT; + } + + /** + * Hook called just before a {@link SemanticsNode} is removed from the Android cache of Flutter's + * semantics tree. + */ + private void willRemoveSemanticsNode(SemanticsNode semanticsNodeToBeRemoved) { + if (BuildConfig.DEBUG) { + if (!flutterSemanticsTree.containsKey(semanticsNodeToBeRemoved.id)) { + Log.e(TAG, "Attempted to remove a node that is not in the tree."); + } + if (flutterSemanticsTree.get(semanticsNodeToBeRemoved.id) != semanticsNodeToBeRemoved) { + Log.e(TAG, "Flutter semantics tree failed to get expected node when searching by id."); + } + } + // TODO(mattcarroll): should parent be set to "null" here? Changing the parent seems like the + // behavior of a method called "removeSemanticsNode()". The same is true + // for null'ing accessibilityFocusedSemanticsNode, inputFocusedSemanticsNode, + // and hoveredObject. Is this a hook method or a command? + semanticsNodeToBeRemoved.parent = null; + + if (semanticsNodeToBeRemoved.platformViewId != -1 + && embeddedAccessibilityFocusedNodeId != null + && accessibilityViewEmbedder.platformViewOfNode(embeddedAccessibilityFocusedNodeId) + == platformViewsAccessibilityDelegate.getPlatformViewById( + semanticsNodeToBeRemoved.platformViewId)) { + // If the currently focused a11y node is within a platform view that is + // getting removed: clear it's a11y focus. + sendAccessibilityEvent( + embeddedAccessibilityFocusedNodeId, + AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); + embeddedAccessibilityFocusedNodeId = null; + } + + if (semanticsNodeToBeRemoved.platformViewId != -1) { + View embeddedView = + platformViewsAccessibilityDelegate.getPlatformViewById( + semanticsNodeToBeRemoved.platformViewId); + if (embeddedView != null) { + embeddedView.setImportantForAccessibility( + View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); + } + } + + if (accessibilityFocusedSemanticsNode == semanticsNodeToBeRemoved) { + sendAccessibilityEvent( + accessibilityFocusedSemanticsNode.id, + AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); + accessibilityFocusedSemanticsNode = null; + } + + if (inputFocusedSemanticsNode == semanticsNodeToBeRemoved) { + inputFocusedSemanticsNode = null; + } + + if (hoveredObject == semanticsNodeToBeRemoved) { + hoveredObject = null; + } + } + + /** + * Resets the {@code AccessibilityBridge}: + * + *

    + *
  • Clears {@link #flutterSemanticsTree}, the Android cache of Flutter's semantics tree + *
  • Releases focus on any active {@link #accessibilityFocusedSemanticsNode} + *
  • Clears any hovered {@code SemanticsNode} + *
  • Sends a {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event + *
+ */ + // TODO(mattcarroll): under what conditions is this method expected to be invoked? + public void reset() { + flutterSemanticsTree.clear(); + if (accessibilityFocusedSemanticsNode != null) { + sendAccessibilityEvent( + accessibilityFocusedSemanticsNode.id, + AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); + } + accessibilityFocusedSemanticsNode = null; + hoveredObject = null; + sendWindowContentChangeEvent(0); + } + + /** + * Listener that can be set on a {@link AccessibilityBridge}, which is invoked any time + * accessibility is turned on/off, or touch exploration is turned on/off. + */ + public interface OnAccessibilityChangeListener { + void onAccessibilityChanged(boolean isAccessibilityEnabled, boolean isTouchExplorationEnabled); + } + + // Must match SemanticsActions in semantics.dart + // https://github.com/flutter/engine/blob/main/lib/ui/semantics.dart + public enum Action { + TAP(1 << 0), + LONG_PRESS(1 << 1), + SCROLL_LEFT(1 << 2), + SCROLL_RIGHT(1 << 3), + SCROLL_UP(1 << 4), + SCROLL_DOWN(1 << 5), + INCREASE(1 << 6), + DECREASE(1 << 7), + SHOW_ON_SCREEN(1 << 8), + MOVE_CURSOR_FORWARD_BY_CHARACTER(1 << 9), + MOVE_CURSOR_BACKWARD_BY_CHARACTER(1 << 10), + SET_SELECTION(1 << 11), + COPY(1 << 12), + CUT(1 << 13), + PASTE(1 << 14), + DID_GAIN_ACCESSIBILITY_FOCUS(1 << 15), + DID_LOSE_ACCESSIBILITY_FOCUS(1 << 16), + CUSTOM_ACTION(1 << 17), + DISMISS(1 << 18), + MOVE_CURSOR_FORWARD_BY_WORD(1 << 19), + MOVE_CURSOR_BACKWARD_BY_WORD(1 << 20), + SET_TEXT(1 << 21), + FOCUS(1 << 22), + SCROLL_TO_OFFSET(1 << 23); + + public final int value; + + Action(int value) { + this.value = value; + } + } + + // Actions that are triggered by Android OS, as opposed to user-triggered actions. + // + // This int is intended to be use in a bitwise comparison. + static int systemAction = + Action.DID_GAIN_ACCESSIBILITY_FOCUS.value + & Action.DID_LOSE_ACCESSIBILITY_FOCUS.value + & Action.SHOW_ON_SCREEN.value; + + // Must match SemanticsFlag in semantics.dart + // https://github.com/flutter/engine/blob/main/lib/ui/semantics.dart + /* Package */ enum Flag { + HAS_CHECKED_STATE(1 << 0), + IS_CHECKED(1 << 1), + IS_SELECTED(1 << 2), + IS_BUTTON(1 << 3), + IS_TEXT_FIELD(1 << 4), + IS_FOCUSED(1 << 5), + HAS_ENABLED_STATE(1 << 6), + IS_ENABLED(1 << 7), + IS_IN_MUTUALLY_EXCLUSIVE_GROUP(1 << 8), + IS_HEADER(1 << 9), + IS_OBSCURED(1 << 10), + SCOPES_ROUTE(1 << 11), + NAMES_ROUTE(1 << 12), + IS_HIDDEN(1 << 13), + IS_IMAGE(1 << 14), + IS_LIVE_REGION(1 << 15), + HAS_TOGGLED_STATE(1 << 16), + IS_TOGGLED(1 << 17), + HAS_IMPLICIT_SCROLLING(1 << 18), + IS_MULTILINE(1 << 19), + IS_READ_ONLY(1 << 20), + IS_FOCUSABLE(1 << 21), + IS_LINK(1 << 22), + IS_SLIDER(1 << 23), + IS_KEYBOARD_KEY(1 << 24), + IS_CHECK_STATE_MIXED(1 << 25), + HAS_EXPANDED_STATE(1 << 26), + IS_EXPANDED(1 << 27), + HAS_SELECTED_STATE(1 << 28), + HAS_REQUIRED_STATE(1 << 29), + IS_REQUIRED(1 << 30); + + final int value; + + Flag(int value) { + this.value = value; + } + } + + // Must match the enum defined in window.dart. + private enum AccessibilityFeature { + ACCESSIBLE_NAVIGATION(1 << 0), + INVERT_COLORS(1 << 1), // NOT SUPPORTED + DISABLE_ANIMATIONS(1 << 2), + BOLD_TEXT(1 << 3), // NOT SUPPORTED + REDUCE_MOTION(1 << 4), // NOT SUPPORTED + HIGH_CONTRAST(1 << 5), // NOT SUPPORTED + ON_OFF_SWITCH_LABELS(1 << 6); // NOT SUPPORTED + + final int value; + + AccessibilityFeature(int value) { + this.value = value; + } + } + + private enum TextDirection { + UNKNOWN, + LTR, + RTL; + + public static TextDirection fromInt(int value) { + switch (value) { + case 1: + return RTL; + case 2: + return LTR; + } + return UNKNOWN; + } + } + + /** + * Accessibility action that is defined within a given Flutter application, as opposed to the + * standard accessibility actions that are available in the Flutter framework. + * + *

Flutter and Android support a number of built-in accessibility actions. However, these + * predefined actions are not always sufficient for a desired interaction. Android facilitates + * custom accessibility actions, + * https://developer.android.com/reference/android/view/accessibility/AccessibilityNodeInfo.AccessibilityAction. + * Flutter supports custom accessibility actions via {@code customSemanticsActions} within a + * {@code Semantics} widget, https://api.flutter.dev/flutter/widgets/Semantics-class.html. + * + *

See the Android documentation for custom accessibility actions: + * https://developer.android.com/reference/android/view/accessibility/AccessibilityNodeInfo.AccessibilityAction + * + *

See the Flutter documentation for the Semantics widget: + * https://api.flutter.dev/flutter/widgets/Semantics-class.html + */ + private static class CustomAccessibilityAction { + CustomAccessibilityAction() {} + + // The ID of the custom action plus a minimum value so that the identifier + // does not collide with existing Android accessibility actions. This ID + // represents and Android resource ID, not a Flutter ID. + private int resourceId = -1; + + // The Flutter ID of this custom accessibility action. See Flutter's Semantics widget for + // custom accessibility action definitions: + // https://api.flutter.dev/flutter/widgets/Semantics-class.html + private int id = -1; + + // The ID of the standard Flutter accessibility action that this {@code + // CustomAccessibilityAction} + // overrides with a custom {@code label} and/or {@code hint}. + private int overrideId = -1; + + // The user presented value which is displayed in the local context menu. + private String label; + + // The text used in overridden standard actions. + 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/semantics.dart + // * engine/src/flutter/lib/ui/semantics/string_attribute.h + + private enum StringAttributeType { + SPELLOUT, + LOCALE, + URL + } + + private static class StringAttribute { + int start; + int end; + StringAttributeType type; + } + + private static class SpellOutStringAttribute extends StringAttribute {} + + private static class LocaleStringAttribute extends StringAttribute { + String locale; + } + + private static class UrlStringAttribute extends StringAttribute { + String url; + } + + /** + * Flutter {@code SemanticsNode} represented in Java/Android. + * + *

Flutter maintains a semantics tree that is controlled by, but is independent of Flutter's + * element tree, i.e., widgets/elements/render objects. Flutter's semantics tree must be cached on + * the Android side so that Android can query any {@code SemanticsNode} at any time. This class + * represents a single node in the semantics tree, and it is a Java representation of the + * analogous concept within Flutter. + * + *

To see how this {@code SemanticsNode}'s fields correspond to Flutter's semantics system, see + * semantics.dart: https://github.com/flutter/engine/blob/main/lib/ui/semantics.dart + */ + private static class SemanticsNode { + private static boolean nullableHasAncestor( + SemanticsNode target, Predicate tester) { + return target != null && target.getAncestor(tester) != null; + } + + final AccessibilityBridge accessibilityBridge; + + // Flutter ID of this {@code SemanticsNode}. + private int id = -1; + + private int flags; + private int actions; + private int maxValueLength; + private int currentValueLength; + private int textSelectionBase; + private int textSelectionExtent; + private int platformViewId; + private int scrollChildren; + private int scrollIndex; + private float scrollPosition; + private float scrollExtentMax; + private float scrollExtentMin; + private String identifier; + 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 textual description of the backing widget's tooltip. + // + // The tooltip is attached through AccessibilityNodeInfo.setTooltipText if + // API level >= 28; otherwise, this is attached to the end of content description. + @Nullable private String tooltip; + + // The Url the widget's points to. + @Nullable private String linkUrl; + + // The id of the sibling node that is before this node in traversal + // order. + // + // The child order alone does not guarantee the TalkBack focus traversal + // order. The AccessibilityNodeInfo.setTraversalAfter must be called with + // its previous sibling to determine the focus traversal order. + // + // This property is updated in AccessibilityBridge.updateRecursively, + // which is called at the end of every semantics update, and it is used in + // AccessibilityBridge.createAccessibilityNodeInfo to set the "traversal + // after" of this node. + private int previousNodeId = -1; + + // See Flutter's {@code SemanticsNode#textDirection}. + private TextDirection textDirection; + + private boolean hadPreviousConfig = false; + private int previousFlags; + private int previousActions; + private int previousTextSelectionBase; + private int previousTextSelectionExtent; + private float previousScrollPosition; + private float previousScrollExtentMax; + private float previousScrollExtentMin; + private String previousValue; + private String previousLabel; + + private float left; + private float top; + private float right; + private float bottom; + private float[] transform; + + private SemanticsNode parent; + private List childrenInTraversalOrder = new ArrayList<>(); + private List childrenInHitTestOrder = new ArrayList<>(); + private List customAccessibilityActions; + private CustomAccessibilityAction onTapOverride; + private CustomAccessibilityAction onLongPressOverride; + + private boolean inverseTransformDirty = true; + private float[] inverseTransform; + + private boolean globalGeometryDirty = true; + private float[] globalTransform; + private Rect globalRect; + + SemanticsNode(@NonNull AccessibilityBridge accessibilityBridge) { + this.accessibilityBridge = accessibilityBridge; + } + + /** + * Returns the ancestor of this {@code SemanticsNode} for which {@link Predicate#test(Object)} + * returns true, or null if no such ancestor exists. + */ + private SemanticsNode getAncestor(Predicate tester) { + SemanticsNode nextAncestor = parent; + while (nextAncestor != null) { + if (tester.test(nextAncestor)) { + return nextAncestor; + } + nextAncestor = nextAncestor.parent; + } + return null; + } + + /** + * Returns true if the given {@code action} is supported by this {@code SemanticsNode}. + * + *

This method only applies to this {@code SemanticsNode} and does not implicitly search its + * children. + */ + private boolean hasAction(@NonNull Action action) { + return (actions & action.value) != 0; + } + + /** + * Returns true if the given {@code action} was supported by the immediately previous version of + * this {@code SemanticsNode}. + */ + private boolean hadAction(@NonNull Action action) { + return (previousActions & action.value) != 0; + } + + private boolean hasFlag(@NonNull Flag flag) { + return (flags & flag.value) != 0; + } + + private boolean hadFlag(@NonNull Flag flag) { + if (BuildConfig.DEBUG && !hadPreviousConfig) { + Log.e(TAG, "Attempted to check hadFlag but had no previous config."); + } + return (previousFlags & flag.value) != 0; + } + + private boolean didScroll() { + return !Float.isNaN(scrollPosition) + && !Float.isNaN(previousScrollPosition) + && previousScrollPosition != scrollPosition; + } + + private boolean didChangeLabel() { + if (label == null && previousLabel == null) { + return false; + } + return label == null || previousLabel == null || !label.equals(previousLabel); + } + + private void log(@NonNull String indent, boolean recursive) { + if (BuildConfig.DEBUG) { + Log.i( + TAG, + indent + + "SemanticsNode id=" + + id + + " identifier=" + + identifier + + " label=" + + label + + " actions=" + + actions + + " flags=" + + flags + + "\n" + + indent + + " +-- textDirection=" + + textDirection + + "\n" + + indent + + " +-- rect.ltrb=(" + + left + + ", " + + top + + ", " + + right + + ", " + + bottom + + ")\n" + + indent + + " +-- transform=" + + Arrays.toString(transform) + + "\n"); + if (recursive) { + String childIndent = indent + " "; + for (SemanticsNode child : childrenInTraversalOrder) { + child.log(childIndent, recursive); + } + } + } + } + + private void updateWith( + @NonNull ByteBuffer buffer, + @NonNull String[] strings, + @NonNull ByteBuffer[] stringAttributeArgs) { + hadPreviousConfig = true; + previousValue = value; + previousLabel = label; + previousFlags = flags; + previousActions = actions; + previousTextSelectionBase = textSelectionBase; + previousTextSelectionExtent = textSelectionExtent; + previousScrollPosition = scrollPosition; + previousScrollExtentMax = scrollExtentMax; + previousScrollExtentMin = scrollExtentMin; + + flags = buffer.getInt(); + actions = buffer.getInt(); + maxValueLength = buffer.getInt(); + currentValueLength = buffer.getInt(); + textSelectionBase = buffer.getInt(); + textSelectionExtent = buffer.getInt(); + platformViewId = buffer.getInt(); + scrollChildren = buffer.getInt(); + scrollIndex = buffer.getInt(); + scrollPosition = buffer.getFloat(); + scrollExtentMax = buffer.getFloat(); + scrollExtentMin = buffer.getFloat(); + + int stringIndex = buffer.getInt(); + + identifier = stringIndex == -1 ? null : strings[stringIndex]; + 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); + + stringIndex = buffer.getInt(); + tooltip = stringIndex == -1 ? null : strings[stringIndex]; + + stringIndex = buffer.getInt(); + linkUrl = stringIndex == -1 ? null : strings[stringIndex]; + + textDirection = TextDirection.fromInt(buffer.getInt()); + + left = buffer.getFloat(); + top = buffer.getFloat(); + right = buffer.getFloat(); + bottom = buffer.getFloat(); + + if (transform == null) { + transform = new float[16]; + } + for (int i = 0; i < 16; ++i) { + transform[i] = buffer.getFloat(); + } + inverseTransformDirty = true; + globalGeometryDirty = true; + + final int childCount = buffer.getInt(); + childrenInTraversalOrder.clear(); + childrenInHitTestOrder.clear(); + for (int i = 0; i < childCount; ++i) { + SemanticsNode child = accessibilityBridge.getOrCreateSemanticsNode(buffer.getInt()); + child.parent = this; + childrenInTraversalOrder.add(child); + } + for (int i = 0; i < childCount; ++i) { + SemanticsNode child = accessibilityBridge.getOrCreateSemanticsNode(buffer.getInt()); + child.parent = this; + childrenInHitTestOrder.add(child); + } + + final int actionCount = buffer.getInt(); + if (actionCount == 0) { + customAccessibilityActions = null; + } else { + if (customAccessibilityActions == null) + customAccessibilityActions = new ArrayList<>(actionCount); + else customAccessibilityActions.clear(); + + for (int i = 0; i < actionCount; i++) { + CustomAccessibilityAction action = + accessibilityBridge.getOrCreateAccessibilityAction(buffer.getInt()); + if (action.overrideId == Action.TAP.value) { + onTapOverride = action; + } else if (action.overrideId == Action.LONG_PRESS.value) { + onLongPressOverride = action; + } else { + // If we receive a different overrideId it means that we were passed + // a standard action to override that we don't yet support. + if (BuildConfig.DEBUG && action.overrideId != -1) { + Log.e(TAG, "Expected action.overrideId to be -1."); + } + customAccessibilityActions.add(action); + } + customAccessibilityActions.add(action); + } + } + } + + 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; + } + inverseTransformDirty = false; + if (inverseTransform == null) { + inverseTransform = new float[16]; + } + if (!Matrix.invertM(inverseTransform, 0, transform, 0)) { + Arrays.fill(inverseTransform, 0); + } + } + + private Rect getGlobalRect() { + if (BuildConfig.DEBUG && globalGeometryDirty) { + Log.e(TAG, "Attempted to getGlobalRect with a dirty geometry."); + } + return globalRect; + } + + /** + * Hit tests {@code point} to find the deepest focusable node in the node tree at that point. + * + * @param point The point to hit test against this node. + * @param stopAtPlatformView Whether to return a platform view if found, regardless of whether + * or not it is focusable. + * @return The found node, or null if no relevant node was found at the given point. + */ + private SemanticsNode hitTest(float[] point, boolean stopAtPlatformView) { + final float w = point[3]; + final float x = point[0] / w; + final float y = point[1] / w; + if (x < left || x >= right || y < top || y >= bottom) return null; + final float[] transformedPoint = new float[4]; + for (SemanticsNode child : childrenInHitTestOrder) { + if (child.hasFlag(Flag.IS_HIDDEN)) { + continue; + } + child.ensureInverseTransform(); + Matrix.multiplyMV(transformedPoint, 0, child.inverseTransform, 0, point, 0); + final SemanticsNode result = child.hitTest(transformedPoint, stopAtPlatformView); + if (result != null) { + return result; + } + } + final boolean foundPlatformView = stopAtPlatformView && platformViewId != -1; + return isFocusable() || foundPlatformView ? this : null; + } + + // TODO(goderbauer): This should be decided by the framework once we have more information + // about focusability there. + private boolean isFocusable() { + // We enforce in the framework that no other useful semantics are merged with these + // nodes. + if (hasFlag(Flag.SCOPES_ROUTE)) { + return false; + } + if (hasFlag(Flag.IS_FOCUSABLE)) { + return true; + } + // If not explicitly set as focusable, then use our legacy + // algorithm. Once all focusable widgets have a Focus widget, then + // this won't be needed. + return (actions & ~SCROLLABLE_ACTIONS) != 0 + || (flags & FOCUSABLE_FLAGS) != 0 + || (label != null && !label.isEmpty()) + || (value != null && !value.isEmpty()) + || (hint != null && !hint.isEmpty()); + } + + private void collectRoutes(List edges) { + if (hasFlag(Flag.SCOPES_ROUTE)) { + edges.add(this); + } + for (SemanticsNode child : childrenInTraversalOrder) { + child.collectRoutes(edges); + } + } + + private String getRouteName() { + // Returns the first non-null and non-empty semantic label of a child + // with an NamesRoute flag. Otherwise returns null. + if (hasFlag(Flag.NAMES_ROUTE)) { + if (label != null && !label.isEmpty()) { + return label; + } + } + for (SemanticsNode child : childrenInTraversalOrder) { + String newName = child.getRouteName(); + if (newName != null && !newName.isEmpty()) { + return newName; + } + } + return null; + } + + private void updateRecursively( + float[] ancestorTransform, Set visitedObjects, boolean forceUpdate) { + visitedObjects.add(this); + + if (globalGeometryDirty) { + forceUpdate = true; + } + + if (forceUpdate) { + if (globalTransform == null) { + globalTransform = new float[16]; + } + if (transform == null) { + if (BuildConfig.DEBUG) { + Log.e(TAG, "transform has not been initialized for id = " + id); + accessibilityBridge.getRootSemanticsNode().log("Semantics tree:", true); + } + transform = new float[16]; + } + Matrix.multiplyMM(globalTransform, 0, ancestorTransform, 0, transform, 0); + + final float[] sample = new float[4]; + sample[2] = 0; + sample[3] = 1; + + final float[] point1 = new float[4]; + final float[] point2 = new float[4]; + final float[] point3 = new float[4]; + final float[] point4 = new float[4]; + + sample[0] = left; + sample[1] = top; + transformPoint(point1, globalTransform, sample); + + sample[0] = right; + sample[1] = top; + transformPoint(point2, globalTransform, sample); + + sample[0] = right; + sample[1] = bottom; + transformPoint(point3, globalTransform, sample); + + sample[0] = left; + sample[1] = bottom; + transformPoint(point4, globalTransform, sample); + + if (globalRect == null) globalRect = new Rect(); + + globalRect.set( + Math.round(min(point1[0], point2[0], point3[0], point4[0])), + Math.round(min(point1[1], point2[1], point3[1], point4[1])), + Math.round(max(point1[0], point2[0], point3[0], point4[0])), + Math.round(max(point1[1], point2[1], point3[1], point4[1]))); + + globalGeometryDirty = false; + } + + if (BuildConfig.DEBUG) { + if (globalTransform == null) { + Log.e(TAG, "Expected globalTransform to not be null."); + } + if (globalRect == null) { + Log.e(TAG, "Expected globalRect to not be null."); + } + } + + int previousNodeId = -1; + for (SemanticsNode child : childrenInTraversalOrder) { + child.previousNodeId = previousNodeId; + previousNodeId = child.id; + child.updateRecursively(globalTransform, visitedObjects, forceUpdate); + } + } + + private void transformPoint(float[] result, float[] transform, float[] point) { + Matrix.multiplyMV(result, 0, transform, 0, point, 0); + final float w = result[3]; + result[0] /= w; + result[1] /= w; + result[2] /= w; + result[3] = 0; + } + + private float min(float a, float b, float c, float d) { + return Math.min(a, Math.min(b, Math.min(c, d))); + } + + private float max(float a, float b, float c, float d) { + return Math.max(a, Math.max(b, Math.max(c, d))); + } + + private CharSequence getValue() { + return createSpannableString(value, valueAttributes); + } + + private CharSequence getLabel() { + List attributes = labelAttributes; + if (linkUrl != null && linkUrl.length() > 0) { + if (attributes == null) { + attributes = new ArrayList(); + } else { + attributes = new ArrayList(attributes); + } + UrlStringAttribute uriStringAttribute = new UrlStringAttribute(); + uriStringAttribute.start = 0; + uriStringAttribute.end = label.length(); + uriStringAttribute.url = linkUrl; + uriStringAttribute.type = StringAttributeType.URL; + attributes.add(uriStringAttribute); + } + return createSpannableString(label, attributes); + } + + private CharSequence getHint() { + return createSpannableString(hint, hintAttributes); + } + + private CharSequence getValueLabelHint() { + CharSequence[] array = new CharSequence[] {getValue(), getLabel(), getHint()}; + CharSequence result = null; + for (CharSequence word : array) { + if (word != null && word.length() > 0) { + if (result == null || result.length() == 0) { + result = word; + } else { + result = TextUtils.concat(result, ", ", word); + } + } + } + return result; + } + + private CharSequence getTextFieldHint() { + CharSequence[] array = new CharSequence[] {getLabel(), getHint()}; + CharSequence result = null; + for (CharSequence word : array) { + if (word != null && word.length() > 0) { + if (result == null || result.length() == 0) { + result = word; + } else { + result = TextUtils.concat(result, ", ", word); + } + } + } + return result; + } + + 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; + } + case URL: + { + UrlStringAttribute uriAttribute = (UrlStringAttribute) attribute; + final URLSpan urlSpan = new URLSpan(uriAttribute.url); + spannableString.setSpan(urlSpan, attribute.start, attribute.end, 0); + break; + } + } + } + } + return spannableString; + } + } + + /** + * Delegates handling of {@link android.view.ViewParent#requestSendAccessibilityEvent} to the + * accessibility bridge. + * + *

This is used by embedded platform views to propagate accessibility events from their view + * hierarchy to the accessibility bridge. + * + *

As the embedded view doesn't have to be the only View in the embedded hierarchy (it can have + * child views) and the event might have been originated from any view in this hierarchy, this + * method gets both a reference to the embedded platform view, and a reference to the view from + * its hierarchy that sent the event. + * + * @param embeddedView the embedded platform view for which the event is delegated + * @param eventOrigin the view in the embedded view's hierarchy that sent the event. + * @return True if the event was sent. + */ + // AccessibilityEvent has many irrelevant cases that would be confusing to list. + @SuppressLint("SwitchIntDef") + public boolean externalViewRequestSendAccessibilityEvent( + View embeddedView, View eventOrigin, AccessibilityEvent event) { + if (!accessibilityViewEmbedder.requestSendAccessibilityEvent( + embeddedView, eventOrigin, event)) { + return false; + } + Integer virtualNodeId = accessibilityViewEmbedder.getRecordFlutterId(embeddedView, event); + if (virtualNodeId == null) { + return false; + } + switch (event.getEventType()) { + case AccessibilityEvent.TYPE_VIEW_HOVER_ENTER: + hoveredObject = null; + break; + case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: + embeddedAccessibilityFocusedNodeId = virtualNodeId; + accessibilityFocusedSemanticsNode = null; + break; + case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: + embeddedInputFocusedNodeId = null; + embeddedAccessibilityFocusedNodeId = null; + break; + case AccessibilityEvent.TYPE_VIEW_FOCUSED: + embeddedInputFocusedNodeId = virtualNodeId; + inputFocusedSemanticsNode = null; + break; + } + return true; + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/view/AccessibilityViewEmbedder.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/view/AccessibilityViewEmbedder.java new file mode 100644 index 0000000000000000000000000000000000000000..7260d4a8681a50441e0c2d127248a5b39622009c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/view/AccessibilityViewEmbedder.java @@ -0,0 +1,626 @@ +// 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. + +package io.flutter.view; + +import static io.flutter.Build.API_LEVELS; + +import android.annotation.SuppressLint; +import android.graphics.Rect; +import android.os.Build; +import android.os.Bundle; +import android.os.Parcel; +import android.util.SparseArray; +import android.view.MotionEvent; +import android.view.View; +import android.view.accessibility.AccessibilityEvent; +import android.view.accessibility.AccessibilityNodeInfo; +import android.view.accessibility.AccessibilityNodeProvider; +import android.view.accessibility.AccessibilityRecord; +import androidx.annotation.Keep; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import io.flutter.Log; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +/** + * Facilitates embedding of platform views in the accessibility tree generated by the accessibility + * bridge. + * + *

Embedding is done by mirroring the accessibility tree of the platform view as a subtree of the + * flutter accessibility tree. + * + *

This class relies on hidden system APIs to extract the accessibility information and does not + * work starting Android P; If the reflection accessors are not available we fail silently by + * embedding a null node, the app continues working but the accessibility information for the + * platform view will not be embedded. + * + *

We use the term `flutterId` for virtual accessibility node IDs in the FlutterView tree, and + * the term `originId` for the virtual accessibility node IDs in the platform view's tree. + * Internally this class maintains a bidirectional mapping between `flutterId`s and the + * corresponding platform view and `originId`. + */ +@Keep +class AccessibilityViewEmbedder { + private static final String TAG = "AccessibilityBridge"; + + private final ReflectionAccessors reflectionAccessors; + + // The view to which the platform view is embedded, this is typically FlutterView. + private final View rootAccessibilityView; + + // Maps a flutterId to the corresponding platform view and originId. + private final SparseArray flutterIdToOrigin; + + // Maps a platform view and originId to a corresponding flutterID. + private final Map originToFlutterId; + + // Maps an embedded view to it's screen bounds. + // This is used to translate the coordinates of the accessibility node subtree to the main + // display's coordinate + // system. + private final Map embeddedViewToDisplayBounds; + + private int nextFlutterId; + + AccessibilityViewEmbedder(@NonNull View rootAccessibiiltyView, int firstVirtualNodeId) { + reflectionAccessors = new ReflectionAccessors(); + flutterIdToOrigin = new SparseArray<>(); + this.rootAccessibilityView = rootAccessibiiltyView; + nextFlutterId = firstVirtualNodeId; + originToFlutterId = new HashMap<>(); + embeddedViewToDisplayBounds = new HashMap<>(); + } + + /** + * Returns the root accessibility node for an embedded platform view. + * + * @param flutterId the virtual accessibility ID for the node in flutter accessibility tree + * @param displayBounds the display bounds for the node in screen coordinates + */ + public AccessibilityNodeInfo getRootNode( + @NonNull View embeddedView, int flutterId, @NonNull Rect displayBounds) { + AccessibilityNodeInfo originNode = embeddedView.createAccessibilityNodeInfo(); + Long originPackedId = reflectionAccessors.getSourceNodeId(originNode); + if (originPackedId == null) { + return null; + } + embeddedViewToDisplayBounds.put(embeddedView, displayBounds); + int originId = ReflectionAccessors.getVirtualNodeId(originPackedId); + cacheVirtualIdMappings(embeddedView, originId, flutterId); + return convertToFlutterNode(originNode, flutterId, embeddedView); + } + + /** Creates the accessibility node info for the node identified with `flutterId`. */ + @Nullable + public AccessibilityNodeInfo createAccessibilityNodeInfo(int flutterId) { + ViewAndId origin = flutterIdToOrigin.get(flutterId); + if (origin == null) { + return null; + } + if (!embeddedViewToDisplayBounds.containsKey(origin.view)) { + // This might happen if the embedded view is sending accessibility event before the first + // Flutter semantics + // tree was sent to the accessibility bridge. In this case we don't return a node as we do not + // know the + // bounds yet. + // https://github.com/flutter/flutter/issues/30068 + return null; + } + AccessibilityNodeProvider provider = origin.view.getAccessibilityNodeProvider(); + if (provider == null) { + // The provider is null for views that don't have a virtual accessibility tree. + // We currently only support embedding virtual hierarchies in the Flutter tree. + // TODO(amirh): support embedding non virtual hierarchies. + // https://github.com/flutter/flutter/issues/29717 + return null; + } + AccessibilityNodeInfo originNode = + origin.view.getAccessibilityNodeProvider().createAccessibilityNodeInfo(origin.id); + if (originNode == null) { + return null; + } + return convertToFlutterNode(originNode, flutterId, origin.view); + } + + /* + * Creates an AccessibilityNodeInfo that can be attached to the Flutter accessibility tree and is equivalent to + * originNode(which belongs to embeddedView). The virtual ID for the created node will be flutterId. + */ + @NonNull + private AccessibilityNodeInfo convertToFlutterNode( + @NonNull AccessibilityNodeInfo originNode, int flutterId, @NonNull View embeddedView) { + AccessibilityNodeInfo result = AccessibilityNodeInfo.obtain(rootAccessibilityView, flutterId); + result.setPackageName(rootAccessibilityView.getContext().getPackageName()); + result.setSource(rootAccessibilityView, flutterId); + result.setClassName(originNode.getClassName()); + + Rect displayBounds = embeddedViewToDisplayBounds.get(embeddedView); + + copyAccessibilityFields(originNode, result); + setFlutterNodesTranslateBounds(originNode, displayBounds, result); + addChildrenToFlutterNode(originNode, embeddedView, result); + setFlutterNodeParent(originNode, embeddedView, result); + + return result; + } + + private void setFlutterNodeParent( + @NonNull AccessibilityNodeInfo originNode, + @NonNull View embeddedView, + @NonNull AccessibilityNodeInfo result) { + Long parentOriginPackedId = reflectionAccessors.getParentNodeId(originNode); + if (parentOriginPackedId == null) { + return; + } + int parentOriginId = ReflectionAccessors.getVirtualNodeId(parentOriginPackedId); + Integer parentFlutterId = originToFlutterId.get(new ViewAndId(embeddedView, parentOriginId)); + if (parentFlutterId != null) { + result.setParent(rootAccessibilityView, parentFlutterId); + } + } + + private void addChildrenToFlutterNode( + @NonNull AccessibilityNodeInfo originNode, + @NonNull View embeddedView, + @NonNull AccessibilityNodeInfo resultNode) { + for (int i = 0; i < originNode.getChildCount(); i++) { + Long originPackedId = reflectionAccessors.getChildId(originNode, i); + if (originPackedId == null) { + continue; + } + int originId = ReflectionAccessors.getVirtualNodeId(originPackedId); + ViewAndId origin = new ViewAndId(embeddedView, originId); + int childFlutterId; + if (originToFlutterId.containsKey(origin)) { + childFlutterId = originToFlutterId.get(origin); + } else { + childFlutterId = nextFlutterId++; + cacheVirtualIdMappings(embeddedView, originId, childFlutterId); + } + resultNode.addChild(rootAccessibilityView, childFlutterId); + } + } + + // Caches a bidirectional mapping of (embeddedView, originId)<-->flutterId. + // Where originId is a virtual node ID in the embeddedView's tree, and flutterId is the ID + // of the corresponding node in the Flutter virtual accessibility nodes tree. + private void cacheVirtualIdMappings(@NonNull View embeddedView, int originId, int flutterId) { + ViewAndId origin = new ViewAndId(embeddedView, originId); + originToFlutterId.put(origin, flutterId); + flutterIdToOrigin.put(flutterId, origin); + } + + // Suppressing deprecation warning for AccessibilityNodeInfo#getBoundsinParent and + // AccessibilityNodeInfo#getBoundsinParent as we are copying the platform view's + // accessibility node and we should not lose any available bounds information. + @SuppressWarnings("deprecation") + private void setFlutterNodesTranslateBounds( + @NonNull AccessibilityNodeInfo originNode, + @NonNull Rect displayBounds, + @NonNull AccessibilityNodeInfo resultNode) { + Rect boundsInParent = new Rect(); + originNode.getBoundsInParent(boundsInParent); + resultNode.setBoundsInParent(boundsInParent); + + Rect boundsInScreen = new Rect(); + originNode.getBoundsInScreen(boundsInScreen); + boundsInScreen.offset(displayBounds.left, displayBounds.top); + resultNode.setBoundsInScreen(boundsInScreen); + } + + private void copyAccessibilityFields( + @NonNull AccessibilityNodeInfo input, @NonNull AccessibilityNodeInfo output) { + output.setAccessibilityFocused(input.isAccessibilityFocused()); + output.setCheckable(input.isCheckable()); + output.setChecked(input.isChecked()); + output.setContentDescription(input.getContentDescription()); + output.setEnabled(input.isEnabled()); + output.setClickable(input.isClickable()); + output.setFocusable(input.isFocusable()); + output.setFocused(input.isFocused()); + output.setLongClickable(input.isLongClickable()); + output.setMovementGranularities(input.getMovementGranularities()); + output.setPassword(input.isPassword()); + output.setScrollable(input.isScrollable()); + output.setSelected(input.isSelected()); + output.setText(input.getText()); + output.setVisibleToUser(input.isVisibleToUser()); + + output.setEditable(input.isEditable()); + output.setCanOpenPopup(input.canOpenPopup()); + output.setCollectionInfo(input.getCollectionInfo()); + output.setCollectionItemInfo(input.getCollectionItemInfo()); + output.setContentInvalid(input.isContentInvalid()); + output.setDismissable(input.isDismissable()); + output.setInputType(input.getInputType()); + output.setLiveRegion(input.getLiveRegion()); + output.setMultiLine(input.isMultiLine()); + output.setRangeInfo(input.getRangeInfo()); + output.setError(input.getError()); + output.setMaxTextLength(input.getMaxTextLength()); + if (Build.VERSION.SDK_INT >= API_LEVELS.API_23) { + output.setContextClickable(input.isContextClickable()); + // TODO(amirh): copy traversal before and after. + // https://github.com/flutter/flutter/issues/29718 + } + if (Build.VERSION.SDK_INT >= API_LEVELS.API_24) { + output.setDrawingOrder(input.getDrawingOrder()); + output.setImportantForAccessibility(input.isImportantForAccessibility()); + } + if (Build.VERSION.SDK_INT >= API_LEVELS.API_26) { + output.setAvailableExtraData(input.getAvailableExtraData()); + output.setHintText(input.getHintText()); + output.setShowingHintText(input.isShowingHintText()); + } + } + + /** + * Delegates an AccessibilityNodeProvider#requestSendAccessibilityEvent from the + * AccessibilityBridge to the embedded view. + * + * @return True if the event was sent. + */ + public boolean requestSendAccessibilityEvent( + @NonNull View embeddedView, @NonNull View eventOrigin, @NonNull AccessibilityEvent event) { + AccessibilityEvent translatedEvent = AccessibilityEvent.obtain(event); + Long originPackedId = reflectionAccessors.getRecordSourceNodeId(event); + if (originPackedId == null) { + return false; + } + int originVirtualId = ReflectionAccessors.getVirtualNodeId(originPackedId); + Integer flutterId = originToFlutterId.get(new ViewAndId(embeddedView, originVirtualId)); + if (flutterId == null) { + flutterId = nextFlutterId++; + cacheVirtualIdMappings(embeddedView, originVirtualId, flutterId); + } + translatedEvent.setSource(rootAccessibilityView, flutterId); + translatedEvent.setClassName(event.getClassName()); + translatedEvent.setPackageName(event.getPackageName()); + + for (int i = 0; i < translatedEvent.getRecordCount(); i++) { + AccessibilityRecord record = translatedEvent.getRecord(i); + Long recordOriginPackedId = reflectionAccessors.getRecordSourceNodeId(record); + if (recordOriginPackedId == null) { + return false; + } + int recordOriginVirtualID = ReflectionAccessors.getVirtualNodeId(recordOriginPackedId); + ViewAndId originViewAndId = new ViewAndId(embeddedView, recordOriginVirtualID); + if (!originToFlutterId.containsKey(originViewAndId)) { + return false; + } + int recordFlutterId = originToFlutterId.get(originViewAndId); + record.setSource(rootAccessibilityView, recordFlutterId); + } + + return rootAccessibilityView + .getParent() + .requestSendAccessibilityEvent(eventOrigin, translatedEvent); + } + + /** + * Delegates an @{link AccessibilityNodeProvider#performAction} from the AccessibilityBridge to + * the embedded view's accessibility node provider. + * + * @return True if the action was performed. + */ + public boolean performAction(int flutterId, int accessibilityAction, @Nullable Bundle arguments) { + ViewAndId origin = flutterIdToOrigin.get(flutterId); + if (origin == null) { + return false; + } + View embeddedView = origin.view; + AccessibilityNodeProvider provider = embeddedView.getAccessibilityNodeProvider(); + if (provider == null) { + return false; + } + return provider.performAction(origin.id, accessibilityAction, arguments); + } + + /** + * Returns a flutterID for an accessibility record, or null if no mapping exists. + * + * @param embeddedView the embedded view that the record is associated with. + */ + @Nullable + public Integer getRecordFlutterId( + @NonNull View embeddedView, @NonNull AccessibilityRecord record) { + Long originPackedId = reflectionAccessors.getRecordSourceNodeId(record); + if (originPackedId == null) { + return null; + } + int originVirtualId = ReflectionAccessors.getVirtualNodeId(originPackedId); + return originToFlutterId.get(new ViewAndId(embeddedView, originVirtualId)); + } + + /** + * Delegates a View#onHoverEvent event from the AccessibilityBridge to an embedded view. + * + *

The pointer coordinates are translated to the embedded view's coordinate system. + */ + public boolean onAccessibilityHoverEvent(int rootFlutterId, @NonNull MotionEvent event) { + ViewAndId origin = flutterIdToOrigin.get(rootFlutterId); + if (origin == null) { + return false; + } + Rect displayBounds = embeddedViewToDisplayBounds.get(origin.view); + int pointerCount = event.getPointerCount(); + MotionEvent.PointerProperties[] pointerProperties = + new MotionEvent.PointerProperties[pointerCount]; + MotionEvent.PointerCoords[] pointerCoords = new MotionEvent.PointerCoords[pointerCount]; + for (int i = 0; i < event.getPointerCount(); i++) { + pointerProperties[i] = new MotionEvent.PointerProperties(); + event.getPointerProperties(i, pointerProperties[i]); + + MotionEvent.PointerCoords originCoords = new MotionEvent.PointerCoords(); + event.getPointerCoords(i, originCoords); + + pointerCoords[i] = new MotionEvent.PointerCoords(originCoords); + pointerCoords[i].x -= displayBounds.left; + pointerCoords[i].y -= displayBounds.top; + } + MotionEvent translatedEvent = + MotionEvent.obtain( + event.getDownTime(), + event.getEventTime(), + event.getAction(), + event.getPointerCount(), + pointerProperties, + pointerCoords, + event.getMetaState(), + event.getButtonState(), + event.getXPrecision(), + event.getYPrecision(), + event.getDeviceId(), + event.getEdgeFlags(), + event.getSource(), + event.getFlags()); + return origin.view.dispatchGenericMotionEvent(translatedEvent); + } + + /** + * Returns the View that contains the accessibility node identified by the provided flutterId or + * null if it doesn't belong to a view. + */ + public View platformViewOfNode(int flutterId) { + ViewAndId viewAndId = flutterIdToOrigin.get(flutterId); + if (viewAndId == null) { + return null; + } + return viewAndId.view; + } + + private static class ViewAndId { + final View view; + final int id; + + private ViewAndId(View view, int id) { + this.view = view; + this.id = id; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof ViewAndId)) return false; + ViewAndId viewAndId = (ViewAndId) o; + return id == viewAndId.id && view.equals(viewAndId.view); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + view.hashCode(); + result = prime * result + id; + return result; + } + } + + private static class ReflectionAccessors { + private @Nullable final Method getSourceNodeId; + private @Nullable final Method getParentNodeId; + private @Nullable final Method getRecordSourceNodeId; + private @Nullable final Method getChildId; + private @Nullable final Field childNodeIdsField; + private @Nullable final Method longArrayGetIndex; + + @SuppressLint("DiscouragedPrivateApi,PrivateApi") + private ReflectionAccessors() { + Method getSourceNodeId = null; + Method getParentNodeId = null; + Method getRecordSourceNodeId = null; + Method getChildId = null; + Field childNodeIdsField = null; + Method longArrayGetIndex = null; + try { + getSourceNodeId = AccessibilityNodeInfo.class.getMethod("getSourceNodeId"); + } catch (NoSuchMethodException e) { + Log.w(TAG, "can't invoke AccessibilityNodeInfo#getSourceNodeId with reflection"); + } + try { + getRecordSourceNodeId = AccessibilityRecord.class.getMethod("getSourceNodeId"); + } catch (NoSuchMethodException e) { + Log.w(TAG, "can't invoke AccessibiiltyRecord#getSourceNodeId with reflection"); + } + // Reflection access is not allowed starting Android P on these methods. + if (Build.VERSION.SDK_INT <= API_LEVELS.API_26) { + try { + getParentNodeId = AccessibilityNodeInfo.class.getMethod("getParentNodeId"); + } catch (NoSuchMethodException e) { + Log.w(TAG, "can't invoke getParentNodeId with reflection"); + } + // Starting P we extract the child id from the mChildNodeIds field (see getChildId + // below). + try { + getChildId = AccessibilityNodeInfo.class.getMethod("getChildId", int.class); + } catch (NoSuchMethodException e) { + Log.w(TAG, "can't invoke getChildId with reflection"); + } + } else { + try { + childNodeIdsField = AccessibilityNodeInfo.class.getDeclaredField("mChildNodeIds"); + childNodeIdsField.setAccessible(true); + // The private member is a private utility class to Android. We need to use + // reflection to actually handle the data too. + longArrayGetIndex = Class.forName("android.util.LongArray").getMethod("get", int.class); + } catch (NoSuchFieldException + | ClassNotFoundException + | NoSuchMethodException + | NullPointerException e) { + Log.w(TAG, "can't access childNodeIdsField with reflection"); + childNodeIdsField = null; + } + } + this.getSourceNodeId = getSourceNodeId; + this.getParentNodeId = getParentNodeId; + this.getRecordSourceNodeId = getRecordSourceNodeId; + this.getChildId = getChildId; + this.childNodeIdsField = childNodeIdsField; + this.longArrayGetIndex = longArrayGetIndex; + } + + /** Returns virtual node ID given packed node ID used internally in accessibility API. */ + private static int getVirtualNodeId(long nodeId) { + return (int) (nodeId >> 32); + } + + @Nullable + private Long getSourceNodeId(@NonNull AccessibilityNodeInfo node) { + if (getSourceNodeId == null) { + return null; + } + try { + return (Long) getSourceNodeId.invoke(node); + } catch (IllegalAccessException e) { + Log.w(TAG, "Failed to access getSourceNodeId method.", e); + } catch (InvocationTargetException e) { + Log.w(TAG, "The getSourceNodeId method threw an exception when invoked.", e); + } + return null; + } + + @Nullable + private Long getChildId(@NonNull AccessibilityNodeInfo node, int child) { + if (getChildId == null && (childNodeIdsField == null || longArrayGetIndex == null)) { + return null; + } + if (getChildId != null) { + try { + return (Long) getChildId.invoke(node, child); + // Using identical separate catch blocks to comply with the following lint: + // Error: Multi-catch with these reflection exceptions requires API level 19 + // (current min is 16) because they get compiled to the common but new super + // type ReflectiveOperationException. As a workaround either create individual + // catch statements, or catch Exception. [NewApi] + } catch (IllegalAccessException e) { + Log.w(TAG, "Failed to access getChildId method.", e); + } catch (InvocationTargetException e) { + Log.w(TAG, "The getChildId method threw an exception when invoked.", e); + } + } else { + try { + return (long) longArrayGetIndex.invoke(childNodeIdsField.get(node), child); + // Using identical separate catch blocks to comply with the following lint: + // Error: Multi-catch with these reflection exceptions requires API level 19 + // (current min is 16) because they get compiled to the common but new super + // type ReflectiveOperationException. As a workaround either create individual + // catch statements, or catch Exception. [NewApi] + } catch (IllegalAccessException e) { + Log.w(TAG, "Failed to access longArrayGetIndex method or the childNodeId field.", e); + } catch (InvocationTargetException | ArrayIndexOutOfBoundsException e) { + Log.w(TAG, "The longArrayGetIndex method threw an exception when invoked.", e); + } + } + return null; + } + + @Nullable + private Long getParentNodeId(@NonNull AccessibilityNodeInfo node) { + if (getParentNodeId != null) { + try { + return (long) getParentNodeId.invoke(node); + // Using identical separate catch blocks to comply with the following lint: + // Error: Multi-catch with these reflection exceptions requires API level 19 + // (current min is 16) because they get compiled to the common but new super + // type ReflectiveOperationException. As a workaround either create individual + // catch statements, or catch Exception. [NewApi] + } catch (IllegalAccessException e) { + Log.w(TAG, "Failed to access getParentNodeId method.", e); + } catch (InvocationTargetException e) { + Log.w(TAG, "The getParentNodeId method threw an exception when invoked.", e); + } + } + + // Fall back on reading the ID from a serialized data if we absolutely have to. + return yoinkParentIdFromParcel(node); + } + + // If this looks like it's failing, that's because it probably is. This method is relying on + // the implementation details of `AccessibilityNodeInfo#writeToParcel` in order to find the + // particular bit in the opaque parcel that represents mParentNodeId. If the implementation + // details change from our assumptions in this method, this will silently break. + @Nullable + private static Long yoinkParentIdFromParcel(AccessibilityNodeInfo node) { + if (Build.VERSION.SDK_INT < API_LEVELS.API_26) { + Log.w(TAG, "Unexpected Android version. Unable to find the parent ID."); + return null; + } + + // We're creating a copy here because writing a node to a parcel recycles it. Objects + // are passed by reference in Java. So even though this method doesn't seem to use the + // node again, it's really used in other methods that would throw exceptions if we + // recycle it here. + AccessibilityNodeInfo copy = AccessibilityNodeInfo.obtain(node); + final Parcel parcel = Parcel.obtain(); + parcel.setDataPosition(0); + copy.writeToParcel(parcel, /*flags=*/ 0); + Long parentNodeId = null; + // Match the internal logic that sets where mParentId actually ends up finally living. + // This logic should match + // https://android.googlesource.com/platform/frameworks/base/+/0b5ca24a4/core/java/android/view/accessibility/AccessibilityNodeInfo.java#3524. + parcel.setDataPosition(0); + long nonDefaultFields = parcel.readLong(); + int fieldIndex = 0; + if (isBitSet(nonDefaultFields, fieldIndex++)) { + parcel.readInt(); // mIsSealed + } + if (isBitSet(nonDefaultFields, fieldIndex++)) { + parcel.readLong(); // mSourceNodeId + } + if (isBitSet(nonDefaultFields, fieldIndex++)) { + parcel.readInt(); // mWindowId + } + if (isBitSet(nonDefaultFields, fieldIndex++)) { + parentNodeId = parcel.readLong(); + } + + parcel.recycle(); + return parentNodeId; + } + + private static boolean isBitSet(long flags, int bitIndex) { + return (flags & (1L << bitIndex)) != 0; + } + + @Nullable + private Long getRecordSourceNodeId(@NonNull AccessibilityRecord node) { + if (getRecordSourceNodeId == null) { + return null; + } + try { + return (Long) getRecordSourceNodeId.invoke(node); + } catch (IllegalAccessException e) { + Log.w(TAG, "Failed to access the getRecordSourceNodeId method.", e); + } catch (InvocationTargetException e) { + Log.w(TAG, "The getRecordSourceNodeId method threw an exception when invoked.", e); + } + return null; + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/view/FlutterCallbackInformation.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/view/FlutterCallbackInformation.java new file mode 100644 index 0000000000000000000000000000000000000000..59498f1e4138e7447d5f05f4e71b6f8456963b28 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/view/FlutterCallbackInformation.java @@ -0,0 +1,37 @@ +// 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. + +package io.flutter.view; + +import androidx.annotation.Keep; +import io.flutter.embedding.engine.FlutterJNI; + +/** + * A class representing information for a callback registered using `PluginUtilities` from + * `dart:ui`. + */ +@Keep +public final class FlutterCallbackInformation { + public final String callbackName; + public final String callbackClassName; + public final String callbackLibraryPath; + + /** + * Get callback information for a given handle. + * + * @param handle the handle for the callback, generated by `PluginUtilities.getCallbackHandle` in + * `dart:ui`. + * @return an instance of FlutterCallbackInformation for the provided handle. + */ + public static FlutterCallbackInformation lookupCallbackInformation(long handle) { + return FlutterJNI.nativeLookupCallbackInformation(handle); + } + + private FlutterCallbackInformation( + String callbackName, String callbackClassName, String callbackLibraryPath) { + this.callbackName = callbackName; + this.callbackClassName = callbackClassName; + this.callbackLibraryPath = callbackLibraryPath; + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/view/FlutterRunArguments.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/view/FlutterRunArguments.java new file mode 100644 index 0000000000000000000000000000000000000000..1a817226cb5eb12b4413b8c0dd8c8eb84235b8bd --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/view/FlutterRunArguments.java @@ -0,0 +1,12 @@ +// 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. + +package io.flutter.view; + +/** A class containing arguments for entering a FlutterNativeView's isolate for the first time. */ +public class FlutterRunArguments { + public String bundlePath; + public String entrypoint; + public String libraryPath; +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/view/TextureRegistry.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/view/TextureRegistry.java new file mode 100644 index 0000000000000000000000000000000000000000..2ba9e6ff947a3bf4e04a732c1e4f4058d4d6b807 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/view/TextureRegistry.java @@ -0,0 +1,340 @@ +// 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. + +package io.flutter.view; + +import android.graphics.SurfaceTexture; +import android.media.Image; +import android.view.Surface; +import androidx.annotation.Keep; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; + +/** + * Registry of backend textures used with a single {@link io.flutter.embedding.android.FlutterView} + * instance. Entries may be embedded into the Flutter view using the Texture widget. + */ +public interface TextureRegistry { + /** + * Creates and registers a {@link SurfaceProducer}, or a Flutter-managed {@link Surface}. + * + *

Uses the {@link SurfaceLifecycle#manual} lifecycle implicitly. + * + * @return A SurfaceProducer. + */ + @NonNull + default SurfaceProducer createSurfaceProducer() { + return createSurfaceProducer(SurfaceLifecycle.manual); + } + /** + * How a {@link SurfaceProducer} created by {@link #createSurfaceProducer()} manages the lifecycle + * of the created surface. + */ + enum SurfaceLifecycle { + /** + * The surface and latest image should be kept, even if the app enters the background. + * + *

The application, or calling code, can choose to (manually) reset the surface at the + * appropriate time (such as to lower memory pressure, or cleanup an unused surface), but by + * default the surface will never be reset, and as a result, new images do not have to be drawn + * to the surface. + * + *

This is an appropriate lifecycle for external textures, as it is not guaranteed that new + * images will be drawn to the surface, and whether the image should be kept when the app is + * backgrounded. + */ + manual, + + /** + * The surface will be reset if the app enters the background. + * + *

While the application can choose to manually reset the surface, Flutter may automatically + * reset the surface when the app enters the background. If the surface is reset, and no new + * images are drawn to the surface, the texture will appear blank. + * + *

This is an appropriate lifecycle for platform views, as the platform implementation will + * request a new surface, and draw to, as appropriate when resuming from the background, and + * producing a new image when coming back to the foreground. + */ + resetInBackground + } + + /** + * Creates and a {@link SurfaceProducer}, or a Flutter-managed {@link Surface}. + * + * @param lifecycle Whether to automatically reset the last image and release the surface. + * @return A SurfaceProducer. + */ + @NonNull + SurfaceProducer createSurfaceProducer(SurfaceLifecycle lifecycle); + + /** + * Creates and registers a SurfaceTexture managed by the Flutter engine. + * + * @return A SurfaceTextureEntry. + */ + @NonNull + SurfaceTextureEntry createSurfaceTexture(); + + /** + * Registers a SurfaceTexture managed by the Flutter engine. + * + * @return A SurfaceTextureEntry. + */ + @NonNull + SurfaceTextureEntry registerSurfaceTexture(@NonNull SurfaceTexture surfaceTexture); + + /** + * Creates and registers a texture managed by the Flutter engine. + * + * @return a ImageTextureEntry. + */ + @NonNull + ImageTextureEntry createImageTexture(); + + /** + * Callback invoked when memory is low. + * + *

Invoke this from {@link android.app.Activity#onTrimMemory(int)}. + */ + default void onTrimMemory(int level) {} + + /** An entry in the texture registry. */ + interface TextureEntry { + /** @return The identity of this texture. */ + long id(); + + /** De-registers and releases all resources . */ + void release(); + } + + /** Uses a Surface to populate the texture. */ + @Keep + interface SurfaceProducer extends TextureEntry { + /** Specify the size of this texture in physical pixels */ + void setSize(int width, int height); + + /** @return The currently specified width (physical pixels) */ + int getWidth(); + + /** @return The currently specified height (physical pixels) */ + int getHeight(); + + /** + * Direct access to the surface object. + * + *

When using this API, you will usually need to implement {@link SurfaceProducer.Callback} + * and provide it to {@link #setCallback(Callback)} in order to be notified when an existing + * surface has been destroyed (such as when the application goes to the background) or a new + * surface has been created (such as when the application is resumed back to the foreground). + * + *

NOTE: You should not cache the returned surface but instead invoke {@code getSurface} each + * time you need to draw. The surface may change when the texture is resized or has its format + * changed. + * + * @return a Surface to use for a drawing target for various APIs. + */ + Surface getSurface(); + + /** + * Direct access to a surface, which will be newly created (and thus, different from any surface + * objects returned from previous calls to {@link #getSurface()} or {@link + * #getForcedNewSurface()}. + * + *

When using this API, you will usually need to implement {@link SurfaceProducer.Callback} + * and provide it to {@link #setCallback(Callback)} in order to be notified when an existing + * surface has been destroyed (such as when the application goes to the background) or a new + * surface has been created (such as when the application is resumed back to the foreground). + * + *

NOTE: You should not cache the returned surface but instead invoke {@code getSurface} each + * time you need to draw. The surface may change when the texture is resized or has its format + * changed. + * + * @return a Surface to use for a drawing target for various APIs. + */ + Surface getForcedNewSurface(); + + /** + * Sets a callback that is notified when a previously created {@link Surface} returned by {@link + * SurfaceProducer#getSurface()} is no longer valid due to being destroyed, or a new surface is + * now available (after the previous one was destroyed) for rendering. + * + * @param callback The callback to notify, or null to remove the callback. + */ + void setCallback(Callback callback); + + /** Callback invoked by {@link #setCallback(Callback)}. */ + interface Callback { + /** + * An alias for {@link Callback#onSurfaceAvailable()} with a less accurate name. + * + * @deprecated Override and use {@link Callback#onSurfaceAvailable()} instead. + */ + @Deprecated(since = "Flutter 3.27", forRemoval = true) + default void onSurfaceCreated() {} + + /** + * Invoked when an Android application is resumed after {@link Callback#onSurfaceDestroyed()}. + * + *

When this method is overridden, {@link Callback#onSurfaceCreated()} is not called. + * + *

Applications should now call {@link SurfaceProducer#getSurface()} to get a new + * {@link Surface}, as the previous one was destroyed and released as a result of a low memory + * event from the Android OS. + * + *

+       * {@code
+       * void example(SurfaceProducer producer) {
+       *   producer.setCallback(new SurfaceProducer.Callback() {
+       *     @override
+       *     public void onSurfaceAvailable() {
+       *       Surface surface = producer.getSurface();
+       *       redrawOrUse(surface);
+       *     }
+       *
+       *     // ...
+       *   });
+       * }
+       * }
+       * 
+ */ + default void onSurfaceAvailable() { + this.onSurfaceCreated(); + } + + /** + * An alias for {@link Callback#onSurfaceCleanup()} with a less accurate name. + * + * @deprecated Override and use {@link Callback#onSurfaceCleanup()} instead. + */ + @Deprecated(since = "Flutter 3.28", forRemoval = true) + default void onSurfaceDestroyed() {} + + /** + * Invoked when a {@link Surface} returned by {@link SurfaceProducer#getSurface()} is about + * to become invalid. + * + *

When this method is overridden, {@link Callback#onSurfaceDestroyed()} is not called. + * + *

In a low memory environment, the Android OS will signal to Flutter to release resources, + * such as surfaces, that are not currently in use, such as when the application is in the + * background, and this method is subsequently called to notify a plugin author to stop + * using or rendering to the last surface. + * + *

Use {@link Callback#onSurfaceAvailable()} to be notified to resume rendering. + * + *

+       * {@code
+       * void example(SurfaceProducer producer) {
+       *   producer.setCallback(new SurfaceProducer.Callback() {
+       *     @override
+       *     public void onSurfaceCleanup() {
+       *       // Store information about the last frame, if necessary.
+       *       // Potentially release other dependent resources.
+       *     }
+       *
+       *     // ...
+       *   });
+       * }
+       * }
+       * 
+ */ + default void onSurfaceCleanup() { + onSurfaceDestroyed(); + } + } + + /** This method is not officially part of the public API surface and will be deprecated. */ + void scheduleFrame(); + + /** + * Returns whether the current rendering path handles crop and rotation metadata. + * + *

On most newer Android devices (API 29+), a {@link android.media.ImageReader} backend is + * used, which has more features, works in new graphic backends directly (such as Impeller's + * Vulkan backend), and is the Android recommended solution. However, crop and rotation metadata + * are not handled automatically, and require plugin authors to make + * appropriate changes ({@see https://github.com/flutter/flutter/issues/144407}). + * + *

{@code
+     * void example(SurfaceProducer producer) {
+     *   bool supported = producer.handlesCropAndRotation();
+     *   if (!supported) {
+     *       // Manually rotate/crop, either in the Android plugin or in the Dart framework layer.
+     *   }
+     * }
+     * }
+ * + * @return {@code true} if crop and rotation is handled automatically, {@code false} otherwise. + */ + boolean handlesCropAndRotation(); + } + + /** A registry entry for a managed SurfaceTexture. */ + @Keep + interface SurfaceTextureEntry extends TextureEntry { + /** @return The managed SurfaceTexture. */ + @NonNull + SurfaceTexture surfaceTexture(); + + /** Set a listener that will be notified when the most recent image has been consumed. */ + default void setOnFrameConsumedListener(@Nullable OnFrameConsumedListener listener) {} + + /** Set a listener that will be notified when a memory pressure warning was forward. */ + default void setOnTrimMemoryListener(@Nullable OnTrimMemoryListener listener) {} + } + + @Keep + interface ImageTextureEntry extends TextureEntry { + /** + * Next paint will update texture to use the contents of image. + * + *

NOTE: Caller should not call Image.close() on the pushed image. + * + *

NOTE: In the case that multiple calls to PushFrame occur before the next paint only the + * last frame pushed will be used (dropping the missed frames). + */ + void pushImage(Image image); + } + + /** Listener invoked when the most recent image has been consumed. */ + interface OnFrameConsumedListener { + /** + * This method will to be invoked when the most recent image from the image stream has been + * consumed. + */ + void onFrameConsumed(); + } + + /** Listener invoked when a memory pressure warning was forward. */ + interface OnTrimMemoryListener { + /** This method will be invoked when a memory pressure warning was forward. */ + void onTrimMemory(int level); + } + + @Keep + interface ImageConsumer { + /** + * Retrieve the last Image produced. Drops all previously produced images. + * + *

NOTE: Caller must call Image.close() on returned image. + * + * @return Image or null. + */ + @Nullable + Image acquireLatestImage(); + } + + @Keep + interface GLTextureConsumer { + /** + * Retrieve the last GL texture produced. + * + * @return SurfaceTexture. + */ + @NonNull + SurfaceTexture getSurfaceTexture(); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/io/flutter/view/VsyncWaiter.java b/flutter/engine/src/flutter/shell/platform/android/io/flutter/view/VsyncWaiter.java new file mode 100644 index 0000000000000000000000000000000000000000..b99b089a5c55e5977385287f89b2e61459b4a94f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/io/flutter/view/VsyncWaiter.java @@ -0,0 +1,131 @@ +// 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. + +package io.flutter.view; + +import android.hardware.display.DisplayManager; +import android.view.Choreographer; +import android.view.Display; +import androidx.annotation.NonNull; +import androidx.annotation.VisibleForTesting; +import io.flutter.embedding.engine.FlutterJNI; + +// TODO(mattcarroll): add javadoc. +public class VsyncWaiter { + class DisplayListener implements DisplayManager.DisplayListener { + DisplayListener(DisplayManager displayManager) { + this.displayManager = displayManager; + } + + private DisplayManager displayManager; + + void register() { + displayManager.registerDisplayListener(this, null); + } + + @Override + public void onDisplayAdded(int displayId) {} + + @Override + public void onDisplayRemoved(int displayId) {} + + @Override + public void onDisplayChanged(int displayId) { + if (displayId == Display.DEFAULT_DISPLAY) { + final Display primaryDisplay = displayManager.getDisplay(Display.DEFAULT_DISPLAY); + float fps = primaryDisplay.getRefreshRate(); + VsyncWaiter.this.refreshPeriodNanos = (long) (1000000000.0 / fps); + VsyncWaiter.this.flutterJNI.setRefreshRateFPS(fps); + } + } + } + + private static VsyncWaiter instance; + private static DisplayListener listener; + private long refreshPeriodNanos = -1; + private FlutterJNI flutterJNI; + private FrameCallback frameCallback = new FrameCallback(0); + + @NonNull + public static VsyncWaiter getInstance(float fps, @NonNull FlutterJNI flutterJNI) { + if (instance == null) { + instance = new VsyncWaiter(flutterJNI); + } + flutterJNI.setRefreshRateFPS(fps); + instance.refreshPeriodNanos = (long) (1000000000.0 / fps); + return instance; + } + + @NonNull + public static VsyncWaiter getInstance( + @NonNull DisplayManager displayManager, @NonNull FlutterJNI flutterJNI) { + if (instance == null) { + instance = new VsyncWaiter(flutterJNI); + } + if (listener == null) { + listener = instance.new DisplayListener(displayManager); + listener.register(); + } + if (instance.refreshPeriodNanos == -1) { + final Display primaryDisplay = displayManager.getDisplay(Display.DEFAULT_DISPLAY); + float fps = primaryDisplay.getRefreshRate(); + instance.refreshPeriodNanos = (long) (1000000000.0 / fps); + flutterJNI.setRefreshRateFPS(fps); + } + return instance; + } + + // For tests, to reset the singleton between tests. + @VisibleForTesting + public static void reset() { + instance = null; + listener = null; + } + + private class FrameCallback implements Choreographer.FrameCallback { + + private long cookie; + + FrameCallback(long cookie) { + this.cookie = cookie; + } + + @Override + public void doFrame(long frameTimeNanos) { + long delay = System.nanoTime() - frameTimeNanos; + if (delay < 0) { + delay = 0; + } + flutterJNI.onVsync(delay, refreshPeriodNanos, cookie); + frameCallback = this; + } + } + + private final FlutterJNI.AsyncWaitForVsyncDelegate asyncWaitForVsyncDelegate = + new FlutterJNI.AsyncWaitForVsyncDelegate() { + + private Choreographer.FrameCallback obtainFrameCallback(final long cookie) { + if (frameCallback != null) { + frameCallback.cookie = cookie; + FrameCallback ret = frameCallback; + frameCallback = null; + return ret; + } + return new FrameCallback(cookie); + } + + @Override + public void asyncWaitForVsync(long cookie) { + Choreographer.getInstance().postFrameCallback(obtainFrameCallback(cookie)); + } + }; + + private VsyncWaiter(@NonNull FlutterJNI flutterJNI) { + this.flutterJNI = flutterJNI; + } + + public void init() { + flutterJNI.setAsyncWaitForVsyncDelegate(asyncWaitForVsyncDelegate); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/jni/BUILD.gn b/flutter/engine/src/flutter/shell/platform/android/jni/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..7a05be011d2f72e7a55b2ad7f8eb1696207bc22c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/jni/BUILD.gn @@ -0,0 +1,51 @@ +# 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. + +import("//flutter/common/config.gni") +import("//flutter/testing/testing.gni") + +source_set("jni") { + sources = [ + "platform_view_android_jni.cc", + "platform_view_android_jni.h", + ] + + public_configs = [ "//flutter:config" ] + + deps = [ + "//flutter/flow", + "//flutter/fml", + "//flutter/lib/ui", + "//flutter/shell/platform/android/surface:native_window", + "//flutter/skia", + ] +} + +source_set("jni_mock") { + testonly = true + + sources = [ "jni_mock.h" ] + + public_configs = [ "//flutter:config" ] + + deps = [ ":jni" ] +} + +test_fixtures("jni_fixtures") { + fixtures = [] +} + +executable("jni_unittests") { + testonly = true + + sources = [ "jni_mock_unittest.cc" ] + + deps = [ + ":jni_fixtures", + ":jni_mock", + "//flutter/testing", + "//flutter/testing:dart", + "//flutter/testing:skia", + ] +} diff --git a/flutter/engine/src/flutter/shell/platform/android/jni/jni_mock.h b/flutter/engine/src/flutter/shell/platform/android/jni/jni_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..8f9158c97de6a9271fe543066ed8f99b6b5ee08e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/jni/jni_mock.h @@ -0,0 +1,169 @@ +// 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_SHELL_PLATFORM_ANDROID_JNI_JNI_MOCK_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_JNI_JNI_MOCK_H_ + +#include "flutter/shell/platform/android/jni/platform_view_android_jni.h" +#include "gmock/gmock.h" + +namespace flutter { + +//------------------------------------------------------------------------------ +/// Mock for |PlatformViewAndroidJNI|. This implementation can be used in unit +/// tests without requiring the Android toolchain. +/// +class JNIMock final : public PlatformViewAndroidJNI { + public: + MOCK_METHOD(void, + FlutterViewHandlePlatformMessage, + (std::unique_ptr message, + int responseId), + (override)); + + MOCK_METHOD(void, + FlutterViewHandlePlatformMessageResponse, + (int responseId, std::unique_ptr data), + (override)); + + MOCK_METHOD(void, + FlutterViewUpdateSemantics, + (std::vector buffer, + std::vector strings, + std::vector> string_attribute_args), + (override)); + + MOCK_METHOD(void, + FlutterViewUpdateCustomAccessibilityActions, + (std::vector actions_buffer, + std::vector strings), + (override)); + + MOCK_METHOD(void, FlutterViewOnFirstFrame, (), (override)); + + MOCK_METHOD(void, FlutterViewOnPreEngineRestart, (), (override)); + + MOCK_METHOD(void, + SurfaceTextureAttachToGLContext, + (JavaLocalRef surface_texture, int textureId), + (override)); + + MOCK_METHOD(bool, + SurfaceTextureShouldUpdate, + (JavaLocalRef surface_texture), + (override)); + + MOCK_METHOD(void, + SurfaceTextureUpdateTexImage, + (JavaLocalRef surface_texture), + (override)); + + MOCK_METHOD(SkM44, + SurfaceTextureGetTransformMatrix, + (JavaLocalRef surface_texture), + (override)); + + MOCK_METHOD(JavaLocalRef, + ImageProducerTextureEntryAcquireLatestImage, + (JavaLocalRef image_texture_entry), + (override)); + + MOCK_METHOD(JavaLocalRef, + ImageGetHardwareBuffer, + (JavaLocalRef image), + (override)); + + MOCK_METHOD(void, ImageClose, (JavaLocalRef image), (override)); + + MOCK_METHOD(void, + HardwareBufferClose, + (JavaLocalRef hardware_buffer), + (override)); + + MOCK_METHOD(void, + SurfaceTextureDetachFromGLContext, + (JavaLocalRef surface_texture), + (override)); + + MOCK_METHOD(void, + FlutterViewOnDisplayPlatformView, + (int view_id, + int x, + int y, + int width, + int height, + int viewWidth, + int viewHeight, + MutatorsStack mutators_stack), + (override)); + + MOCK_METHOD(void, + FlutterViewDisplayOverlaySurface, + (int surface_id, int x, int y, int width, int height), + (override)); + + MOCK_METHOD(void, FlutterViewBeginFrame, (), (override)); + + MOCK_METHOD(void, FlutterViewEndFrame, (), (override)); + + MOCK_METHOD(std::unique_ptr, + FlutterViewCreateOverlaySurface, + (), + (override)); + + MOCK_METHOD(void, FlutterViewDestroyOverlaySurfaces, (), (override)); + + MOCK_METHOD(ASurfaceTransaction*, createTransaction, (), (override)); + + MOCK_METHOD(void, swapTransaction, (), (override)); + + MOCK_METHOD(void, applyTransaction, (), (override)); + + MOCK_METHOD(void, destroyOverlaySurface2, (), (override)); + + MOCK_METHOD(std::unique_ptr, + createOverlaySurface2, + (), + (override)); + + MOCK_METHOD(void, + onDisplayPlatformView2, + (int32_t view_id, + int32_t x, + int32_t y, + int32_t width, + int32_t height, + int32_t viewWidth, + int32_t viewHeight, + MutatorsStack mutators_stack), + (override)); + + MOCK_METHOD(void, onEndFrame2, (), (override)); + MOCK_METHOD(void, hideOverlaySurface2, (), (override)); + MOCK_METHOD(void, showOverlaySurface2, (), (override)); + + MOCK_METHOD(std::unique_ptr>, + FlutterViewComputePlatformResolvedLocale, + (std::vector supported_locales_data), + (override)); + + MOCK_METHOD(double, GetDisplayRefreshRate, (), (override)); + MOCK_METHOD(double, GetDisplayWidth, (), (override)); + MOCK_METHOD(double, GetDisplayHeight, (), (override)); + MOCK_METHOD(double, GetDisplayDensity, (), (override)); + + MOCK_METHOD(bool, + RequestDartDeferredLibrary, + (int loading_unit_id), + (override)); + + MOCK_METHOD(double, + FlutterViewGetScaledFontSize, + (double font_size, int configuration_id), + (const, override)); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_JNI_JNI_MOCK_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/jni/jni_mock_unittest.cc b/flutter/engine/src/flutter/shell/platform/android/jni/jni_mock_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..6c7564c71416611a5e8820f4f841eb0f2ee8b4d7 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/jni/jni_mock_unittest.cc @@ -0,0 +1,29 @@ +// 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/shell/platform/android/jni/jni_mock.h" + +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +namespace flutter { +namespace testing { + +TEST(JNIMock, FlutterViewHandlePlatformMessage) { + JNIMock mock; + + auto message = std::make_unique("", nullptr); + auto response_id = 1; + + EXPECT_CALL(mock, + FlutterViewHandlePlatformMessage( + ::testing::Property(&std::unique_ptr::get, + message.get()), + response_id)); + + mock.FlutterViewHandlePlatformMessage(std::move(message), response_id); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/jni/platform_view_android_jni.cc b/flutter/engine/src/flutter/shell/platform/android/jni/platform_view_android_jni.cc new file mode 100644 index 0000000000000000000000000000000000000000..b00a39be3bae05de80f1f78026a3f2f9b8551803 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/jni/platform_view_android_jni.cc @@ -0,0 +1,11 @@ +// 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/shell/platform/android/jni/platform_view_android_jni.h" + +namespace flutter { + +PlatformViewAndroidJNI::~PlatformViewAndroidJNI() = default; + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/jni/platform_view_android_jni.h b/flutter/engine/src/flutter/shell/platform/android/jni/platform_view_android_jni.h new file mode 100644 index 0000000000000000000000000000000000000000..1412cddad1fe3cd2d6d85e58de33aaf8a1c704a2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/jni/platform_view_android_jni.h @@ -0,0 +1,267 @@ +// 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_SHELL_PLATFORM_ANDROID_JNI_PLATFORM_VIEW_ANDROID_JNI_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_JNI_PLATFORM_VIEW_ANDROID_JNI_H_ + +#include + +#include "flutter/fml/mapping.h" + +#include "flutter/flow/embedded_views.h" +#include "flutter/lib/ui/window/platform_message.h" +#include "flutter/shell/platform/android/surface/android_native_window.h" + +#if FML_OS_ANDROID +#include "flutter/fml/platform/android/scoped_java_ref.h" +#endif + +struct ASurfaceTransaction; + +namespace flutter { + +#if FML_OS_ANDROID +using JavaLocalRef = fml::jni::ScopedJavaLocalRef; +#else +using JavaLocalRef = std::nullptr_t; +#endif + +//------------------------------------------------------------------------------ +/// Allows to call Java code running in the JVM from any thread. However, most +/// methods can only be called from the platform thread as that is where the +/// Java code runs. +/// +/// This interface must not depend on the Android toolchain directly, so it can +/// be used in unit tests compiled with the host toolchain. +/// +class PlatformViewAndroidJNI { + public: + virtual ~PlatformViewAndroidJNI(); + + //---------------------------------------------------------------------------- + /// @brief Sends a platform message. The message may be empty. + /// + virtual void FlutterViewHandlePlatformMessage( + std::unique_ptr message, + int responseId) = 0; + + //---------------------------------------------------------------------------- + /// @brief Responds to a platform message. The data may be a `nullptr`. + /// + virtual void FlutterViewHandlePlatformMessageResponse( + int responseId, + std::unique_ptr data) = 0; + + //---------------------------------------------------------------------------- + /// @brief Sends semantics tree updates. + /// + /// @note Must be called from the platform thread. + /// + virtual void FlutterViewUpdateSemantics( + std::vector buffer, + std::vector strings, + std::vector> string_attribute_args) = 0; + + //---------------------------------------------------------------------------- + /// @brief Sends new custom accessibility events. + /// + /// @note Must be called from the platform thread. + /// + virtual void FlutterViewUpdateCustomAccessibilityActions( + std::vector actions_buffer, + std::vector strings) = 0; + + //---------------------------------------------------------------------------- + /// @brief Indicates that FlutterView should start painting pixels. + /// + /// @note Must be called from the platform thread. + /// + virtual void FlutterViewOnFirstFrame() = 0; + + //---------------------------------------------------------------------------- + /// @brief Indicates that a hot restart is about to happen. + /// + virtual void FlutterViewOnPreEngineRestart() = 0; + + //---------------------------------------------------------------------------- + /// @brief Attach the SurfaceTexture to the OpenGL ES context that is + /// current on the calling thread. + /// + virtual void SurfaceTextureAttachToGLContext(JavaLocalRef surface_texture, + int textureId) = 0; + + //---------------------------------------------------------------------------- + /// @brief Returns true if surface_texture should be updated. + /// + virtual bool SurfaceTextureShouldUpdate(JavaLocalRef surface_texture) = 0; + + //---------------------------------------------------------------------------- + /// @brief Updates the texture image to the most recent frame from the + /// image stream. + /// + virtual void SurfaceTextureUpdateTexImage(JavaLocalRef surface_texture) = 0; + + //---------------------------------------------------------------------------- + /// @brief Gets the transform matrix from the SurfaceTexture. + /// Then, it updates the `transform` matrix, so it fill the canvas + /// and preserve the aspect ratio. + /// + virtual SkM44 SurfaceTextureGetTransformMatrix( + JavaLocalRef surface_texture) = 0; + + //---------------------------------------------------------------------------- + /// @brief Detaches a SurfaceTexture from the OpenGL ES context. + /// + virtual void SurfaceTextureDetachFromGLContext( + JavaLocalRef surface_texture) = 0; + + //---------------------------------------------------------------------------- + /// @brief Acquire the latest image available. + /// + virtual JavaLocalRef ImageProducerTextureEntryAcquireLatestImage( + JavaLocalRef image_texture_entry) = 0; + + //---------------------------------------------------------------------------- + /// @brief Grab the HardwareBuffer from image. + /// + virtual JavaLocalRef ImageGetHardwareBuffer(JavaLocalRef image) = 0; + + //---------------------------------------------------------------------------- + /// @brief Call close on image. + /// + virtual void ImageClose(JavaLocalRef image) = 0; + + //---------------------------------------------------------------------------- + /// @brief Call close on hardware_buffer. + /// + virtual void HardwareBufferClose(JavaLocalRef hardware_buffer) = 0; + + //---------------------------------------------------------------------------- + /// @brief Positions and sizes a platform view if using hybrid + /// composition. + /// + /// @note Must be called from the platform thread. + /// + virtual void FlutterViewOnDisplayPlatformView( + int view_id, + int x, + int y, + int width, + int height, + int viewWidth, + int viewHeight, + MutatorsStack mutators_stack) = 0; + + //---------------------------------------------------------------------------- + /// @brief Positions and sizes an overlay surface in hybrid composition. + /// + /// @note Must be called from the platform thread. + /// + virtual void FlutterViewDisplayOverlaySurface(int surface_id, + int x, + int y, + int width, + int height) = 0; + + //---------------------------------------------------------------------------- + /// @brief Initiates a frame if using hybrid composition. + /// + /// + /// @note Must be called from the platform thread. + /// + virtual void FlutterViewBeginFrame() = 0; + + //---------------------------------------------------------------------------- + /// @brief Indicates that the current frame ended. + /// It's used to clean up state. + /// + /// @note Must be called from the platform thread. + /// + virtual void FlutterViewEndFrame() = 0; + + //------------------------------------------------------------------------------ + /// The metadata returned from Java which is converted into an |OverlayLayer| + /// by |SurfacePool|. + /// + struct OverlayMetadata { + OverlayMetadata(int id, fml::RefPtr window) + : id(id), window(std::move(window)){}; + + ~OverlayMetadata() = default; + + // A unique id to identify the overlay when it gets recycled. + const int id; + + // Holds a reference to the native window. That is, an `ANativeWindow`, + // which is the C counterpart of the `android.view.Surface` object in Java. + const fml::RefPtr window; + }; + + //---------------------------------------------------------------------------- + /// @brief Instantiates an overlay surface in hybrid composition and + /// provides the necessary metadata to operate the surface in C. + /// + /// @note Must be called from the platform thread. + /// + virtual std::unique_ptr + FlutterViewCreateOverlaySurface() = 0; + + //---------------------------------------------------------------------------- + /// @brief Destroys the overlay surfaces. + /// + /// @note Must be called from the platform thread. + /// + virtual void FlutterViewDestroyOverlaySurfaces() = 0; + + // New Platform View Support. + virtual ASurfaceTransaction* createTransaction() = 0; + + virtual void swapTransaction() = 0; + + virtual void applyTransaction() = 0; + + virtual std::unique_ptr + createOverlaySurface2() = 0; + + virtual void destroyOverlaySurface2() = 0; + + virtual void onEndFrame2() = 0; + + virtual void onDisplayPlatformView2(int32_t view_id, + int32_t x, + int32_t y, + int32_t width, + int32_t height, + int32_t viewWidth, + int32_t viewHeight, + MutatorsStack mutators_stack) = 0; + + virtual void showOverlaySurface2() = 0; + + virtual void hideOverlaySurface2() = 0; + + //---------------------------------------------------------------------------- + /// @brief Computes the locale Android would select. + /// + virtual std::unique_ptr> + FlutterViewComputePlatformResolvedLocale( + std::vector supported_locales_data) = 0; + + virtual double GetDisplayRefreshRate() = 0; + + virtual double GetDisplayWidth() = 0; + + virtual double GetDisplayHeight() = 0; + + virtual double GetDisplayDensity() = 0; + + virtual bool RequestDartDeferredLibrary(int loading_unit_id) = 0; + + virtual double FlutterViewGetScaledFontSize(double unscaled_font_size, + int configuration_id) const = 0; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_JNI_PLATFORM_VIEW_ANDROID_JNI_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/platform_view_android_delegate/BUILD.gn b/flutter/engine/src/flutter/shell/platform/android/platform_view_android_delegate/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..fbec934de2693bc1a5706af231b2d0372c0bb28c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/platform_view_android_delegate/BUILD.gn @@ -0,0 +1,43 @@ +# 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. + +import("//flutter/common/config.gni") +import("//flutter/testing/testing.gni") + +source_set("platform_view_android_delegate") { + sources = [ + "platform_view_android_delegate.cc", + "platform_view_android_delegate.h", + ] + + public_configs = [ "//flutter:config" ] + + deps = [ + "//flutter/common", + "//flutter/fml", + "//flutter/lib/ui", + "//flutter/shell/common", + "//flutter/shell/platform/android/jni", + "//flutter/skia", + ] +} + +test_fixtures("platform_view_android_delegate_fixtures") { + fixtures = [] +} + +executable("platform_view_android_delegate_unittests") { + testonly = true + + sources = [ "platform_view_android_delegate_unittests.cc" ] + + deps = [ + ":platform_view_android_delegate", + ":platform_view_android_delegate_fixtures", + "//flutter/shell/platform/android/jni:jni_mock", + "//flutter/testing", + "//flutter/testing:dart", + "//flutter/txt", + ] +} diff --git a/flutter/engine/src/flutter/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate.cc b/flutter/engine/src/flutter/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate.cc new file mode 100644 index 0000000000000000000000000000000000000000..4893eaa9cf52f5eda608400d6780b66a5efe197f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate.cc @@ -0,0 +1,235 @@ +// 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/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate.h" + +#include + +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_(std::move(jni_facade)){}; + +void PlatformViewAndroidDelegate::UpdateSemantics( + const flutter::SemanticsNodeUpdates& update, + const flutter::CustomAccessibilityActionUpdates& actions) { + { + size_t num_bytes = 0; + for (const auto& value : update) { + num_bytes += kBytesPerNode; + 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.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: + // + // * AccessibilityBridge.java + // * AccessibilityBridgeTest.java + // * accessibility_bridge.mm + // + // If any of the encoding structure or length is changed, those locations + // must be updated (at a minimum). + std::vector buffer(num_bytes); + int32_t* buffer_int32 = reinterpret_cast(&buffer[0]); + 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 + // and/or kBytesPerChild above to match the number of values you are + // sending. + const flutter::SemanticsNode& node = value.second; + buffer_int32[position++] = node.id; + buffer_int32[position++] = node.flags; + buffer_int32[position++] = node.actions; + buffer_int32[position++] = node.maxValueLength; + buffer_int32[position++] = node.currentValueLength; + buffer_int32[position++] = node.textSelectionBase; + buffer_int32[position++] = node.textSelectionExtent; + buffer_int32[position++] = node.platformViewId; + buffer_int32[position++] = node.scrollChildren; + buffer_int32[position++] = node.scrollIndex; + buffer_float32[position++] = static_cast(node.scrollPosition); + buffer_float32[position++] = static_cast(node.scrollExtentMax); + buffer_float32[position++] = static_cast(node.scrollExtentMin); + + if (node.identifier.empty()) { + buffer_int32[position++] = -1; + } else { + buffer_int32[position++] = strings.size(); + strings.push_back(node.identifier); + } + + if (node.label.empty()) { + buffer_int32[position++] = -1; + } else { + 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); + + if (node.tooltip.empty()) { + buffer_int32[position++] = -1; + } else { + buffer_int32[position++] = strings.size(); + strings.push_back(node.tooltip); + } + + if (node.linkUrl.empty()) { + buffer_int32[position++] = -1; + } else { + buffer_int32[position++] = strings.size(); + strings.push_back(node.linkUrl); + } + + buffer_int32[position++] = node.textDirection; + buffer_float32[position++] = node.rect.left(); + buffer_float32[position++] = node.rect.top(); + buffer_float32[position++] = node.rect.right(); + buffer_float32[position++] = node.rect.bottom(); + node.transform.getColMajor(&buffer_float32[position]); + position += 16; + + buffer_int32[position++] = node.childrenInTraversalOrder.size(); + for (int32_t child : node.childrenInTraversalOrder) { + buffer_int32[position++] = child; + } + + for (int32_t child : node.childrenInHitTestOrder) { + buffer_int32[position++] = child; + } + + buffer_int32[position++] = node.customAccessibilityActions.size(); + for (int32_t child : node.customAccessibilityActions) { + buffer_int32[position++] = child; + } + } + + // custom accessibility actions. + size_t num_action_bytes = actions.size() * kBytesPerAction; + std::vector actions_buffer(num_action_bytes); + int32_t* actions_buffer_int32 = + reinterpret_cast(&actions_buffer[0]); + + std::vector action_strings; + size_t actions_position = 0; + for (const auto& value : actions) { + // If you edit this code, make sure you update kBytesPerAction + // to match the number of values you are + // sending. + const flutter::CustomAccessibilityAction& action = value.second; + actions_buffer_int32[actions_position++] = action.id; + actions_buffer_int32[actions_position++] = action.overrideId; + if (action.label.empty()) { + actions_buffer_int32[actions_position++] = -1; + } else { + actions_buffer_int32[actions_position++] = action_strings.size(); + action_strings.push_back(action.label); + } + if (action.hint.empty()) { + actions_buffer_int32[actions_position++] = -1; + } else { + actions_buffer_int32[actions_position++] = action_strings.size(); + action_strings.push_back(action.hint); + } + } + + // Calling NewDirectByteBuffer in API level 22 and below with a size of zero + // will cause a JNI crash. + if (!actions_buffer.empty()) { + jni_facade_->FlutterViewUpdateCustomAccessibilityActions(actions_buffer, + action_strings); + } + + if (!buffer.empty()) { + jni_facade_->FlutterViewUpdateSemantics(buffer, strings, + string_attribute_args); + } + } +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate.h b/flutter/engine/src/flutter/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate.h new file mode 100644 index 0000000000000000000000000000000000000000..5e2b59f70e211af7dc436d8a6f7b63c0580b19b9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate.h @@ -0,0 +1,35 @@ +// 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_SHELL_PLATFORM_ANDROID_PLATFORM_VIEW_ANDROID_DELEGATE_PLATFORM_VIEW_ANDROID_DELEGATE_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_PLATFORM_VIEW_ANDROID_DELEGATE_PLATFORM_VIEW_ANDROID_DELEGATE_H_ + +#include +#include +#include + +#include "flutter/shell/common/platform_view.h" +#include "flutter/shell/platform/android/jni/platform_view_android_jni.h" + +namespace flutter { + +class PlatformViewAndroidDelegate { + public: + static constexpr size_t kBytesPerNode = 49 * sizeof(int32_t); + static constexpr size_t kBytesPerChild = sizeof(int32_t); + static constexpr size_t kBytesPerCustomAction = sizeof(int32_t); + static constexpr size_t kBytesPerAction = 4 * sizeof(int32_t); + static constexpr size_t kBytesPerStringAttribute = 4 * sizeof(int32_t); + explicit PlatformViewAndroidDelegate( + std::shared_ptr jni_facade); + void UpdateSemantics( + const flutter::SemanticsNodeUpdates& update, + const flutter::CustomAccessibilityActionUpdates& actions); + + private: + const std::shared_ptr jni_facade_; +}; +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_PLATFORM_VIEW_ANDROID_DELEGATE_PLATFORM_VIEW_ANDROID_DELEGATE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate_unittests.cc b/flutter/engine/src/flutter/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..687c7b354e0b66903f9d570c7a6fa2b768e219f5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate_unittests.cc @@ -0,0 +1,269 @@ +// 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/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate.h" + +#include "flutter/shell/platform/android/jni/jni_mock.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +namespace flutter { +namespace testing { + +TEST(PlatformViewShell, UpdateSemanticsDoesFlutterViewUpdateSemantics) { + auto jni_mock = std::make_shared(); + auto delegate = std::make_unique(jni_mock); + + flutter::SemanticsNodeUpdates update; + flutter::SemanticsNode node0; + node0.id = 0; + node0.identifier = "identifier"; + node0.label = "label"; + node0.tooltip = "tooltip"; + update.insert(std::make_pair(0, node0)); + + std::vector expected_buffer( + PlatformViewAndroidDelegate::kBytesPerNode); + 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]); + 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.identifier + expected_strings.push_back(node0.identifier); + 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++] = expected_strings.size(); // node0.tooltip + expected_strings.push_back(node0.tooltip); + buffer_int32[position++] = -1; // node0.linkUrl + 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); +} + +TEST(PlatformViewShell, UpdateSemanticsDoesUpdatelinkUrl) { + auto jni_mock = std::make_shared(); + auto delegate = std::make_unique(jni_mock); + + flutter::SemanticsNodeUpdates update; + flutter::SemanticsNode node0; + node0.id = 0; + node0.identifier = "identifier"; + node0.label = "label"; + node0.linkUrl = "url"; + update.insert(std::make_pair(0, node0)); + + std::vector expected_buffer( + PlatformViewAndroidDelegate::kBytesPerNode); + 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]); + 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.identifier + expected_strings.push_back(node0.identifier); + 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++] = -1; // node0.tooltip + buffer_int32[position++] = expected_strings.size(); // node0.tooltip + expected_strings.push_back(node0.linkUrl); + 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); +} + +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.identifier = "identifier"; + 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, node0)); + + std::vector expected_buffer( + PlatformViewAndroidDelegate::kBytesPerNode + + // 1 label attribute + 1 hint attribute. + 2 * PlatformViewAndroidDelegate::kBytesPerStringAttribute); + 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.identifier + expected_strings.push_back(node0.identifier); + 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.hintAttributes[0].args + expected_string_attribute_args.push_back( + {locale_attribute->locale.begin(), locale_attribute->locale.end()}); + buffer_int32[position++] = -1; // node0.tooltip + buffer_int32[position++] = -1; // node0.linkUrl + 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); +} + +TEST(PlatformViewShell, + UpdateSemanticsDoesFlutterViewUpdateCustomAccessibilityActions) { + auto jni_mock = std::make_shared(); + auto delegate = std::make_unique(jni_mock); + + flutter::CustomAccessibilityActionUpdates actions; + flutter::CustomAccessibilityAction action0; + action0.id = 0; + action0.overrideId = 1; + action0.label = "label"; + action0.hint = "hint"; + actions.insert(std::make_pair(0, action0)); + + std::vector expected_actions_buffer( + PlatformViewAndroidDelegate::kBytesPerAction); + int32_t* actions_buffer_int32 = + reinterpret_cast(&expected_actions_buffer[0]); + std::vector expected_action_strings; + actions_buffer_int32[0] = action0.id; + actions_buffer_int32[1] = action0.overrideId; + actions_buffer_int32[2] = expected_action_strings.size(); + expected_action_strings.push_back(action0.label); + actions_buffer_int32[3] = expected_action_strings.size(); + expected_action_strings.push_back(action0.hint); + + EXPECT_CALL(*jni_mock, FlutterViewUpdateCustomAccessibilityActions( + expected_actions_buffer, expected_action_strings)); + // Creates empty update. + flutter::SemanticsNodeUpdates update; + delegate->UpdateSemantics(update, actions); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/surface/BUILD.gn b/flutter/engine/src/flutter/shell/platform/android/surface/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..ecc46d1145f6e5e581e2852e438c8b2f74863294 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/surface/BUILD.gn @@ -0,0 +1,63 @@ +# 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. + +import("//flutter/shell/config.gni") + +source_set("surface") { + sources = [ + "android_surface.cc", + "android_surface.h", + "snapshot_surface_producer.cc", + "snapshot_surface_producer.h", + ] + + public_configs = [ "//flutter:config" ] + + deps = [ + ":native_window", + "//flutter/flow", + "//flutter/fml", + "//flutter/shell/common", + "//flutter/shell/platform/android/context", + "//flutter/shell/platform/android/jni", + "//flutter/skia", + ] +} + +source_set("native_window") { + sources = [ + "android_native_window.cc", + "android_native_window.h", + ] + + public_configs = [ "//flutter:config" ] + + deps = [ + "//flutter/fml", + "//flutter/skia", + ] +} + +source_set("surface_mock") { + testonly = true + + sources = [ + "android_surface_mock.cc", + "android_surface_mock.h", + ] + + public_configs = [ "//flutter:config" ] + + deps = [ + ":surface", + "//flutter/flow", + "//flutter/shell/gpu:gpu_surface_gl", + "//flutter/third_party/googletest:gmock", + "//flutter/third_party/googletest:gtest", + ] + + if (shell_enable_vulkan) { + deps += [ "//flutter/vulkan" ] + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/surface/android_native_window.cc b/flutter/engine/src/flutter/shell/platform/android/surface/android_native_window.cc new file mode 100644 index 0000000000000000000000000000000000000000..34e6d43827909898906326b7ba8b02311d4b177e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/surface/android_native_window.cc @@ -0,0 +1,42 @@ +// 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/shell/platform/android/surface/android_native_window.h" + +namespace flutter { + +AndroidNativeWindow::AndroidNativeWindow(Handle window, bool is_fake_window) + : window_(window), is_fake_window_(is_fake_window) {} + +AndroidNativeWindow::AndroidNativeWindow(Handle window) + : AndroidNativeWindow(window, /*is_fake_window=*/false) {} + +AndroidNativeWindow::~AndroidNativeWindow() { + if (window_ != nullptr) { +#if FML_OS_ANDROID + ANativeWindow_release(window_); + window_ = nullptr; +#endif // FML_OS_ANDROID + } +} + +bool AndroidNativeWindow::IsValid() const { + return window_ != nullptr; +} + +AndroidNativeWindow::Handle AndroidNativeWindow::handle() const { + return window_; +} + +SkISize AndroidNativeWindow::GetSize() const { +#if FML_OS_ANDROID + return window_ == nullptr ? SkISize::Make(0, 0) + : SkISize::Make(ANativeWindow_getWidth(window_), + ANativeWindow_getHeight(window_)); +#else // FML_OS_ANDROID + return SkISize::Make(0, 0); +#endif // FML_OS_ANDROID +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/surface/android_native_window.h b/flutter/engine/src/flutter/shell/platform/android/surface/android_native_window.h new file mode 100644 index 0000000000000000000000000000000000000000..6b5a45f9f701fcda79383f6d26058a6e5b0298a9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/surface/android_native_window.h @@ -0,0 +1,58 @@ +// 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_SHELL_PLATFORM_ANDROID_SURFACE_ANDROID_NATIVE_WINDOW_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_ANDROID_NATIVE_WINDOW_H_ + +#include "flutter/fml/build_config.h" + +#include "flutter/fml/macros.h" +#include "flutter/fml/memory/ref_counted.h" +#include "third_party/skia/include/core/SkSize.h" + +#if FML_OS_ANDROID +#include +#endif // FML_OS_ANDROID + +namespace flutter { + +class AndroidNativeWindow + : public fml::RefCountedThreadSafe { + public: +#if FML_OS_ANDROID + using Handle = ANativeWindow*; +#else // FML_OS_ANDROID + using Handle = std::nullptr_t; +#endif // FML_OS_ANDROID + + bool IsValid() const; + + Handle handle() const; + + SkISize GetSize() const; + + /// Returns true when this AndroidNativeWindow is not backed by a real window + /// (used for testing). + bool IsFakeWindow() const { return is_fake_window_; } + + private: + Handle window_; + const bool is_fake_window_; + + /// Creates a native window with the given handle. Handle ownership is assumed + /// by this instance of the native window. + explicit AndroidNativeWindow(Handle window); + + explicit AndroidNativeWindow(Handle window, bool is_fake_window); + + ~AndroidNativeWindow(); + + FML_FRIEND_MAKE_REF_COUNTED(AndroidNativeWindow); + FML_FRIEND_REF_COUNTED_THREAD_SAFE(AndroidNativeWindow); + FML_DISALLOW_COPY_AND_ASSIGN(AndroidNativeWindow); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_ANDROID_NATIVE_WINDOW_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/surface/android_surface.cc b/flutter/engine/src/flutter/shell/platform/android/surface/android_surface.cc new file mode 100644 index 0000000000000000000000000000000000000000..e301491b5fce074cde095a0b0dae33b653ef53ac --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/surface/android_surface.cc @@ -0,0 +1,22 @@ +// 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/shell/platform/android/surface/android_surface.h" +#include "flutter/fml/logging.h" + +namespace flutter { + +AndroidSurface::AndroidSurface() = default; + +AndroidSurface::~AndroidSurface() = default; + +std::unique_ptr AndroidSurface::CreateSnapshotSurface() { + return nullptr; +} + +std::shared_ptr AndroidSurface::GetImpellerContext() { + return nullptr; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/surface/android_surface.h b/flutter/engine/src/flutter/shell/platform/android/surface/android_surface.h new file mode 100644 index 0000000000000000000000000000000000000000..16013504cb30ab21eae8b5dbbe23e412d2f6e2aa --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/surface/android_surface.h @@ -0,0 +1,65 @@ +// 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_SHELL_PLATFORM_ANDROID_SURFACE_ANDROID_SURFACE_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_ANDROID_SURFACE_H_ + +#include +#include "flutter/flow/embedded_views.h" +#include "flutter/flow/surface.h" +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/android/context/android_context.h" +#include "flutter/shell/platform/android/jni/platform_view_android_jni.h" +#include "flutter/shell/platform/android/surface/android_native_window.h" +#include "third_party/skia/include/core/SkSize.h" + +namespace impeller { +class Context; +} // namespace impeller + +namespace flutter { + +class AndroidExternalViewEmbedder; + +class AndroidSurface { + public: + virtual ~AndroidSurface(); + + virtual bool IsValid() const = 0; + + virtual void TeardownOnScreenContext() = 0; + + virtual std::unique_ptr CreateGPUSurface( + GrDirectContext* gr_context = nullptr) = 0; + + virtual bool OnScreenSurfaceResize(const SkISize& size) = 0; + + virtual bool ResourceContextMakeCurrent() = 0; + + virtual bool ResourceContextClearCurrent() = 0; + + virtual bool SetNativeWindow( + fml::RefPtr window, + const std::shared_ptr& jni_facade) = 0; + + virtual std::unique_ptr CreateSnapshotSurface(); + + virtual std::shared_ptr GetImpellerContext(); + + protected: + AndroidSurface(); +}; + +class AndroidSurfaceFactory { + public: + AndroidSurfaceFactory() = default; + + virtual ~AndroidSurfaceFactory() = default; + + virtual std::unique_ptr CreateSurface() = 0; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_ANDROID_SURFACE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/surface/android_surface_mock.cc b/flutter/engine/src/flutter/shell/platform/android/surface/android_surface_mock.cc new file mode 100644 index 0000000000000000000000000000000000000000..0f7c6d1a6d80c7e154139d5469eacea7d3039381 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/surface/android_surface_mock.cc @@ -0,0 +1,27 @@ +// 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/shell/platform/android/surface/android_surface_mock.h" + +namespace flutter { + +std::unique_ptr AndroidSurfaceMock::GLContextMakeCurrent() { + return std::make_unique(/*static_result=*/true); +} + +bool AndroidSurfaceMock::GLContextClearCurrent() { + return true; +} + +bool AndroidSurfaceMock::GLContextPresent(const GLPresentInfo& present_info) { + return true; +} + +GLFBOInfo AndroidSurfaceMock::GLContextFBO(GLFrameInfo frame_info) const { + return GLFBOInfo{ + .fbo_id = 0, + }; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/surface/android_surface_mock.h b/flutter/engine/src/flutter/shell/platform/android/surface/android_surface_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..b43f6895108db2b25acf4f7382ba1cd43a344aa5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/surface/android_surface_mock.h @@ -0,0 +1,57 @@ +// 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_SHELL_PLATFORM_ANDROID_SURFACE_ANDROID_SURFACE_MOCK_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_ANDROID_SURFACE_MOCK_H_ + +#include "flutter/shell/gpu/gpu_surface_gl_skia.h" +#include "flutter/shell/platform/android/surface/android_surface.h" +#include "gmock/gmock.h" + +namespace flutter { + +//------------------------------------------------------------------------------ +/// Mock for |AndroidSurface|. This implementation can be used in unit +/// tests without requiring the Android toolchain. +/// +class AndroidSurfaceMock final : public GPUSurfaceGLDelegate, + public AndroidSurface { + public: + MOCK_METHOD(bool, IsValid, (), (const, override)); + + MOCK_METHOD(void, TeardownOnScreenContext, (), (override)); + + MOCK_METHOD(std::unique_ptr, + CreateGPUSurface, + (GrDirectContext * gr_context), + (override)); + + MOCK_METHOD(bool, OnScreenSurfaceResize, (const SkISize& size), (override)); + + MOCK_METHOD(bool, ResourceContextMakeCurrent, (), (override)); + + MOCK_METHOD(bool, ResourceContextClearCurrent, (), (override)); + + MOCK_METHOD(bool, + SetNativeWindow, + (fml::RefPtr window, + const std::shared_ptr& jni_facade), + (override)); + + // |GPUSurfaceGLDelegate| + std::unique_ptr GLContextMakeCurrent() override; + + // |GPUSurfaceGLDelegate| + bool GLContextClearCurrent() override; + + // |GPUSurfaceGLDelegate| + bool GLContextPresent(const GLPresentInfo& present_info) override; + + // |GPUSurfaceGLDelegate| + GLFBOInfo GLContextFBO(GLFrameInfo frame_info) const override; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_ANDROID_SURFACE_MOCK_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/surface/snapshot_surface_producer.cc b/flutter/engine/src/flutter/shell/platform/android/surface/snapshot_surface_producer.cc new file mode 100644 index 0000000000000000000000000000000000000000..3ca4c37f3ce6a1d60445646e748feca736a559f2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/surface/snapshot_surface_producer.cc @@ -0,0 +1,18 @@ +// 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/shell/platform/android/surface/snapshot_surface_producer.h" + +namespace flutter { + +AndroidSnapshotSurfaceProducer::AndroidSnapshotSurfaceProducer( + AndroidSurface& android_surface) + : android_surface_(android_surface) {} + +std::unique_ptr +AndroidSnapshotSurfaceProducer::CreateSnapshotSurface() { + return android_surface_.CreateSnapshotSurface(); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/surface/snapshot_surface_producer.h b/flutter/engine/src/flutter/shell/platform/android/surface/snapshot_surface_producer.h new file mode 100644 index 0000000000000000000000000000000000000000..7fdbf63063a37464d0b577b80127c7f1e50feafe --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/surface/snapshot_surface_producer.h @@ -0,0 +1,26 @@ +// 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_SHELL_PLATFORM_ANDROID_SURFACE_SNAPSHOT_SURFACE_PRODUCER_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_SNAPSHOT_SURFACE_PRODUCER_H_ + +#include "flutter/flow/surface.h" +#include "flutter/shell/common/snapshot_surface_producer.h" +#include "flutter/shell/platform/android/surface/android_surface.h" + +namespace flutter { + +class AndroidSnapshotSurfaceProducer : public SnapshotSurfaceProducer { + public: + explicit AndroidSnapshotSurfaceProducer(AndroidSurface& android_surface); + + // |SnapshotSurfaceProducer| + std::unique_ptr CreateSnapshotSurface() override; + + private: + AndroidSurface& android_surface_; +}; + +} // namespace flutter +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_SNAPSHOT_SURFACE_PRODUCER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/test/README.md b/flutter/engine/src/flutter/shell/platform/android/test/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8ec14481fc888e033c3b546dcbf7817a879e9e11 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/README.md @@ -0,0 +1,46 @@ +# Unit testing Java code + +All Java code in the engine should now be able to be tested with Robolectric 4.12.1 +and JUnit 4. The test suite has been added after the bulk of the Java code was +first written, so most of these classes do not have existing tests. Ideally code +after this point should be tested, either with unit tests here or with +integration tests in other repos. + +## Adding a new test + +1. Create a file under `test/` matching the path and name of the class under + test. For example, + `shell/platform/android/io/flutter/util/Preconditions.java` -> + `shell/platform/android/**test**/io/flutter/util/Preconditions**Test**.java`. +2. Add your file to the `sources` of the `robolectric_tests` build target in + `/shell/platform/android/BUILD.gn`. This compiles the test class into the + test jar. +3. Import your test class and add it to the `@SuiteClasses` annotation in + `FlutterTestSuite.java`. This makes sure the test is actually executed at + run time. +4. Write your test. +5. Build and run with `testing/run_tests.py [--type=java] [--java-filter=]`. + +Example: from engine/src/flutter on a Mac +`et build -c android_debug_unopt_arm64` +`testing/run_tests.py --android-variant=android_debug_unopt_arm64 --type=java --java-filter=io.flutter.embedding.android.FlutterViewTest` + +Note that `testing/run_tests.py` does not build the engine binaries; instead they +should be built prior to running this command and also when the source files +change. See [Compiling the engine](https://github.com/flutter/flutter/wiki/Compiling-the-engine) +for details on how to do so. + +## Q&A + +### My new test won't run. There's a "ClassNotFoundException". + +See [Updating Embedding Dependencies](/tools/cipd/android_embedding_bundle). + +### My new test won't compile. It can't find one of my imports. + +See [Updating Embedding Dependencies](/tools/cipd/android_embedding_bundle). + +### My test does not show log output in the console + +Import `org.robolectric.shadows.ShadowLog;` then +Use `ShadowLog.stream = System.out;` in your test or setup method. diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/CustomShadowContextImpl.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/CustomShadowContextImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..feab3607987be887a416be195cab27a0d9c4515e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/CustomShadowContextImpl.java @@ -0,0 +1,20 @@ +package io.flutter; + +import android.content.Context; +import org.robolectric.annotation.Implementation; +import org.robolectric.annotation.Implements; +import org.robolectric.shadows.ShadowContextImpl; + +@Implements(className = ShadowContextImpl.CLASS_NAME) +public class CustomShadowContextImpl extends ShadowContextImpl { + public static final String CLASS_NAME = "android.app.ContextImpl"; + + @Implementation + @Override + public final Object getSystemService(String name) { + if (name == Context.TEXT_SERVICES_MANAGER_SERVICE) { + return null; + } + return super.getSystemService(name); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/FlutterInjectorTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/FlutterInjectorTest.java new file mode 100644 index 0000000000000000000000000000000000000000..1a72a0a56bb76efa9855fa463618fb11777f3806 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/FlutterInjectorTest.java @@ -0,0 +1,119 @@ +// 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. + +package io.flutter; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.deferredcomponents.PlayStoreDeferredComponentManager; +import io.flutter.embedding.engine.loader.FlutterLoader; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class FlutterInjectorTest { + @Mock FlutterLoader mockFlutterLoader; + @Mock PlayStoreDeferredComponentManager mockDeferredComponentManager; + @Mock ExecutorService mockExecutorService; + + @Before + public void setUp() { + // Since the intent is to have a convenient static class to use for production. + FlutterInjector.reset(); + MockitoAnnotations.openMocks(this); + } + + @After + public void tearDown() { + FlutterInjector.reset(); + } + + @Test + public void itHasSomeReasonableDefaults() { + // Implicitly builds when first accessed. + FlutterInjector injector = FlutterInjector.instance(); + assertNotNull(injector.flutterLoader()); + assertNull(injector.deferredComponentManager()); + assertNotNull(injector.executorService()); + } + + @Test + public void executorCreatesAndNamesNewThreadsByDefault() + throws InterruptedException, ExecutionException { + // Implicitly builds when first accessed. + FlutterInjector injector = FlutterInjector.instance(); + + List> callables = + Arrays.asList( + () -> { + return Thread.currentThread().getName(); + }, + () -> { + return Thread.currentThread().getName(); + }); + + List> threadNames; + threadNames = injector.executorService().invokeAll(callables); + + assertEquals(threadNames.size(), 2); + for (Future name : threadNames) { + assertTrue(name.get().startsWith("flutter-worker-")); + } + } + + @Test + public void canPartiallyOverride() { + FlutterInjector.setInstance( + new FlutterInjector.Builder().setFlutterLoader(mockFlutterLoader).build()); + FlutterInjector injector = FlutterInjector.instance(); + assertEquals(injector.flutterLoader(), mockFlutterLoader); + } + + @Test + public void canInjectDeferredComponentManager() { + FlutterInjector.setInstance( + new FlutterInjector.Builder() + .setDeferredComponentManager(mockDeferredComponentManager) + .build()); + FlutterInjector injector = FlutterInjector.instance(); + assertEquals(injector.deferredComponentManager(), mockDeferredComponentManager); + } + + @Test + public void canInjectExecutorService() { + FlutterInjector.setInstance( + new FlutterInjector.Builder().setExecutorService(mockExecutorService).build()); + FlutterInjector injector = FlutterInjector.instance(); + assertEquals(injector.executorService(), mockExecutorService); + } + + @Test() + public void cannotBeChangedOnceRead() { + FlutterInjector.instance(); + + assertThrows( + IllegalStateException.class, + () -> { + FlutterInjector.setInstance( + new FlutterInjector.Builder().setFlutterLoader(mockFlutterLoader).build()); + }); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/LogTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/LogTest.java new file mode 100644 index 0000000000000000000000000000000000000000..e5fe1f3196d8a26babdc377b6357fb723408094a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/LogTest.java @@ -0,0 +1,32 @@ +// 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. + +package io.flutter; + +import static org.junit.Assert.assertEquals; + +import java.io.PrintWriter; +import java.io.StringWriter; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(RobolectricTestRunner.class) +public class LogTest { + + @Test + public void canGetStacktraceString() { + Exception exception = new Exception(); + String str = Log.getStackTraceString(exception); + + StringWriter stringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stringWriter); + exception.printStackTrace(printWriter); + String expectStr = stringWriter.toString(); + + assertEquals(str, expectStr); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/SmokeTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/SmokeTest.java new file mode 100644 index 0000000000000000000000000000000000000000..c41821c2421036abaa0e64579d2e5f6b2ef5c62e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/SmokeTest.java @@ -0,0 +1,23 @@ +// 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. + +package io.flutter; + +import static org.junit.Assert.assertTrue; + +import android.text.TextUtils; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +/** Basic smoke test verifying that Robolectric is loaded and mocking out Android APIs. */ +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class SmokeTest { + @Test + public void androidLibraryLoaded() { + assertTrue(TextUtils.equals("xyzzy", "xyzzy")); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/AndroidTouchProcessorTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/AndroidTouchProcessorTest.java new file mode 100644 index 0000000000000000000000000000000000000000..d037745e089c272e83b608b71f6b4d639a773af1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/AndroidTouchProcessorTest.java @@ -0,0 +1,776 @@ +// 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. + +package io.flutter.embedding.android; + +import static io.flutter.Build.API_LEVELS; +import static junit.framework.TestCase.assertEquals; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.annotation.TargetApi; +import android.content.Context; +import android.view.InputDevice; +import android.view.MotionEvent; +import android.view.ViewConfiguration; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.renderer.FlutterRenderer; +import java.nio.ByteBuffer; +import java.util.concurrent.TimeUnit; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InOrder; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +@TargetApi(API_LEVELS.API_28) +public class AndroidTouchProcessorTest { + @Mock FlutterRenderer mockRenderer; + AndroidTouchProcessor touchProcessor; + @Captor ArgumentCaptor packetCaptor; + @Captor ArgumentCaptor packetSizeCaptor; + // Used for mock events in SystemClock.uptimeMillis() time base. + // 2 days in milliseconds + final long eventTimeMilliseconds = 172800000; + final float pressure = 0.8f; + // https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/gestures/events.dart + final int enginePrimaryStylusButton = 0x02; + + @Before + public void setUp() { + MockitoAnnotations.openMocks(this); + touchProcessor = new AndroidTouchProcessor(mockRenderer, false); + } + + private long readTimeStamp(ByteBuffer buffer) { + return buffer.getLong(1 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private long readPointerChange(ByteBuffer buffer) { + return readPointerChangeForPointer(buffer, 0); + } + + private long readPointerChangeForPointer(ByteBuffer buffer, int pointerIndex) { + return buffer.getLong( + 2 * AndroidTouchProcessor.BYTES_PER_FIELD + + (AndroidTouchProcessor.BYTES_PER_FIELD + * AndroidTouchProcessor.POINTER_DATA_FIELD_COUNT + * pointerIndex)); + } + + private long readPointerDeviceKind(ByteBuffer buffer) { + return readPointerDeviceKindForPointer(buffer, 0); + } + + private long readPointerDeviceKindForPointer(ByteBuffer buffer, int pointerIndex) { + return buffer.getLong( + 3 * AndroidTouchProcessor.BYTES_PER_FIELD + + (AndroidTouchProcessor.BYTES_PER_FIELD + * AndroidTouchProcessor.POINTER_DATA_FIELD_COUNT + * pointerIndex)); + } + + private long readPointerSignalKind(ByteBuffer buffer) { + return readPointerSignalKindForPointer(buffer, 0); + } + + private long readPointerSignalKindForPointer(ByteBuffer buffer, int pointerIndex) { + return buffer.getLong( + 4 * AndroidTouchProcessor.BYTES_PER_FIELD + + (AndroidTouchProcessor.BYTES_PER_FIELD + * AndroidTouchProcessor.POINTER_DATA_FIELD_COUNT + * pointerIndex)); + } + + private long readDevice(ByteBuffer buffer) { + return buffer.getLong(5 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readPointerPhysicalX(ByteBuffer buffer) { + return readPointerPhysicalXForPointer(buffer, 0); + } + + private double readPointerPhysicalXForPointer(ByteBuffer buffer, int pointerIndex) { + return buffer.getDouble( + 7 * AndroidTouchProcessor.BYTES_PER_FIELD + + (AndroidTouchProcessor.BYTES_PER_FIELD + * AndroidTouchProcessor.POINTER_DATA_FIELD_COUNT + * pointerIndex)); + } + + private double readPointerPhysicalY(ByteBuffer buffer) { + return readPointerPhysicalYForPointer(buffer, 0); + } + + private double readPointerPhysicalYForPointer(ByteBuffer buffer, int pointerIndex) { + return buffer.getDouble( + 8 * AndroidTouchProcessor.BYTES_PER_FIELD + + (AndroidTouchProcessor.BYTES_PER_FIELD + * AndroidTouchProcessor.POINTER_DATA_FIELD_COUNT + * pointerIndex)); + } + + private long readButtons(ByteBuffer buffer) { + return buffer.getLong(11 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readObscured(ByteBuffer buffer) { + return buffer.getDouble(12 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readSynthesized(ByteBuffer buffer) { + return buffer.getDouble(13 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readPressure(ByteBuffer buffer) { + return buffer.getDouble(14 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readPressureMin(ByteBuffer buffer) { + return buffer.getDouble(15 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readPressureMax(ByteBuffer buffer) { + return buffer.getDouble(16 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readDistance(ByteBuffer buffer) { + return buffer.getDouble(17 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readDistanceMax(ByteBuffer buffer) { + return buffer.getDouble(18 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readSize(ByteBuffer buffer) { + return buffer.getDouble(19 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readRadiusMajor(ByteBuffer buffer) { + return buffer.getDouble(20 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readRadiusMinor(ByteBuffer buffer) { + return buffer.getDouble(21 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readRadiusMin(ByteBuffer buffer) { + return buffer.getDouble(22 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readRadiusMax(ByteBuffer buffer) { + return buffer.getDouble(23 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readStylusTilt(ByteBuffer buffer) { + return buffer.getDouble(25 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readScrollDeltaX(ByteBuffer buffer) { + return buffer.getDouble(27 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readScrollDeltaY(ByteBuffer buffer) { + return buffer.getDouble(28 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readPointerPanX(ByteBuffer buffer) { + return buffer.getDouble(29 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readPointerPanY(ByteBuffer buffer) { + return buffer.getDouble(30 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readPointerPanDeltaX(ByteBuffer buffer) { + return buffer.getDouble(31 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readPointerPanDeltaY(ByteBuffer buffer) { + return buffer.getDouble(32 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readScale(ByteBuffer buffer) { + return buffer.getDouble(33 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readRotation(ByteBuffer buffer) { + return buffer.getDouble(34 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private class MotionEventMocker { + int pointerId; + int source; + int toolType; + + MotionEventMocker(int pointerId, int source, int toolType) { + this.pointerId = pointerId; + this.source = source; + this.toolType = toolType; + } + + MotionEvent mockEvent(int action, float x, float y, int buttonState) { + return mockEvent(action, x, y, buttonState, x, y, x, y, x, x, y); + } + + MotionEvent mockEvent( + int action, + float x, + float y, + int buttonState, + float hScroll, + float vScroll, + float axisDistance, + float axisTilt, + float size, + float toolMajor, + float toolMinor) { + MotionEvent event = mock(MotionEvent.class); + when(event.getDevice()).thenReturn(null); + when(event.getSource()).thenReturn(source); + when(event.getEventTime()).thenReturn(eventTimeMilliseconds); + when(event.getPointerCount()).thenReturn(1); + when(event.getActionMasked()).thenReturn(action); + final int actionIndex = 0; + when(event.getActionIndex()).thenReturn(actionIndex); + when(event.getButtonState()).thenReturn(buttonState); + when(event.getPointerId(actionIndex)).thenReturn(pointerId); + when(event.getX(actionIndex)).thenReturn(x); + when(event.getY(actionIndex)).thenReturn(y); + when(event.getToolType(actionIndex)).thenReturn(toolType); + when(event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)).thenReturn(true); + when(event.getAxisValue(MotionEvent.AXIS_HSCROLL, pointerId)).thenReturn(hScroll); + when(event.getAxisValue(MotionEvent.AXIS_VSCROLL, pointerId)).thenReturn(vScroll); + when(event.getAxisValue(MotionEvent.AXIS_DISTANCE, pointerId)).thenReturn(axisDistance); + when(event.getAxisValue(MotionEvent.AXIS_TILT, pointerId)).thenReturn(axisTilt); + when(event.getPressure(actionIndex)).thenReturn(pressure); + when(event.getSize(actionIndex)).thenReturn(size); + when(event.getToolMajor(actionIndex)).thenReturn(toolMajor); + when(event.getToolMinor(actionIndex)).thenReturn(toolMinor); + return event; + } + } + + @Test + public void normalTouch() { + MotionEventMocker mocker = + new MotionEventMocker(0, InputDevice.SOURCE_TOUCHSCREEN, MotionEvent.TOOL_TYPE_FINGER); + touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_DOWN, 0.0f, 0.0f, 0)); + InOrder inOrder = inOrder(mockRenderer); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + ByteBuffer packet = packetCaptor.getValue(); + assertEquals(AndroidTouchProcessor.PointerChange.DOWN, readPointerChange(packet)); + assertEquals(AndroidTouchProcessor.PointerDeviceKind.TOUCH, readPointerDeviceKind(packet)); + assertEquals(AndroidTouchProcessor.PointerSignalKind.NONE, readPointerSignalKind(packet)); + assertEquals(0.0, readPointerPhysicalX(packet)); + assertEquals(0.0, readPointerPhysicalY(packet)); + touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_MOVE, 10.0f, 5.0f, 0)); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + packet = packetCaptor.getValue(); + assertEquals(AndroidTouchProcessor.PointerChange.MOVE, readPointerChange(packet)); + assertEquals(AndroidTouchProcessor.PointerDeviceKind.TOUCH, readPointerDeviceKind(packet)); + assertEquals(AndroidTouchProcessor.PointerSignalKind.NONE, readPointerSignalKind(packet)); + assertEquals(10.0, readPointerPhysicalX(packet)); + assertEquals(5.0, readPointerPhysicalY(packet)); + touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_UP, 10.0f, 5.0f, 0)); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + packet = packetCaptor.getValue(); + assertEquals(AndroidTouchProcessor.PointerChange.UP, readPointerChange(packet)); + assertEquals(AndroidTouchProcessor.PointerDeviceKind.TOUCH, readPointerDeviceKind(packet)); + assertEquals(AndroidTouchProcessor.PointerSignalKind.NONE, readPointerSignalKind(packet)); + assertEquals(10.0, readPointerPhysicalX(packet)); + assertEquals(5.0, readPointerPhysicalY(packet)); + assertEquals( + AndroidTouchProcessor.PointerChange.REMOVE, readPointerChangeForPointer(packet, 1)); + assertEquals( + AndroidTouchProcessor.PointerDeviceKind.TOUCH, readPointerDeviceKindForPointer(packet, 1)); + assertEquals( + AndroidTouchProcessor.PointerSignalKind.NONE, readPointerSignalKindForPointer(packet, 1)); + assertEquals(10.0, readPointerPhysicalXForPointer(packet, 1)); + assertEquals(5.0, readPointerPhysicalYForPointer(packet, 1)); + // Expect two pointer changes - the original UP and the synthesized REMOVE. + assertEquals( + AndroidTouchProcessor.BYTES_PER_FIELD * AndroidTouchProcessor.POINTER_DATA_FIELD_COUNT * 2, + packet.capacity()); + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void trackpadGesture() { + MotionEventMocker mocker = + new MotionEventMocker(1, InputDevice.SOURCE_MOUSE, MotionEvent.TOOL_TYPE_MOUSE); + touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_DOWN, 0.0f, 0.0f, 0)); + InOrder inOrder = inOrder(mockRenderer); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + ByteBuffer packet = packetCaptor.getValue(); + assertEquals(AndroidTouchProcessor.PointerChange.PAN_ZOOM_START, readPointerChange(packet)); + assertEquals(AndroidTouchProcessor.PointerDeviceKind.TRACKPAD, readPointerDeviceKind(packet)); + assertEquals(AndroidTouchProcessor.PointerSignalKind.NONE, readPointerSignalKind(packet)); + assertEquals(0.0, readPointerPhysicalX(packet)); + assertEquals(0.0, readPointerPhysicalY(packet)); + touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_MOVE, 10.0f, 5.0f, 0)); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + packet = packetCaptor.getValue(); + assertEquals(AndroidTouchProcessor.PointerChange.PAN_ZOOM_UPDATE, readPointerChange(packet)); + assertEquals(AndroidTouchProcessor.PointerDeviceKind.TRACKPAD, readPointerDeviceKind(packet)); + assertEquals(AndroidTouchProcessor.PointerSignalKind.NONE, readPointerSignalKind(packet)); + assertEquals(0.0, readPointerPhysicalX(packet)); + assertEquals(0.0, readPointerPhysicalY(packet)); + assertEquals(10.0, readPointerPanX(packet)); + assertEquals(5.0, readPointerPanY(packet)); + // Always zero. + assertEquals(0.0, readPointerPanDeltaX(packet)); + assertEquals(0.0, readPointerPanDeltaY(packet)); + assertEquals(0.0, readRotation(packet)); + // Always 1. + assertEquals(1.0, readScale(packet)); + touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_UP, 10.0f, 5.0f, 0)); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + packet = packetCaptor.getValue(); + assertEquals(AndroidTouchProcessor.PointerChange.PAN_ZOOM_END, readPointerChange(packet)); + assertEquals(AndroidTouchProcessor.PointerDeviceKind.TRACKPAD, readPointerDeviceKind(packet)); + assertEquals(AndroidTouchProcessor.PointerSignalKind.NONE, readPointerSignalKind(packet)); + assertEquals(0.0, readPointerPhysicalX(packet)); + assertEquals(0.0, readPointerPhysicalY(packet)); + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void mouse() { + MotionEventMocker mocker = + new MotionEventMocker(2, InputDevice.SOURCE_MOUSE, MotionEvent.TOOL_TYPE_MOUSE); + touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_DOWN, 0.0f, 0.0f, 1)); + InOrder inOrder = inOrder(mockRenderer); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + ByteBuffer packet = packetCaptor.getValue(); + assertEquals(AndroidTouchProcessor.PointerChange.DOWN, readPointerChange(packet)); + assertEquals(AndroidTouchProcessor.PointerDeviceKind.MOUSE, readPointerDeviceKind(packet)); + assertEquals(AndroidTouchProcessor.PointerSignalKind.NONE, readPointerSignalKind(packet)); + assertEquals(0.0, readPointerPhysicalX(packet)); + assertEquals(0.0, readPointerPhysicalY(packet)); + touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_MOVE, 10.0f, 5.0f, 1)); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + packet = packetCaptor.getValue(); + assertEquals(AndroidTouchProcessor.PointerChange.MOVE, readPointerChange(packet)); + assertEquals(AndroidTouchProcessor.PointerDeviceKind.MOUSE, readPointerDeviceKind(packet)); + assertEquals(AndroidTouchProcessor.PointerSignalKind.NONE, readPointerSignalKind(packet)); + assertEquals(10.0, readPointerPhysicalX(packet)); + assertEquals(5.0, readPointerPhysicalY(packet)); + touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_UP, 10.0f, 5.0f, 1)); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + packet = packetCaptor.getValue(); + assertEquals(AndroidTouchProcessor.PointerChange.UP, readPointerChange(packet)); + assertEquals(AndroidTouchProcessor.PointerDeviceKind.MOUSE, readPointerDeviceKind(packet)); + assertEquals(AndroidTouchProcessor.PointerSignalKind.NONE, readPointerSignalKind(packet)); + assertEquals(10.0, readPointerPhysicalX(packet)); + assertEquals(5.0, readPointerPhysicalY(packet)); + // Ensure that we don't send a synthesized remove when using a mouse. + assertEquals( + AndroidTouchProcessor.BYTES_PER_FIELD * AndroidTouchProcessor.POINTER_DATA_FIELD_COUNT, + packet.capacity()); + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void unexpectedMaskedAction() { + // Regression test for https://github.com/flutter/flutter/issues/111068 + MotionEventMocker mocker = + new MotionEventMocker(1, InputDevice.SOURCE_STYLUS, MotionEvent.TOOL_TYPE_STYLUS); + // ACTION_BUTTON_PRESS is not handled by AndroidTouchProcessor, nothing should be dispatched. + touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_BUTTON_PRESS, 0.0f, 0.0f, 0)); + verify(mockRenderer, never()).dispatchPointerDataPacket(ByteBuffer.allocate(0), 0); + } + + @Test + @Config(minSdk = API_LEVELS.API_26) + public void scrollWheelAbove26() { + // Pointer id must be zero to match actionIndex in mocked event. + final int pointerId = 0; + MotionEventMocker mocker = + new MotionEventMocker( + pointerId, InputDevice.SOURCE_CLASS_POINTER, MotionEvent.TOOL_TYPE_MOUSE); + final float horizontalScrollValue = -1f; + final float verticalScrollValue = .5f; + final Context context = ApplicationProvider.getApplicationContext(); + final double horizontalScaleFactor = + ViewConfiguration.get(context).getScaledHorizontalScrollFactor(); + final double verticalScaleFactor = + ViewConfiguration.get(context).getScaledVerticalScrollFactor(); + // Zero verticalScaleFactor will cause this test to miss bugs. + assertEquals("zero horizontal scale factor", true, horizontalScaleFactor != 0); + assertEquals("zero vertical scale factor", true, verticalScaleFactor != 0); + + final MotionEvent event = + mocker.mockEvent( + MotionEvent.ACTION_SCROLL, + 0.0f, + 0.0f, + 1, + horizontalScrollValue, + verticalScrollValue, + 0.0f, + 0.0f, + 0.0f, + 0.0f, + 0.0f); + boolean handled = touchProcessor.onGenericMotionEvent(event, context); + + InOrder inOrder = inOrder(mockRenderer); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + ByteBuffer packet = packetCaptor.getValue(); + + assertEquals(-horizontalScrollValue * horizontalScaleFactor, readScrollDeltaX(packet)); + assertEquals(-verticalScrollValue * verticalScaleFactor, readScrollDeltaY(packet)); + verify(event).getAxisValue(MotionEvent.AXIS_HSCROLL, pointerId); + verify(event).getAxisValue(MotionEvent.AXIS_VSCROLL, pointerId); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + @Config(sdk = API_LEVELS.API_25) + public void scrollWheelBelow26() { + // Pointer id must be zero to match actionIndex in mocked event. + final int pointerId = 0; + MotionEventMocker mocker = + new MotionEventMocker( + pointerId, InputDevice.SOURCE_CLASS_POINTER, MotionEvent.TOOL_TYPE_MOUSE); + final float horizontalScrollValue = -1f; + final float verticalScrollValue = .5f; + final Context context = ApplicationProvider.getApplicationContext(); + + final MotionEvent event = + mocker.mockEvent( + MotionEvent.ACTION_SCROLL, + 0.0f, + 0.0f, + 1, + horizontalScrollValue, + verticalScrollValue, + 0.0f, + 0.0f, + 0.0f, + 0.0f, + 0.0f); + boolean handled = touchProcessor.onGenericMotionEvent(event, context); + assertEquals(true, handled); + + InOrder inOrder = inOrder(mockRenderer); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + ByteBuffer packet = packetCaptor.getValue(); + + // Magic number from roboletric's theme. + final double magicScrollFactor = 64; + assertEquals(-horizontalScrollValue * magicScrollFactor, readScrollDeltaX(packet)); + assertEquals(-verticalScrollValue * magicScrollFactor, readScrollDeltaY(packet)); + verify(event).getAxisValue(MotionEvent.AXIS_HSCROLL, pointerId); + verify(event).getAxisValue(MotionEvent.AXIS_VSCROLL, pointerId); + + // Trigger default values. + touchProcessor.onGenericMotionEvent(event, null); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + packet = packetCaptor.getValue(); + + assertEquals( + (double) -horizontalScrollValue * AndroidTouchProcessor.DEFAULT_HORIZONTAL_SCROLL_FACTOR, + readScrollDeltaX(packet)); + assertEquals( + (double) -verticalScrollValue * AndroidTouchProcessor.DEFAULT_VERTICAL_SCROLL_FACTOR, + readScrollDeltaY(packet)); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void timeStamp() { + final int pointerId = 0; + MotionEventMocker mocker = + new MotionEventMocker( + pointerId, InputDevice.SOURCE_CLASS_POINTER, MotionEvent.TOOL_TYPE_MOUSE); + + final MotionEvent event = mocker.mockEvent(MotionEvent.ACTION_SCROLL, 1f, 1f, 1); + boolean handled = touchProcessor.onTouchEvent(event); + + InOrder inOrder = inOrder(mockRenderer); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + ByteBuffer packet = packetCaptor.getValue(); + + assertEquals(TimeUnit.MILLISECONDS.toMicros(eventTimeMilliseconds), readTimeStamp(packet)); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void device() { + final int pointerId = 2; + MotionEventMocker mocker = + new MotionEventMocker( + pointerId, InputDevice.SOURCE_CLASS_POINTER, MotionEvent.TOOL_TYPE_MOUSE); + + final MotionEvent event = mocker.mockEvent(MotionEvent.ACTION_SCROLL, 1f, 1f, 1); + boolean handled = touchProcessor.onTouchEvent(event); + + InOrder inOrder = inOrder(mockRenderer); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + ByteBuffer packet = packetCaptor.getValue(); + + assertEquals(pointerId, readDevice(packet)); + verify(event).getPointerId(0); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void physicalXPhysicalY() { + MotionEventMocker mocker = + new MotionEventMocker(1, InputDevice.SOURCE_CLASS_POINTER, MotionEvent.TOOL_TYPE_MOUSE); + final float x = 10.0f; + final float y = 20.0f; + final MotionEvent event = mocker.mockEvent(MotionEvent.ACTION_DOWN, x, y, 0); + boolean handled = touchProcessor.onTouchEvent(event); + + InOrder inOrder = inOrder(mockRenderer); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + ByteBuffer packet = packetCaptor.getValue(); + + assertEquals((double) x, readPointerPhysicalX(packet)); + assertEquals((double) y, readPointerPhysicalY(packet)); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void obscured() { + MotionEventMocker mocker = + new MotionEventMocker(1, InputDevice.SOURCE_CLASS_POINTER, MotionEvent.TOOL_TYPE_MOUSE); + final MotionEvent event = mocker.mockEvent(MotionEvent.ACTION_DOWN, 10.0f, 20.0f, 0); + boolean handled = touchProcessor.onTouchEvent(event); + + InOrder inOrder = inOrder(mockRenderer); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + ByteBuffer packet = packetCaptor.getValue(); + + // Always zero. + assertEquals(0.0, readObscured(packet)); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void synthesized() { + MotionEventMocker mocker = + new MotionEventMocker(1, InputDevice.SOURCE_CLASS_POINTER, MotionEvent.TOOL_TYPE_MOUSE); + final MotionEvent event = mocker.mockEvent(MotionEvent.ACTION_DOWN, 10.0f, 20.0f, 0); + boolean handled = touchProcessor.onTouchEvent(event); + + InOrder inOrder = inOrder(mockRenderer); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + ByteBuffer packet = packetCaptor.getValue(); + + // Always zero. + assertEquals(0.0, readSynthesized(packet)); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void pressure() { + MotionEventMocker mocker = + new MotionEventMocker(1, InputDevice.SOURCE_CLASS_POINTER, MotionEvent.TOOL_TYPE_MOUSE); + final MotionEvent event = mocker.mockEvent(MotionEvent.ACTION_DOWN, 10.0f, 20.0f, 0); + boolean handled = touchProcessor.onTouchEvent(event); + + InOrder inOrder = inOrder(mockRenderer); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + ByteBuffer packet = packetCaptor.getValue(); + + // Always zero. + assertEquals((double) pressure, readPressure(packet)); + // Verify default range with null device. + assertEquals(0.0, readPressureMin(packet)); + assertEquals(1.0, readPressureMax(packet)); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void stylusDistance() { + MotionEventMocker mocker = + new MotionEventMocker(0, InputDevice.SOURCE_STYLUS, MotionEvent.TOOL_TYPE_STYLUS); + final float distance = 10.0f; + final float tilt = 20.0f; + final MotionEvent event = + mocker.mockEvent( + MotionEvent.ACTION_DOWN, + 0.0f, + 0.0f, + MotionEvent.BUTTON_STYLUS_PRIMARY, + 0.0f, + 0.0f, + distance, + tilt, + 0.0f, + 0.0f, + 0.0f); + boolean handled = touchProcessor.onTouchEvent(event); + + InOrder inOrder = inOrder(mockRenderer); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + ByteBuffer packet = packetCaptor.getValue(); + assertEquals(AndroidTouchProcessor.PointerDeviceKind.STYLUS, readPointerDeviceKind(packet)); + assertEquals((double) distance, readDistance(packet)); + // Always zero. + assertEquals(0.0, readDistanceMax(packet)); + assertEquals((double) tilt, readStylusTilt(packet)); + assertEquals(enginePrimaryStylusButton, readButtons(packet)); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void sizeAndRadius() { + MotionEventMocker mocker = + new MotionEventMocker(0, InputDevice.SOURCE_STYLUS, MotionEvent.TOOL_TYPE_STYLUS); + final float size = 10.0f; + final float radiusMajor = 20.0f; + final float radiusMinor = 30.0f; + final MotionEvent event = + mocker.mockEvent( + MotionEvent.ACTION_DOWN, + 0.0f, + 0.0f, + 0, + 0.0f, + 0.0f, + 0.0f, + 0.0f, + size, + radiusMajor, + radiusMinor); + boolean handled = touchProcessor.onTouchEvent(event); + + InOrder inOrder = inOrder(mockRenderer); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + ByteBuffer packet = packetCaptor.getValue(); + + verify(event).getSize(0); + verify(event).getToolMajor(0); + verify(event).getToolMinor(0); + + assertEquals((double) size, readSize(packet)); + assertEquals((double) radiusMajor, readRadiusMajor(packet)); + assertEquals((double) radiusMinor, readRadiusMinor(packet)); + // Always zero. + assertEquals(0.0, readRadiusMin(packet)); + assertEquals(0.0, readRadiusMax(packet)); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void unexpectedPointerChange() { + // Regression test for https://github.com/flutter/flutter/issues/129765 + MotionEventMocker mocker = + new MotionEventMocker(0, InputDevice.SOURCE_MOUSE, MotionEvent.TOOL_TYPE_MOUSE); + + touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_DOWN, 0.0f, 0.0f, 0)); + InOrder inOrder = inOrder(mockRenderer); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + ByteBuffer packet = packetCaptor.getValue(); + assertEquals(AndroidTouchProcessor.PointerChange.PAN_ZOOM_START, readPointerChange(packet)); + assertEquals(AndroidTouchProcessor.PointerDeviceKind.TRACKPAD, readPointerDeviceKind(packet)); + assertEquals(AndroidTouchProcessor.PointerSignalKind.NONE, readPointerSignalKind(packet)); + assertEquals(0.0, readPointerPhysicalX(packet)); + assertEquals(0.0, readPointerPhysicalY(packet)); + + touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_MOVE, 10.0f, 5.0f, 0)); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + packet = packetCaptor.getValue(); + assertEquals(AndroidTouchProcessor.PointerChange.PAN_ZOOM_UPDATE, readPointerChange(packet)); + assertEquals(AndroidTouchProcessor.PointerDeviceKind.TRACKPAD, readPointerDeviceKind(packet)); + assertEquals(AndroidTouchProcessor.PointerSignalKind.NONE, readPointerSignalKind(packet)); + assertEquals(0.0, readPointerPhysicalX(packet)); + assertEquals(0.0, readPointerPhysicalY(packet)); + assertEquals(10.0, readPointerPanX(packet)); + assertEquals(5.0, readPointerPanY(packet)); + + touchProcessor.onGenericMotionEvent( + mocker.mockEvent(MotionEvent.ACTION_SCROLL, 0.0f, 0.0f, 0), + ApplicationProvider.getApplicationContext()); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + packet = packetCaptor.getValue(); + packet.rewind(); + while (packet.hasRemaining()) { + assertEquals(0, packet.get()); + } + + touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_UP, 10.0f, 5.0f, 0)); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + packet = packetCaptor.getValue(); + assertEquals(AndroidTouchProcessor.PointerChange.PAN_ZOOM_END, readPointerChange(packet)); + assertEquals(AndroidTouchProcessor.PointerDeviceKind.TRACKPAD, readPointerDeviceKind(packet)); + assertEquals(AndroidTouchProcessor.PointerSignalKind.NONE, readPointerSignalKind(packet)); + assertEquals(0.0, readPointerPhysicalX(packet)); + assertEquals(0.0, readPointerPhysicalY(packet)); + inOrder.verifyNoMoreInteractions(); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/FlutterActivityAndFragmentDelegateTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/FlutterActivityAndFragmentDelegateTest.java new file mode 100644 index 0000000000000000000000000000000000000000..9cc1f115d8c8124c7bde9668b13e749636d43ed6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/FlutterActivityAndFragmentDelegateTest.java @@ -0,0 +1,1491 @@ +// 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. + +package io.flutter.embedding.android; + +import static android.content.ComponentCallbacks2.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNotNull; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.net.Uri; +import android.view.View; +import android.window.BackEvent; +import androidx.annotation.NonNull; +import androidx.lifecycle.Lifecycle; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.FlutterInjector; +import io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.Host; +import io.flutter.embedding.engine.FlutterEngine; +import io.flutter.embedding.engine.FlutterEngineCache; +import io.flutter.embedding.engine.FlutterEngineGroup; +import io.flutter.embedding.engine.FlutterEngineGroupCache; +import io.flutter.embedding.engine.FlutterShellArgs; +import io.flutter.embedding.engine.dart.DartExecutor; +import io.flutter.embedding.engine.loader.FlutterLoader; +import io.flutter.embedding.engine.plugins.activity.ActivityControlSurface; +import io.flutter.embedding.engine.renderer.FlutterRenderer; +import io.flutter.embedding.engine.renderer.FlutterUiDisplayListener; +import io.flutter.embedding.engine.systemchannels.AccessibilityChannel; +import io.flutter.embedding.engine.systemchannels.BackGestureChannel; +import io.flutter.embedding.engine.systemchannels.LifecycleChannel; +import io.flutter.embedding.engine.systemchannels.LocalizationChannel; +import io.flutter.embedding.engine.systemchannels.MouseCursorChannel; +import io.flutter.embedding.engine.systemchannels.NavigationChannel; +import io.flutter.embedding.engine.systemchannels.ScribeChannel; +import io.flutter.embedding.engine.systemchannels.SettingsChannel; +import io.flutter.embedding.engine.systemchannels.SystemChannel; +import io.flutter.embedding.engine.systemchannels.TextInputChannel; +import io.flutter.plugin.localization.LocalizationPlugin; +import io.flutter.plugin.platform.PlatformViewsController; +import io.flutter.plugin.platform.PlatformViewsController2; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.robolectric.Robolectric; +import org.robolectric.android.controller.ActivityController; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class FlutterActivityAndFragmentDelegateTest { + private final Context ctx = ApplicationProvider.getApplicationContext(); + private FlutterEngine mockFlutterEngine; + private FlutterActivityAndFragmentDelegate.Host mockHost; + private FlutterActivityAndFragmentDelegate.Host mockHost2; + + @SuppressWarnings("deprecation") + // Robolectric.setupActivity + // TODO(reidbaker): https://github.com/flutter/flutter/issues/133151 + @Before + public void setup() { + FlutterInjector.reset(); + // Create a mocked FlutterEngine for the various interactions required by the delegate + // being tested. + mockFlutterEngine = mockFlutterEngine(); + + // Create a mocked Host, which is required by the delegate being tested. + mockHost = mock(FlutterActivityAndFragmentDelegate.Host.class); + when(mockHost.getContext()).thenReturn(ctx); + when(mockHost.getActivity()).thenReturn(Robolectric.setupActivity(Activity.class)); + when(mockHost.getLifecycle()).thenReturn(mock(Lifecycle.class)); + when(mockHost.getFlutterShellArgs()).thenReturn(new FlutterShellArgs(new String[] {})); + when(mockHost.getDartEntrypointFunctionName()).thenReturn("main"); + when(mockHost.getDartEntrypointArgs()).thenReturn(null); + when(mockHost.getAppBundlePath()).thenReturn("/fake/path"); + when(mockHost.getInitialRoute()).thenReturn("/"); + when(mockHost.getRenderMode()).thenReturn(RenderMode.surface); + when(mockHost.getTransparencyMode()).thenReturn(TransparencyMode.transparent); + when(mockHost.provideFlutterEngine(any(Context.class))).thenReturn(mockFlutterEngine); + when(mockHost.shouldAttachEngineToActivity()).thenReturn(true); + when(mockHost.shouldHandleDeeplinking()).thenReturn(false); + when(mockHost.shouldDestroyEngineWithHost()).thenReturn(true); + when(mockHost.shouldDispatchAppLifecycleState()).thenReturn(true); + when(mockHost.attachToEngineAutomatically()).thenReturn(true); + + mockHost2 = mock(FlutterActivityAndFragmentDelegate.Host.class); + when(mockHost2.getContext()).thenReturn(ctx); + when(mockHost2.getActivity()).thenReturn(Robolectric.setupActivity(Activity.class)); + when(mockHost2.getLifecycle()).thenReturn(mock(Lifecycle.class)); + when(mockHost2.getFlutterShellArgs()).thenReturn(new FlutterShellArgs(new String[] {})); + when(mockHost2.getDartEntrypointFunctionName()).thenReturn("main"); + when(mockHost2.getDartEntrypointArgs()).thenReturn(null); + when(mockHost2.getAppBundlePath()).thenReturn("/fake/path"); + when(mockHost2.getInitialRoute()).thenReturn("/"); + when(mockHost2.getRenderMode()).thenReturn(RenderMode.surface); + when(mockHost2.getTransparencyMode()).thenReturn(TransparencyMode.transparent); + when(mockHost2.provideFlutterEngine(any(Context.class))).thenReturn(mockFlutterEngine); + when(mockHost2.shouldAttachEngineToActivity()).thenReturn(true); + when(mockHost2.shouldHandleDeeplinking()).thenReturn(false); + when(mockHost2.shouldDestroyEngineWithHost()).thenReturn(true); + when(mockHost2.shouldDispatchAppLifecycleState()).thenReturn(true); + when(mockHost2.attachToEngineAutomatically()).thenReturn(true); + } + + @Test + public void itSendsLifecycleEventsToFlutter() { + // ---- Test setup ---- + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // We're testing lifecycle behaviors, which require/expect that certain methods have already + // been executed by the time they run. Therefore, we run those expected methods first. + delegate.onAttach(ctx); + delegate.onCreateView(null, null, null, 0, true); + + // --- Execute the behavior under test --- + // By the time an Activity/Fragment is started, we don't expect any lifecycle messages + // to have been sent to Flutter. + delegate.onStart(); + verify(mockFlutterEngine.getLifecycleChannel(), never()).aWindowIsFocused(); + verify(mockFlutterEngine.getLifecycleChannel(), never()).noWindowsAreFocused(); + verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsResumed(); + verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsInactive(); + verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsPaused(); + verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsDetached(); + + // When the Activity/Fragment is resumed, a resumed message should have been sent to Flutter. + delegate.onResume(); + verify(mockFlutterEngine.getLifecycleChannel(), never()).aWindowIsFocused(); + verify(mockFlutterEngine.getLifecycleChannel(), never()).noWindowsAreFocused(); + verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsResumed(); + verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsInactive(); + verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsPaused(); + verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsDetached(); + + // When the app loses focus because something else has it (e.g. notification + // windowshade or app switcher), it should go to inactive. + delegate.onWindowFocusChanged(false); + verify(mockFlutterEngine.getLifecycleChannel(), never()).aWindowIsFocused(); + verify(mockFlutterEngine.getLifecycleChannel(), times(1)).noWindowsAreFocused(); + verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsResumed(); + verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsInactive(); + verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsPaused(); + verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsDetached(); + + // When the app regains focus, it should go to resumed again. + delegate.onWindowFocusChanged(true); + verify(mockFlutterEngine.getLifecycleChannel(), times(1)).aWindowIsFocused(); + verify(mockFlutterEngine.getLifecycleChannel(), times(1)).noWindowsAreFocused(); + verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsResumed(); + verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsInactive(); + verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsPaused(); + verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsDetached(); + + // When the Activity/Fragment is paused, an inactive message should have been sent to Flutter. + delegate.onPause(); + verify(mockFlutterEngine.getLifecycleChannel(), times(1)).aWindowIsFocused(); + verify(mockFlutterEngine.getLifecycleChannel(), times(1)).noWindowsAreFocused(); + verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsResumed(); + verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsInactive(); + verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsPaused(); + verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsDetached(); + + // When the Activity/Fragment is stopped, a paused message should have been sent to Flutter. + // Notice that Flutter uses the term "paused" in a different way, and at a different time + // than the Android OS. + delegate.onStop(); + verify(mockFlutterEngine.getLifecycleChannel(), times(1)).aWindowIsFocused(); + verify(mockFlutterEngine.getLifecycleChannel(), times(1)).noWindowsAreFocused(); + verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsResumed(); + verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsInactive(); + verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsPaused(); + verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsDetached(); + + // When activity detaches, a detached message should have been sent to Flutter. + delegate.onDetach(); + verify(mockFlutterEngine.getLifecycleChannel(), times(1)).aWindowIsFocused(); + verify(mockFlutterEngine.getLifecycleChannel(), times(1)).noWindowsAreFocused(); + verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsResumed(); + verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsInactive(); + verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsPaused(); + verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsDetached(); + } + + @Test + public void itDoesNotSendsLifecycleEventsToFlutter() { + // ---- Test setup ---- + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + when(mockHost.shouldDispatchAppLifecycleState()).thenReturn(false); + + // We're testing lifecycle behaviors, which require/expect that certain methods have already + // been executed by the time they run. Therefore, we run those expected methods first. + delegate.onAttach(ctx); + delegate.onCreateView(null, null, null, 0, true); + delegate.onStart(); + delegate.onResume(); + delegate.onWindowFocusChanged(false); + delegate.onWindowFocusChanged(true); + delegate.onPause(); + delegate.onStop(); + delegate.onDetach(); + + verify(mockFlutterEngine.getLifecycleChannel(), never()).aWindowIsFocused(); + verify(mockFlutterEngine.getLifecycleChannel(), never()).noWindowsAreFocused(); + verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsResumed(); + verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsPaused(); + verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsInactive(); + verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsDetached(); + } + + @Test + public void itDefersToTheHostToProvideFlutterEngine() { + // ---- Test setup ---- + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is created in onAttach(). + delegate.onAttach(ctx); + + // Verify that the host was asked to provide a FlutterEngine. + verify(mockHost, times(1)).provideFlutterEngine(any(Context.class)); + + // Verify that the delegate's FlutterEngine is our mock FlutterEngine. + assertEquals( + "The delegate failed to use the host's FlutterEngine.", + mockFlutterEngine, + delegate.getFlutterEngine()); + } + + @Test + public void itUsesCachedEngineWhenProvided() { + // ---- Test setup ---- + // Place a FlutterEngine in the static cache. + FlutterEngine cachedEngine = mockFlutterEngine(); + FlutterEngineCache.getInstance().put("my_flutter_engine", cachedEngine); + + // Adjust fake host to request cached engine. + when(mockHost.getCachedEngineId()).thenReturn("my_flutter_engine"); + + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is obtained in onAttach(). + delegate.onAttach(ctx); + delegate.onCreateView(null, null, null, 0, true); + delegate.onStart(); + delegate.onResume(); + + // --- Verify that the cached engine was used --- + // Verify that the non-cached engine was not used. + verify(mockFlutterEngine.getDartExecutor(), never()) + .executeDartEntrypoint(any(DartExecutor.DartEntrypoint.class)); + + // We should never instruct a cached engine to execute Dart code - it should already be + // executing it. + verify(cachedEngine.getDartExecutor(), never()) + .executeDartEntrypoint(any(DartExecutor.DartEntrypoint.class)); + + // If the cached engine is being used, it should have sent a resumed lifecycle event. + verify(cachedEngine.getLifecycleChannel(), times(1)).appIsResumed(); + } + + @Test(expected = IllegalStateException.class) + public void itThrowsExceptionIfCachedEngineDoesNotExist() { + // ---- Test setup ---- + // Adjust fake host to request cached engine that does not exist. + when(mockHost.getCachedEngineId()).thenReturn("my_flutter_engine"); + + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine existence is verified in onAttach() + delegate.onAttach(ctx); + + // Expect IllegalStateException. + } + + // Bug: b/271100292 + @Test + public void flutterEngineGroupGetsInitialRouteFromIntent() { + // ---- Test setup ---- + FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); + Activity mockActivity = mock(Activity.class); + Intent mockIntent = mock(Intent.class); + when(mockFlutterLoader.findAppBundlePath()).thenReturn("default_flutter_assets/path"); + FlutterInjector.setInstance( + new FlutterInjector.Builder().setFlutterLoader(mockFlutterLoader).build()); + FlutterEngineGroup flutterEngineGroup = mock(FlutterEngineGroup.class); + FlutterEngineGroupCache.getInstance().put("my_flutter_engine_group", flutterEngineGroup); + + List entryPointArgs = new ArrayList<>(); + entryPointArgs.add("entrypoint-arg"); + + // Adjust fake host to request cached engine group. + when(mockHost.getInitialRoute()).thenReturn(null); + when(mockHost.getCachedEngineGroupId()).thenReturn("my_flutter_engine_group"); + when(mockHost.provideFlutterEngine(any(Context.class))).thenReturn(null); + when(mockHost.shouldAttachEngineToActivity()).thenReturn(false); + when(mockHost.getDartEntrypointArgs()).thenReturn(entryPointArgs); + when(mockHost.shouldHandleDeeplinking()).thenReturn(true); + when(mockHost.getActivity()).thenReturn(mockActivity); + when(mockActivity.getIntent()).thenReturn(mockIntent); + when(mockIntent.getData()).thenReturn(Uri.parse("foo://example.com/initial_route")); + + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is obtained in onAttach(). + delegate.onAttach(ctx); + + DartExecutor.DartEntrypoint entrypoint = new DartExecutor.DartEntrypoint("/fake/path", "main"); + ArgumentCaptor optionsCaptor = + ArgumentCaptor.forClass(FlutterEngineGroup.Options.class); + verify(flutterEngineGroup, times(1)).createAndRunEngine(optionsCaptor.capture()); + assertEquals("foo://example.com/initial_route", optionsCaptor.getValue().getInitialRoute()); + } + + @Test + public void itUsesNewEngineInGroupWhenProvided() { + // ---- Test setup ---- + FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); + when(mockFlutterLoader.findAppBundlePath()).thenReturn("default_flutter_assets/path"); + FlutterInjector.setInstance( + new FlutterInjector.Builder().setFlutterLoader(mockFlutterLoader).build()); + FlutterEngineGroup flutterEngineGroup = mock(FlutterEngineGroup.class); + FlutterEngineGroupCache.getInstance().put("my_flutter_engine_group", flutterEngineGroup); + + List entryPointArgs = new ArrayList<>(); + entryPointArgs.add("entrypoint-arg"); + + // Adjust fake host to request cached engine group. + when(mockHost.getCachedEngineGroupId()).thenReturn("my_flutter_engine_group"); + when(mockHost.provideFlutterEngine(any(Context.class))).thenReturn(null); + when(mockHost.shouldAttachEngineToActivity()).thenReturn(false); + when(mockHost.getDartEntrypointArgs()).thenReturn(entryPointArgs); + + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is obtained in onAttach(). + delegate.onAttach(ctx); + + // If the engine in FlutterEngineGroup is being used, it should have sent a resumed lifecycle + // event. + // Note: "/fake/path" and "main" come from `setUp()`. + DartExecutor.DartEntrypoint entrypoint = new DartExecutor.DartEntrypoint("/fake/path", "main"); + ArgumentCaptor optionsCaptor = + ArgumentCaptor.forClass(FlutterEngineGroup.Options.class); + verify(flutterEngineGroup, times(1)).createAndRunEngine(optionsCaptor.capture()); + assertEquals(mockHost.getContext(), optionsCaptor.getValue().getContext()); + assertEquals(entrypoint, optionsCaptor.getValue().getDartEntrypoint()); + assertEquals(mockHost.getInitialRoute(), optionsCaptor.getValue().getInitialRoute()); + assertNotNull(optionsCaptor.getValue().getDartEntrypointArgs()); + assertEquals(1, optionsCaptor.getValue().getDartEntrypointArgs().size()); + assertEquals("entrypoint-arg", optionsCaptor.getValue().getDartEntrypointArgs().get(0)); + } + + @Test(expected = IllegalStateException.class) + public void itThrowsExceptionIfNewEngineInGroupNotExist() { + // ---- Test setup ---- + FlutterEngineGroupCache.getInstance().clear(); + + // Adjust fake host to request cached engine group that does not exist. + when(mockHost.getCachedEngineGroupId()).thenReturn("my_flutter_engine_group"); + when(mockHost.getCachedEngineId()).thenReturn(null); + when(mockHost.provideFlutterEngine(any(Context.class))).thenReturn(null); + when(mockHost.shouldAttachEngineToActivity()).thenReturn(false); + + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine existence is verified in onAttach() + delegate.onAttach(ctx); + + // Expect IllegalStateException. + } + + @Test + public void itGivesHostAnOpportunityToConfigureFlutterEngine() { + // ---- Test setup ---- + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is created in onAttach(). + delegate.onAttach(ctx); + + // Verify that the host was asked to configure our FlutterEngine. + verify(mockHost, times(1)).configureFlutterEngine(mockFlutterEngine); + } + + @Test + public void itGivesHostAnOpportunityToConfigureFlutterSurfaceView() { + // ---- Test setup ---- + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + delegate.onAttach(ctx); + delegate.onCreateView(null, null, null, 0, true); + + // Verify that the host was asked to configure a FlutterSurfaceView. + verify(mockHost, times(1)).onFlutterSurfaceViewCreated(isNotNull()); + } + + @SuppressWarnings("deprecation") + // Robolectric.setupActivity + // TODO(reidbaker): https://github.com/flutter/flutter/issues/133151 + @Test + public void itGivesHostAnOpportunityToConfigureFlutterTextureView() { + // ---- Test setup ---- + Host customMockHost = mock(Host.class); + when(customMockHost.getContext()).thenReturn(ctx); + when(customMockHost.getActivity()).thenReturn(Robolectric.setupActivity(Activity.class)); + when(customMockHost.getLifecycle()).thenReturn(mock(Lifecycle.class)); + when(customMockHost.getFlutterShellArgs()).thenReturn(new FlutterShellArgs(new String[] {})); + when(customMockHost.getDartEntrypointFunctionName()).thenReturn("main"); + when(customMockHost.getAppBundlePath()).thenReturn("/fake/path"); + when(customMockHost.getInitialRoute()).thenReturn("/"); + when(customMockHost.getRenderMode()).thenReturn(RenderMode.texture); + when(customMockHost.getTransparencyMode()).thenReturn(TransparencyMode.transparent); + when(customMockHost.provideFlutterEngine(any(Context.class))).thenReturn(mockFlutterEngine); + when(customMockHost.shouldAttachEngineToActivity()).thenReturn(true); + when(customMockHost.shouldDestroyEngineWithHost()).thenReturn(true); + + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = + new FlutterActivityAndFragmentDelegate(customMockHost); + + // --- Execute the behavior under test --- + delegate.onAttach(ctx); + delegate.onCreateView(null, null, null, 0, false); + + // Verify that the host was asked to configure a FlutterTextureView. + verify(customMockHost, times(1)).onFlutterTextureViewCreated(isNotNull()); + } + + @Test + public void itGivesHostAnOpportunityToCleanUpFlutterEngine() { + // ---- Test setup ---- + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is created in onAttach(). + delegate.onAttach(ctx); + delegate.onDetach(); + + // Verify that the host was asked to configure our FlutterEngine. + verify(mockHost, times(1)).cleanUpFlutterEngine(mockFlutterEngine); + } + + @Test + public void itSendsInitialRouteToFlutter() { + // ---- Test setup ---- + // Set initial route on our fake Host. + when(mockHost.getInitialRoute()).thenReturn("/my/route"); + + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The initial route is sent in onStart(). + delegate.onAttach(ctx); + delegate.onCreateView(null, null, null, 0, true); + delegate.onStart(); + + // Verify that the navigation channel was given our initial route. + verify(mockFlutterEngine.getNavigationChannel(), times(1)).setInitialRoute("/my/route"); + } + + @Test + public void itExecutesDartEntrypointProvidedByHost() { + // ---- Test setup ---- + // Set Dart entrypoint parameters on fake host. + when(mockHost.getAppBundlePath()).thenReturn("/my/bundle/path"); + when(mockHost.getDartEntrypointFunctionName()).thenReturn("myEntrypoint"); + + // Create the DartEntrypoint that we expect to be executed. + DartExecutor.DartEntrypoint dartEntrypoint = + new DartExecutor.DartEntrypoint("/my/bundle/path", "myEntrypoint"); + + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // Dart is executed in onStart(). + delegate.onAttach(ctx); + delegate.onCreateView(null, null, null, 0, true); + delegate.onStart(); + + // Verify that the host's Dart entrypoint was used. + verify(mockFlutterEngine.getDartExecutor(), times(1)) + .executeDartEntrypoint(eq(dartEntrypoint), isNull()); + } + + @Test + public void itExecutesDartEntrypointWithArgsProvidedByHost() { + // ---- Test setup ---- + // Set Dart entrypoint parameters on fake host. + when(mockHost.getAppBundlePath()).thenReturn("/my/bundle/path"); + when(mockHost.getDartEntrypointFunctionName()).thenReturn("myEntrypoint"); + List dartEntrypointArgs = new ArrayList(Arrays.asList("foo", "bar")); + when(mockHost.getDartEntrypointArgs()).thenReturn(dartEntrypointArgs); + + // Create the DartEntrypoint that we expect to be executed + DartExecutor.DartEntrypoint dartEntrypoint = + new DartExecutor.DartEntrypoint("/my/bundle/path", "myEntrypoint"); + + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // Dart is executed in onStart(). + delegate.onAttach(ctx); + delegate.onCreateView(null, null, null, 0, true); + delegate.onStart(); + + // Verify that the host's Dart entrypoint was used. + verify(mockFlutterEngine.getDartExecutor(), times(1)) + .executeDartEntrypoint(any(DartExecutor.DartEntrypoint.class), eq(dartEntrypointArgs)); + } + + @Test + public void itExecutesDartLibraryUriProvidedByHost() { + when(mockHost.getAppBundlePath()).thenReturn("/my/bundle/path"); + when(mockHost.getDartEntrypointFunctionName()).thenReturn("myEntrypoint"); + when(mockHost.getDartEntrypointLibraryUri()).thenReturn("package:foo/bar.dart"); + + DartExecutor.DartEntrypoint expectedEntrypoint = + new DartExecutor.DartEntrypoint("/my/bundle/path", "package:foo/bar.dart", "myEntrypoint"); + + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + delegate.onAttach(ctx); + delegate.onCreateView(null, null, null, 0, true); + delegate.onStart(); + + verify(mockFlutterEngine.getDartExecutor(), times(1)) + .executeDartEntrypoint(eq(expectedEntrypoint), isNull()); + } + + @Test + public void itUsesDefaultFlutterLoaderAppBundlePathWhenUnspecified() { + // ---- Test setup ---- + FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); + when(mockFlutterLoader.findAppBundlePath()).thenReturn("default_flutter_assets/path"); + FlutterInjector.setInstance( + new FlutterInjector.Builder().setFlutterLoader(mockFlutterLoader).build()); + + // Set Dart entrypoint parameters on fake host. + when(mockHost.getAppBundlePath()).thenReturn(null); + when(mockHost.getDartEntrypointFunctionName()).thenReturn("myEntrypoint"); + + // Create the DartEntrypoint that we expect to be executed. + DartExecutor.DartEntrypoint dartEntrypoint = + new DartExecutor.DartEntrypoint("default_flutter_assets/path", "myEntrypoint"); + + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // Dart is executed in onStart(). + delegate.onAttach(ctx); + delegate.onCreateView(null, null, null, 0, true); + delegate.onStart(); + + // Verify that the host's Dart entrypoint was used. + verify(mockFlutterEngine.getDartExecutor(), times(1)) + .executeDartEntrypoint(eq(dartEntrypoint), isNull()); + } + + // "Attaching" to the surrounding Activity refers to Flutter being able to control + // system chrome and other Activity-level details. If Flutter is not attached to the + // surrounding Activity, it cannot control those details. This includes plugins. + @Test + public void itAttachesFlutterToTheActivityIfDesired() { + // ---- Test setup ---- + // Declare that the host wants Flutter to attach to the surrounding Activity. + when(mockHost.shouldAttachEngineToActivity()).thenReturn(true); + + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // Flutter is attached to the surrounding Activity in onAttach. + delegate.onAttach(ctx); + + // Verify that the ActivityControlSurface was told to attach to an Activity. + verify(mockFlutterEngine.getActivityControlSurface(), times(1)) + .attachToActivity(any(ExclusiveAppComponent.class), any(Lifecycle.class)); + + // Flutter is detached from the surrounding Activity in onDetach. + delegate.onDetach(); + + // Verify that the ActivityControlSurface was told to detach from the Activity. + verify(mockFlutterEngine.getActivityControlSurface(), times(1)).detachFromActivity(); + } + + // "Attaching" to the surrounding Activity refers to Flutter being able to control + // system chrome and other Activity-level details. If Flutter is not attached to the + // surrounding Activity, it cannot control those details. This includes plugins. + @Test + public void itDoesNotAttachFlutterToTheActivityIfNotDesired() { + // ---- Test setup ---- + // Declare that the host does NOT want Flutter to attach to the surrounding Activity. + when(mockHost.shouldAttachEngineToActivity()).thenReturn(false); + + // getActivity() returns null if the activity is not attached + when(mockHost.getActivity()).thenReturn(null); + + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // Flutter is attached to the surrounding Activity in onAttach. + delegate.onAttach(ctx); + + // Make sure all of the other lifecycle methods can run safely as well + // without a valid Activity + delegate.onCreateView(null, null, null, 0, true); + delegate.onStart(); + delegate.onResume(); + delegate.onPause(); + delegate.onStop(); + delegate.onDestroyView(); + + // Flutter is detached from the surrounding Activity in onDetach. + delegate.onDetach(); + + // Verify that the ActivityControlSurface was NOT told to attach or detach to an Activity. + verify(mockFlutterEngine.getActivityControlSurface(), never()) + .attachToActivity(any(ExclusiveAppComponent.class), any(Lifecycle.class)); + verify(mockFlutterEngine.getActivityControlSurface(), never()).detachFromActivity(); + } + + @Test + public void itSendsPopRouteMessageToFlutterWhenHardwareBackButtonIsPressed() { + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is set up in onAttach(). + delegate.onAttach(ctx); + + // Emulate the host and inform our delegate that the back button was pressed. + delegate.onBackPressed(); + + // Verify that the navigation channel tried to send a message to Flutter. + verify(mockFlutterEngine.getNavigationChannel(), times(1)).popRoute(); + } + + @Test + public void itForwardsStartBackGestureToFlutter() { + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is set up in onAttach(). + delegate.onAttach(ctx); + + // Emulate the host and inform our delegate of the start back gesture with a mocked BackEvent + BackEvent backEvent = mock(BackEvent.class); + delegate.startBackGesture(backEvent); + + // Verify that the back gesture tried to send a message to Flutter. + verify(mockFlutterEngine.getBackGestureChannel(), times(1)).startBackGesture(backEvent); + } + + @Test + public void itForwardsUpdateBackGestureProgressToFlutter() { + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is set up in onAttach(). + delegate.onAttach(ctx); + + // Emulate the host and inform our delegate of the back gesture progress with a mocked BackEvent + BackEvent backEvent = mock(BackEvent.class); + delegate.updateBackGestureProgress(backEvent); + + // Verify that the back gesture tried to send a message to Flutter. + verify(mockFlutterEngine.getBackGestureChannel(), times(1)) + .updateBackGestureProgress(backEvent); + } + + @Test + public void itForwardsCommitBackGestureToFlutter() { + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is set up in onAttach(). + delegate.onAttach(ctx); + + // Emulate the host and inform our delegate when the back gesture is committed + delegate.commitBackGesture(); + + // Verify that the back gesture tried to send a message to Flutter. + verify(mockFlutterEngine.getBackGestureChannel(), times(1)).commitBackGesture(); + } + + @Test + public void itForwardsCancelBackGestureToFlutter() { + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is set up in onAttach(). + delegate.onAttach(ctx); + + // Emulate the host and inform our delegate of the back gesture cancellation + delegate.cancelBackGesture(); + + // Verify that the back gesture tried to send a message to Flutter. + verify(mockFlutterEngine.getBackGestureChannel(), times(1)).cancelBackGesture(); + } + + @Test + public void itForwardsOnRequestPermissionsResultToFlutterEngine() { + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is set up in onAttach(). + delegate.onAttach(ctx); + + // Emulate the host and call the method that we expect to be forwarded. + delegate.onRequestPermissionsResult(0, new String[] {}, new int[] {}); + + // Verify that the call was forwarded to the engine. + verify(mockFlutterEngine.getActivityControlSurface(), times(1)) + .onRequestPermissionsResult(any(Integer.class), any(String[].class), any(int[].class)); + } + + @Test + public void + itSendsInitialRouteFromIntentOnStartIfNoInitialRouteFromActivityAndShouldHandleDeeplinking() { + Intent intent = FlutterActivity.createDefaultIntent(ctx); + intent.setData(Uri.parse("http://myApp/custom/route?query=test")); + + ActivityController activityController = + Robolectric.buildActivity(FlutterActivity.class, intent); + FlutterActivity flutterActivity = activityController.get(); + + when(mockHost.getActivity()).thenReturn(flutterActivity); + when(mockHost.getInitialRoute()).thenReturn(null); + when(mockHost.shouldHandleDeeplinking()).thenReturn(true); + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is set up in onAttach(). + delegate.onAttach(ctx); + delegate.onCreateView(null, null, null, 0, true); + // Emulate app start. + delegate.onStart(); + + // Verify that the navigation channel was given the initial route message. + verify(mockFlutterEngine.getNavigationChannel(), times(1)) + .setInitialRoute("http://myApp/custom/route?query=test"); + } + + @Test + public void + itSendsInitialRouteFromIntentOnStartIfNoInitialRouteFromActivityAndShouldHandleDeeplinkingWithQueryParameterAndFragment() { + Intent intent = FlutterActivity.createDefaultIntent(ctx); + intent.setData(Uri.parse("http://myApp/custom/route?query=test#fragment")); + + ActivityController activityController = + Robolectric.buildActivity(FlutterActivity.class, intent); + FlutterActivity flutterActivity = activityController.get(); + + when(mockHost.getActivity()).thenReturn(flutterActivity); + when(mockHost.getInitialRoute()).thenReturn(null); + when(mockHost.shouldHandleDeeplinking()).thenReturn(true); + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is set up in onAttach(). + delegate.onAttach(ctx); + delegate.onCreateView(null, null, null, 0, true); + // Emulate app start. + delegate.onStart(); + + // Verify that the navigation channel was given the initial route message. + verify(mockFlutterEngine.getNavigationChannel(), times(1)) + .setInitialRoute("http://myApp/custom/route?query=test#fragment"); + } + + @Test + public void + itSendsInitialRouteFromIntentOnStartIfNoInitialRouteFromActivityAndShouldHandleDeeplinkingWithFragmentNoQueryParameter() { + Intent intent = FlutterActivity.createDefaultIntent(ctx); + intent.setData(Uri.parse("http://myApp/custom/route#fragment")); + + ActivityController activityController = + Robolectric.buildActivity(FlutterActivity.class, intent); + FlutterActivity flutterActivity = activityController.get(); + + when(mockHost.getActivity()).thenReturn(flutterActivity); + when(mockHost.getInitialRoute()).thenReturn(null); + when(mockHost.shouldHandleDeeplinking()).thenReturn(true); + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is set up in onAttach(). + delegate.onAttach(ctx); + delegate.onCreateView(null, null, null, 0, true); + // Emulate app start. + delegate.onStart(); + + // Verify that the navigation channel was given the initial route message. + verify(mockFlutterEngine.getNavigationChannel(), times(1)) + .setInitialRoute("http://myApp/custom/route#fragment"); + } + + @Test + public void + itSendsInitialRouteFromIntentOnStartIfNoInitialRouteFromActivityAndShouldHandleDeeplinkingNoQueryParameter() { + Intent intent = FlutterActivity.createDefaultIntent(ctx); + intent.setData(Uri.parse("http://myApp/custom/route")); + + ActivityController activityController = + Robolectric.buildActivity(FlutterActivity.class, intent); + FlutterActivity flutterActivity = activityController.get(); + + when(mockHost.getActivity()).thenReturn(flutterActivity); + when(mockHost.getInitialRoute()).thenReturn(null); + when(mockHost.shouldHandleDeeplinking()).thenReturn(true); + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is set up in onAttach(). + delegate.onAttach(ctx); + delegate.onCreateView(null, null, null, 0, true); + // Emulate app start. + delegate.onStart(); + + // Verify that the navigation channel was given the initial route message. + verify(mockFlutterEngine.getNavigationChannel(), times(1)) + .setInitialRoute("http://myApp/custom/route"); + } + + @Test + public void itSendsdefaultInitialRouteOnStartIfNotDeepLinkingFromIntent() { + // Creates an empty intent without launch uri. + Intent intent = FlutterActivity.createDefaultIntent(ctx); + + ActivityController activityController = + Robolectric.buildActivity(FlutterActivity.class, intent); + FlutterActivity flutterActivity = activityController.get(); + + when(mockHost.getActivity()).thenReturn(flutterActivity); + when(mockHost.getInitialRoute()).thenReturn(null); + when(mockHost.shouldHandleDeeplinking()).thenReturn(true); + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is set up in onAttach(). + delegate.onAttach(ctx); + delegate.onCreateView(null, null, null, 0, true); + // Emulate app start. + delegate.onStart(); + + // Verify that the navigation channel was given the default initial route message. + verify(mockFlutterEngine.getNavigationChannel(), times(1)).setInitialRoute("/"); + } + + @Test + public void itSendsPushRouteInformationMessageWhenOnNewIntent() { + when(mockHost.shouldHandleDeeplinking()).thenReturn(true); + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is set up in onAttach(). + delegate.onAttach(ctx); + String expected = "http://myApp/custom/route?query=test"; + + Intent mockIntent = mock(Intent.class); + when(mockIntent.getData()).thenReturn(Uri.parse(expected)); + // Emulate the host and call the method that we expect to be forwarded. + delegate.onNewIntent(mockIntent); + + // Verify that the navigation channel was given the push route message. + verify(mockFlutterEngine.getNavigationChannel(), times(1)).pushRouteInformation(expected); + } + + @Test + public void itDoesSendPushRouteInformationMessageWhenOnNewIntentIsNonHierarchicalUri() { + when(mockHost.shouldHandleDeeplinking()).thenReturn(true); + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is set up in onAttach(). + delegate.onAttach(ctx); + + Intent mockIntent = mock(Intent.class); + + // mailto: URIs are non-hierarchical + when(mockIntent.getData()).thenReturn(Uri.parse("mailto:test@test.com")); + + // Emulate the host and call the method + delegate.onNewIntent(mockIntent); + + // Verify that the navigation channel was not given a push route message. + verify(mockFlutterEngine.getNavigationChannel(), times(1)) + .pushRouteInformation("mailto:test@test.com"); + } + + @Test + public void itSendsPushRouteInformationMessageWhenOnNewIntentWithQueryParameterAndFragment() { + when(mockHost.shouldHandleDeeplinking()).thenReturn(true); + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is set up in onAttach(). + delegate.onAttach(ctx); + String expected = "http://myApp/custom/route?query=test#fragment"; + + Intent mockIntent = mock(Intent.class); + when(mockIntent.getData()).thenReturn(Uri.parse(expected)); + // Emulate the host and call the method that we expect to be forwarded. + delegate.onNewIntent(mockIntent); + + // Verify that the navigation channel was given the push route message. + verify(mockFlutterEngine.getNavigationChannel(), times(1)).pushRouteInformation(expected); + } + + @Test + public void itSendsPushRouteInformationMessageWhenOnNewIntentWithFragmentNoQueryParameter() { + when(mockHost.shouldHandleDeeplinking()).thenReturn(true); + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is set up in onAttach(). + delegate.onAttach(ctx); + String expected = "http://myApp/custom/route#fragment"; + + Intent mockIntent = mock(Intent.class); + when(mockIntent.getData()).thenReturn(Uri.parse(expected)); + // Emulate the host and call the method that we expect to be forwarded. + delegate.onNewIntent(mockIntent); + + // Verify that the navigation channel was given the push route message. + verify(mockFlutterEngine.getNavigationChannel(), times(1)).pushRouteInformation(expected); + } + + @Test + public void itSendsPushRouteInformationMessageWhenOnNewIntentNoQueryParameter() { + when(mockHost.shouldHandleDeeplinking()).thenReturn(true); + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is set up in onAttach(). + delegate.onAttach(ctx); + String expected = "http://myApp/custom/route#fragment"; + + Intent mockIntent = mock(Intent.class); + when(mockIntent.getData()).thenReturn(Uri.parse(expected)); + // Emulate the host and call the method that we expect to be forwarded. + delegate.onNewIntent(mockIntent); + + // Verify that the navigation channel was given the push route message. + verify(mockFlutterEngine.getNavigationChannel(), times(1)).pushRouteInformation(expected); + } + + @Test + public void itForwardsOnNewIntentToFlutterEngine() { + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is set up in onAttach(). + delegate.onAttach(ctx); + + // Emulate the host and call the method that we expect to be forwarded. + delegate.onNewIntent(mock(Intent.class)); + + // Verify that the call was forwarded to the engine. + verify(mockFlutterEngine.getActivityControlSurface(), times(1)).onNewIntent(any(Intent.class)); + } + + @Test + public void itForwardsOnActivityResultToFlutterEngine() { + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is set up in onAttach(). + delegate.onAttach(ctx); + + // Emulate the host and call the method that we expect to be forwarded. + delegate.onActivityResult(0, 0, null); + + // Verify that the call was forwarded to the engine. + verify(mockFlutterEngine.getActivityControlSurface(), times(1)) + .onActivityResult(any(Integer.class), any(Integer.class), /*intent=*/ isNull()); + } + + @Test + public void itForwardsOnUserLeaveHintToFlutterEngine() { + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is set up in onAttach(). + delegate.onAttach(ctx); + + // Emulate the host and call the method that we expect to be forwarded. + delegate.onUserLeaveHint(); + + // Verify that the call was forwarded to the engine. + verify(mockFlutterEngine.getActivityControlSurface(), times(1)).onUserLeaveHint(); + } + + @Test + @SuppressWarnings("deprecation") + // TRIM_MEMORY_COMPLETE, TRIM_MEMORY_MODERATE, TRIM_MEMORY_RUNNING_LOW, + // TRIM_MEMORY_RUNNING_MODERATE, TRIM_MEMORY_RUNNING_CRITICAL + public void itNotifiesDartExecutorAndSendsMessageOverSystemChannelWhenToldToTrimMemory() { + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // The FlutterEngine is set up in onAttach(). + delegate.onAttach(ctx); + + // Test assumes no frames have been displayed. + verify(mockHost, times(0)).onFlutterUiDisplayed(); + + // Emulate the host and call the method that we expect to be forwarded. + delegate.onTrimMemory(TRIM_MEMORY_RUNNING_MODERATE); + delegate.onTrimMemory(TRIM_MEMORY_RUNNING_LOW); + verify(mockFlutterEngine.getDartExecutor(), times(0)).notifyLowMemoryWarning(); + verify(mockFlutterEngine.getSystemChannel(), times(0)).sendMemoryPressureWarning(); + + delegate.onTrimMemory(TRIM_MEMORY_RUNNING_CRITICAL); + delegate.onTrimMemory(TRIM_MEMORY_BACKGROUND); + delegate.onTrimMemory(TRIM_MEMORY_COMPLETE); + delegate.onTrimMemory(TRIM_MEMORY_MODERATE); + delegate.onTrimMemory(TRIM_MEMORY_UI_HIDDEN); + verify(mockFlutterEngine.getDartExecutor(), times(0)).notifyLowMemoryWarning(); + verify(mockFlutterEngine.getSystemChannel(), times(0)).sendMemoryPressureWarning(); + + verify(mockHost, times(0)).onFlutterUiDisplayed(); + + delegate.onCreateView(null, null, null, 0, false); + final FlutterRenderer renderer = mockFlutterEngine.getRenderer(); + ArgumentCaptor listenerCaptor = + ArgumentCaptor.forClass(FlutterUiDisplayListener.class); + // 2 times: once for engine attachment, once for view creation. + verify(renderer, times(2)).addIsDisplayingFlutterUiListener(listenerCaptor.capture()); + listenerCaptor.getValue().onFlutterUiDisplayed(); + + verify(mockHost, times(1)).onFlutterUiDisplayed(); + + delegate.onTrimMemory(TRIM_MEMORY_RUNNING_MODERATE); + verify(mockFlutterEngine.getDartExecutor(), times(0)).notifyLowMemoryWarning(); + verify(mockFlutterEngine.getSystemChannel(), times(0)).sendMemoryPressureWarning(); + + delegate.onTrimMemory(TRIM_MEMORY_RUNNING_LOW); + delegate.onTrimMemory(TRIM_MEMORY_RUNNING_CRITICAL); + delegate.onTrimMemory(TRIM_MEMORY_BACKGROUND); + delegate.onTrimMemory(TRIM_MEMORY_COMPLETE); + delegate.onTrimMemory(TRIM_MEMORY_MODERATE); + delegate.onTrimMemory(TRIM_MEMORY_UI_HIDDEN); + verify(mockFlutterEngine.getDartExecutor(), times(6)).notifyLowMemoryWarning(); + verify(mockFlutterEngine.getSystemChannel(), times(6)).sendMemoryPressureWarning(); + } + + @Test + public void itDestroysItsOwnEngineIfHostRequestsIt() { + // ---- Test setup ---- + // Adjust fake host to request engine destruction. + when(mockHost.shouldDestroyEngineWithHost()).thenReturn(true); + + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // Push the delegate through all lifecycle methods all the way to destruction. + delegate.onAttach(ctx); + delegate.onCreateView(null, null, null, 0, true); + delegate.onStart(); + delegate.onResume(); + delegate.onPause(); + delegate.onStop(); + delegate.onDestroyView(); + delegate.onDetach(); + + // --- Verify that the cached engine was destroyed --- + verify(mockFlutterEngine, times(1)).destroy(); + } + + @Test + public void itDoesNotDestroyItsOwnEngineWhenHostSaysNotTo() { + // ---- Test setup ---- + // Adjust fake host to request engine destruction. + when(mockHost.shouldDestroyEngineWithHost()).thenReturn(false); + + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // Push the delegate through all lifecycle methods all the way to destruction. + delegate.onAttach(ctx); + delegate.onCreateView(null, null, null, 0, true); + delegate.onStart(); + delegate.onResume(); + delegate.onPause(); + delegate.onStop(); + delegate.onDestroyView(); + delegate.onDetach(); + + // --- Verify that the cached engine was destroyed --- + verify(mockFlutterEngine, never()).destroy(); + } + + @Test + public void itDestroysCachedEngineWhenHostRequestsIt() { + // ---- Test setup ---- + // Place a FlutterEngine in the static cache. + FlutterEngine cachedEngine = mockFlutterEngine(); + FlutterEngineCache.getInstance().put("my_flutter_engine", cachedEngine); + + // Adjust fake host to request cached engine. + when(mockHost.getCachedEngineId()).thenReturn("my_flutter_engine"); + + // Adjust fake host to request engine destruction. + when(mockHost.shouldDestroyEngineWithHost()).thenReturn(true); + + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // Push the delegate through all lifecycle methods all the way to destruction. + delegate.onAttach(ctx); + delegate.onCreateView(null, null, null, 0, true); + delegate.onStart(); + delegate.onResume(); + delegate.onPause(); + delegate.onStop(); + delegate.onDestroyView(); + delegate.onDetach(); + + // --- Verify that the cached engine was destroyed --- + verify(cachedEngine, times(1)).destroy(); + assertNull(FlutterEngineCache.getInstance().get("my_flutter_engine")); + } + + @Test + public void itDoesNotDestroyCachedEngineWhenHostSaysNotTo() { + // ---- Test setup ---- + // Place a FlutterEngine in the static cache. + FlutterEngine cachedEngine = mockFlutterEngine(); + FlutterEngineCache.getInstance().put("my_flutter_engine", cachedEngine); + + // Adjust fake host to request cached engine. + when(mockHost.getCachedEngineId()).thenReturn("my_flutter_engine"); + + // Adjust fake host to request engine retention. + when(mockHost.shouldDestroyEngineWithHost()).thenReturn(false); + + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + // Push the delegate through all lifecycle methods all the way to destruction. + delegate.onAttach(ctx); + delegate.onCreateView(null, null, null, 0, true); + delegate.onStart(); + delegate.onResume(); + delegate.onPause(); + delegate.onStop(); + delegate.onDestroyView(); + delegate.onDetach(); + + // --- Verify that the cached engine was NOT destroyed --- + verify(cachedEngine, never()).destroy(); + } + + @Test + public void itDelaysFirstDrawWhenRequested() { + // ---- Test setup ---- + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // We're testing lifecycle behaviors, which require/expect that certain methods have already + // been executed by the time they run. Therefore, we run those expected methods first. + delegate.onAttach(ctx); + + // --- Execute the behavior under test --- + boolean shouldDelayFirstAndroidViewDraw = true; + delegate.onCreateView(null, null, null, 0, shouldDelayFirstAndroidViewDraw); + + assertNotNull(delegate.activePreDrawListener); + } + + @Test + public void itDoesNotDelayFirstDrawWhenNotRequested() { + // ---- Test setup ---- + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // We're testing lifecycle behaviors, which require/expect that certain methods have already + // been executed by the time they run. Therefore, we run those expected methods first. + delegate.onAttach(ctx); + + // --- Execute the behavior under test --- + boolean shouldDelayFirstAndroidViewDraw = false; + delegate.onCreateView(null, null, null, 0, shouldDelayFirstAndroidViewDraw); + + assertNull(delegate.activePreDrawListener); + } + + @Test + public void itThrowsWhenDelayingTheFirstDrawAndUsingATextureView() { + // ---- Test setup ---- + when(mockHost.getRenderMode()).thenReturn(RenderMode.texture); + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // We're testing lifecycle behaviors, which require/expect that certain methods have already + // been executed by the time they run. Therefore, we run those expected methods first. + delegate.onAttach(ctx); + + // --- Execute the behavior under test --- + boolean shouldDelayFirstAndroidViewDraw = true; + assertThrows( + IllegalArgumentException.class, + () -> { + delegate.onCreateView(null, null, null, 0, shouldDelayFirstAndroidViewDraw); + }); + } + + @Test + public void itChangesFlutterViewVisibilityWhenOnStartAndOnStop() { + // ---- Test setup ---- + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + + // --- Execute the behavior under test --- + delegate.onAttach(ctx); + delegate.onCreateView(null, null, null, 0, true); + delegate.onStart(); + // Verify that the flutterView is visible. + assertEquals(View.VISIBLE, delegate.flutterView.getVisibility()); + delegate.onStop(); + // Verify that the flutterView is gone. + assertEquals(View.GONE, delegate.flutterView.getVisibility()); + delegate.onStart(); + // Verify that the flutterView is visible. + assertEquals(View.VISIBLE, delegate.flutterView.getVisibility()); + + delegate.flutterView.setVisibility(View.INVISIBLE); + delegate.onStop(); + // Verify that the flutterView is gone. + assertEquals(View.GONE, delegate.flutterView.getVisibility()); + delegate.onStart(); + // Verify that the flutterView is invisible. + assertEquals(View.INVISIBLE, delegate.flutterView.getVisibility()); + + delegate.flutterView.setVisibility(View.GONE); + delegate.onStop(); + // Verify that the flutterView is gone. + assertEquals(View.GONE, delegate.flutterView.getVisibility()); + delegate.onStart(); + // Verify that the flutterView is gone. + assertEquals(View.GONE, delegate.flutterView.getVisibility()); + } + + @Test + public void flutterSurfaceViewVisibilityChangedWithFlutterView() { + // ---- Test setup ---- + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + delegate.onAttach(ctx); + delegate.onCreateView(null, null, null, 0, true); + // --- Execute the behavior under test --- + // For `FlutterSurfaceView`, setting visibility to the current `FlutterView` will not take + // effect since it is not in the view tree. So we need to make sure that when the visibility of + // `FlutterView` changes, the `FlutterSurfaceView` changes at the same time + // See https://github.com/flutter/flutter/issues/105203 + assertEquals(FlutterSurfaceView.class, delegate.flutterView.renderSurface.getClass()); + FlutterSurfaceView surfaceView = (FlutterSurfaceView) delegate.flutterView.renderSurface; + // Verify that the `FlutterSurfaceView` is gone. + delegate.flutterView.setVisibility(View.GONE); + assertEquals(View.GONE, surfaceView.getVisibility()); + // Verify that the `FlutterSurfaceView` is visible. + delegate.flutterView.setVisibility(View.VISIBLE); + assertEquals(View.VISIBLE, surfaceView.getVisibility()); + // Verify that the `FlutterSurfaceView` is invisible. + delegate.flutterView.setVisibility(View.INVISIBLE); + assertEquals(View.INVISIBLE, surfaceView.getVisibility()); + } + + @Test + public void usesFlutterEngineGroup() { + FlutterEngineGroup mockEngineGroup = mock(FlutterEngineGroup.class); + when(mockEngineGroup.createAndRunEngine(any(FlutterEngineGroup.Options.class))) + .thenReturn(mockFlutterEngine); + FlutterActivityAndFragmentDelegate.Host host = + mock(FlutterActivityAndFragmentDelegate.Host.class); + when(mockHost.getContext()).thenReturn(ctx); + + FlutterActivityAndFragmentDelegate delegate = + new FlutterActivityAndFragmentDelegate(mockHost, mockEngineGroup); + delegate.onAttach(ctx); + FlutterEngine engineUnderTest = delegate.getFlutterEngine(); + assertEquals(engineUnderTest, mockFlutterEngine); + } + + @Test + public void itDoesAttachFlutterViewToEngine() { + // ---- Test setup ---- + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + delegate.onAttach(ctx); + delegate.onCreateView(null, null, null, 0, true); + + // --- Execute the behavior under test --- + assertTrue(delegate.flutterView.isAttachedToFlutterEngine()); + } + + @Test + public void itDoesNotAttachFlutterViewToEngine() { + // ---- Test setup ---- + // Create the real object that we're testing. + when(mockHost.attachToEngineAutomatically()).thenReturn(false); + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + delegate.onAttach(ctx); + delegate.onCreateView(null, null, null, 0, true); + + // --- Execute the behavior under test --- + assertFalse(delegate.flutterView.isAttachedToFlutterEngine()); + } + + @Test + public void itDoesNotDetachTwice() { + FlutterEngine cachedEngine = mockFlutterEngine(); + FlutterEngineCache.getInstance().put("my_flutter_engine", cachedEngine); + + // Engine is a cached singleton that isn't owned by either hosts. + when(mockHost.shouldDestroyEngineWithHost()).thenReturn(false); + when(mockHost2.shouldDestroyEngineWithHost()).thenReturn(false); + + // Adjust fake hosts to request cached engine. + when(mockHost.getCachedEngineId()).thenReturn("my_flutter_engine"); + when(mockHost2.getCachedEngineId()).thenReturn("my_flutter_engine"); + + // Create the real objects that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost); + FlutterActivityAndFragmentDelegate delegate2 = + new FlutterActivityAndFragmentDelegate(mockHost2); + + // This test is written to recreate the following scenario: + // 1. We have a FlutterFragment_A attached to a singleton cached engine. + // 2. An intent arrives that spawns FlutterFragment_B. + // 3. FlutterFragment_B starts and steals the engine from FlutterFragment_A while attaching. + // Via a call to FlutterActivityAndFragmentDelegate.detachFromFlutterEngine(). + // 4. FlutterFragment_A is forcibly detached from the engine. + // 5. FlutterFragment_B is attached to the engine. + // 6. FlutterFragment_A is detached from the engine. + // Note that the second detach for FlutterFragment_A is done unconditionally when the Fragment + // is being + // torn down. + + // At this point the engine's life cycle channel receives a message (triggered by + // FlutterFragment_A's second detach) + // that indicates the app is detached. This breaks FlutterFragment_B. + + // Below is a sequence of calls that mimicks the calls that the above scenario would trigger + // without + // relying on an intent to trigger the behaviour. + + // FlutterFragment_A is attached to the engine. + delegate.onAttach(ctx); + + // NOTE: The following two calls happen in a slightly different order in reality. That is, via, + // a call to host.detachFromFlutterEngine, delegate2.onAttach ends up invoking + // delegate.onDetach. + // To keep this regression test simple, we call them directly. + + // Detach FlutterFragment_A. + delegate.onDetach(); + + verify(cachedEngine.getLifecycleChannel(), times(1)).appIsDetached(); + + // Attaches to the engine FlutterFragment_B. + delegate2.onAttach(ctx); + delegate2.onResume(); + + verify(cachedEngine.getLifecycleChannel(), times(1)).appIsResumed(); + verify(cachedEngine.getLifecycleChannel(), times(1)).appIsDetached(); + + // A second Detach of FlutterFragment_A happens when the Fragment is detached. + delegate.onDetach(); + + // IMPORTANT: The bug we fixed would have resulted in the engine thinking the app + // is detached twice instead of once. + verify(cachedEngine.getLifecycleChannel(), times(1)).appIsDetached(); + } + + /** + * Creates a mock {@link io.flutter.embedding.engine.FlutterEngine}. + * + *

The heuristic for deciding what to mock in the given {@link + * io.flutter.embedding.engine.FlutterEngine} is that we should mock the minimum number of + * necessary methods and associated objects. Maintaining developers should add more mock behavior + * as required for tests, but should avoid mocking things that are not required for the correct + * execution of tests. + */ + @NonNull + private FlutterEngine mockFlutterEngine() { + // The use of SettingsChannel by the delegate requires some behavior of its own, so it is + // explicitly mocked with some internal behavior. + SettingsChannel fakeSettingsChannel = mock(SettingsChannel.class); + SettingsChannel.MessageBuilder fakeMessageBuilder = mock(SettingsChannel.MessageBuilder.class); + when(fakeMessageBuilder.setPlatformBrightness(any(SettingsChannel.PlatformBrightness.class))) + .thenReturn(fakeMessageBuilder); + when(fakeMessageBuilder.setTextScaleFactor(any(Float.class))).thenReturn(fakeMessageBuilder); + when(fakeMessageBuilder.setDisplayMetrics(any())).thenReturn(fakeMessageBuilder); + when(fakeMessageBuilder.setNativeSpellCheckServiceDefined(any(Boolean.class))) + .thenReturn(fakeMessageBuilder); + when(fakeMessageBuilder.setBrieflyShowPassword(any(Boolean.class))) + .thenReturn(fakeMessageBuilder); + when(fakeMessageBuilder.setUse24HourFormat(any(Boolean.class))).thenReturn(fakeMessageBuilder); + when(fakeSettingsChannel.startMessage()).thenReturn(fakeMessageBuilder); + + // Mock FlutterEngine and all of its required direct calls. + FlutterEngine engine = mock(FlutterEngine.class); + when(engine.getAccessibilityChannel()).thenReturn(mock(AccessibilityChannel.class)); + when(engine.getActivityControlSurface()).thenReturn(mock(ActivityControlSurface.class)); + when(engine.getDartExecutor()).thenReturn(mock(DartExecutor.class)); + when(engine.getLifecycleChannel()).thenReturn(mock(LifecycleChannel.class)); + when(engine.getLocalizationChannel()).thenReturn(mock(LocalizationChannel.class)); + when(engine.getLocalizationPlugin()).thenReturn(mock(LocalizationPlugin.class)); + when(engine.getMouseCursorChannel()).thenReturn(mock(MouseCursorChannel.class)); + when(engine.getNavigationChannel()).thenReturn(mock(NavigationChannel.class)); + when(engine.getBackGestureChannel()).thenReturn(mock(BackGestureChannel.class)); + when(engine.getPlatformViewsController()).thenReturn(mock(PlatformViewsController.class)); + when(engine.getPlatformViewsController2()).thenReturn(mock(PlatformViewsController2.class)); + + FlutterRenderer renderer = mock(FlutterRenderer.class); + when(engine.getRenderer()).thenReturn(renderer); + + when(engine.getSettingsChannel()).thenReturn(fakeSettingsChannel); + when(engine.getSystemChannel()).thenReturn(mock(SystemChannel.class)); + when(engine.getTextInputChannel()).thenReturn(mock(TextInputChannel.class)); + when(engine.getScribeChannel()).thenReturn(mock(ScribeChannel.class)); + + return engine; + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/FlutterActivityTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/FlutterActivityTest.java new file mode 100644 index 0000000000000000000000000000000000000000..d3686a6dbcf114fd9f4bdda3aa9a773cd4a1cdaa --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/FlutterActivityTest.java @@ -0,0 +1,784 @@ +// 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. + +package io.flutter.embedding.android; + +import static io.flutter.Build.API_LEVELS; +import static io.flutter.embedding.android.FlutterActivityLaunchConfigs.EXTRA_CACHED_ENGINE_ID; +import static io.flutter.embedding.android.FlutterActivityLaunchConfigs.HANDLE_DEEPLINKING_META_DATA_KEY; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.annotation.SuppressLint; +import android.annotation.TargetApi; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.os.Bundle; +import android.window.BackEvent; +import android.window.OnBackAnimationCallback; +import android.window.OnBackInvokedCallback; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.RequiresApi; +import androidx.lifecycle.DefaultLifecycleObserver; +import androidx.lifecycle.LifecycleOwner; +import androidx.test.core.app.ActivityScenario; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.FlutterInjector; +import io.flutter.embedding.android.FlutterActivityLaunchConfigs.BackgroundMode; +import io.flutter.embedding.engine.FlutterEngine; +import io.flutter.embedding.engine.FlutterEngineCache; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.loader.FlutterLoader; +import io.flutter.embedding.engine.plugins.FlutterPlugin; +import io.flutter.embedding.engine.plugins.activity.ActivityAware; +import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; +import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding.OnSaveInstanceStateListener; +import io.flutter.plugins.GeneratedPluginRegistrant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.Robolectric; +import org.robolectric.android.controller.ActivityController; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class FlutterActivityTest { + private final Context ctx = ApplicationProvider.getApplicationContext(); + boolean isDelegateAttached; + + @Before + public void setUp() { + FlutterInjector.reset(); + GeneratedPluginRegistrant.clearRegisteredEngines(); + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + when(mockFlutterJNI.isAttached()).thenReturn(true); + FlutterJNI.Factory mockFlutterJNIFactory = mock(FlutterJNI.Factory.class); + when(mockFlutterJNIFactory.provideFlutterJNI()).thenReturn(mockFlutterJNI); + FlutterInjector.setInstance( + new FlutterInjector.Builder().setFlutterJNIFactory(mockFlutterJNIFactory).build()); + } + + @After + public void tearDown() { + GeneratedPluginRegistrant.clearRegisteredEngines(); + FlutterInjector.reset(); + } + + @Test + public void flutterViewHasId() { + Intent intent = FlutterActivity.createDefaultIntent(ctx); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivity.class, intent); + FlutterActivity activity = activityController.get(); + + activity.onCreate(null); + assertNotNull(activity.findViewById(FlutterActivity.FLUTTER_VIEW_ID)); + assertTrue(activity.findViewById(FlutterActivity.FLUTTER_VIEW_ID) instanceof FlutterView); + } + + @Test + @Config(minSdk = API_LEVELS.API_34) + @TargetApi(API_LEVELS.API_34) + public void whenUsingCachedEngine_predictiveBackStateIsSaved() { + FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); + FlutterJNI mockFlutterJni = mock(FlutterJNI.class); + when(mockFlutterJni.isAttached()).thenReturn(true); + FlutterEngine cachedEngine = new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni); + FlutterEngineCache.getInstance().put("my_cached_engine", cachedEngine); + + ActivityScenario flutterActivityScenario = + ActivityScenario.launch(FlutterActivity.class); + + // Set to framework handling and then recreate the activity and check the state is preserved. + flutterActivityScenario.onActivity(activity -> activity.setFrameworkHandlesBack(true)); + flutterActivityScenario.onActivity( + activity -> activity.getIntent().putExtra(EXTRA_CACHED_ENGINE_ID, "my_cached_engine")); + + flutterActivityScenario.recreate(); + flutterActivityScenario.onActivity(activity -> assertTrue(activity.hasRegisteredBackCallback)); + + // Clean up. + flutterActivityScenario.close(); + } + + @Test + @Config(minSdk = API_LEVELS.API_34) + @TargetApi(API_LEVELS.API_34) + public void whenNotUsingCachedEngine_predictiveBackStateIsNotSaved() { + ActivityScenario flutterActivityScenario = + ActivityScenario.launch(FlutterActivity.class); + + // Set to framework handling and then recreate the activity and check the state is preserved. + flutterActivityScenario.onActivity(activity -> activity.setFrameworkHandlesBack(true)); + + flutterActivityScenario.recreate(); + flutterActivityScenario.onActivity(activity -> assertFalse(activity.hasRegisteredBackCallback)); + + // Clean up. + flutterActivityScenario.close(); + } + + // TODO(garyq): Robolectric does not yet support android api 33 yet. Switch to a robolectric + // test that directly exercises the OnBackInvoked APIs when API 33 is supported. + @Test + @TargetApi(API_LEVELS.API_33) + public void itRegistersOnBackInvokedCallbackOnChangingFrameworkHandlesBack() { + Intent intent = FlutterActivityWithReportFullyDrawn.createDefaultIntent(ctx); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivityWithReportFullyDrawn.class, intent); + FlutterActivityWithReportFullyDrawn activity = spy(activityController.get()); + + activity.onCreate(null); + + verify(activity, times(0)).registerOnBackInvokedCallback(); + + activity.setFrameworkHandlesBack(false); + verify(activity, times(0)).registerOnBackInvokedCallback(); + + activity.setFrameworkHandlesBack(true); + verify(activity, times(1)).registerOnBackInvokedCallback(); + } + + // TODO(garyq): Robolectric does not yet support android api 33 yet. Switch to a robolectric + // test that directly exercises the OnBackInvoked APIs when API 33 is supported. + @Test + @TargetApi(API_LEVELS.API_33) + public void itUnregistersOnBackInvokedCallbackOnRelease() { + Intent intent = FlutterActivityWithReportFullyDrawn.createDefaultIntent(ctx); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivityWithReportFullyDrawn.class, intent); + FlutterActivityWithReportFullyDrawn activity = spy(activityController.get()); + + activity.release(); + + verify(activity, times(1)).unregisterOnBackInvokedCallback(); + } + + @Test + @Config(sdk = API_LEVELS.API_32) + public void onBackInvokedCallbackIsNullForSdk32OrLower() { + Intent intent = FlutterActivity.createDefaultIntent(ctx); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivity.class, intent); + FlutterActivity flutterActivity = activityController.get(); + + assertNull( + "onBackInvokedCallback should be null for SDK 32 or lower", + flutterActivity.getOnBackInvokedCallback()); + } + + @Test + @Config(sdk = API_LEVELS.API_33) + @TargetApi(API_LEVELS.API_33) + public void onBackInvokedCallbackCallsOnBackPressedForSdk33() { + Intent intent = FlutterActivityWithMockBackInvokedHandling.createDefaultIntent(ctx); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivityWithMockBackInvokedHandling.class, intent); + FlutterActivityWithMockBackInvokedHandling activity = activityController.get(); + + OnBackInvokedCallback callback = activity.getOnBackInvokedCallback(); + assertNotNull("onBackInvokedCallback should not be null for SDK 33", callback); + + callback.onBackInvoked(); + assertEquals("Expected onBackPressed to be called 1 times", 1, activity.onBackPressedCounter); + } + + @Test + @Config(sdk = API_LEVELS.API_34) + @TargetApi(API_LEVELS.API_34) + public void itHandlesOnBackAnimationCallbackAsExpectedForSdk34OrHigher() { + Intent intent = FlutterActivityWithMockBackInvokedHandling.createDefaultIntent(ctx); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivityWithMockBackInvokedHandling.class, intent); + FlutterActivityWithMockBackInvokedHandling activity = activityController.get(); + + assertTrue( + "onBackInvokedCallback should be an instance of OnBackAnimationCallback for SDK 34 or higher", + activity.getOnBackInvokedCallback() instanceof OnBackAnimationCallback); + + OnBackAnimationCallback callback = + (OnBackAnimationCallback) activity.getOnBackInvokedCallback(); + + BackEvent mockBackEvent = mock(BackEvent.class); + callback.onBackStarted(mockBackEvent); + assertEquals( + "Expected startBackGesture to be called 1 times", 1, activity.startBackGestureCounter); + + callback.onBackProgressed(mockBackEvent); + assertEquals( + "Expected updateBackGestureProgress to be called 1 times", + 1, + activity.updateBackGestureProgressCounter); + + callback.onBackInvoked(); + assertEquals( + "Expected commitBackGesture to be called 1 times", 1, activity.commitBackGestureCounter); + + callback.onBackCancelled(); + assertEquals( + "Expected cancelBackGesture to be called 1 times", 1, activity.cancelBackGestureCounter); + } + + @Test + public void itCreatesDefaultIntentWithExpectedDefaults() { + Intent intent = FlutterActivity.createDefaultIntent(ctx); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivity.class, intent); + FlutterActivity flutterActivity = activityController.get(); + flutterActivity.setDelegate(new FlutterActivityAndFragmentDelegate(flutterActivity)); + + assertEquals("main", flutterActivity.getDartEntrypointFunctionName()); + assertNull(flutterActivity.getDartEntrypointLibraryUri()); + assertNull(flutterActivity.getDartEntrypointArgs()); + assertEquals("/", flutterActivity.getInitialRoute()); + assertArrayEquals(new String[] {}, flutterActivity.getFlutterShellArgs().toArray()); + assertTrue(flutterActivity.shouldAttachEngineToActivity()); + assertNull(flutterActivity.getCachedEngineId()); + assertTrue(flutterActivity.shouldDestroyEngineWithHost()); + assertEquals(BackgroundMode.opaque, flutterActivity.getBackgroundMode()); + assertEquals(RenderMode.surface, flutterActivity.getRenderMode()); + assertEquals(TransparencyMode.opaque, flutterActivity.getTransparencyMode()); + } + + @Test + public void itDestroysNewEngineWhenIntentIsMissingParameter() { + // All clients should use the static members of FlutterActivity to construct an + // Intent. Missing extras is an error. However, Flutter has number of tests that + // don't seem to use the static members of FlutterActivity to construct the + // launching Intent, so this test explicitly verifies that even illegal Intents + // result in the automatic destruction of a non-cached FlutterEngine, which prevents + // the breakage of memory usage benchmark tests. + Intent intent = new Intent(ctx, FlutterActivity.class); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivity.class, intent); + FlutterActivity flutterActivity = activityController.get(); + flutterActivity.setDelegate(new FlutterActivityAndFragmentDelegate(flutterActivity)); + + assertTrue(flutterActivity.shouldDestroyEngineWithHost()); + } + + @Test + public void itDoesNotDestroyFlutterEngineWhenProvidedByHost() { + Intent intent = new Intent(ctx, FlutterActivityWithProvidedEngine.class); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivityWithProvidedEngine.class, intent); + activityController.create(); + FlutterActivityWithProvidedEngine flutterActivity = activityController.get(); + + assertFalse(flutterActivity.shouldDestroyEngineWithHost()); + } + + @Test + public void itCreatesNewEngineIntentWithRequestedSettings() { + Intent intent = + FlutterActivity.withNewEngine() + .initialRoute("/custom/route") + .dartEntrypointArgs(new ArrayList(Arrays.asList("foo", "bar"))) + .backgroundMode(BackgroundMode.transparent) + .build(ctx); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivity.class, intent); + FlutterActivity flutterActivity = activityController.get(); + flutterActivity.setDelegate(new FlutterActivityAndFragmentDelegate(flutterActivity)); + + assertEquals("/custom/route", flutterActivity.getInitialRoute()); + assertArrayEquals( + new String[] {"foo", "bar"}, flutterActivity.getDartEntrypointArgs().toArray()); + assertArrayEquals(new String[] {}, flutterActivity.getFlutterShellArgs().toArray()); + assertTrue(flutterActivity.shouldAttachEngineToActivity()); + assertNull(flutterActivity.getCachedEngineId()); + assertTrue(flutterActivity.shouldDestroyEngineWithHost()); + assertEquals(BackgroundMode.transparent, flutterActivity.getBackgroundMode()); + assertEquals(RenderMode.texture, flutterActivity.getRenderMode()); + assertEquals(TransparencyMode.transparent, flutterActivity.getTransparencyMode()); + } + + @Test + public void itCreatesNewEngineInGroupIntentWithRequestedSettings() { + Intent intent = + FlutterActivity.withNewEngineInGroup("my_cached_engine_group") + .dartEntrypoint("custom_entrypoint") + .initialRoute("/custom/route") + .backgroundMode(BackgroundMode.transparent) + .build(ctx); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivity.class, intent); + FlutterActivity flutterActivity = activityController.get(); + flutterActivity.setDelegate(new FlutterActivityAndFragmentDelegate(flutterActivity)); + + assertEquals("my_cached_engine_group", flutterActivity.getCachedEngineGroupId()); + assertEquals("custom_entrypoint", flutterActivity.getDartEntrypointFunctionName()); + assertEquals("/custom/route", flutterActivity.getInitialRoute()); + assertArrayEquals(new String[] {}, flutterActivity.getFlutterShellArgs().toArray()); + assertTrue(flutterActivity.shouldAttachEngineToActivity()); + assertTrue(flutterActivity.shouldDestroyEngineWithHost()); + assertNull(flutterActivity.getCachedEngineId()); + assertEquals(BackgroundMode.transparent, flutterActivity.getBackgroundMode()); + assertEquals(RenderMode.texture, flutterActivity.getRenderMode()); + assertEquals(TransparencyMode.transparent, flutterActivity.getTransparencyMode()); + } + + @Test + public void itReturnsValueFromMetaDataWhenCallsShouldHandleDeepLinkingCase1() + throws PackageManager.NameNotFoundException { + Intent intent = + FlutterActivity.withNewEngine().backgroundMode(BackgroundMode.transparent).build(ctx); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivity.class, intent); + FlutterActivity flutterActivity = activityController.get(); + Bundle bundle = new Bundle(); + bundle.putBoolean(HANDLE_DEEPLINKING_META_DATA_KEY, true); + FlutterActivity spyFlutterActivity = spy(flutterActivity); + when(spyFlutterActivity.getMetaData()).thenReturn(bundle); + assertTrue(spyFlutterActivity.shouldHandleDeeplinking()); + } + + @Test + public void itReturnsValueFromMetaDataWhenCallsShouldHandleDeepLinkingCase2() + throws PackageManager.NameNotFoundException { + Intent intent = + FlutterActivity.withNewEngine().backgroundMode(BackgroundMode.transparent).build(ctx); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivity.class, intent); + FlutterActivity flutterActivity = activityController.get(); + Bundle bundle = new Bundle(); + bundle.putBoolean(HANDLE_DEEPLINKING_META_DATA_KEY, false); + FlutterActivity spyFlutterActivity = spy(flutterActivity); + when(spyFlutterActivity.getMetaData()).thenReturn(bundle); + assertFalse(spyFlutterActivity.shouldHandleDeeplinking()); + } + + @Test + public void itReturnsValueFromMetaDataWhenCallsShouldHandleDeepLinkingCase3() + throws PackageManager.NameNotFoundException { + Intent intent = + FlutterActivity.withNewEngine().backgroundMode(BackgroundMode.transparent).build(ctx); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivity.class, intent); + FlutterActivity flutterActivity = activityController.get(); + // Creates an empty bundle. + Bundle bundle = new Bundle(); + FlutterActivity spyFlutterActivity = spy(flutterActivity); + when(spyFlutterActivity.getMetaData()).thenReturn(bundle); + // Empty bundle should return true. + assertTrue(spyFlutterActivity.shouldHandleDeeplinking()); + } + + @Test + public void itCreatesCachedEngineIntentThatDoesNotDestroyTheEngine() { + Intent intent = + FlutterActivity.withCachedEngine("my_cached_engine") + .destroyEngineWithActivity(false) + .build(ctx); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivity.class, intent); + FlutterActivity flutterActivity = activityController.get(); + + assertArrayEquals(new String[] {}, flutterActivity.getFlutterShellArgs().toArray()); + assertTrue(flutterActivity.shouldAttachEngineToActivity()); + assertEquals("my_cached_engine", flutterActivity.getCachedEngineId()); + assertFalse(flutterActivity.shouldDestroyEngineWithHost()); + } + + @Test + public void itCreatesCachedEngineIntentThatDestroysTheEngine() { + Intent intent = + FlutterActivity.withCachedEngine("my_cached_engine") + .destroyEngineWithActivity(true) + .build(ctx); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivity.class, intent); + FlutterActivity flutterActivity = activityController.get(); + + assertArrayEquals(new String[] {}, flutterActivity.getFlutterShellArgs().toArray()); + assertTrue(flutterActivity.shouldAttachEngineToActivity()); + assertEquals("my_cached_engine", flutterActivity.getCachedEngineId()); + assertTrue(flutterActivity.shouldDestroyEngineWithHost()); + } + + @Test + public void itRegistersPluginsAtConfigurationTime() { + Intent intent = FlutterActivity.createDefaultIntent(ctx); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivity.class, intent); + FlutterActivity activity = activityController.get(); + + // This calls onAttach on FlutterActivityAndFragmentDelegate and subsequently + // configureFlutterEngine which registers the plugins. + activity.onCreate(null); + + List registeredEngines = GeneratedPluginRegistrant.getRegisteredEngines(); + assertEquals(1, registeredEngines.size()); + assertEquals(activity.getFlutterEngine(), registeredEngines.get(0)); + } + + @Test + public void itCanBeDetachedFromTheEngineAndStopSendingFurtherEvents() { + FlutterActivityAndFragmentDelegate mockDelegate = + mock(FlutterActivityAndFragmentDelegate.class); + FlutterEngine mockEngine = mock(FlutterEngine.class); + FlutterEngineCache.getInstance().put("my_cached_engine", mockEngine); + + Intent intent = FlutterActivity.withCachedEngine("my_cached_engine").build(ctx); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivity.class, intent); + FlutterActivity flutterActivity = activityController.get(); + + isDelegateAttached = true; + when(mockDelegate.isAttached()).thenAnswer(invocation -> isDelegateAttached); + doAnswer(invocation -> isDelegateAttached = false).when(mockDelegate).onDetach(); + + flutterActivity.setDelegate(mockDelegate); + flutterActivity.onStart(); + flutterActivity.onResume(); + + verify(mockDelegate, times(1)).onStart(); + verify(mockDelegate, times(1)).onResume(); + + flutterActivity.onPause(); + flutterActivity.detachFromFlutterEngine(); + verify(mockDelegate, times(1)).onPause(); + verify(mockDelegate, times(1)).onDestroyView(); + verify(mockDelegate, times(1)).onDetach(); + + flutterActivity.onStop(); + verify(mockDelegate, never()).onStop(); + + // Simulate the disconnected activity resuming again. + flutterActivity.onStart(); + flutterActivity.onResume(); + // Shouldn't send more events to the delegates as before and shouldn't crash. + verify(mockDelegate, times(1)).onStart(); + verify(mockDelegate, times(1)).onResume(); + + flutterActivity.onDestroy(); + // 1 time same as before. + verify(mockDelegate, times(1)).onDestroyView(); + verify(mockDelegate, times(1)).onDetach(); + verify(mockDelegate, times(1)).release(); + } + + @Test + public void itReturnsExclusiveAppComponent() { + Intent intent = FlutterActivity.createDefaultIntent(ctx); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivity.class, intent); + FlutterActivity flutterActivity = activityController.get(); + FlutterActivityAndFragmentDelegate delegate = + new FlutterActivityAndFragmentDelegate(flutterActivity); + flutterActivity.setDelegate(delegate); + + assertEquals(flutterActivity.getExclusiveAppComponent(), delegate); + } + + @Test + public void itDelaysDrawing() { + Intent intent = FlutterActivity.createDefaultIntent(ctx); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivity.class, intent); + FlutterActivity flutterActivity = activityController.get(); + + flutterActivity.onCreate(null); + + assertNotNull(flutterActivity.delegate.activePreDrawListener); + } + + @Test + public void itDoesNotDelayDrawingwhenUsingTextureRendering() { + Intent intent = FlutterActivityWithTextureRendering.createDefaultIntent(ctx); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivityWithTextureRendering.class, intent); + FlutterActivityWithTextureRendering flutterActivity = activityController.get(); + + flutterActivity.onCreate(null); + + assertNull(flutterActivity.delegate.activePreDrawListener); + } + + @Test + public void itRestoresPluginStateBeforePluginOnCreate() { + FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); + FlutterJNI mockFlutterJni = mock(FlutterJNI.class); + when(mockFlutterJni.isAttached()).thenReturn(true); + FlutterEngine cachedEngine = new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni); + FakeFlutterPlugin fakeFlutterPlugin = new FakeFlutterPlugin(); + cachedEngine.getPlugins().add(fakeFlutterPlugin); + FlutterEngineCache.getInstance().put("my_cached_engine", cachedEngine); + + Intent intent = FlutterActivity.withCachedEngine("my_cached_engine").build(ctx); + Robolectric.buildActivity(FlutterActivity.class, intent).setup(); + assertTrue( + "Expected FakeFlutterPlugin onCreateCalled to be true", fakeFlutterPlugin.onCreateCalled); + } + + @Test + public void itDoesNotRegisterPluginsTwiceWhenUsingACachedEngine() { + Intent intent = new Intent(ctx, FlutterActivityWithProvidedEngine.class); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivityWithProvidedEngine.class, intent); + activityController.create(); + FlutterActivityWithProvidedEngine flutterActivity = activityController.get(); + flutterActivity.configureFlutterEngine(flutterActivity.getFlutterEngine()); + + List registeredEngines = GeneratedPluginRegistrant.getRegisteredEngines(); + // This might cause the plugins to be registered twice, once by the FlutterEngine constructor, + // and once by the default FlutterActivity.configureFlutterEngine implementation. + // Test that it doesn't happen. + assertEquals(1, registeredEngines.size()); + } + + @Test + public void itDoesNotReleaseEnginewhenDetachFromFlutterEngine() { + FlutterActivityAndFragmentDelegate mockDelegate = + mock(FlutterActivityAndFragmentDelegate.class); + isDelegateAttached = true; + when(mockDelegate.isAttached()).thenAnswer(invocation -> isDelegateAttached); + doAnswer(invocation -> isDelegateAttached = false).when(mockDelegate).onDetach(); + FlutterEngine mockEngine = mock(FlutterEngine.class); + FlutterEngineCache.getInstance().put("my_cached_engine", mockEngine); + + Intent intent = FlutterActivity.withCachedEngine("my_cached_engine").build(ctx); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivity.class, intent); + FlutterActivity flutterActivity = activityController.get(); + + flutterActivity.setDelegate(mockDelegate); + flutterActivity.onStart(); + flutterActivity.onResume(); + flutterActivity.onPause(); + + assertTrue(mockDelegate.isAttached()); + flutterActivity.detachFromFlutterEngine(); + verify(mockDelegate, times(1)).onDetach(); + verify(mockDelegate, never()).release(); + assertFalse(mockDelegate.isAttached()); + } + + @Test + public void itReleaseEngineWhenOnDestroy() { + FlutterActivityAndFragmentDelegate mockDelegate = + mock(FlutterActivityAndFragmentDelegate.class); + isDelegateAttached = true; + when(mockDelegate.isAttached()).thenAnswer(invocation -> isDelegateAttached); + doAnswer(invocation -> isDelegateAttached = false).when(mockDelegate).onDetach(); + FlutterEngine mockEngine = mock(FlutterEngine.class); + FlutterEngineCache.getInstance().put("my_cached_engine", mockEngine); + + Intent intent = FlutterActivity.withCachedEngine("my_cached_engine").build(ctx); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivity.class, intent); + FlutterActivity flutterActivity = activityController.get(); + + flutterActivity.setDelegate(mockDelegate); + flutterActivity.onStart(); + flutterActivity.onResume(); + flutterActivity.onPause(); + + assertTrue(mockDelegate.isAttached()); + flutterActivity.onDestroy(); + verify(mockDelegate, times(1)).onDetach(); + verify(mockDelegate, times(1)).release(); + assertFalse(mockDelegate.isAttached()); + } + + @Test + @Config(minSdk = API_LEVELS.API_21, maxSdk = API_LEVELS.API_28) + public void fullyDrawn_beforeAndroidQ() { + Intent intent = FlutterActivityWithReportFullyDrawn.createDefaultIntent(ctx); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivityWithReportFullyDrawn.class, intent); + FlutterActivityWithReportFullyDrawn flutterActivity = activityController.get(); + + // See https://github.com/flutter/flutter/issues/46172, and + // https://github.com/flutter/flutter/issues/88767. + flutterActivity.onFlutterUiDisplayed(); + assertFalse("reportFullyDrawn isn't used", flutterActivity.isFullyDrawn()); + } + + @Test + @Config(minSdk = API_LEVELS.API_29) + public void fullyDrawn_fromAndroidQ() { + Intent intent = FlutterActivityWithReportFullyDrawn.createDefaultIntent(ctx); + ActivityController activityController = + Robolectric.buildActivity(FlutterActivityWithReportFullyDrawn.class, intent); + FlutterActivityWithReportFullyDrawn flutterActivity = activityController.get(); + + flutterActivity.onFlutterUiDisplayed(); + assertTrue("reportFullyDrawn is used", flutterActivity.isFullyDrawn()); + flutterActivity.resetFullyDrawn(); + } + + static class FlutterActivityWithProvidedEngine extends FlutterActivity { + @Override + @SuppressLint("MissingSuperCall") + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.delegate = new FlutterActivityAndFragmentDelegate(this); + super.delegate.setUpFlutterEngine(); + } + + @Nullable + @Override + public FlutterEngine provideFlutterEngine(@NonNull Context context) { + FlutterJNI flutterJNI = mock(FlutterJNI.class); + FlutterLoader flutterLoader = mock(FlutterLoader.class); + when(flutterJNI.isAttached()).thenReturn(true); + when(flutterLoader.automaticallyRegisterPlugins()).thenReturn(true); + + return new FlutterEngine(context, flutterLoader, flutterJNI, new String[] {}, true); + } + } + + // This is just a compile time check to ensure that it's possible for FlutterActivity subclasses + // to provide their own intent builders which builds their own runtime types. + static class FlutterActivityWithIntentBuilders extends FlutterActivity { + + public static NewEngineIntentBuilder withNewEngine() { + return new NewEngineIntentBuilder(FlutterActivityWithIntentBuilders.class); + } + + public static CachedEngineIntentBuilder withCachedEngine(@NonNull String cachedEngineId) { + return new CachedEngineIntentBuilder(FlutterActivityWithIntentBuilders.class, cachedEngineId); + } + } + + private static class FlutterActivityWithTextureRendering extends FlutterActivity { + @Override + public RenderMode getRenderMode() { + return RenderMode.texture; + } + } + + private static class FlutterActivityWithReportFullyDrawn extends FlutterActivity { + private boolean fullyDrawn = false; + + @Override + public void reportFullyDrawn() { + fullyDrawn = true; + } + + public boolean isFullyDrawn() { + return fullyDrawn; + } + + public void resetFullyDrawn() { + fullyDrawn = false; + } + } + + private static class FlutterActivityWithMockBackInvokedHandling extends FlutterActivity { + + int onBackPressedCounter = 0; + int startBackGestureCounter = 0; + int updateBackGestureProgressCounter = 0; + int commitBackGestureCounter = 0; + int cancelBackGestureCounter = 0; + + @Override + public void onBackPressed() { + onBackPressedCounter++; + } + + @TargetApi(API_LEVELS.API_34) + @RequiresApi(API_LEVELS.API_34) + @Override + public void startBackGesture(@NonNull BackEvent backEvent) { + startBackGestureCounter++; + } + + @TargetApi(API_LEVELS.API_34) + @RequiresApi(API_LEVELS.API_34) + @Override + public void updateBackGestureProgress(@NonNull BackEvent backEvent) { + updateBackGestureProgressCounter++; + } + + @TargetApi(API_LEVELS.API_34) + @RequiresApi(API_LEVELS.API_34) + @Override + public void commitBackGesture() { + commitBackGestureCounter++; + } + + @TargetApi(API_LEVELS.API_34) + @RequiresApi(API_LEVELS.API_34) + @Override + public void cancelBackGesture() { + cancelBackGestureCounter++; + } + } + + private static final class FakeFlutterPlugin + implements FlutterPlugin, + ActivityAware, + OnSaveInstanceStateListener, + DefaultLifecycleObserver { + + private ActivityPluginBinding activityPluginBinding; + private boolean stateRestored = false; + private boolean onCreateCalled = false; + + @Override + public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {} + + @Override + public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {} + + @Override + public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) { + activityPluginBinding = binding; + binding.addOnSaveStateListener(this); + ((FlutterActivity) binding.getActivity()).getLifecycle().addObserver(this); + } + + @Override + public void onDetachedFromActivityForConfigChanges() { + onDetachedFromActivity(); + } + + @Override + public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) { + onAttachedToActivity(binding); + } + + @Override + public void onDetachedFromActivity() { + ((FlutterActivity) activityPluginBinding.getActivity()).getLifecycle().removeObserver(this); + activityPluginBinding.removeOnSaveStateListener(this); + activityPluginBinding = null; + } + + @Override + public void onSaveInstanceState(@NonNull Bundle bundle) {} + + @Override + public void onRestoreInstanceState(@Nullable Bundle bundle) { + stateRestored = true; + } + + @Override + public void onCreate(@NonNull LifecycleOwner lifecycleOwner) { + assertTrue("State was restored before onCreate", stateRestored); + onCreateCalled = true; + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/FlutterAndroidComponentTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/FlutterAndroidComponentTest.java new file mode 100644 index 0000000000000000000000000000000000000000..901ac61b2a002d8f441f5599cabab6d0a37128a5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/FlutterAndroidComponentTest.java @@ -0,0 +1,435 @@ +// 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. + +package io.flutter.embedding.android; + +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.withSettings; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.lifecycle.Lifecycle; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.FlutterEngine; +import io.flutter.embedding.engine.FlutterEngineCache; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.FlutterShellArgs; +import io.flutter.embedding.engine.loader.FlutterLoader; +import io.flutter.embedding.engine.plugins.FlutterPlugin; +import io.flutter.embedding.engine.plugins.activity.ActivityAware; +import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; +import io.flutter.embedding.engine.systemchannels.LifecycleChannel; +import io.flutter.plugin.platform.PlatformPlugin; +import java.util.List; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.robolectric.Robolectric; +import org.robolectric.android.controller.ActivityController; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class FlutterAndroidComponentTest { + private final Context ctx = ApplicationProvider.getApplicationContext(); + + @Test + public void pluginsReceiveFlutterPluginBinding() { + // ---- Test setup ---- + // Place a FlutterEngine in the static cache. + FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); + FlutterJNI mockFlutterJni = mock(FlutterJNI.class); + when(mockFlutterJni.isAttached()).thenReturn(true); + FlutterEngine cachedEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + FlutterEngineCache.getInstance().put("my_flutter_engine", cachedEngine); + + // Add mock plugin. + FlutterPlugin mockPlugin = mock(FlutterPlugin.class); + cachedEngine.getPlugins().add(mockPlugin); + + // Create a fake Host, which is required by the delegate. + FakeHost fakeHost = new FakeHost(cachedEngine); + fakeHost.shouldDestroyEngineWithHost = true; + + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(fakeHost); + + // --- Execute the behavior under test --- + // Push the delegate through all lifecycle methods all the way to destruction. + delegate.onAttach(ctx); + + // Verify that the plugin is attached to the FlutterEngine. + ArgumentCaptor pluginBindingCaptor = + ArgumentCaptor.forClass(FlutterPlugin.FlutterPluginBinding.class); + verify(mockPlugin, times(1)).onAttachedToEngine(pluginBindingCaptor.capture()); + FlutterPlugin.FlutterPluginBinding binding = pluginBindingCaptor.getValue(); + assertNotNull(binding.getApplicationContext()); + assertNotNull(binding.getBinaryMessenger()); + assertNotNull(binding.getTextureRegistry()); + assertNotNull(binding.getPlatformViewRegistry()); + + delegate.onRestoreInstanceState(null); + delegate.onCreateView(null, null, null, 0, true); + delegate.onStart(); + delegate.onResume(); + delegate.onPause(); + delegate.onStop(); + delegate.onDestroyView(); + delegate.onDetach(); + + // Verify the plugin was detached from the FlutterEngine. + pluginBindingCaptor = ArgumentCaptor.forClass(FlutterPlugin.FlutterPluginBinding.class); + verify(mockPlugin, times(1)).onDetachedFromEngine(pluginBindingCaptor.capture()); + binding = pluginBindingCaptor.getValue(); + assertNotNull(binding.getApplicationContext()); + assertNotNull(binding.getBinaryMessenger()); + assertNotNull(binding.getTextureRegistry()); + assertNotNull(binding.getPlatformViewRegistry()); + } + + @Test + public void activityAwarePluginsReceiveActivityBinding() { + // ---- Test setup ---- + // Place a FlutterEngine in the static cache. + FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); + FlutterJNI mockFlutterJni = mock(FlutterJNI.class); + when(mockFlutterJni.isAttached()).thenReturn(true); + FlutterEngine cachedEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + FlutterEngineCache.getInstance().put("my_flutter_engine", cachedEngine); + + // Add mock plugin. + FlutterPlugin mockPlugin = + mock(FlutterPlugin.class, withSettings().extraInterfaces(ActivityAware.class)); + ActivityAware activityAwarePlugin = (ActivityAware) mockPlugin; + ActivityPluginBinding.OnSaveInstanceStateListener mockSaveStateListener = + mock(ActivityPluginBinding.OnSaveInstanceStateListener.class); + + // Add a OnSaveStateListener when the Activity plugin binding is made available. + doAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + ActivityPluginBinding binding = + (ActivityPluginBinding) invocation.getArguments()[0]; + binding.addOnSaveStateListener(mockSaveStateListener); + return null; + } + }) + .when(activityAwarePlugin) + .onAttachedToActivity(any(ActivityPluginBinding.class)); + + cachedEngine.getPlugins().add(mockPlugin); + + // Create a fake Host, which is required by the delegate. + FlutterActivityAndFragmentDelegate.Host fakeHost = new FakeHost(cachedEngine); + + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(fakeHost); + + // --- Execute the behavior under test --- + // Push the delegate through all lifecycle methods all the way to destruction. + delegate.onAttach(ctx); + + // Verify plugin was given an ActivityPluginBinding. + ArgumentCaptor pluginBindingCaptor = + ArgumentCaptor.forClass(ActivityPluginBinding.class); + verify(activityAwarePlugin, times(1)).onAttachedToActivity(pluginBindingCaptor.capture()); + ActivityPluginBinding binding = pluginBindingCaptor.getValue(); + assertNotNull(binding.getActivity()); + assertNotNull(binding.getLifecycle()); + + delegate.onRestoreInstanceState(null); + + // Verify that after Activity creation, the plugin was allowed to restore state. + verify(mockSaveStateListener, times(1)).onRestoreInstanceState(isNull()); + + delegate.onCreateView(null, null, null, 0, true); + delegate.onStart(); + delegate.onResume(); + delegate.onPause(); + delegate.onStop(); + delegate.onSaveInstanceState(mock(Bundle.class)); + + // Verify that the plugin was allowed to save state. + verify(mockSaveStateListener, times(1)).onSaveInstanceState(any(Bundle.class)); + + delegate.onDestroyView(); + delegate.onDetach(); + + // Verify that the plugin was detached from the Activity. + verify(activityAwarePlugin, times(1)).onDetachedFromActivity(); + } + + @Test + public void normalLifecycleStepsDoNotTriggerADetachFromFlutterEngine() { + // ---- Test setup ---- + // Place a FlutterEngine in the static cache. + FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); + FlutterJNI mockFlutterJni = mock(FlutterJNI.class); + when(mockFlutterJni.isAttached()).thenReturn(true); + FlutterEngine cachedEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + FlutterEngineCache.getInstance().put("my_flutter_engine", cachedEngine); + + // Create a fake Host, which is required by the delegate. + FakeHost fakeHost = new FakeHost(cachedEngine); + + // Create the real object that we're testing. + FlutterActivityAndFragmentDelegate delegate = + spy(new FlutterActivityAndFragmentDelegate(fakeHost)); + + // --- Execute the behavior under test --- + // Push the delegate through all lifecycle methods all the way to destruction. + delegate.onAttach(ctx); + delegate.onRestoreInstanceState(null); + delegate.onCreateView(null, null, null, 0, true); + delegate.onStart(); + delegate.onResume(); + delegate.onPause(); + delegate.onStop(); + delegate.onDestroyView(); + delegate.onDetach(); + + verify(delegate, never()).detachFromFlutterEngine(); + } + + @Test + public void twoOverlappingFlutterActivitiesDoNotCrosstalk() { + // ---- Test setup ---- + // Place a FlutterEngine in the static cache. + FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); + FlutterJNI mockFlutterJni = mock(FlutterJNI.class); + when(mockFlutterJni.isAttached()).thenReturn(true); + FlutterEngine cachedEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + FlutterEngineCache.getInstance().put("my_flutter_engine", cachedEngine); + LifecycleChannel mockLifecycleChannel = mock(LifecycleChannel.class); + when(cachedEngine.getLifecycleChannel()).thenReturn(mockLifecycleChannel); + + Intent intent = FlutterActivity.withCachedEngine("my_flutter_engine").build(ctx); + ActivityController activityController1 = + Robolectric.buildActivity(FlutterActivity.class, intent); + activityController1.create().start().resume(); + + InOrder inOrder = inOrder(mockLifecycleChannel); + inOrder.verify(mockLifecycleChannel, times(1)).appIsResumed(); + verifyNoMoreInteractions(mockLifecycleChannel); + + activityController1.pause(); + // Create a second instance on the same engine and start running it as well. + ActivityController activityController2 = + Robolectric.buildActivity(FlutterActivity.class, intent); + activityController2.create().start().resume(); + + // From the onPause of the first activity. + inOrder.verify(mockLifecycleChannel, times(1)).appIsInactive(); + // By creating the second activity, we should automatically detach the first activity. + inOrder.verify(mockLifecycleChannel, times(1)).appIsDetached(); + // In order, the second activity then is resumed. + inOrder.verify(mockLifecycleChannel, times(1)).appIsResumed(); + verifyNoMoreInteractions(mockLifecycleChannel); + + // The first activity goes through the normal lifecycles of destruction, but since we + // detached the first activity during the second activity's creation, we should ignore the + // first activity's destruction events to avoid crosstalk. + activityController1.stop().destroy(); + verifyNoMoreInteractions(mockLifecycleChannel); + } + + private static class FakeHost implements FlutterActivityAndFragmentDelegate.Host { + final FlutterEngine cachedEngine; + Activity activity; + boolean shouldDestroyEngineWithHost = false; + Lifecycle lifecycle = mock(Lifecycle.class); + + private FakeHost(@NonNull FlutterEngine flutterEngine) { + cachedEngine = flutterEngine; + } + + @NonNull + @Override + public Context getContext() { + return ApplicationProvider.getApplicationContext(); + } + + @SuppressWarnings("deprecation") + // Robolectric.setupActivity + // TODO(reidbaker): https://github.com/flutter/flutter/issues/133151 + @Nullable + @Override + public Activity getActivity() { + if (activity == null) { + activity = Robolectric.setupActivity(Activity.class); + } + return activity; + } + + @NonNull + @Override + public Lifecycle getLifecycle() { + return lifecycle; + } + + @NonNull + @Override + public FlutterShellArgs getFlutterShellArgs() { + return new FlutterShellArgs(new String[] {}); + } + + @Nullable + @Override + public String getCachedEngineId() { + return "my_flutter_engine"; + } + + @Nullable + @Override + public String getCachedEngineGroupId() { + return "my_flutter_engine_group"; + } + + @Override + public boolean shouldDestroyEngineWithHost() { + return shouldDestroyEngineWithHost; + } + + @NonNull + @Override + public String getDartEntrypointFunctionName() { + return "main"; + } + + @Nullable + @Override + public String getDartEntrypointLibraryUri() { + return null; + } + + @Nullable + @Override + public List getDartEntrypointArgs() { + return null; + } + + @NonNull + @Override + public String getAppBundlePath() { + return "/fake/path"; + } + + @Nullable + @Override + public String getInitialRoute() { + return "/"; + } + + @NonNull + @Override + public RenderMode getRenderMode() { + return RenderMode.surface; + } + + @NonNull + @Override + public TransparencyMode getTransparencyMode() { + return TransparencyMode.transparent; + } + + @Override + public ExclusiveAppComponent getExclusiveAppComponent() { + return null; + } + + @Nullable + @Override + public FlutterEngine provideFlutterEngine(@NonNull Context context) { + return cachedEngine; + } + + @Nullable + @Override + public PlatformPlugin providePlatformPlugin( + @Nullable Activity activity, @NonNull FlutterEngine flutterEngine) { + return null; + } + + @Override + public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {} + + @Override + public void cleanUpFlutterEngine(@NonNull FlutterEngine flutterEngine) {} + + @Override + public boolean shouldAttachEngineToActivity() { + return true; + } + + @Override + public boolean shouldHandleDeeplinking() { + return false; + } + + @Override + public boolean shouldRestoreAndSaveState() { + return true; + } + + @Override + public boolean shouldDispatchAppLifecycleState() { + return true; + } + + @Override + public boolean attachToEngineAutomatically() { + return true; + } + + @Override + public boolean getBackCallbackState() { + return false; + } + + @Override + public void onFlutterSurfaceViewCreated(@NonNull FlutterSurfaceView flutterSurfaceView) {} + + @Override + public void onFlutterTextureViewCreated(@NonNull FlutterTextureView flutterTextureView) {} + + @Override + public void onFlutterUiDisplayed() {} + + @Override + public void onFlutterUiNoLongerDisplayed() {} + + @Override + public void detachFromFlutterEngine() {} + + @Override + public void updateSystemUiOverlays() {} + + @Override + public boolean popSystemNavigator() { + return false; + } + + @Override + public void setFrameworkHandlesBack(boolean frameworkHandlesBack) {} + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/FlutterFragmentActivityTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/FlutterFragmentActivityTest.java new file mode 100644 index 0000000000000000000000000000000000000000..f25b1341376fbd09986399c67130912fa95ea8a5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/FlutterFragmentActivityTest.java @@ -0,0 +1,423 @@ +// 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. + +package io.flutter.embedding.android; + +import static io.flutter.embedding.android.FlutterActivityLaunchConfigs.HANDLE_DEEPLINKING_META_DATA_KEY; +import static io.flutter.embedding.android.FlutterFragment.ARG_CACHED_ENGINE_ID; +import static io.flutter.embedding.android.FlutterFragment.ARG_DESTROY_ENGINE_WITH_FRAGMENT; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.annotation.TargetApi; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.os.Bundle; +import android.view.View; +import android.view.ViewGroup; +import android.widget.FrameLayout; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.test.core.app.ActivityScenario; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.Build; +import io.flutter.FlutterInjector; +import io.flutter.embedding.android.FlutterActivityLaunchConfigs.BackgroundMode; +import io.flutter.embedding.engine.FlutterEngine; +import io.flutter.embedding.engine.FlutterEngineCache; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.loader.FlutterLoader; +import io.flutter.plugins.GeneratedPluginRegistrant; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.Robolectric; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class FlutterFragmentActivityTest { + private final Context ctx = ApplicationProvider.getApplicationContext(); + + @Before + public void setUp() { + FlutterInjector.reset(); + GeneratedPluginRegistrant.clearRegisteredEngines(); + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + when(mockFlutterJNI.isAttached()).thenReturn(true); + FlutterJNI.Factory mockFlutterJNIFactory = mock(FlutterJNI.Factory.class); + when(mockFlutterJNIFactory.provideFlutterJNI()).thenReturn(mockFlutterJNI); + FlutterInjector.setInstance( + new FlutterInjector.Builder().setFlutterJNIFactory(mockFlutterJNIFactory).build()); + } + + @After + public void tearDown() { + GeneratedPluginRegistrant.clearRegisteredEngines(); + FlutterInjector.reset(); + } + + @Test + public void createFlutterFragment_defaultRenderModeSurface() { + final FlutterFragmentActivity activity = new FakeFlutterFragmentActivity(); + assertEquals(activity.createFlutterFragment().getRenderMode(), RenderMode.surface); + } + + @Test + public void createFlutterFragment_defaultRenderModeTexture() { + final FlutterFragmentActivity activity = + new FakeFlutterFragmentActivity() { + @Override + protected BackgroundMode getBackgroundMode() { + return BackgroundMode.transparent; + } + }; + assertEquals(activity.createFlutterFragment().getRenderMode(), RenderMode.texture); + } + + @Test + public void createFlutterFragment_customRenderMode() { + final FlutterFragmentActivity activity = + new FakeFlutterFragmentActivity() { + @Override + protected RenderMode getRenderMode() { + return RenderMode.texture; + } + }; + assertEquals(activity.createFlutterFragment().getRenderMode(), RenderMode.texture); + } + + @Test + public void createFlutterFragment_customDartEntrypointLibraryUri() { + final FlutterFragmentActivity activity = + new FakeFlutterFragmentActivity() { + @Override + public String getDartEntrypointLibraryUri() { + return "package:foo/bar.dart"; + } + }; + assertEquals( + activity.createFlutterFragment().getDartEntrypointLibraryUri(), "package:foo/bar.dart"); + } + + @Test + public void hasRootLayoutId() { + FlutterFragmentActivityWithRootLayout activity = + Robolectric.buildActivity(FlutterFragmentActivityWithRootLayout.class).get(); + activity.onCreate(null); + assertNotNull(activity.FRAGMENT_CONTAINER_ID); + assertTrue(activity.FRAGMENT_CONTAINER_ID != View.NO_ID); + } + + @Test + public void itRegistersPluginsAtConfigurationTime() { + try (ActivityScenario scenario = + ActivityScenario.launch(FlutterFragmentActivity.class)) { + scenario.onActivity( + activity -> { + List registeredEngines = + GeneratedPluginRegistrant.getRegisteredEngines(); + assertEquals(1, registeredEngines.size()); + assertEquals(activity.getFlutterEngine(), registeredEngines.get(0)); + }); + } + } + + @Test + public void itDoesNotRegisterPluginsTwiceWhenUsingACachedEngine() { + try (ActivityScenario scenario = + ActivityScenario.launch(FlutterFragmentActivity.class)) { + scenario.onActivity( + activity -> { + List registeredEngines = + GeneratedPluginRegistrant.getRegisteredEngines(); + assertEquals(1, registeredEngines.size()); + assertEquals(activity.getFlutterEngine(), registeredEngines.get(0)); + }); + } + + List registeredEngines = GeneratedPluginRegistrant.getRegisteredEngines(); + // This might cause the plugins to be registered twice, once by the FlutterEngine constructor, + // and once by the default FlutterFragmentActivity.configureFlutterEngine implementation. + // Test that it doesn't happen. + assertEquals(1, registeredEngines.size()); + } + + @Test + public void itReturnsValueFromMetaDataWhenCallsShouldHandleDeepLinkingCase1() + throws PackageManager.NameNotFoundException { + FlutterFragmentActivity activity = + Robolectric.buildActivity(FlutterFragmentActivityWithProvidedEngine.class).get(); + assertTrue(GeneratedPluginRegistrant.getRegisteredEngines().isEmpty()); + Bundle bundle = new Bundle(); + bundle.putBoolean(HANDLE_DEEPLINKING_META_DATA_KEY, true); + FlutterFragmentActivity spyFlutterActivity = spy(activity); + when(spyFlutterActivity.getMetaData()).thenReturn(bundle); + assertTrue(spyFlutterActivity.shouldHandleDeeplinking()); + } + + @Test + public void itReturnsValueFromMetaDataWhenCallsShouldHandleDeepLinkingCase2() + throws PackageManager.NameNotFoundException { + FlutterFragmentActivity activity = + Robolectric.buildActivity(FlutterFragmentActivityWithProvidedEngine.class).get(); + assertTrue(GeneratedPluginRegistrant.getRegisteredEngines().isEmpty()); + Bundle bundle = new Bundle(); + bundle.putBoolean(HANDLE_DEEPLINKING_META_DATA_KEY, false); + FlutterFragmentActivity spyFlutterActivity = spy(activity); + when(spyFlutterActivity.getMetaData()).thenReturn(bundle); + assertFalse(spyFlutterActivity.shouldHandleDeeplinking()); + } + + @Test + public void itReturnsValueFromMetaDataWhenCallsShouldHandleDeepLinkingCase3() + throws PackageManager.NameNotFoundException { + FlutterFragmentActivity activity = + Robolectric.buildActivity(FlutterFragmentActivityWithProvidedEngine.class).get(); + assertTrue(GeneratedPluginRegistrant.getRegisteredEngines().isEmpty()); + // Creates an empty bundle. + Bundle bundle = new Bundle(); + FlutterFragmentActivity spyFlutterActivity = spy(activity); + when(spyFlutterActivity.getMetaData()).thenReturn(bundle); + // Empty bundle should return true. + assertTrue(spyFlutterActivity.shouldHandleDeeplinking()); + } + + @Test + public void itAllowsRootLayoutOverride() { + FlutterFragmentActivityWithRootLayout activity = + Robolectric.buildActivity(FlutterFragmentActivityWithRootLayout.class).get(); + + activity.onCreate(null); + ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content); + boolean foundCustomView = false; + for (int i = 0; i < contentView.getChildCount(); i++) { + foundCustomView = + contentView.getChildAt(i) instanceof FlutterFragmentActivityWithRootLayout.CustomLayout; + if (foundCustomView) { + break; + } + } + assertTrue(foundCustomView); + } + + @Test + public void itCreatesAValidFlutterFragment() { + try (ActivityScenario scenario = + ActivityScenario.launch(FlutterFragmentActivityWithProvidedEngine.class)) { + scenario.onActivity( + activity -> { + assertNotNull(activity.getFlutterEngine()); + assertEquals(1, activity.numberOfEnginesCreated); + }); + } + } + + @Test + public void itRetrievesExistingFlutterFragmentWhenRecreated() { + FlutterFragmentActivityWithProvidedEngine activity = + spy(Robolectric.buildActivity(FlutterFragmentActivityWithProvidedEngine.class).get()); + + FlutterFragment fragment = mock(FlutterFragment.class); + when(activity.retrieveExistingFlutterFragmentIfPossible()).thenReturn(fragment); + + FlutterEngine engine = mock(FlutterEngine.class); + when(fragment.getFlutterEngine()).thenReturn(engine); + + activity.onCreate(null); + assertEquals(engine, activity.getFlutterEngine()); + assertEquals(0, activity.numberOfEnginesCreated); + } + + @Test + public void itHandlesNewFragmentRecreationDuringRestoreWhenActivityIsRecreated() { + FlutterFragmentActivityWithProvidedEngine activity = + spy(Robolectric.buildActivity(FlutterFragmentActivityWithProvidedEngine.class).get()); + + FlutterFragment fragment = mock(FlutterFragment.class); + // Similar to the above case, except here, it's not just the activity that was destroyed and + // could have its fragment restored in the fragment manager. Here, both activity and fragment + // are destroyed. And the fragment manager recreated the fragment on activity recreate. + when(activity.retrieveExistingFlutterFragmentIfPossible()).thenReturn(null, fragment); + + FlutterEngine engine = mock(FlutterEngine.class); + when(fragment.getFlutterEngine()).thenReturn(engine); + + activity.onCreate(null); + // The framework would have recreated a new fragment but the fragment activity wouldn't have + // created a new one again. + assertEquals(0, activity.numberOfEnginesCreated); + } + + @Test + @Config(minSdk = Build.API_LEVELS.API_34) + @TargetApi(Build.API_LEVELS.API_34) + public void whenUsingCachedEngine_predictiveBackStateIsSaved() { + FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); + FlutterJNI mockFlutterJni = mock(FlutterJNI.class); + when(mockFlutterJni.isAttached()).thenReturn(true); + FlutterEngine cachedEngine = new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni); + FlutterEngineCache.getInstance().put("my_cached_engine", cachedEngine); + + ActivityScenario flutterFragmentActivityActivityScenario = + ActivityScenario.launch(FlutterFragmentActivity.class); + + // Set to framework handling and then recreate the activity and check the state is preserved. + flutterFragmentActivityActivityScenario.onActivity( + activity -> { + FlutterFragment flutterFragment = activity.retrieveExistingFlutterFragmentIfPossible(); + flutterFragment.setFrameworkHandlesBack(true); + Bundle bundle = flutterFragment.getArguments(); + bundle.putString(ARG_CACHED_ENGINE_ID, "my_cached_engine"); + bundle.putBoolean(ARG_DESTROY_ENGINE_WITH_FRAGMENT, false); + FlutterEngineCache.getInstance().put("my_cached_engine", cachedEngine); + flutterFragment.setArguments(bundle); + }); + + flutterFragmentActivityActivityScenario.recreate(); + + flutterFragmentActivityActivityScenario.onActivity( + activity -> { + assertTrue( + activity + .retrieveExistingFlutterFragmentIfPossible() + .onBackPressedCallback + .isEnabled()); + }); + + // Clean up. + flutterFragmentActivityActivityScenario.close(); + } + + @Test + @Config(minSdk = Build.API_LEVELS.API_34) + @TargetApi(Build.API_LEVELS.API_34) + public void onBackPressedCallsGetForwardedToFragment() { + FlutterFragmentActivityWithProvidedEngine activity = + spy(Robolectric.buildActivity(FlutterFragmentActivityWithProvidedEngine.class).get()); + + FlutterFragment fragment = mock(FlutterFragment.class); + when(activity.retrieveExistingFlutterFragmentIfPossible()).thenReturn(null, fragment); + FlutterEngine engine = mock(FlutterEngine.class); + when(fragment.getFlutterEngine()).thenReturn(engine); + activity.onCreate(null); + + activity.onBackPressed(); + verify(fragment).onBackPressed(); + } + + @Test + @Config(minSdk = Build.API_LEVELS.API_34) + @TargetApi(Build.API_LEVELS.API_34) + public void whenNotUsingCachedEngine_predictiveBackStateIsNotSaved() { + ActivityScenario flutterActivityScenario = + ActivityScenario.launch(FlutterActivity.class); + + // Set to framework handling and then recreate the activity and check the state is preserved. + flutterActivityScenario.onActivity(activity -> activity.setFrameworkHandlesBack(true)); + + flutterActivityScenario.recreate(); + flutterActivityScenario.onActivity(activity -> assertFalse(activity.hasRegisteredBackCallback)); + + // Clean up. + flutterActivityScenario.close(); + } + + static class FlutterFragmentActivityWithProvidedEngine extends FlutterFragmentActivity { + int numberOfEnginesCreated = 0; + + @Override + protected FlutterFragment createFlutterFragment() { + return FlutterFragment.createDefault(); + } + + @Nullable + @Override + public FlutterEngine provideFlutterEngine(@NonNull Context context) { + FlutterJNI flutterJNI = mock(FlutterJNI.class); + FlutterLoader flutterLoader = mock(FlutterLoader.class); + when(flutterJNI.isAttached()).thenReturn(true); + when(flutterLoader.automaticallyRegisterPlugins()).thenReturn(true); + + numberOfEnginesCreated++; + return new FlutterEngine(context, flutterLoader, flutterJNI, new String[] {}, true); + } + } + + private static class FakeFlutterFragmentActivity extends FlutterFragmentActivity { + @Override + public Intent getIntent() { + return new Intent(); + } + + @Override + public String getDartEntrypointFunctionName() { + return ""; + } + + @Nullable + public String getDartEntrypointLibraryUri() { + return null; + } + + @Override + protected String getInitialRoute() { + return ""; + } + + @Override + protected String getAppBundlePath() { + return ""; + } + + @Override + protected boolean shouldHandleDeeplinking() { + return false; + } + } + + private static class FlutterFragmentActivityWithRootLayout + extends FlutterFragmentActivityWithProvidedEngine { + public static class CustomLayout extends FrameLayout { + public CustomLayout(Context context) { + super(context); + } + } + + @Override + protected FrameLayout provideRootLayout(Context context) { + return new CustomLayout(context); + } + } + + // This is just a compile time check to ensure that it's possible for FlutterFragmentActivity + // subclasses + // to provide their own intent builders which builds their own runtime types. + private static class FlutterFragmentActivityWithIntentBuilders extends FlutterFragmentActivity { + public static NewEngineIntentBuilder withNewEngine() { + return new NewEngineIntentBuilder(FlutterFragmentActivityWithIntentBuilders.class); + } + + public static CachedEngineIntentBuilder withCachedEngine(@NonNull String cachedEngineId) { + return new CachedEngineIntentBuilder( + FlutterFragmentActivityWithIntentBuilders.class, cachedEngineId); + } + + public static NewEngineInGroupIntentBuilder withNewEngineInGroup( + @NonNull String engineGroupId) { + return new NewEngineInGroupIntentBuilder( + FlutterFragmentActivityWithIntentBuilders.class, engineGroupId); + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/FlutterFragmentTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/FlutterFragmentTest.java new file mode 100644 index 0000000000000000000000000000000000000000..a52fac850fd8f8bc4a758745420ff2cbadbcafd6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/FlutterFragmentTest.java @@ -0,0 +1,423 @@ +// 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. + +package io.flutter.embedding.android; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.content.Context; +import androidx.activity.OnBackPressedCallback; +import androidx.fragment.app.FragmentActivity; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.FlutterEngine; +import io.flutter.embedding.engine.FlutterEngineCache; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.loader.FlutterLoader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.Robolectric; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class FlutterFragmentTest { + private final Context ctx = ApplicationProvider.getApplicationContext(); + boolean isDelegateAttached; + + class TestDelegateFactory implements FlutterActivityAndFragmentDelegate.DelegateFactory { + FlutterActivityAndFragmentDelegate delegate; + + TestDelegateFactory(FlutterActivityAndFragmentDelegate delegate) { + this.delegate = delegate; + } + + public FlutterActivityAndFragmentDelegate createDelegate( + FlutterActivityAndFragmentDelegate.Host host) { + return delegate; + } + } + + @Test + public void itCreatesDefaultFragmentWithExpectedDefaults() { + FlutterFragment fragment = FlutterFragment.createDefault(); + TestDelegateFactory delegateFactory = + new TestDelegateFactory(new FlutterActivityAndFragmentDelegate(fragment)); + fragment.setDelegateFactory(delegateFactory); + + assertEquals("main", fragment.getDartEntrypointFunctionName()); + assertNull(fragment.getDartEntrypointLibraryUri()); + assertNull(fragment.getDartEntrypointArgs()); + assertEquals("/", fragment.getInitialRoute()); + assertArrayEquals(new String[] {}, fragment.getFlutterShellArgs().toArray()); + assertTrue(fragment.shouldAttachEngineToActivity()); + assertFalse(fragment.shouldHandleDeeplinking()); + assertNull(fragment.getCachedEngineId()); + assertTrue(fragment.shouldDestroyEngineWithHost()); + assertEquals(RenderMode.surface, fragment.getRenderMode()); + assertEquals(TransparencyMode.transparent, fragment.getTransparencyMode()); + assertFalse(fragment.shouldDelayFirstAndroidViewDraw()); + } + + @Test + public void itCreatesNewEngineFragmentWithRequestedSettings() { + FlutterFragment fragment = + FlutterFragment.withNewEngine() + .dartEntrypoint("custom_entrypoint") + .dartLibraryUri("package:foo/bar.dart") + .dartEntrypointArgs(new ArrayList(Arrays.asList("foo", "bar"))) + .initialRoute("/custom/route") + .shouldAttachEngineToActivity(false) + .handleDeeplinking(true) + .renderMode(RenderMode.texture) + .transparencyMode(TransparencyMode.opaque) + .build(); + TestDelegateFactory delegateFactory = + new TestDelegateFactory(new FlutterActivityAndFragmentDelegate(fragment)); + fragment.setDelegateFactory(delegateFactory); + + assertEquals("custom_entrypoint", fragment.getDartEntrypointFunctionName()); + assertEquals("package:foo/bar.dart", fragment.getDartEntrypointLibraryUri()); + assertEquals("/custom/route", fragment.getInitialRoute()); + assertArrayEquals(new String[] {"foo", "bar"}, fragment.getDartEntrypointArgs().toArray()); + assertArrayEquals(new String[] {}, fragment.getFlutterShellArgs().toArray()); + assertFalse(fragment.shouldAttachEngineToActivity()); + assertTrue(fragment.shouldHandleDeeplinking()); + assertNull(fragment.getCachedEngineId()); + assertTrue(fragment.shouldDestroyEngineWithHost()); + assertEquals(RenderMode.texture, fragment.getRenderMode()); + assertEquals(TransparencyMode.opaque, fragment.getTransparencyMode()); + } + + @Test + public void itCreatesNewEngineInGroupFragmentWithRequestedSettings() { + FlutterFragment fragment = + FlutterFragment.withNewEngineInGroup("my_cached_engine_group") + .dartEntrypoint("custom_entrypoint") + .initialRoute("/custom/route") + .shouldAttachEngineToActivity(false) + .handleDeeplinking(true) + .renderMode(RenderMode.texture) + .transparencyMode(TransparencyMode.opaque) + .build(); + + TestDelegateFactory delegateFactory = + new TestDelegateFactory(new FlutterActivityAndFragmentDelegate(fragment)); + + fragment.setDelegateFactory(delegateFactory); + + assertEquals("my_cached_engine_group", fragment.getCachedEngineGroupId()); + assertEquals("custom_entrypoint", fragment.getDartEntrypointFunctionName()); + assertEquals("/custom/route", fragment.getInitialRoute()); + assertArrayEquals(new String[] {}, fragment.getFlutterShellArgs().toArray()); + assertFalse(fragment.shouldAttachEngineToActivity()); + assertTrue(fragment.shouldHandleDeeplinking()); + assertNull(fragment.getCachedEngineId()); + assertTrue(fragment.shouldDestroyEngineWithHost()); + assertEquals(RenderMode.texture, fragment.getRenderMode()); + assertEquals(TransparencyMode.opaque, fragment.getTransparencyMode()); + } + + @Test + public void itCreatesNewEngineFragmentThatDelaysFirstDrawWhenRequested() { + FlutterFragment fragment = + FlutterFragment.withNewEngine().shouldDelayFirstAndroidViewDraw(true).build(); + + assertNotNull(fragment.shouldDelayFirstAndroidViewDraw()); + } + + @Test + public void itCreatesCachedEngineFragmentWithExpectedDefaults() { + FlutterFragment fragment = FlutterFragment.withCachedEngine("my_cached_engine").build(); + + assertTrue(fragment.shouldAttachEngineToActivity()); + assertEquals("my_cached_engine", fragment.getCachedEngineId()); + assertFalse(fragment.shouldDestroyEngineWithHost()); + assertFalse(fragment.shouldDelayFirstAndroidViewDraw()); + } + + @Test + public void itCreatesCachedEngineFragmentThatDestroysTheEngine() { + FlutterFragment fragment = + FlutterFragment.withCachedEngine("my_cached_engine") + .destroyEngineWithFragment(true) + .build(); + + assertTrue(fragment.shouldAttachEngineToActivity()); + assertEquals("my_cached_engine", fragment.getCachedEngineId()); + assertTrue(fragment.shouldDestroyEngineWithHost()); + } + + @Test + public void itCreatesCachedEngineFragmentThatDelaysFirstDrawWhenRequested() { + FlutterFragment fragment = + FlutterFragment.withCachedEngine("my_cached_engine") + .shouldDelayFirstAndroidViewDraw(true) + .build(); + + assertNotNull(fragment.shouldDelayFirstAndroidViewDraw()); + } + + @Test + public void itCanBeDetachedFromTheEngineAndStopSendingFurtherEvents() { + FlutterActivityAndFragmentDelegate mockDelegate = + mock(FlutterActivityAndFragmentDelegate.class); + TestDelegateFactory delegateFactory = new TestDelegateFactory(mockDelegate); + FlutterFragment fragment = + FlutterFragment.withCachedEngine("my_cached_engine") + .destroyEngineWithFragment(true) + .build(); + + isDelegateAttached = true; + when(mockDelegate.isAttached()).thenAnswer(invocation -> isDelegateAttached); + doAnswer(invocation -> isDelegateAttached = false).when(mockDelegate).onDetach(); + + fragment.setDelegateFactory(delegateFactory); + fragment.onStart(); + fragment.onResume(); + fragment.onPostResume(); + + verify(mockDelegate, times(1)).onStart(); + verify(mockDelegate, times(1)).onResume(); + verify(mockDelegate, times(1)).onPostResume(); + + fragment.onPause(); + fragment.detachFromFlutterEngine(); + verify(mockDelegate, times(1)).onPause(); + verify(mockDelegate, times(1)).onDestroyView(); + verify(mockDelegate, times(1)).onDetach(); + + fragment.onStop(); + verify(mockDelegate, never()).onStop(); + + fragment.onStart(); + fragment.onResume(); + fragment.onPostResume(); + // No more events through to the delegate. + verify(mockDelegate, times(1)).onStart(); + verify(mockDelegate, times(1)).onResume(); + verify(mockDelegate, times(1)).onPostResume(); + + fragment.onDestroy(); + // 1 time same as before. + verify(mockDelegate, times(1)).onDestroyView(); + verify(mockDelegate, times(1)).onDetach(); + } + + @Test + public void itDoesNotReleaseEnginewhenDetachFromFlutterEngine() { + FlutterActivityAndFragmentDelegate mockDelegate = + mock(FlutterActivityAndFragmentDelegate.class); + isDelegateAttached = true; + when(mockDelegate.isAttached()).thenAnswer(invocation -> isDelegateAttached); + doAnswer(invocation -> isDelegateAttached = false).when(mockDelegate).onDetach(); + TestDelegateFactory delegateFactory = new TestDelegateFactory(mockDelegate); + + FlutterFragment fragment = + FlutterFragment.withCachedEngine("my_cached_engine") + .destroyEngineWithFragment(true) + .build(); + + fragment.setDelegateFactory(delegateFactory); + fragment.onStart(); + fragment.onResume(); + fragment.onPostResume(); + fragment.onPause(); + + assertTrue(mockDelegate.isAttached()); + fragment.detachFromFlutterEngine(); + verify(mockDelegate, times(1)).onDetach(); + verify(mockDelegate, never()).release(); + assertFalse(mockDelegate.isAttached()); + } + + @Test + public void itReleaseEngineWhenOnDetach() { + FlutterActivityAndFragmentDelegate mockDelegate = + mock(FlutterActivityAndFragmentDelegate.class); + isDelegateAttached = true; + when(mockDelegate.isAttached()).thenAnswer(invocation -> isDelegateAttached); + doAnswer(invocation -> isDelegateAttached = false).when(mockDelegate).onDetach(); + TestDelegateFactory delegateFactory = new TestDelegateFactory(mockDelegate); + + FlutterFragment fragment = + spy( + FlutterFragment.withCachedEngine("my_cached_engine") + .destroyEngineWithFragment(true) + .build()); + when(fragment.getContext()).thenReturn(mock(Context.class)); + + fragment.setDelegateFactory(delegateFactory); + fragment.onStart(); + fragment.onResume(); + fragment.onPostResume(); + fragment.onPause(); + + assertTrue(mockDelegate.isAttached()); + fragment.onDetach(); + verify(mockDelegate, times(1)).onDetach(); + verify(mockDelegate, times(1)).release(); + assertFalse(mockDelegate.isAttached()); + } + + @Test + public void itReturnsExclusiveAppComponent() { + FlutterFragment fragment = FlutterFragment.createDefault(); + FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(fragment); + TestDelegateFactory delegateFactory = new TestDelegateFactory(delegate); + fragment.setDelegateFactory(delegateFactory); + + assertEquals(fragment.getExclusiveAppComponent(), delegate); + } + + @SuppressWarnings("deprecation") + private FragmentActivity getMockFragmentActivity() { + // TODO(reidbaker): https://github.com/flutter/flutter/issues/133151 + return Robolectric.setupActivity(FragmentActivity.class); + } + + @Test + public void itDelegatesOnBackPressedWithSetFrameworkHandlesBack() { + // We need to mock FlutterJNI to avoid triggering native code. + FlutterJNI flutterJNI = mock(FlutterJNI.class); + when(flutterJNI.isAttached()).thenReturn(true); + + FlutterEngine flutterEngine = + new FlutterEngine(ctx, new FlutterLoader(), flutterJNI, null, false); + FlutterEngineCache.getInstance().put("my_cached_engine", flutterEngine); + + FlutterFragment fragment = + FlutterFragment.withCachedEngine("my_cached_engine") + // This enables the use of onBackPressedCallback, which is what + // sends backs to the framework if setFrameworkHandlesBack is true. + .shouldAutomaticallyHandleOnBackPressed(true) + .build(); + FragmentActivity activity = getMockFragmentActivity(); + activity + .getSupportFragmentManager() + .beginTransaction() + .add(android.R.id.content, fragment) + .commitNow(); + + FlutterActivityAndFragmentDelegate mockDelegate = + mock(FlutterActivityAndFragmentDelegate.class); + isDelegateAttached = true; + when(mockDelegate.isAttached()).thenAnswer(invocation -> isDelegateAttached); + doAnswer(invocation -> isDelegateAttached = false).when(mockDelegate).onDetach(); + TestDelegateFactory delegateFactory = new TestDelegateFactory(mockDelegate); + fragment.setDelegateFactory(delegateFactory); + + // Calling onBackPressed now will still be handled by Android (the default), + // until setFrameworkHandlesBack is set to true. + activity.getOnBackPressedDispatcher().onBackPressed(); + verify(mockDelegate, times(0)).onBackPressed(); + + // Setting setFrameworkHandlesBack to true means the delegate will receive + // the back and Android won't handle it. + fragment.setFrameworkHandlesBack(true); + activity.getOnBackPressedDispatcher().onBackPressed(); + verify(mockDelegate, times(1)).onBackPressed(); + } + + @SuppressWarnings("deprecation") + // Robolectric.setupActivity + // TODO(reidbaker): https://github.com/flutter/flutter/issues/133151 + @Test + public void itHandlesPopSystemNavigationAutomaticallyWhenEnabled() { + // We need to mock FlutterJNI to avoid triggering native code. + FlutterJNI flutterJNI = mock(FlutterJNI.class); + when(flutterJNI.isAttached()).thenReturn(true); + + FlutterEngine flutterEngine = + new FlutterEngine(ctx, new FlutterLoader(), flutterJNI, null, false); + FlutterEngineCache.getInstance().put("my_cached_engine", flutterEngine); + + FlutterFragment fragment = + FlutterFragment.withCachedEngine("my_cached_engine") + .shouldAutomaticallyHandleOnBackPressed(true) + .build(); + FragmentActivity activity = getMockFragmentActivity(); + activity + .getSupportFragmentManager() + .beginTransaction() + .add(android.R.id.content, fragment) + .commitNow(); + final AtomicBoolean onBackPressedCalled = new AtomicBoolean(false); + OnBackPressedCallback callback = + new OnBackPressedCallback(true) { + @Override + public void handleOnBackPressed() { + onBackPressedCalled.set(true); + } + }; + activity.getOnBackPressedDispatcher().addCallback(callback); + + FlutterActivityAndFragmentDelegate mockDelegate = + mock(FlutterActivityAndFragmentDelegate.class); + TestDelegateFactory delegateFactory = new TestDelegateFactory(mockDelegate); + fragment.setDelegateFactory(delegateFactory); + + assertTrue(callback.isEnabled()); + + assertTrue(fragment.popSystemNavigator()); + + verify(mockDelegate, never()).onBackPressed(); + assertTrue(onBackPressedCalled.get()); + assertTrue(callback.isEnabled()); + + callback.setEnabled(false); + assertFalse(callback.isEnabled()); + assertTrue(fragment.popSystemNavigator()); + + verify(mockDelegate, never()).onBackPressed(); + assertFalse(callback.isEnabled()); + } + + @Test + public void itRegistersComponentCallbacks() { + FlutterActivityAndFragmentDelegate mockDelegate = + mock(FlutterActivityAndFragmentDelegate.class); + isDelegateAttached = true; + when(mockDelegate.isAttached()).thenAnswer(invocation -> isDelegateAttached); + doAnswer(invocation -> isDelegateAttached = false).when(mockDelegate).onDetach(); + TestDelegateFactory delegateFactory = new TestDelegateFactory(mockDelegate); + + Context spyCtx = spy(ctx); + // We need to mock FlutterJNI to avoid triggering native code. + FlutterJNI flutterJNI = mock(FlutterJNI.class); + when(flutterJNI.isAttached()).thenReturn(true); + + FlutterEngine flutterEngine = + new FlutterEngine(spyCtx, new FlutterLoader(), flutterJNI, null, false); + FlutterEngineCache.getInstance().put("my_cached_engine", flutterEngine); + + FlutterFragment fragment = spy(FlutterFragment.withCachedEngine("my_cached_engine").build()); + when(fragment.getContext()).thenReturn(spyCtx); + fragment.setDelegateFactory(delegateFactory); + + fragment.onAttach(spyCtx); + verify(spyCtx, times(1)).registerComponentCallbacks(any()); + verify(spyCtx, never()).unregisterComponentCallbacks(any()); + + fragment.onDetach(); + verify(spyCtx, times(1)).registerComponentCallbacks(any()); + verify(spyCtx, times(1)).unregisterComponentCallbacks(any()); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/FlutterSurfaceViewTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/FlutterSurfaceViewTest.java new file mode 100644 index 0000000000000000000000000000000000000000..48478d317f53d0172554d0d6fcf332c425f60bca --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/FlutterSurfaceViewTest.java @@ -0,0 +1,76 @@ +// 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. + +package io.flutter.embedding.android; + +import static io.flutter.Build.API_LEVELS; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.annotation.TargetApi; +import android.view.Surface; +import android.view.SurfaceHolder; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.renderer.FlutterRenderer; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +@TargetApi(API_LEVELS.API_30) +public class FlutterSurfaceViewTest { + @Test + public void itShouldCreateANewSurfaceWhenReattachedAfterDetachingFromRenderer() { + // Consider this scenario: In an add-to-app context, where multiple Flutter activities share the + // same engine, a situation occurs. When navigating from FlutterActivity1 to FlutterActivity2, + // the Flutter view associated with FlutterActivity1 is detached from the engine. Then, the + // Flutter view of FlutterActivity2 is attached. Upon navigating back to FlutterActivity1, its + // Flutter view is re-attached to the shared engine. + // + // The expected behavior is: When a Flutter view detaches from the shared engine, the associated + // surface should be released. When the Flutter view re-attaches, a new surface should be + // created. + + // Setup the test. + final FlutterSurfaceView surfaceView = + spy(new FlutterSurfaceView(ApplicationProvider.getApplicationContext())); + + FlutterJNI fakeFlutterJNI = mock(FlutterJNI.class); + FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI); + + SurfaceHolder fakeSurfaceHolder = mock(SurfaceHolder.class); + Surface fakeSurface = mock(Surface.class); + when(surfaceView.getHolder()).thenReturn(fakeSurfaceHolder); + when(fakeSurfaceHolder.getSurface()).thenReturn(fakeSurface); + when(surfaceView.isSurfaceAvailableForRendering()).thenReturn(true); + when(surfaceView.getWindowToken()).thenReturn(mock(android.os.IBinder.class)); + + // Execute the behavior under test. + surfaceView.attachToRenderer(flutterRenderer); + + // Verify the behavior under test. + verify(fakeFlutterJNI, times(1)).onSurfaceCreated(any(Surface.class)); + + // Execute the behavior under test. + surfaceView.detachFromRenderer(); + + // Verify the behavior under test. + verify(fakeFlutterJNI, times(1)).onSurfaceDestroyed(); + + // Execute the behavior under test. + surfaceView.attachToRenderer(flutterRenderer); + + // Verify the behavior under test. + verify(fakeFlutterJNI, never()).onSurfaceWindowChanged(any(Surface.class)); + verify(fakeFlutterJNI, times(2)).onSurfaceCreated(any(Surface.class)); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/FlutterTextureViewTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/FlutterTextureViewTest.java new file mode 100644 index 0000000000000000000000000000000000000000..9a5531a8063a0f0b86b3cf8034ffa434f5299c5f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/FlutterTextureViewTest.java @@ -0,0 +1,88 @@ +// 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. + +package io.flutter.embedding.android; + +import static io.flutter.Build.API_LEVELS; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.annotation.TargetApi; +import android.graphics.SurfaceTexture; +import android.view.Surface; +import android.view.TextureView; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.renderer.FlutterRenderer; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +@TargetApi(API_LEVELS.API_30) +public class FlutterTextureViewTest { + @Test + public void surfaceTextureListenerReleasesRenderer() { + final FlutterTextureView textureView = + new FlutterTextureView(ApplicationProvider.getApplicationContext()); + final Surface mockRenderSurface = mock(Surface.class); + + textureView.setRenderSurface(mockRenderSurface); + + final TextureView.SurfaceTextureListener listener = textureView.getSurfaceTextureListener(); + listener.onSurfaceTextureDestroyed(mock(SurfaceTexture.class)); + + verify(mockRenderSurface).release(); + } + + @Test + public void itShouldCreateANewSurfaceWhenReattachedAfterDetachingFromRenderer() { + // Consider this scenario: In an add-to-app context, where multiple Flutter activities share the + // same engine, a situation occurs. When navigating from FlutterActivity1 to FlutterActivity2, + // the Flutter view associated with FlutterActivity1 is detached from the engine. Then, the + // Flutter view of FlutterActivity2 is attached. Upon navigating back to FlutterActivity1, its + // Flutter view is re-attached to the shared engine. + // + // The expected behavior is: When a Flutter view detaches from the shared engine, the associated + // surface should be released. When the Flutter view re-attaches, a new surface should be + // created. + + // Setup the test. + final FlutterTextureView textureView = + spy(new FlutterTextureView(ApplicationProvider.getApplicationContext())); + + FlutterJNI fakeFlutterJNI = mock(FlutterJNI.class); + FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI); + + when(textureView.isSurfaceAvailableForRendering()).thenReturn(true); + when(textureView.getSurfaceTexture()).thenReturn(mock(SurfaceTexture.class)); + when(textureView.getWindowToken()).thenReturn(mock(android.os.IBinder.class)); + + // Execute the behavior under test. + textureView.attachToRenderer(flutterRenderer); + + // Verify the behavior under test. + verify(fakeFlutterJNI, times(1)).onSurfaceCreated(any(Surface.class)); + + // Execute the behavior under test. + textureView.detachFromRenderer(); + + // Verify the behavior under test. + verify(fakeFlutterJNI, times(1)).onSurfaceDestroyed(); + + // Execute the behavior under test. + textureView.attachToRenderer(flutterRenderer); + + // Verify the behavior under test. + verify(fakeFlutterJNI, never()).onSurfaceWindowChanged(any(Surface.class)); + verify(fakeFlutterJNI, times(2)).onSurfaceCreated(any(Surface.class)); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/FlutterViewTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/FlutterViewTest.java new file mode 100644 index 0000000000000000000000000000000000000000..ee19437afb302c5b9609f5803b81add237b8706c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/FlutterViewTest.java @@ -0,0 +1,1408 @@ +// 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. + +package io.flutter.embedding.android; + +import static junit.framework.TestCase.assertEquals; +import static junit.framework.TestCase.assertFalse; +import static junit.framework.TestCase.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.annotation.SuppressLint; +import android.annotation.TargetApi; +import android.app.Activity; +import android.content.Context; +import android.content.res.Configuration; +import android.content.res.Resources; +import android.graphics.Canvas; +import android.graphics.Insets; +import android.graphics.Rect; +import android.graphics.Region; +import android.hardware.HardwareBuffer; +import android.hardware.display.DisplayManager; +import android.media.Image; +import android.media.Image.Plane; +import android.media.ImageReader; +import android.os.Build; +import android.provider.Settings; +import android.util.DisplayMetrics; +import android.view.DisplayCutout; +import android.view.Surface; +import android.view.View; +import android.view.WindowInsets; +import android.widget.FrameLayout; +import androidx.core.util.Consumer; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import androidx.window.layout.FoldingFeature; +import androidx.window.layout.WindowLayoutInfo; +import io.flutter.Build.API_LEVELS; +import io.flutter.embedding.engine.FlutterEngine; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.loader.FlutterLoader; +import io.flutter.embedding.engine.renderer.FlutterRenderer; +import io.flutter.embedding.engine.systemchannels.SettingsChannel; +import io.flutter.plugin.platform.PlatformViewsController; +import io.flutter.plugin.platform.PlatformViewsController2; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.robolectric.Robolectric; +import org.robolectric.Shadows; +import org.robolectric.annotation.Config; +import org.robolectric.annotation.Implementation; +import org.robolectric.annotation.Implements; +import org.robolectric.shadows.ShadowDisplay; +import org.robolectric.shadows.ShadowViewGroup; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +@TargetApi(30) +public class FlutterViewTest { + private final Context ctx = ApplicationProvider.getApplicationContext(); + @Mock FlutterJNI mockFlutterJni; + @Mock FlutterLoader mockFlutterLoader; + @Spy PlatformViewsController platformViewsController; + @Spy PlatformViewsController2 platformViewsController2; + + @Before + public void setUp() { + MockitoAnnotations.openMocks(this); + when(mockFlutterJni.isAttached()).thenReturn(true); + // Uncomment the following line to enable logging output in test. + // ShadowLog.stream = System.out; + } + + @Test + public void attachToFlutterEngine_alertsPlatformViews() { + FlutterView flutterView = new FlutterView(ctx); + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + when(flutterEngine.getPlatformViewsController()).thenReturn(platformViewsController); + when(flutterEngine.getPlatformViewsController2()).thenReturn(platformViewsController2); + + flutterView.attachToFlutterEngine(flutterEngine); + + verify(platformViewsController, times(1)).attachToView(flutterView); + verify(platformViewsController2, times(1)).attachToView(flutterView); + } + + @Test + public void flutterView_importantForAutofillDoesNotExcludeDescendants() { + FlutterView flutterView = new FlutterView(ctx); + + // Value should not exclude descendants because platform views are added as child views and + // can be eligible for autofill (e.g. a WebView). + assertEquals(View.IMPORTANT_FOR_AUTOFILL_YES, flutterView.getImportantForAutofill()); + } + + @Test + public void detachFromFlutterEngine_alertsPlatformViews() { + FlutterView flutterView = new FlutterView(ctx); + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + when(flutterEngine.getPlatformViewsController()).thenReturn(platformViewsController); + when(flutterEngine.getPlatformViewsController2()).thenReturn(platformViewsController2); + + flutterView.attachToFlutterEngine(flutterEngine); + flutterView.detachFromFlutterEngine(); + + verify(platformViewsController, times(1)).detachFromView(); + verify(platformViewsController2, times(1)).detachFromView(); + } + + @Test + public void detachFromFlutterEngine_turnsOffA11y() { + FlutterView flutterView = new FlutterView(ctx); + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + FlutterRenderer flutterRenderer = spy(new FlutterRenderer(mockFlutterJni)); + when(flutterEngine.getRenderer()).thenReturn(flutterRenderer); + + flutterView.attachToFlutterEngine(flutterEngine); + flutterView.detachFromFlutterEngine(); + + verify(flutterRenderer, times(1)).setSemanticsEnabled(false); + } + + @Test + public void detachFromFlutterEngine_revertImageView() { + FlutterView flutterView = new FlutterView(ctx); + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + + flutterView.attachToFlutterEngine(flutterEngine); + assertFalse(flutterView.renderSurface instanceof FlutterImageView); + + flutterView.convertToImageView(); + assertTrue(flutterView.renderSurface instanceof FlutterImageView); + + flutterView.detachFromFlutterEngine(); + assertFalse(flutterView.renderSurface instanceof FlutterImageView); + } + + @Test + public void detachFromFlutterEngine_removeImageView() { + FlutterView flutterView = new FlutterView(ctx); + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + + flutterView.attachToFlutterEngine(flutterEngine); + flutterView.convertToImageView(); + assertEquals(flutterView.getChildCount(), 2); + View view = flutterView.getChildAt(1); + assertTrue(view instanceof FlutterImageView); + + flutterView.detachFromFlutterEngine(); + assertEquals(flutterView.getChildCount(), 1); + view = flutterView.getChildAt(0); + assertFalse(view instanceof FlutterImageView); + } + + @Test + public void detachFromFlutterEngine_closesImageView() { + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + + FlutterRenderer flutterRenderer = spy(new FlutterRenderer(mockFlutterJni)); + when(flutterEngine.getRenderer()).thenReturn(flutterRenderer); + + FlutterImageView imageViewMock = mock(FlutterImageView.class); + when(imageViewMock.getAttachedRenderer()).thenReturn(flutterRenderer); + + FlutterView flutterView = spy(new FlutterView(ctx)); + when(flutterView.createImageView()).thenReturn(imageViewMock); + + flutterView.attachToFlutterEngine(flutterEngine); + + assertFalse(flutterView.renderSurface == imageViewMock); + + flutterView.convertToImageView(); + assertTrue(flutterView.renderSurface == imageViewMock); + + flutterView.detachFromFlutterEngine(); + assertFalse(flutterView.renderSurface == imageViewMock); + verify(imageViewMock, times(1)).closeImageReader(); + } + + @Test + public void flutterImageView_revertImageViewAndAvoidNPE() { + FlutterView flutterView = new FlutterView(ctx); + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + FlutterRenderer flutterRenderer = spy(new FlutterRenderer(mockFlutterJni)); + when(flutterEngine.getRenderer()).thenReturn(flutterRenderer); + + flutterView.attachToFlutterEngine(flutterEngine); + flutterView.convertToImageView(); + assertTrue(flutterView.renderSurface instanceof FlutterImageView); + + // Register a `FlutterUiDisplayListener` callback. + // During callback execution it will invoke `flutterImageView.detachFromRenderer()`. + flutterView.revertImageView( + () -> { + // No-op + }); + assertFalse(flutterView.renderSurface instanceof FlutterImageView); + + flutterView.detachFromFlutterEngine(); + assertEquals(null, flutterView.getCurrentImageSurface()); + + // Invoke all registered `FlutterUiDisplayListener` callback + mockFlutterJni.onFirstFrame(); + } + + @Test + public void onConfigurationChanged_fizzlesWhenNullEngine() { + FlutterView flutterView = new FlutterView(ctx); + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + + Configuration configuration = ctx.getResources().getConfiguration(); + // 1 invocation of channels. + flutterView.attachToFlutterEngine(flutterEngine); + flutterView.onConfigurationChanged(configuration); + flutterView.detachFromFlutterEngine(); + + // Should fizzle. + flutterView.onConfigurationChanged(configuration); + + verify(flutterEngine, times(1)).getLocalizationPlugin(); + verify(flutterEngine, times(2)).getSettingsChannel(); + } + + @SuppressWarnings("deprecation") + // Robolectric.setupActivity + // TODO(reidbaker): https://github.com/flutter/flutter/issues/133151 + @Test + public void onConfigurationChanged_notifiesEngineOfDisplaySize() { + FlutterView flutterView = new FlutterView(Robolectric.setupActivity(Activity.class)); + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + + Configuration configuration = ctx.getResources().getConfiguration(); + + flutterView.attachToFlutterEngine(flutterEngine); + flutterView.onConfigurationChanged(configuration); + + verify(flutterEngine, times(1)) + .updateDisplayMetrics(any(Float.class), any(Float.class), any(Float.class)); + } + + public void itSendsTextHidePasswordToFrameworkOnAttach() { + // Setup test. + AtomicReference reportedShowPassword = new AtomicReference<>(); + + FlutterView flutterView = new FlutterView(ctx); + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + Settings.System.putInt( + flutterView.getContext().getContentResolver(), Settings.System.TEXT_SHOW_PASSWORD, 0); + + SettingsChannel fakeSettingsChannel = mock(SettingsChannel.class); + SettingsChannel.MessageBuilder fakeMessageBuilder = mock(SettingsChannel.MessageBuilder.class); + when(fakeMessageBuilder.setTextScaleFactor(any(Float.class))).thenReturn(fakeMessageBuilder); + when(fakeMessageBuilder.setPlatformBrightness(any(SettingsChannel.PlatformBrightness.class))) + .thenReturn(fakeMessageBuilder); + when(fakeMessageBuilder.setUse24HourFormat(any(Boolean.class))).thenReturn(fakeMessageBuilder); + when(fakeMessageBuilder.setBrieflyShowPassword(any(Boolean.class))) + .thenAnswer( + new Answer() { + @Override + public SettingsChannel.MessageBuilder answer(InvocationOnMock invocation) + throws Throwable { + reportedShowPassword.set((Boolean) invocation.getArguments()[0]); + return fakeMessageBuilder; + } + }); + when(fakeSettingsChannel.startMessage()).thenReturn(fakeMessageBuilder); + when(flutterEngine.getSettingsChannel()).thenReturn(fakeSettingsChannel); + + flutterView.attachToFlutterEngine(flutterEngine); + + // Verify results. + assertFalse(reportedShowPassword.get()); + } + + @SuppressWarnings("deprecation") + // getSystemUiVisibility + // This test uses the API 30+ Algorithm for window insets. The legacy algorithm is + // set to -1 values, so it is clear if the wrong algorithm is used. + @Test + @TargetApi(30) + @Config(sdk = 30) + public void reportSystemInsetWhenNotFullscreen() { + // Without custom shadows, the default system ui visibility flags is 0. + FlutterView flutterView = new FlutterView(ctx); + assertEquals(0, flutterView.getSystemUiVisibility()); + + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + FlutterRenderer flutterRenderer = spy(new FlutterRenderer(mockFlutterJni)); + when(flutterEngine.getRenderer()).thenReturn(flutterRenderer); + + // When we attach a new FlutterView to the engine without any system insets, the viewport + // metrics + // default to 0. + flutterView.attachToFlutterEngine(flutterEngine); + ArgumentCaptor viewportMetricsCaptor = + ArgumentCaptor.forClass(FlutterRenderer.ViewportMetrics.class); + verify(flutterRenderer).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(0, viewportMetricsCaptor.getValue().viewPaddingTop); + + // Then we simulate the system applying a window inset. + WindowInsets windowInsets = + new WindowInsets.Builder() + .setInsets( + android.view.WindowInsets.Type.navigationBars() + | android.view.WindowInsets.Type.statusBars(), + Insets.of(100, 100, 100, 100)) + .build(); + flutterView.onApplyWindowInsets(windowInsets); + + // Verify. + verify(flutterRenderer, times(3)).setViewportMetrics(viewportMetricsCaptor.capture()); + // Top padding is reported as-is. + validateViewportMetricPadding(viewportMetricsCaptor, 100, 100, 100, 100); + } + + @SuppressWarnings("deprecation") + // getSystemUiVisibility + // This test uses the API 30+ Algorithm for window insets. This test requires API 34 or + // higher to use the systemOverlays inset. The legacy algorithm is + // set to -1 values, so it is clear if the wrong algorithm is used. + @Test + @TargetApi(34) + @Config(minSdk = 34) + public void reportSystemInsetWhenNotFullscreenForSystemBar() { + // Without custom shadows, the default system ui visibility flags is 0. + FlutterView flutterView = new FlutterView(ctx); + assertEquals(0, flutterView.getSystemUiVisibility()); + + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + FlutterRenderer flutterRenderer = spy(new FlutterRenderer(mockFlutterJni)); + when(flutterEngine.getRenderer()).thenReturn(flutterRenderer); + + flutterView.attachToFlutterEngine(flutterEngine); + ArgumentCaptor viewportMetricsCaptor = + ArgumentCaptor.forClass(FlutterRenderer.ViewportMetrics.class); + verify(flutterRenderer).setViewportMetrics(viewportMetricsCaptor.capture()); + + // When we attach a new FlutterView to the engine without any system insets, the viewport + // metrics default to 0. + assertEquals(0, viewportMetricsCaptor.getValue().viewPaddingTop); + + // Then we simulate the system applying a statusBar inset. + WindowInsets statusBarwindowInsets = + new WindowInsets.Builder() + .setInsets(android.view.WindowInsets.Type.captionBar(), Insets.of(0, 50, 0, 0)) + .setInsets(android.view.WindowInsets.Type.statusBars(), Insets.of(0, 100, 0, 0)) + .build(); + flutterView.onApplyWindowInsets(statusBarwindowInsets); + + // Verify. + verify(flutterRenderer, times(3)).setViewportMetrics(viewportMetricsCaptor.capture()); + // Confirm that the statusBar inset is used because it is the largest of the insets faked. + validateViewportMetricPadding(viewportMetricsCaptor, 0, 100, 0, 0); + clearInvocations(flutterRenderer); + + // Then we simulate the system applying a navigationBar window inset. + WindowInsets navigationBarwindowInsets = + new WindowInsets.Builder() + .setInsets(android.view.WindowInsets.Type.systemOverlays(), Insets.of(0, 0, 0, 10)) + .setInsets(android.view.WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 50)) + .build(); + flutterView.onApplyWindowInsets(navigationBarwindowInsets); + + // Verify. + verify(flutterRenderer, times(2)).setViewportMetrics(viewportMetricsCaptor.capture()); + // Confirm that the navigationBar inset is used because it is the largest of the insets faked. + validateViewportMetricPadding(viewportMetricsCaptor, 0, 0, 0, 50); + clearInvocations(flutterRenderer); + + // Then we simulate the system applying a captionBar window inset. + WindowInsets captionBarwindowInsets = + new WindowInsets.Builder() + .setInsets(android.view.WindowInsets.Type.statusBars(), Insets.of(0, 20, 0, 0)) + .setInsets(android.view.WindowInsets.Type.captionBar(), Insets.of(0, 60, 0, 0)) + .build(); + flutterView.onApplyWindowInsets(captionBarwindowInsets); + // Verify. + verify(flutterRenderer, times(2)).setViewportMetrics(viewportMetricsCaptor.capture()); + // Confirm that the captionBar inset is used because it is the largest of the insets faked. + validateViewportMetricPadding(viewportMetricsCaptor, 0, 60, 0, 0); + clearInvocations(flutterRenderer); + + // Then we simulate the system applying a systemOverlay window inset. + WindowInsets systemOverlayWindowInsets = + new WindowInsets.Builder() + .setInsets(android.view.WindowInsets.Type.statusBars(), Insets.of(0, 100, 0, 0)) + .setInsets(android.view.WindowInsets.Type.systemOverlays(), Insets.of(0, 200, 0, 0)) + .build(); + flutterView.onApplyWindowInsets(systemOverlayWindowInsets); + // Verify. + verify(flutterRenderer, times(2)).setViewportMetrics(viewportMetricsCaptor.capture()); + // Confirm that the systemOverlay inset is used because it is the largest of the insets faked. + validateViewportMetricPadding(viewportMetricsCaptor, 0, 200, 0, 0); + } + + @SuppressWarnings("deprecation") + // getSystemUiVisibility + // This test uses the pre-API 30 Algorithm for window insets. + @Test + @TargetApi(28) + @Config(sdk = 28) + public void reportSystemInsetWhenNotFullscreenLegacy() { + // Without custom shadows, the default system ui visibility flags is 0. + FlutterView flutterView = new FlutterView(ctx); + assertEquals(0, flutterView.getSystemUiVisibility()); + + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + FlutterRenderer flutterRenderer = spy(new FlutterRenderer(mockFlutterJni)); + when(flutterEngine.getRenderer()).thenReturn(flutterRenderer); + + // When we attach a new FlutterView to the engine without any system insets, the viewport + // metrics + // default to 0. + flutterView.attachToFlutterEngine(flutterEngine); + ArgumentCaptor viewportMetricsCaptor = + ArgumentCaptor.forClass(FlutterRenderer.ViewportMetrics.class); + verify(flutterRenderer).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(0, viewportMetricsCaptor.getValue().viewPaddingTop); + + // Then we simulate the system applying a window inset. + WindowInsets windowInsets = mock(WindowInsets.class); + mockSystemWindowInsets(windowInsets, 100, 100, 100, 100); + flutterView.onApplyWindowInsets(windowInsets); + + // Verify. + verify(flutterRenderer, times(2)).setViewportMetrics(viewportMetricsCaptor.capture()); + // Top padding is reported as-is. + validateViewportMetricPadding(viewportMetricsCaptor, 100, 100, 100, 0); + } + + @SuppressWarnings("deprecation") + // getSystemUiVisibility, getWindowSystemUiVisibility, required to test pre api 30 behavior. + @Test + @Config(minSdk = 23, maxSdk = 29, qualifiers = "land") + public void systemInsetHandlesFullscreenNavbarRight() { + FlutterView flutterView = spy(new FlutterView(ctx)); + setExpectedDisplayRotation(Surface.ROTATION_90); + assertEquals(0, flutterView.getSystemUiVisibility()); + when(flutterView.getWindowSystemUiVisibility()) + .thenReturn(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); + when(flutterView.getContext()).thenReturn(ctx); + + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + FlutterRenderer flutterRenderer = spy(new FlutterRenderer(mockFlutterJni)); + when(flutterEngine.getRenderer()).thenReturn(flutterRenderer); + + // When we attach a new FlutterView to the engine without any system insets, + // the viewport metrics default to 0. + flutterView.attachToFlutterEngine(flutterEngine); + ArgumentCaptor viewportMetricsCaptor = + ArgumentCaptor.forClass(FlutterRenderer.ViewportMetrics.class); + verify(flutterRenderer).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(0, viewportMetricsCaptor.getValue().viewPaddingTop); + + // Then we simulate the system applying a window inset. + WindowInsets windowInsets = mock(WindowInsets.class); + mockSystemWindowInsets(windowInsets, 100, 100, 100, 100); + mockSystemGestureInsetsIfNeed(windowInsets); + + flutterView.onApplyWindowInsets(windowInsets); + + verify(flutterRenderer, times(2)).setViewportMetrics(viewportMetricsCaptor.capture()); + // Top padding is removed due to full screen. + // Right padding is zero because the rotation is 90deg + // Bottom padding is removed due to hide navigation. + validateViewportMetricPadding(viewportMetricsCaptor, 100, 0, 0, 0); + } + + @SuppressWarnings("deprecation") + // getSystemUiVisibility, getWindowSystemUiVisibility required to test pre api 30 behavior. + @Test + @Config(minSdk = 20, maxSdk = 22, qualifiers = "land") + public void systemInsetHandlesFullscreenNavbarRightBelowSDK23() { + FlutterView flutterView = spy(new FlutterView(ctx)); + setExpectedDisplayRotation(Surface.ROTATION_270); + assertEquals(0, flutterView.getSystemUiVisibility()); + when(flutterView.getWindowSystemUiVisibility()) + .thenReturn(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); + when(flutterView.getContext()).thenReturn(ctx); + + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + FlutterRenderer flutterRenderer = spy(new FlutterRenderer(mockFlutterJni)); + when(flutterEngine.getRenderer()).thenReturn(flutterRenderer); + + // When we attach a new FlutterView to the engine without any system insets, + // the viewport metrics default to 0. + flutterView.attachToFlutterEngine(flutterEngine); + ArgumentCaptor viewportMetricsCaptor = + ArgumentCaptor.forClass(FlutterRenderer.ViewportMetrics.class); + verify(flutterRenderer).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(0, viewportMetricsCaptor.getValue().viewPaddingTop); + + // Then we simulate the system applying a window inset. + WindowInsets windowInsets = mock(WindowInsets.class); + mockSystemWindowInsets(windowInsets, 100, 100, 100, 100); + mockSystemGestureInsetsIfNeed(windowInsets); + + flutterView.onApplyWindowInsets(windowInsets); + + verify(flutterRenderer, times(2)).setViewportMetrics(viewportMetricsCaptor.capture()); + // Top padding is removed due to full screen. + // Right padding is zero because the rotation is 270deg under SDK 23 + // Bottom padding is removed due to hide navigation. + validateViewportMetricPadding(viewportMetricsCaptor, 100, 0, 0, 0); + } + + @Test + @Config(minSdk = API_LEVELS.FLUTTER_MIN, maxSdk = API_LEVELS.API_29, qualifiers = "port") + public void calculateShouldZeroSidesInPortrait() { + FlutterView flutterView = spy(new FlutterView(ctx)); + assertEquals(FlutterView.ZeroSides.NONE, flutterView.calculateShouldZeroSides()); + } + + @Test + @Config(minSdk = API_LEVELS.FLUTTER_MIN, maxSdk = API_LEVELS.API_29, qualifiers = "land") + public void calculateShouldZeroSidesInLandscapeNeutralRotation() { + FlutterView flutterView = spy(new FlutterView(ctx)); + setExpectedDisplayRotation(Surface.ROTATION_0); + assertEquals(FlutterView.ZeroSides.BOTH, flutterView.calculateShouldZeroSides()); + + setExpectedDisplayRotation(Surface.ROTATION_180); + assertEquals(FlutterView.ZeroSides.BOTH, flutterView.calculateShouldZeroSides()); + } + + @Test + @Config(minSdk = API_LEVELS.FLUTTER_MIN, maxSdk = API_LEVELS.API_29, qualifiers = "land") + public void calculateShouldZeroSidesInLandscapeRotation90() { + FlutterView flutterView = spy(new FlutterView(ctx)); + setExpectedDisplayRotation(Surface.ROTATION_90); + assertEquals(FlutterView.ZeroSides.RIGHT, flutterView.calculateShouldZeroSides()); + } + + @Test + @Config(minSdk = API_LEVELS.API_21, maxSdk = API_LEVELS.API_22, qualifiers = "land") + public void calculateShouldZeroSidesInLandscapeRotation270API22() { + FlutterView flutterView = spy(new FlutterView(ctx)); + setExpectedDisplayRotation(Surface.ROTATION_270); + assertEquals(FlutterView.ZeroSides.RIGHT, flutterView.calculateShouldZeroSides()); + } + + @Test + @Config(minSdk = API_LEVELS.API_23, maxSdk = API_LEVELS.API_29, qualifiers = "land") + public void calculateShouldZeroSidesInLandscapeRotation270API23Plus() { + FlutterView flutterView = spy(new FlutterView(ctx)); + setExpectedDisplayRotation(Surface.ROTATION_270); + assertEquals(FlutterView.ZeroSides.LEFT, flutterView.calculateShouldZeroSides()); + } + + @SuppressWarnings("deprecation") + // getSystemUiVisibility, getWindowSystemUiVisibility required to test pre api 30 behavior. + @Test + @Config(minSdk = 23, maxSdk = 29, qualifiers = "land") + public void systemInsetHandlesFullscreenNavbarLeft() { + FlutterView flutterView = spy(new FlutterView(ctx)); + setExpectedDisplayRotation(Surface.ROTATION_270); + assertEquals(0, flutterView.getSystemUiVisibility()); + when(flutterView.getWindowSystemUiVisibility()) + .thenReturn(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); + when(flutterView.getContext()).thenReturn(ctx); + + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + FlutterRenderer flutterRenderer = spy(new FlutterRenderer(mockFlutterJni)); + when(flutterEngine.getRenderer()).thenReturn(flutterRenderer); + + // When we attach a new FlutterView to the engine without any system insets, + // the viewport metrics default to 0. + flutterView.attachToFlutterEngine(flutterEngine); + ArgumentCaptor viewportMetricsCaptor = + ArgumentCaptor.forClass(FlutterRenderer.ViewportMetrics.class); + verify(flutterRenderer).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(0, viewportMetricsCaptor.getValue().viewPaddingTop); + + // Then we simulate the system applying a window inset. + WindowInsets windowInsets = mock(WindowInsets.class); + mockSystemWindowInsets(windowInsets, 100, 100, 100, 100); + mockSystemGestureInsetsIfNeed(windowInsets); + + flutterView.onApplyWindowInsets(windowInsets); + + verify(flutterRenderer, times(2)).setViewportMetrics(viewportMetricsCaptor.capture()); + // Left padding is zero because the rotation is 270deg + // Top padding is removed due to full screen. + // Bottom padding is removed due to hide navigation. + validateViewportMetricPadding(viewportMetricsCaptor, 0, 0, 100, 0); + } + + @SuppressWarnings("deprecation") + // getSystemUiVisibility, getWindowSystemUiVisibility required to test interop with api 30 + // behavior. + // This test uses the API 30+ Algorithm for window insets. The legacy algorithm is + // set to -1 values, so it is clear if the wrong algorithm is used. + @Test + @TargetApi(30) + @Config(sdk = 30, qualifiers = "land") + public void systemInsetGetInsetsFullscreen() { + FlutterView flutterView = spy(new FlutterView(ctx)); + setExpectedDisplayRotation(Surface.ROTATION_270); + assertEquals(0, flutterView.getSystemUiVisibility()); + when(flutterView.getWindowSystemUiVisibility()) + .thenReturn(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); + when(flutterView.getContext()).thenReturn(ctx); + + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + FlutterRenderer flutterRenderer = spy(new FlutterRenderer(mockFlutterJni)); + when(flutterEngine.getRenderer()).thenReturn(flutterRenderer); + + // When we attach a new FlutterView to the engine without any system insets, + // the viewport metrics default to 0. + flutterView.attachToFlutterEngine(flutterEngine); + ArgumentCaptor viewportMetricsCaptor = + ArgumentCaptor.forClass(FlutterRenderer.ViewportMetrics.class); + verify(flutterRenderer).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(0, viewportMetricsCaptor.getValue().viewPaddingTop); + + Insets insets = Insets.of(10, 20, 30, 40); + // Then we simulate the system applying a window inset. + WindowInsets windowInsets = mock(WindowInsets.class); + mockSystemWindowInsets(windowInsets, -1, -1, -1, -1); + when(windowInsets.getInsets(anyInt())).thenReturn(insets); + + flutterView.onApplyWindowInsets(windowInsets); + + verify(flutterRenderer, times(2)).setViewportMetrics(viewportMetricsCaptor.capture()); + validateViewportMetricPadding(viewportMetricsCaptor, 10, 20, 30, 40); + } + + @SuppressWarnings("deprecation") + // getSystemUiVisibility, getWindowSystemUiVisibility required to test pre api 30 behavior. + // This test uses the pre-API 30 Algorithm for window insets. + @Test + @TargetApi(28) + @Config(sdk = 28, qualifiers = "land") + public void systemInsetGetInsetsFullscreenLegacy() { + FlutterView flutterView = spy(new FlutterView(ctx)); + setExpectedDisplayRotation(Surface.ROTATION_270); + assertEquals(0, flutterView.getSystemUiVisibility()); + when(flutterView.getWindowSystemUiVisibility()) + .thenReturn(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); + when(flutterView.getContext()).thenReturn(ctx); + + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + FlutterRenderer flutterRenderer = spy(new FlutterRenderer(mockFlutterJni)); + when(flutterEngine.getRenderer()).thenReturn(flutterRenderer); + + // When we attach a new FlutterView to the engine without any system insets, + // the viewport metrics default to 0. + flutterView.attachToFlutterEngine(flutterEngine); + ArgumentCaptor viewportMetricsCaptor = + ArgumentCaptor.forClass(FlutterRenderer.ViewportMetrics.class); + verify(flutterRenderer).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(0, viewportMetricsCaptor.getValue().viewPaddingTop); + + // Then we simulate the system applying a window inset. + WindowInsets windowInsets = mock(WindowInsets.class); + mockSystemWindowInsets(windowInsets, 102, 100, 103, 101); + + flutterView.onApplyWindowInsets(windowInsets); + + verify(flutterRenderer, times(2)).setViewportMetrics(viewportMetricsCaptor.capture()); + // Left padding is zero because the rotation is 270deg + // Top padding is removed due to full screen. + // Bottom padding is removed due to hide navigation. + validateViewportMetricPadding(viewportMetricsCaptor, 0, 0, 103, 0); + } + + @SuppressWarnings("deprecation") + // getSystemUiVisibility, getWindowSystemUiVisibility, getSystemGestureInsets required + // to test pre api 30 interop behavior. + // This test uses the API 30+ Algorithm for window insets. The legacy algorithm is + // set to -1 values, so it is clear if the wrong algorithm is used. + @Test + @TargetApi(30) + @Config(sdk = 30, qualifiers = "land") + public void systemInsetDisplayCutoutSimple() { + FlutterView flutterView = spy(new FlutterView(ctx)); + assertEquals(0, flutterView.getSystemUiVisibility()); + when(flutterView.getWindowSystemUiVisibility()).thenReturn(0); + when(flutterView.getContext()).thenReturn(ctx); + + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + FlutterRenderer flutterRenderer = spy(new FlutterRenderer(mockFlutterJni)); + when(flutterEngine.getRenderer()).thenReturn(flutterRenderer); + + // When we attach a new FlutterView to the engine without any system insets, + // the viewport metrics default to 0. + flutterView.attachToFlutterEngine(flutterEngine); + ArgumentCaptor viewportMetricsCaptor = + ArgumentCaptor.forClass(FlutterRenderer.ViewportMetrics.class); + verify(flutterRenderer).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(0, viewportMetricsCaptor.getValue().viewPaddingTop); + + Insets insets = Insets.of(100, 100, 100, 100); + Insets systemGestureInsets = Insets.of(110, 110, 110, 110); + // Then we simulate the system applying a window inset. + WindowInsets windowInsets = mock(WindowInsets.class); + DisplayCutout displayCutout = mock(DisplayCutout.class); + mockSystemWindowInsets(windowInsets, -1, -1, -1, -1); + when(windowInsets.getInsets(anyInt())).thenReturn(insets); + when(windowInsets.getSystemGestureInsets()).thenReturn(systemGestureInsets); + when(windowInsets.getDisplayCutout()).thenReturn(displayCutout); + + Insets waterfallInsets = Insets.of(200, 0, 250, 0); + when(displayCutout.getWaterfallInsets()).thenReturn(waterfallInsets); + when(displayCutout.getSafeInsetLeft()).thenReturn(110); + when(displayCutout.getSafeInsetTop()).thenReturn(120); + when(displayCutout.getSafeInsetRight()).thenReturn(130); + when(displayCutout.getSafeInsetBottom()).thenReturn(140); + + flutterView.onApplyWindowInsets(windowInsets); + + verify(flutterRenderer, times(2)).setViewportMetrics(viewportMetricsCaptor.capture()); + // Each dimension of the viewport metric paddings should be the maximum of the corresponding + // dimension from the display cutout's safe insets and waterfall insets. + validateViewportMetricPadding(viewportMetricsCaptor, 200, 120, 250, 140); + + assertEquals(100, viewportMetricsCaptor.getValue().viewInsetTop); + } + + @SuppressWarnings("deprecation") + @Test + @Config(minSdk = 28) + public void onApplyWindowInsetsSetsDisplayCutouts() { + // Use an Activity context so that FlutterView.onAttachedToWindow completes. + Context context = Robolectric.setupActivity(Activity.class); + FlutterView flutterView = spy(new FlutterView(context)); + assertEquals(0, flutterView.getSystemUiVisibility()); + when(flutterView.getWindowSystemUiVisibility()).thenReturn(0); + when(flutterView.getContext()).thenReturn(context); + + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + FlutterRenderer flutterRenderer = spy(new FlutterRenderer(mockFlutterJni)); + when(flutterEngine.getRenderer()).thenReturn(flutterRenderer); + + // When we attach a new FlutterView to the engine without any system insets, + // the viewport metrics default to 0. + flutterView.attachToFlutterEngine(flutterEngine); + ArgumentCaptor viewportMetricsCaptor = + ArgumentCaptor.forClass(FlutterRenderer.ViewportMetrics.class); + verify(flutterRenderer).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(0, viewportMetricsCaptor.getValue().viewPaddingTop); + + // Capture flutterView.setWindowInfoListenerDisplayFeatures. + WindowInfoRepositoryCallbackAdapterWrapper windowInfoRepo = + mock(WindowInfoRepositoryCallbackAdapterWrapper.class); + doReturn(windowInfoRepo).when(flutterView).createWindowInfoRepo(); + ArgumentCaptor> consumerCaptor = + ArgumentCaptor.forClass(Consumer.class); + flutterView.onAttachedToWindow(); + verify(windowInfoRepo).addWindowLayoutInfoListener(any(), any(), consumerCaptor.capture()); + Consumer consumer = consumerCaptor.getValue(); + + // Set display features in flutterView to ensure they are not overridden by display cutouts. + FoldingFeature displayFeature = mock(FoldingFeature.class); + Rect featureBounds = new Rect(10, 20, 30, 40); + when(displayFeature.getBounds()).thenReturn(featureBounds); + when(displayFeature.getOcclusionType()).thenReturn(FoldingFeature.OcclusionType.FULL); + when(displayFeature.getState()).thenReturn(FoldingFeature.State.FLAT); + WindowLayoutInfo windowLayout = new WindowLayoutInfo(Collections.singletonList(displayFeature)); + clearInvocations(flutterRenderer); + consumer.accept(windowLayout); + + // Assert the display feature is set. + verify(flutterRenderer).setViewportMetrics(viewportMetricsCaptor.capture()); + List features = + viewportMetricsCaptor.getValue().getDisplayFeatures(); + assertEquals(1, features.size()); + assertEquals(FlutterRenderer.DisplayFeatureType.HINGE, features.get(0).type); + assertEquals(FlutterRenderer.DisplayFeatureState.POSTURE_FLAT, features.get(0).state); + assertEquals(featureBounds, features.get(0).bounds); + + // Then we simulate the system applying a window inset. + List cutoutBoundingRects = + Arrays.asList(new Rect(0, 200, 300, 400), new Rect(150, 0, 300, 150)); + WindowInsets windowInsets = setupMockDisplayCutout(cutoutBoundingRects); + + clearInvocations(flutterRenderer); + flutterView.onApplyWindowInsets(windowInsets); + verify(flutterRenderer).setViewportMetrics(viewportMetricsCaptor.capture()); + + features = viewportMetricsCaptor.getValue().getDisplayFeatures(); + + // Assert the old display feature is still present. + assertEquals(1, features.size()); + assertEquals(FlutterRenderer.DisplayFeatureType.HINGE, features.get(0).type); + assertEquals(FlutterRenderer.DisplayFeatureState.POSTURE_FLAT, features.get(0).state); + assertEquals(featureBounds, features.get(0).bounds); + + List cutouts = + viewportMetricsCaptor.getValue().getDisplayCutouts(); + // Asserts for display cutouts. + assertEquals(2, cutouts.size()); + for (int i = 0; i < 2; i++) { + assertEquals(cutoutBoundingRects.get(i), cutouts.get(i).bounds); + assertEquals(FlutterRenderer.DisplayFeatureType.CUTOUT, cutouts.get(i).type); + assertEquals(FlutterRenderer.DisplayFeatureState.UNKNOWN, cutouts.get(i).state); + } + } + + @SuppressWarnings("deprecation") + // Robolectric.setupActivity + // TODO(reidbaker): https://github.com/flutter/flutter/issues/133151 + // getDefaultDisplay + // TODO(jesswrd): https://github.com/flutter/flutter/issues/99421 + @Test + public void itRegistersAndUnregistersToWindowManager() { + Context context = Robolectric.setupActivity(Activity.class); + FlutterView flutterView = spy(new FlutterView(context)); + WindowInfoRepositoryCallbackAdapterWrapper windowInfoRepo = + mock(WindowInfoRepositoryCallbackAdapterWrapper.class); + // For reasoning behing using doReturn instead of when, read "Important gotcha" at + // https://www.javadoc.io/doc/org.mockito/mockito-core/1.10.19/org/mockito/Mockito.html#13 + doReturn(windowInfoRepo).when(flutterView).createWindowInfoRepo(); + + // When a new FlutterView is attached to the window + flutterView.onAttachedToWindow(); + + // Then the WindowManager callback is registered + verify(windowInfoRepo, times(1)).addWindowLayoutInfoListener(any(), any(), any()); + + // When the FlutterView is detached from the window + flutterView.onDetachedFromWindow(); + + // Then the WindowManager callback is unregistered + verify(windowInfoRepo, times(1)).removeWindowLayoutInfoListener(any()); + } + + @SuppressWarnings("deprecation") + // Robolectric.setupActivity + // TODO(reidbaker): https://github.com/flutter/flutter/issues/133151 + // getDefaultDisplay + // TODO(jesswrd): https://github.com/flutter/flutter/issues/99421 + @Test + public void itSendsHingeDisplayFeatureToFlutter() { + Context context = Robolectric.setupActivity(Activity.class); + FlutterView flutterView = spy(new FlutterView(context)); + when(flutterView.getContext()).thenReturn(context); + WindowInfoRepositoryCallbackAdapterWrapper windowInfoRepo = + mock(WindowInfoRepositoryCallbackAdapterWrapper.class); + doReturn(windowInfoRepo).when(flutterView).createWindowInfoRepo(); + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + FlutterRenderer flutterRenderer = spy(new FlutterRenderer(mockFlutterJni)); + when(flutterEngine.getRenderer()).thenReturn(flutterRenderer); + + // Display features should be empty on attaching to engine. + flutterView.attachToFlutterEngine(flutterEngine); + ArgumentCaptor viewportMetricsCaptor = + ArgumentCaptor.forClass(FlutterRenderer.ViewportMetrics.class); + verify(flutterRenderer).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(Collections.emptyList(), viewportMetricsCaptor.getValue().getDisplayFeatures()); + clearInvocations(flutterRenderer); + + // Test that display features do not override cutouts. + List cutoutBoundingRects = Collections.singletonList(new Rect(0, 200, 300, 400)); + WindowInsets windowInsets = setupMockDisplayCutout(cutoutBoundingRects); + flutterView.onApplyWindowInsets(windowInsets); + verify(flutterRenderer).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(1, viewportMetricsCaptor.getValue().getDisplayCutouts().size()); + assertEquals( + cutoutBoundingRects.get(0), + viewportMetricsCaptor.getValue().getDisplayCutouts().get(0).bounds); + clearInvocations(flutterRenderer); + + FoldingFeature displayFeature = mock(FoldingFeature.class); + Rect featureRect = new Rect(0, 0, 100, 100); + when(displayFeature.getBounds()).thenReturn(featureRect); + when(displayFeature.getOcclusionType()).thenReturn(FoldingFeature.OcclusionType.FULL); + when(displayFeature.getState()).thenReturn(FoldingFeature.State.FLAT); + + WindowLayoutInfo testWindowLayout = + new WindowLayoutInfo(Collections.singletonList(displayFeature)); + + // When FlutterView is attached to the engine and window, and a hinge display feature exists + flutterView.onAttachedToWindow(); + ArgumentCaptor> wmConsumerCaptor = + ArgumentCaptor.forClass(Consumer.class); + verify(windowInfoRepo).addWindowLayoutInfoListener(any(), any(), wmConsumerCaptor.capture()); + Consumer wmConsumer = wmConsumerCaptor.getValue(); + clearInvocations(flutterRenderer); + wmConsumer.accept(testWindowLayout); + + // Then the Renderer receives the display feature + verify(flutterRenderer).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(1, viewportMetricsCaptor.getValue().getDisplayFeatures().size()); + FlutterRenderer.DisplayFeature feature = + viewportMetricsCaptor.getValue().getDisplayFeatures().get(0); + assertEquals(FlutterRenderer.DisplayFeatureType.HINGE, feature.type); + assertEquals(FlutterRenderer.DisplayFeatureState.POSTURE_FLAT, feature.state); + assertEquals(featureRect, feature.bounds); + + // Assert the display cutout is unaffected. + assertEquals(1, viewportMetricsCaptor.getValue().getDisplayCutouts().size()); + FlutterRenderer.DisplayFeature cutout = + viewportMetricsCaptor.getValue().getDisplayCutouts().get(0); + assertEquals(cutoutBoundingRects.get(0), cutout.bounds); + assertEquals(FlutterRenderer.DisplayFeatureType.CUTOUT, cutout.type); + assertEquals(FlutterRenderer.DisplayFeatureState.UNKNOWN, cutout.state); + } + + @Test + public void flutterImageView_acquiresImageAndInvalidates() { + final ImageReader mockReader = mock(ImageReader.class); + when(mockReader.getMaxImages()).thenReturn(2); + + final FlutterImageView imageView = + spy(new FlutterImageView(ctx, mockReader, FlutterImageView.SurfaceKind.background)); + + final FlutterJNI jni = mock(FlutterJNI.class); + imageView.attachToRenderer(new FlutterRenderer(jni)); + + final Image mockImage = mock(Image.class); + when(mockReader.acquireLatestImage()).thenReturn(mockImage); + + assertTrue(imageView.acquireLatestImage()); + verify(mockReader, times(1)).acquireLatestImage(); + verify(imageView, times(1)).invalidate(); + } + + @Test + @SuppressLint("WrongCall") /*View#onDraw*/ + public void flutterImageView_acquiresImageClosesPreviousImageUnlessNoNewImage() { + final ImageReader mockReader = mock(ImageReader.class); + when(mockReader.getMaxImages()).thenReturn(3); + + final Image mockImage = mock(Image.class); + when(mockImage.getPlanes()).thenReturn(new Plane[0]); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + final HardwareBuffer mockHardwareBuffer = mock(HardwareBuffer.class); + when(mockHardwareBuffer.getUsage()).thenReturn(HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE); + when(mockImage.getHardwareBuffer()).thenReturn(mockHardwareBuffer); + } + // Mock no latest image on the second time + when(mockReader.acquireLatestImage()) + .thenReturn(mockImage) + .thenReturn(null) + .thenReturn(mockImage); + + final FlutterImageView imageView = + spy(new FlutterImageView(ctx, mockReader, FlutterImageView.SurfaceKind.background)); + + final FlutterJNI jni = mock(FlutterJNI.class); + imageView.attachToRenderer(new FlutterRenderer(jni)); + doNothing().when(imageView).invalidate(); + + assertTrue(imageView.acquireLatestImage()); // No previous, acquire latest image + assertFalse( + imageView.acquireLatestImage()); // Mock no image when acquire, don't close, and assertFalse + assertTrue(imageView.acquireLatestImage()); // Acquire latest image and close previous + assertTrue(imageView.acquireLatestImage()); // Acquire latest image and close previous + assertTrue(imageView.acquireLatestImage()); // Acquire latest image and close previous + verify(mockImage, times(3)).close(); // Close 3 times + + imageView.onDraw(mock(Canvas.class)); // Draw latest image + + assertTrue(imageView.acquireLatestImage()); // acquire latest image and close previous + + imageView.onDraw(mock(Canvas.class)); // Draw latest image + imageView.onDraw(mock(Canvas.class)); // Draw latest image + imageView.onDraw(mock(Canvas.class)); // Draw latest image + + verify(mockReader, times(6)).acquireLatestImage(); + } + + @Test + public void flutterImageView_detachFromRendererClosesPreviousImage() { + final ImageReader mockReader = mock(ImageReader.class); + when(mockReader.getMaxImages()).thenReturn(2); + + final Image mockImage = mock(Image.class); + when(mockReader.acquireLatestImage()).thenReturn(mockImage); + + final FlutterImageView imageView = + spy(new FlutterImageView(ctx, mockReader, FlutterImageView.SurfaceKind.background)); + + final FlutterJNI jni = mock(FlutterJNI.class); + imageView.attachToRenderer(new FlutterRenderer(jni)); + + doNothing().when(imageView).invalidate(); + imageView.acquireLatestImage(); + imageView.acquireLatestImage(); + verify(mockImage, times(1)).close(); + + imageView.detachFromRenderer(); + // There's an acquireLatestImage() in detachFromRenderer(), + // so it will be 2 times called close() inside detachFromRenderer() + verify(mockImage, times(3)).close(); + } + + @Test + public void flutterImageView_workaroundWithOnePixelWhenResizeWithZero() { + final ImageReader mockReader = mock(ImageReader.class); + when(mockReader.getMaxImages()).thenReturn(2); + + final FlutterImageView imageView = + spy(new FlutterImageView(ctx, mockReader, FlutterImageView.SurfaceKind.background)); + + final FlutterJNI jni = mock(FlutterJNI.class); + imageView.attachToRenderer(new FlutterRenderer(jni)); + + final Image mockImage = mock(Image.class); + when(mockReader.acquireLatestImage()).thenReturn(mockImage); + + final int incorrectWidth = 0; + final int incorrectHeight = -100; + imageView.resizeIfNeeded(incorrectWidth, incorrectHeight); + assertEquals(1, imageView.getImageReader().getWidth()); + assertEquals(1, imageView.getImageReader().getHeight()); + } + + @Test + public void flutterImageView_closesReader() { + final ImageReader mockReader = mock(ImageReader.class); + when(mockReader.getMaxImages()).thenReturn(1); + + final FlutterImageView imageView = + spy(new FlutterImageView(ctx, mockReader, FlutterImageView.SurfaceKind.background)); + + imageView.closeImageReader(); + verify(mockReader, times(1)).close(); + } + + @Test + public void flutterSurfaceView_GathersTransparentRegion() { + final Region mockRegion = mock(Region.class); + final FlutterSurfaceView surfaceView = new FlutterSurfaceView(ctx); + + surfaceView.setAlpha(0.0f); + assertFalse(surfaceView.gatherTransparentRegion(mockRegion)); + verify(mockRegion, times(0)).op(anyInt(), anyInt(), anyInt(), anyInt(), any()); + + surfaceView.setAlpha(1.0f); + assertTrue(surfaceView.gatherTransparentRegion(mockRegion)); + verify(mockRegion, times(1)).op(0, 0, 0, 0, Region.Op.DIFFERENCE); + } + + @Test + @SuppressLint("PrivateApi") + @Config(sdk = Build.VERSION_CODES.P) + public void findViewByAccessibilityIdTraversal_returnsRootViewOnAndroid28() throws Exception { + FlutterView flutterView = new FlutterView(ctx); + + Method getAccessibilityViewIdMethod = View.class.getDeclaredMethod("getAccessibilityViewId"); + Integer accessibilityViewId = (Integer) getAccessibilityViewIdMethod.invoke(flutterView); + + assertEquals(flutterView, flutterView.findViewByAccessibilityIdTraversal(accessibilityViewId)); + } + + @Test + @Config(sdk = Build.VERSION_CODES.P) + @SuppressLint("PrivateApi") + public void findViewByAccessibilityIdTraversal_returnsChildViewOnAndroid28() throws Exception { + FlutterView flutterView = new FlutterView(ctx); + FrameLayout childView1 = new FrameLayout(ctx); + flutterView.addView(childView1); + + FrameLayout childView2 = new FrameLayout(ctx); + childView1.addView(childView2); + + Method getAccessibilityViewIdMethod = View.class.getDeclaredMethod("getAccessibilityViewId"); + Integer accessibilityViewId = (Integer) getAccessibilityViewIdMethod.invoke(childView2); + + assertEquals(childView2, flutterView.findViewByAccessibilityIdTraversal(accessibilityViewId)); + } + + @Test + @Config(sdk = Build.VERSION_CODES.Q) + @SuppressLint("PrivateApi") + public void findViewByAccessibilityIdTraversal_returnsRootViewOnAndroid29() throws Exception { + FlutterView flutterView = new FlutterView(ctx); + + Method getAccessibilityViewIdMethod = View.class.getDeclaredMethod("getAccessibilityViewId"); + Integer accessibilityViewId = (Integer) getAccessibilityViewIdMethod.invoke(flutterView); + + assertEquals(null, flutterView.findViewByAccessibilityIdTraversal(accessibilityViewId)); + } + + @Test + public void itSendsTextShowPasswordToFrameworkOnAttach() { + // Setup test. + AtomicReference reportedShowPassword = new AtomicReference<>(); + + FlutterView flutterView = new FlutterView(ctx); + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + Settings.System.putInt( + flutterView.getContext().getContentResolver(), Settings.System.TEXT_SHOW_PASSWORD, 1); + + SettingsChannel fakeSettingsChannel = mock(SettingsChannel.class); + SettingsChannel.MessageBuilder fakeMessageBuilder = mock(SettingsChannel.MessageBuilder.class); + when(fakeMessageBuilder.setTextScaleFactor(any(Float.class))).thenReturn(fakeMessageBuilder); + when(fakeMessageBuilder.setDisplayMetrics(any(DisplayMetrics.class))) + .thenReturn(fakeMessageBuilder); + when(fakeMessageBuilder.setNativeSpellCheckServiceDefined(any(Boolean.class))) + .thenReturn(fakeMessageBuilder); + when(fakeMessageBuilder.setPlatformBrightness(any(SettingsChannel.PlatformBrightness.class))) + .thenReturn(fakeMessageBuilder); + when(fakeMessageBuilder.setUse24HourFormat(any(Boolean.class))).thenReturn(fakeMessageBuilder); + when(fakeMessageBuilder.setBrieflyShowPassword(any(Boolean.class))) + .thenAnswer( + new Answer() { + @Override + public SettingsChannel.MessageBuilder answer(InvocationOnMock invocation) + throws Throwable { + reportedShowPassword.set((Boolean) invocation.getArguments()[0]); + return fakeMessageBuilder; + } + }); + when(fakeSettingsChannel.startMessage()).thenReturn(fakeMessageBuilder); + when(flutterEngine.getSettingsChannel()).thenReturn(fakeSettingsChannel); + + flutterView.attachToFlutterEngine(flutterEngine); + + // Verify results. + assertTrue(reportedShowPassword.get()); + } + + public void ViewportMetrics_initializedPhysicalTouchSlop() { + FlutterView flutterView = new FlutterView(ctx); + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + FlutterRenderer flutterRenderer = spy(new FlutterRenderer(mockFlutterJni)); + when(flutterEngine.getRenderer()).thenReturn(flutterRenderer); + + flutterView.attachToFlutterEngine(flutterEngine); + ArgumentCaptor viewportMetricsCaptor = + ArgumentCaptor.forClass(FlutterRenderer.ViewportMetrics.class); + verify(flutterRenderer).setViewportMetrics(viewportMetricsCaptor.capture()); + + assertFalse(-1 == viewportMetricsCaptor.getValue().physicalTouchSlop); + } + + // This test uses the API 30+ Algorithm for window insets. The legacy algorithm is + // set to -1 values, so it is clear if the wrong algorithm is used. + @Test + @TargetApi(30) + @Config(sdk = 30) + public void setPaddingTopToZeroForFullscreenMode() { + FlutterView flutterView = new FlutterView(ctx); + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + FlutterRenderer flutterRenderer = spy(new FlutterRenderer(mockFlutterJni)); + when(flutterEngine.getRenderer()).thenReturn(flutterRenderer); + + // When we attach a new FlutterView to the engine without any system insets, the viewport + // metrics + // default to 0. + flutterView.attachToFlutterEngine(flutterEngine); + ArgumentCaptor viewportMetricsCaptor = + ArgumentCaptor.forClass(FlutterRenderer.ViewportMetrics.class); + verify(flutterRenderer).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(0, viewportMetricsCaptor.getValue().viewPaddingTop); + + // Then we simulate the system applying a window inset. + WindowInsets windowInsets = + new WindowInsets.Builder() + .setInsets( + android.view.WindowInsets.Type.navigationBars() + | android.view.WindowInsets.Type.systemBars(), + Insets.of(100, 100, 100, 100)) + .build(); + flutterView.onApplyWindowInsets(windowInsets); + + // Verify. + verify(flutterRenderer, times(3)).setViewportMetrics(viewportMetricsCaptor.capture()); + validateViewportMetricPadding(viewportMetricsCaptor, 100, 100, 100, 100); + } + + @SuppressWarnings("deprecation") + // SYSTEM_UI_FLAG_FULLSCREEN, getWindowSystemUiVisibility + // This test uses the pre-API 30 Algorithm for window insets. + @Test + @TargetApi(28) + @Config( + sdk = 28, + shadows = { + FlutterViewTest.ShadowFullscreenView.class, + }) + public void setPaddingTopToZeroForFullscreenModeLegacy() { + FlutterView flutterView = spy(new FlutterView(ctx)); + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + FlutterRenderer flutterRenderer = spy(new FlutterRenderer(mockFlutterJni)); + when(flutterEngine.getRenderer()).thenReturn(flutterRenderer); + + // When we attach a new FlutterView to the engine without any system insets, the viewport + // metrics + // default to 0. + flutterView.attachToFlutterEngine(flutterEngine); + ArgumentCaptor viewportMetricsCaptor = + ArgumentCaptor.forClass(FlutterRenderer.ViewportMetrics.class); + verify(flutterRenderer).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(0, viewportMetricsCaptor.getValue().viewPaddingTop); + clearInvocations(flutterRenderer); + // Then we simulate the system applying a window inset. + WindowInsets windowInsets = mock(WindowInsets.class); + mockSystemWindowInsets(windowInsets, 100, 100, 100, 100); + flutterView.onApplyWindowInsets(windowInsets); + + // Verify. + verify(flutterRenderer, times(1)).setViewportMetrics(viewportMetricsCaptor.capture()); + validateViewportMetricPadding(viewportMetricsCaptor, 100, 100, 100, 0); + clearInvocations(flutterRenderer); + + // Validation when fullscreen + when(flutterView.getWindowSystemUiVisibility()).thenReturn(View.SYSTEM_UI_FLAG_FULLSCREEN); + + // Then we simulate the system applying a window inset. + mockSystemWindowInsets(windowInsets, 100, 100, 100, 100); + flutterView.onApplyWindowInsets(windowInsets); + + // Verify. + verify(flutterRenderer, times(1)).setViewportMetrics(viewportMetricsCaptor.capture()); + validateViewportMetricPadding(viewportMetricsCaptor, 100, 0, 100, 0); + } + + // TODO(mattcarroll): turn this into an e2e test. GitHub #42990 + @Test + public void itSendsDarkPlatformBrightnessToFlutter() { + // Setup test. + AtomicReference reportedBrightness = + new AtomicReference<>(); + + Context spiedContext = spy(ctx); + + Resources spiedResources = spy(spiedContext.getResources()); + when(spiedContext.getResources()).thenReturn(spiedResources); + + Configuration spiedConfiguration = spy(spiedResources.getConfiguration()); + spiedConfiguration.uiMode = + (spiedResources.getConfiguration().uiMode | Configuration.UI_MODE_NIGHT_YES) + & ~Configuration.UI_MODE_NIGHT_NO; + when(spiedResources.getConfiguration()).thenReturn(spiedConfiguration); + + FlutterView flutterView = new FlutterView(spiedContext); + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + + SettingsChannel fakeSettingsChannel = mock(SettingsChannel.class); + SettingsChannel.MessageBuilder fakeMessageBuilder = mock(SettingsChannel.MessageBuilder.class); + when(fakeMessageBuilder.setTextScaleFactor(any(Float.class))).thenReturn(fakeMessageBuilder); + when(fakeMessageBuilder.setDisplayMetrics(any(DisplayMetrics.class))) + .thenReturn(fakeMessageBuilder); + when(fakeMessageBuilder.setNativeSpellCheckServiceDefined(any(Boolean.class))) + .thenReturn(fakeMessageBuilder); + when(fakeMessageBuilder.setBrieflyShowPassword(any(Boolean.class))) + .thenReturn(fakeMessageBuilder); + when(fakeMessageBuilder.setUse24HourFormat(any(Boolean.class))).thenReturn(fakeMessageBuilder); + when(fakeMessageBuilder.setPlatformBrightness(any(SettingsChannel.PlatformBrightness.class))) + .thenAnswer( + new Answer() { + @Override + public SettingsChannel.MessageBuilder answer(InvocationOnMock invocation) + throws Throwable { + reportedBrightness.set( + (SettingsChannel.PlatformBrightness) invocation.getArguments()[0]); + return fakeMessageBuilder; + } + }); + when(fakeSettingsChannel.startMessage()).thenReturn(fakeMessageBuilder); + when(flutterEngine.getSettingsChannel()).thenReturn(fakeSettingsChannel); + + // Execute behavior under test. + flutterView.attachToFlutterEngine(flutterEngine); + flutterView.sendUserSettingsToFlutter(); + + // Verify results. + assertEquals(SettingsChannel.PlatformBrightness.dark, reportedBrightness.get()); + } + + @SuppressWarnings("deprecation") + // SYSTEM_UI_FLAG_FULLSCREEN, getWindowSystemUiVisibility + // TODO(mattcarroll): turn this into an e2e test. GitHub #42990 + @Test + public void itSendsLightPlatformBrightnessToFlutter() { + // Setup test. + AtomicReference reportedBrightness = + new AtomicReference<>(); + + // FYI - The default brightness is LIGHT, which is why we don't need to configure it. + FlutterView flutterView = new FlutterView(ctx); + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + + SettingsChannel fakeSettingsChannel = mock(SettingsChannel.class); + SettingsChannel.MessageBuilder fakeMessageBuilder = mock(SettingsChannel.MessageBuilder.class); + when(fakeMessageBuilder.setTextScaleFactor(any(Float.class))).thenReturn(fakeMessageBuilder); + when(fakeMessageBuilder.setDisplayMetrics(any(DisplayMetrics.class))) + .thenReturn(fakeMessageBuilder); + when(fakeMessageBuilder.setNativeSpellCheckServiceDefined(any(Boolean.class))) + .thenReturn(fakeMessageBuilder); + when(fakeMessageBuilder.setBrieflyShowPassword(any(Boolean.class))) + .thenReturn(fakeMessageBuilder); + when(fakeMessageBuilder.setUse24HourFormat(any(Boolean.class))).thenReturn(fakeMessageBuilder); + when(fakeMessageBuilder.setPlatformBrightness(any(SettingsChannel.PlatformBrightness.class))) + .thenAnswer( + new Answer() { + @Override + public SettingsChannel.MessageBuilder answer(InvocationOnMock invocation) + throws Throwable { + reportedBrightness.set( + (SettingsChannel.PlatformBrightness) invocation.getArguments()[0]); + return fakeMessageBuilder; + } + }); + when(fakeSettingsChannel.startMessage()).thenReturn(fakeMessageBuilder); + when(flutterEngine.getSettingsChannel()).thenReturn(fakeSettingsChannel); + + flutterView.attachToFlutterEngine(flutterEngine); + + // Execute behavior under test. + flutterView.sendUserSettingsToFlutter(); + + // Verify results. + assertEquals(SettingsChannel.PlatformBrightness.light, reportedBrightness.get()); + } + + @SuppressWarnings("deprecation") + private void setExpectedDisplayRotation(int rotation) { + ShadowDisplay myDisplay = + Shadows.shadowOf( + ((DisplayManager) ctx.getSystemService(Context.DISPLAY_SERVICE)).getDisplay(0)); + myDisplay.setRotation(rotation); + } + + private void validateViewportMetricPadding( + ArgumentCaptor viewportMetricsCaptor, + int left, + int top, + int right, + int bottom) { + assertEquals(left, viewportMetricsCaptor.getValue().viewPaddingLeft); + assertEquals(top, viewportMetricsCaptor.getValue().viewPaddingTop); + assertEquals(right, viewportMetricsCaptor.getValue().viewPaddingRight); + assertEquals(bottom, viewportMetricsCaptor.getValue().viewPaddingBottom); + } + + @SuppressWarnings("deprecation") + private void mockSystemWindowInsets( + WindowInsets windowInsets, int left, int top, int right, int bottom) { + when(windowInsets.getSystemWindowInsetLeft()).thenReturn(left); + when(windowInsets.getSystemWindowInsetTop()).thenReturn(top); + when(windowInsets.getSystemWindowInsetRight()).thenReturn(right); + when(windowInsets.getSystemWindowInsetBottom()).thenReturn(bottom); + } + + @SuppressWarnings("deprecation") + private void mockSystemGestureInsetsIfNeed(WindowInsets windowInsets) { + if (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) { + when(windowInsets.getSystemGestureInsets()).thenReturn(Insets.NONE); + } + } + + @SuppressWarnings("deprecation") + private WindowInsets setupMockDisplayCutout(List boundingRects) { + WindowInsets windowInsets = mock(WindowInsets.class); + DisplayCutout displayCutout = mock(DisplayCutout.class); + when(windowInsets.getDisplayCutout()).thenReturn(displayCutout); + when(displayCutout.getBoundingRects()).thenReturn(boundingRects); + // The following mocked methods are necessary to avoid a NullPointerException when calling + // onApplyWindowInsets, but are irrelevant to the behavior this test concerns. + Insets unusedInsets = Insets.of(100, 100, 100, 100); + // WindowInsets::getSystemGestureInsets was added in API 29, deprecated in API 30. + if (Build.VERSION.SDK_INT == 29) { + when(windowInsets.getSystemGestureInsets()).thenReturn(unusedInsets); + } + // WindowInsets::getInsets was added in API 30. + if (Build.VERSION.SDK_INT >= 30) { + when(windowInsets.getInsets(anyInt())).thenReturn(unusedInsets); + } + // DisplayCutout::getWaterfallInsets was added in API 30. + if (Build.VERSION.SDK_INT >= 30) { + when(displayCutout.getWaterfallInsets()).thenReturn(unusedInsets); + } + when(displayCutout.getSafeInsetTop()).thenReturn(100); + when(displayCutout.getSafeInsetLeft()).thenReturn(100); + when(displayCutout.getSafeInsetBottom()).thenReturn(100); + when(displayCutout.getSafeInsetRight()).thenReturn(100); + return windowInsets; + } + + /* + * A custom shadow that reports fullscreen flag for system UI visibility + */ + @Implements(FrameLayout.class) + @SuppressWarnings("deprecation") + public static class ShadowFullscreenView extends ShadowViewGroup { + @Implementation + public int getWindowSystemUiVisibility() { + return View.SYSTEM_UI_FLAG_FULLSCREEN; + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/KeyChannelResponderTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/KeyChannelResponderTest.java new file mode 100644 index 0000000000000000000000000000000000000000..4e164f42af0dd92f7ef28f262707ca30f5de3c17 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/KeyChannelResponderTest.java @@ -0,0 +1,60 @@ +// 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. + +package io.flutter.embedding.android; + +import static io.flutter.Build.API_LEVELS; +import static junit.framework.TestCase.assertEquals; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.doAnswer; + +import android.annotation.TargetApi; +import android.view.KeyEvent; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.systemchannels.KeyEventChannel; +import io.flutter.embedding.engine.systemchannels.KeyEventChannel.EventResponseHandler; +import io.flutter.embedding.engine.systemchannels.KeyEventChannel.FlutterKeyEvent; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +@TargetApi(API_LEVELS.API_28) +public class KeyChannelResponderTest { + + @Mock KeyEventChannel keyEventChannel; + KeyChannelResponder channelResponder; + + @Before + public void setUp() { + MockitoAnnotations.openMocks(this); + channelResponder = new KeyChannelResponder(keyEventChannel); + } + + @Test + public void primaryResponderTest() { + final int[] completionCallbackInvocationCounter = {0}; + + doAnswer( + invocation -> { + ((EventResponseHandler) invocation.getArgument(2)).onFrameworkResponse(true); + return null; + }) + .when(keyEventChannel) + .sendFlutterKeyEvent( + any(FlutterKeyEvent.class), any(boolean.class), any(EventResponseHandler.class)); + + final KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, 65); + channelResponder.handleEvent( + keyEvent, + (canHandleEvent) -> { + completionCallbackInvocationCounter[0]++; + }); + assertEquals(completionCallbackInvocationCounter[0], 1); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/KeyboardManagerTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/KeyboardManagerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..2dfa602c3e3145f6aec7569edddab811da67e05d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/KeyboardManagerTest.java @@ -0,0 +1,2075 @@ +// 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. + +package io.flutter.embedding.android; + +import static android.view.KeyEvent.*; +import static io.flutter.embedding.android.KeyData.Type; +import static io.flutter.util.KeyCodes.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import android.view.InputDevice; +import android.view.KeyCharacterMap; +import android.view.KeyEvent; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.android.KeyData.DeviceType; +import io.flutter.plugin.common.BinaryMessenger; +import io.flutter.plugin.common.JSONMessageCodec; +import io.flutter.util.FakeKeyEvent; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.invocation.InvocationOnMock; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class KeyboardManagerTest { + public static final int SCAN_KEY_A = 0x1e; + public static final int SCAN_DIGIT1 = 0x2; + public static final int SCAN_SHIFT_LEFT = 0x2a; + public static final int SCAN_SHIFT_RIGHT = 0x36; + public static final int SCAN_CONTROL_LEFT = 0x1d; + public static final int SCAN_CONTROL_RIGHT = 0x61; + public static final int SCAN_ALT_LEFT = 0x38; + public static final int SCAN_ALT_RIGHT = 0x64; + public static final int SCAN_ARROW_LEFT = 0x69; + public static final int SCAN_ARROW_RIGHT = 0x6a; + public static final int SCAN_CAPS_LOCK = 0x3a; + + public static final boolean DOWN_EVENT = true; + public static final boolean UP_EVENT = false; + public static final boolean SHIFT_LEFT_EVENT = true; + public static final boolean SHIFT_RIGHT_EVENT = false; + + private static final int DEAD_KEY = '`' | KeyCharacterMap.COMBINING_ACCENT; + + /** + * Records a message that {@link KeyboardManager} sends to outside. + * + *

A call record can originate from many sources, indicated by its {@link type}. Different + * types will have different fields filled, leaving others empty. + */ + static class CallRecord { + enum Kind { + /** + * The channel responder sent a message through the key event channel. + * + *

This call record will have a non-null {@link channelObject}, with an optional {@link + * reply}. + */ + kChannel, + /** + * The embedder responder sent a message through the key data channel. + * + *

This call record will have a non-null {@link keyData}, with an optional {@link reply}. + */ + kEmbedder, + } + + /** + * Construct an empty call record. + * + *

Use the static functions to construct specific types instead. + */ + private CallRecord() {} + + Kind kind; + + /** + * The callback given by the keyboard manager. + * + *

It might be null, which probably means it is a synthesized event and requires no reply. + * Otherwise, invoke this callback with whether the event is handled for the keyboard manager to + * continue processing the key event. + */ + public Consumer reply; + /** The data for a call record of kind {@link Kind.kChannel}. */ + public JSONObject channelObject; + /** The data for a call record of kind {@link Kind.kEmbedder}. */ + public KeyData keyData; + + /** Construct a call record of kind {@link Kind.kChannel}. */ + static CallRecord channelCall( + @NonNull JSONObject channelObject, @Nullable Consumer reply) { + final CallRecord record = new CallRecord(); + record.kind = Kind.kChannel; + record.channelObject = channelObject; + record.reply = reply; + return record; + } + + /** Construct a call record of kind {@link Kind.kEmbedder}. */ + static CallRecord embedderCall(@NonNull KeyData keyData, @Nullable Consumer reply) { + final CallRecord record = new CallRecord(); + record.kind = Kind.kEmbedder; + record.keyData = keyData; + record.reply = reply; + return record; + } + } + + /** + * Build a response to a channel message sent by the channel responder. + * + * @param handled whether the event is handled. + */ + static ByteBuffer buildJsonResponse(boolean handled) { + JSONObject body = new JSONObject(); + try { + body.put("handled", handled); + } catch (JSONException e) { + assertNull(e); + } + ByteBuffer binaryReply = JSONMessageCodec.INSTANCE.encodeMessage(body); + binaryReply.rewind(); + return binaryReply; + } + + /** + * Build a response to an embedder message sent by the embedder responder. + * + * @param handled whether the event is handled. + */ + static ByteBuffer buildBinaryResponse(boolean handled) { + byte[] body = new byte[1]; + body[0] = (byte) (handled ? 1 : 0); + final ByteBuffer binaryReply = ByteBuffer.wrap(body); + binaryReply.rewind(); + return binaryReply; + } + + /** + * Used to configure how to process a channel message. + * + *

When the channel responder sends a channel message, this functional interface will be + * invoked. Its first argument will be the detailed data. The second argument will be a nullable + * reply callback, which should be called to mock the reply from the framework. + */ + @FunctionalInterface + static interface ChannelCallHandler extends BiConsumer> {} + + /** + * Used to configure how to process an embedder message. + * + *

When the embedder responder sends a key data, this functional interface will be invoked. Its + * first argument will be the detailed data. The second argument will be a nullable reply + * callback, which should be called to mock the reply from the framework. + */ + @FunctionalInterface + static interface EmbedderCallHandler extends BiConsumer> {} + + static class KeyboardTester { + public KeyboardTester() { + respondToChannelCallsWith(false); + respondToEmbedderCallsWith(false); + respondToTextInputWith(false); + + BinaryMessenger mockMessenger = mock(BinaryMessenger.class); + doAnswer(invocation -> onMessengerMessage(invocation)) + .when(mockMessenger) + .send(any(String.class), any(ByteBuffer.class), eq(null)); + doAnswer(invocation -> onMessengerMessage(invocation)) + .when(mockMessenger) + .send(any(String.class), any(ByteBuffer.class), any(BinaryMessenger.BinaryReply.class)); + + mockView = mock(KeyboardManager.ViewDelegate.class); + doAnswer(invocation -> mockMessenger).when(mockView).getBinaryMessenger(); + doAnswer(invocation -> textInputResult) + .when(mockView) + .onTextInputKeyEvent(any(KeyEvent.class)); + doAnswer( + invocation -> { + KeyEvent event = invocation.getArgument(0); + boolean handled = keyboardManager.handleEvent(event); + assertEquals(handled, false); + return null; + }) + .when(mockView) + .redispatch(any(KeyEvent.class)); + + keyboardManager = new KeyboardManager(mockView); + } + + public @Mock KeyboardManager.ViewDelegate mockView; + public KeyboardManager keyboardManager; + + /** Set channel calls to respond immediately with the given response. */ + public void respondToChannelCallsWith(boolean handled) { + channelHandler = + (JSONObject data, Consumer reply) -> { + if (reply != null) { + reply.accept(handled); + } + }; + } + + /** + * Record channel calls to the given storage. + * + *

They are not responded to until the stored callbacks are manually called. + */ + public void recordChannelCallsTo(@NonNull ArrayList storage) { + channelHandler = + (JSONObject data, Consumer reply) -> { + storage.add(CallRecord.channelCall(data, reply)); + }; + } + + /** Set embedder calls to respond immediately with the given response. */ + public void respondToEmbedderCallsWith(boolean handled) { + embedderHandler = + (KeyData keyData, Consumer reply) -> { + if (reply != null) { + reply.accept(handled); + } + }; + } + + /** + * Record embedder calls to the given storage. + * + *

They are not responded to until the stored callbacks are manually called. + */ + public void recordEmbedderCallsTo(@NonNull ArrayList storage) { + embedderHandler = + (KeyData keyData, Consumer reply) -> + storage.add(CallRecord.embedderCall(keyData, reply)); + } + + /** Set text calls to respond with the given response. */ + public void respondToTextInputWith(boolean response) { + textInputResult = response; + } + + private ChannelCallHandler channelHandler; + private EmbedderCallHandler embedderHandler; + private Boolean textInputResult; + + private Object onMessengerMessage(@NonNull InvocationOnMock invocation) { + final String channel = invocation.getArgument(0); + final ByteBuffer buffer = invocation.getArgument(1); + buffer.rewind(); + + final BinaryMessenger.BinaryReply reply = invocation.getArgument(2); + if (channel == "flutter/keyevent") { + // Parse a channel call. + final JSONObject jsonObject = (JSONObject) JSONMessageCodec.INSTANCE.decodeMessage(buffer); + final Consumer jsonReply = + reply == null ? null : handled -> reply.reply(buildJsonResponse(handled)); + channelHandler.accept(jsonObject, jsonReply); + } else if (channel == "flutter/keydata") { + // Parse an embedder call. + final KeyData keyData = new KeyData(buffer); + final Consumer booleanReply = + reply == null ? null : handled -> reply.reply(buildBinaryResponse(handled)); + embedderHandler.accept(keyData, booleanReply); + } else { + assertTrue(false); + } + return null; + } + } + + /** + * Assert that the channel call is an event that matches the given data. + * + *

For now this function only validates key code, but not scancode or characters. + * + * @param data the target data to be tested. + * @param type the type of the data, usually "keydown" or "keyup". + * @param keyCode the key code. + */ + static void assertChannelEventEquals( + @NonNull JSONObject message, @NonNull String type, @NonNull Integer keyCode) { + try { + assertEquals(type, message.get("type")); + assertEquals("android", message.get("keymap")); + assertEquals(keyCode, message.get("keyCode")); + } catch (JSONException e) { + assertNull(e); + } + } + + /** Assert that the embedder call is an event that matches the given data. */ + static void assertEmbedderEventEquals( + @NonNull KeyData data, + Type type, + long physicalKey, + long logicalKey, + String character, + boolean synthesized, + DeviceType deviceType) { + assertEquals(type, data.type); + assertEquals(physicalKey, data.physicalKey); + assertEquals(logicalKey, data.logicalKey); + assertEquals(character, data.character); + assertEquals(synthesized, data.synthesized); + assertEquals(deviceType, data.deviceType); + } + + static void verifyEmbedderEvents(List receivedCalls, KeyData[] expectedData) { + assertEquals(receivedCalls.size(), expectedData.length); + for (int idx = 0; idx < receivedCalls.size(); idx += 1) { + final KeyData data = expectedData[idx]; + assertEmbedderEventEquals( + receivedCalls.get(idx).keyData, + data.type, + data.physicalKey, + data.logicalKey, + data.character, + data.synthesized, + data.deviceType); + } + } + + static KeyData buildKeyData( + Type type, + long physicalKey, + long logicalKey, + @Nullable String characters, + boolean synthesized, + DeviceType deviceType) { + final KeyData result = new KeyData(); + result.physicalKey = physicalKey; + result.logicalKey = logicalKey; + result.timestamp = 0x0; + result.type = type; + result.character = characters; + result.synthesized = synthesized; + result.deviceType = deviceType; + return result; + } + + /** + * Start a new tester, generate a ShiftRight event under the specified condition, and return the + * output events for that event. + * + * @param preEventLeftPressed Whether ShiftLeft was recorded as pressed before the event. + * @param preEventRightPressed Whether ShiftRight was recorded as pressed before the event. + * @param rightEventIsDown Whether the dispatched event is a key down of key up of ShiftRight. + * @param truePressed Whether Shift is pressed as shown in the metaState of the event. + * @return + */ + public static List testShiftRightEvent( + boolean preEventLeftPressed, + boolean preEventRightPressed, + boolean rightEventIsDown, + boolean truePressed) { + final ArrayList calls = new ArrayList<>(); + // Even though the event is for ShiftRight, we still set SHIFT | SHIFT_LEFT here. + // See the comment in synchronizePressingKey for the reason. + final int SHIFT_LEFT_ON = META_SHIFT_LEFT_ON | META_SHIFT_ON; + + final KeyboardTester tester = new KeyboardTester(); + tester.respondToTextInputWith(true); // Suppress redispatching + if (preEventLeftPressed) { + tester.keyboardManager.handleEvent( + new FakeKeyEvent( + ACTION_DOWN, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', SHIFT_LEFT_ON)); + } + if (preEventRightPressed) { + tester.keyboardManager.handleEvent( + new FakeKeyEvent( + ACTION_DOWN, SCAN_SHIFT_RIGHT, KEYCODE_SHIFT_RIGHT, 0, '\0', SHIFT_LEFT_ON)); + } + tester.recordEmbedderCallsTo(calls); + tester.keyboardManager.handleEvent( + new FakeKeyEvent( + rightEventIsDown ? ACTION_DOWN : ACTION_UP, + SCAN_SHIFT_RIGHT, + KEYCODE_SHIFT_RIGHT, + 0, + '\0', + truePressed ? SHIFT_LEFT_ON : 0)); + return calls.stream() + .filter(data -> data.keyData.physicalKey != 0) + .collect(Collectors.toList()); + } + + public static KeyData buildShiftKeyData(boolean isLeft, boolean isDown, boolean isSynthesized) { + final KeyData data = new KeyData(); + data.type = isDown ? Type.kDown : Type.kUp; + data.physicalKey = isLeft ? PHYSICAL_SHIFT_LEFT : PHYSICAL_SHIFT_RIGHT; + data.logicalKey = isLeft ? LOGICAL_SHIFT_LEFT : LOGICAL_SHIFT_RIGHT; + data.synthesized = isSynthesized; + data.deviceType = KeyData.DeviceType.kKeyboard; + return data; + } + + /** + * Print each byte of the given buffer as a hex (such as "0a" for 0x0a), and return the + * concatenated string. + * + *

Used to compare binary content in byte buffers. + */ + static String printBufferBytes(@NonNull ByteBuffer buffer) { + final String[] results = new String[buffer.capacity()]; + for (int byteIdx = 0; byteIdx < buffer.capacity(); byteIdx += 1) { + results[byteIdx] = String.format("%02x", buffer.get(byteIdx)); + } + return String.join("", results); + } + + @Before + public void setUp() { + MockitoAnnotations.openMocks(this); + } + + // Tests start + + @Test + public void serializeAndDeserializeKeyData() { + // Test data1: Non-empty character, synthesized. + final KeyData data1 = new KeyData(); + data1.physicalKey = 0x0a; + data1.logicalKey = 0x0b; + data1.timestamp = 0x0c; + data1.type = Type.kRepeat; + data1.character = "A"; + data1.synthesized = true; + data1.deviceType = DeviceType.kKeyboard; + + final ByteBuffer data1Buffer = data1.toBytes(); + + assertEquals( + "" + + "0100000000000000" + + "0c00000000000000" + + "0200000000000000" + + "0a00000000000000" + + "0b00000000000000" + + "0100000000000000" + + "0000000000000000" + + "41", + printBufferBytes(data1Buffer)); + // `position` is considered as the message size. + assertEquals(57, data1Buffer.position()); + + data1Buffer.rewind(); + final KeyData data1Loaded = new KeyData(data1Buffer); + assertEquals(data1Loaded.timestamp, data1.timestamp); + + // Test data2: Empty character, not synthesized. + final KeyData data2 = new KeyData(); + data2.physicalKey = 0xaaaabbbbccccl; + data2.logicalKey = 0x666677778888l; + data2.timestamp = 0x333344445555l; + data2.type = Type.kUp; + data2.character = null; + data2.synthesized = false; + data2.deviceType = DeviceType.kDirectionalPad; + + final ByteBuffer data2Buffer = data2.toBytes(); + + assertEquals( + "" + + "0000000000000000" + + "5555444433330000" + + "0100000000000000" + + "ccccbbbbaaaa0000" + + "8888777766660000" + + "0000000000000000" + + "0100000000000000", + printBufferBytes(data2Buffer)); + + data2Buffer.rewind(); + final KeyData data2Loaded = new KeyData(data2Buffer); + assertEquals(data2Loaded.timestamp, data2.timestamp); + } + + @Test + public void basicCombingCharactersTest() { + final KeyboardManager.CharacterCombiner combiner = new KeyboardManager.CharacterCombiner(); + assertEquals(0, (int) combiner.applyCombiningCharacterToBaseCharacter(0)); + assertEquals('B', (int) combiner.applyCombiningCharacterToBaseCharacter('B')); + assertEquals('B', (int) combiner.applyCombiningCharacterToBaseCharacter('B')); + assertEquals('A', (int) combiner.applyCombiningCharacterToBaseCharacter('A')); + assertEquals(0, (int) combiner.applyCombiningCharacterToBaseCharacter(0)); + assertEquals(0, (int) combiner.applyCombiningCharacterToBaseCharacter(0)); + + assertEquals('`', (int) combiner.applyCombiningCharacterToBaseCharacter(DEAD_KEY)); + assertEquals('`', (int) combiner.applyCombiningCharacterToBaseCharacter(DEAD_KEY)); + assertEquals('À', (int) combiner.applyCombiningCharacterToBaseCharacter('A')); + + assertEquals('`', (int) combiner.applyCombiningCharacterToBaseCharacter(DEAD_KEY)); + assertEquals(0, (int) combiner.applyCombiningCharacterToBaseCharacter(0)); + // The 0 input should remove the combining state. + assertEquals('A', (int) combiner.applyCombiningCharacterToBaseCharacter('A')); + + assertEquals(0, (int) combiner.applyCombiningCharacterToBaseCharacter(0)); + assertEquals('`', (int) combiner.applyCombiningCharacterToBaseCharacter(DEAD_KEY)); + assertEquals('À', (int) combiner.applyCombiningCharacterToBaseCharacter('A')); + } + + @Test + public void respondsTrueWhenHandlingNewEvents() { + final KeyboardTester tester = new KeyboardTester(); + final KeyEvent keyEvent = new FakeKeyEvent(ACTION_DOWN, 65); + final ArrayList calls = new ArrayList<>(); + + tester.recordChannelCallsTo(calls); + + final boolean result = tester.keyboardManager.handleEvent(keyEvent); + + assertEquals(true, result); + assertEquals(calls.size(), 1); + assertChannelEventEquals(calls.get(0).channelObject, "keydown", 65); + + // Don't send the key event to the text plugin if the only primary responder + // hasn't responded. + verify(tester.mockView, times(0)).onTextInputKeyEvent(any(KeyEvent.class)); + verify(tester.mockView, times(0)).redispatch(any(KeyEvent.class)); + } + + @Test + public void channelResponderHandlesEvents() { + final KeyboardTester tester = new KeyboardTester(); + final KeyEvent keyEvent = new FakeKeyEvent(ACTION_DOWN, 65); + final ArrayList calls = new ArrayList<>(); + + tester.recordChannelCallsTo(calls); + + final boolean result = tester.keyboardManager.handleEvent(keyEvent); + + assertEquals(true, result); + assertEquals(calls.size(), 1); + assertChannelEventEquals(calls.get(0).channelObject, "keydown", 65); + + // Don't send the key event to the text plugin if the only primary responder + // hasn't responded. + verify(tester.mockView, times(0)).onTextInputKeyEvent(any(KeyEvent.class)); + verify(tester.mockView, times(0)).redispatch(any(KeyEvent.class)); + + // If a primary responder handles the key event the propagation stops. + assertNotNull(calls.get(0).reply); + calls.get(0).reply.accept(true); + verify(tester.mockView, times(0)).onTextInputKeyEvent(any(KeyEvent.class)); + verify(tester.mockView, times(0)).redispatch(any(KeyEvent.class)); + } + + @Test + public void embedderResponderHandlesEvents() { + final KeyboardTester tester = new KeyboardTester(); + final KeyEvent keyEvent = new FakeKeyEvent(ACTION_DOWN, SCAN_KEY_A, KEYCODE_A, 0, 'a', 0); + final ArrayList calls = new ArrayList<>(); + + tester.recordEmbedderCallsTo(calls); + + final boolean result = tester.keyboardManager.handleEvent(keyEvent); + + assertEquals(true, result); + assertEquals(calls.size(), 1); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kDown, + PHYSICAL_KEY_A, + LOGICAL_KEY_A, + "a", + false, + DeviceType.kKeyboard); + + // Don't send the key event to the text plugin if the only primary responder + // hasn't responded. + verify(tester.mockView, times(0)).onTextInputKeyEvent(any(KeyEvent.class)); + verify(tester.mockView, times(0)).redispatch(any(KeyEvent.class)); + + // If a primary responder handles the key event the propagation stops. + assertNotNull(calls.get(0).reply); + calls.get(0).reply.accept(true); + verify(tester.mockView, times(0)).onTextInputKeyEvent(any(KeyEvent.class)); + verify(tester.mockView, times(0)).redispatch(any(KeyEvent.class)); + } + + @Test + public void embedderResponderHandlesNullReply() { + // Regression test for https://github.com/flutter/flutter/issues/141662. + final BinaryMessenger mockMessenger = mock(BinaryMessenger.class); + doAnswer( + invocation -> { + final BinaryMessenger.BinaryReply reply = invocation.getArgument(2); + // Simulate a null reply. + // In release mode, a null reply might happen when the engine sends a message + // before the framework has started. + reply.reply(null); + return null; + }) + .when(mockMessenger) + .send(any(String.class), any(ByteBuffer.class), any(BinaryMessenger.BinaryReply.class)); + + final KeyboardManager.ViewDelegate mockView = mock(KeyboardManager.ViewDelegate.class); + doAnswer(invocation -> mockMessenger).when(mockView).getBinaryMessenger(); + + final KeyboardManager keyboardManager = new KeyboardManager(mockView); + final KeyEvent keyEvent = new FakeKeyEvent(ACTION_DOWN, SCAN_KEY_A, KEYCODE_A, 0, 'a', 0); + + boolean exceptionThrown = false; + try { + final boolean result = keyboardManager.handleEvent(keyEvent); + } catch (Exception exception) { + exceptionThrown = true; + } + + assertEquals(false, exceptionThrown); + } + + @Test + public void bothRespondersHandlesEvents() { + final KeyboardTester tester = new KeyboardTester(); + final ArrayList calls = new ArrayList<>(); + + tester.recordChannelCallsTo(calls); + tester.recordEmbedderCallsTo(calls); + tester.respondToTextInputWith(true); + + final boolean result = + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_DOWN, SCAN_KEY_A, KEYCODE_A, 0, 'a', 0)); + + assertEquals(true, result); + assertEquals(calls.size(), 2); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kDown, + PHYSICAL_KEY_A, + LOGICAL_KEY_A, + "a", + false, + DeviceType.kKeyboard); + assertChannelEventEquals(calls.get(1).channelObject, "keydown", KEYCODE_A); + + verify(tester.mockView, times(0)).onTextInputKeyEvent(any(KeyEvent.class)); + verify(tester.mockView, times(0)).redispatch(any(KeyEvent.class)); + + calls.get(0).reply.accept(true); + verify(tester.mockView, times(0)).onTextInputKeyEvent(any(KeyEvent.class)); + verify(tester.mockView, times(0)).redispatch(any(KeyEvent.class)); + + calls.get(1).reply.accept(true); + verify(tester.mockView, times(0)).onTextInputKeyEvent(any(KeyEvent.class)); + verify(tester.mockView, times(0)).redispatch(any(KeyEvent.class)); + } + + @Test + public void textInputHandlesEventsIfNoRespondersDo() { + final KeyboardTester tester = new KeyboardTester(); + final KeyEvent keyEvent = new FakeKeyEvent(ACTION_DOWN, 65); + final ArrayList calls = new ArrayList<>(); + + tester.recordChannelCallsTo(calls); + + final boolean result = tester.keyboardManager.handleEvent(keyEvent); + + assertEquals(true, result); + assertEquals(calls.size(), 1); + assertChannelEventEquals(calls.get(0).channelObject, "keydown", 65); + + // Don't send the key event to the text plugin if the only primary responder + // hasn't responded. + verify(tester.mockView, times(0)).onTextInputKeyEvent(any(KeyEvent.class)); + verify(tester.mockView, times(0)).redispatch(any(KeyEvent.class)); + + // If no primary responder handles the key event the propagates to the text + // input plugin. + assertNotNull(calls.get(0).reply); + // Let text input plugin handle the key event. + tester.respondToTextInputWith(true); + calls.get(0).reply.accept(false); + + verify(tester.mockView, times(1)).onTextInputKeyEvent(keyEvent); + verify(tester.mockView, times(0)).redispatch(any(KeyEvent.class)); + } + + @Test + public void redispatchEventsIfTextInputDoesntHandle() { + final KeyboardTester tester = new KeyboardTester(); + final KeyEvent keyEvent = new FakeKeyEvent(ACTION_DOWN, 65); + final ArrayList calls = new ArrayList<>(); + + tester.recordChannelCallsTo(calls); + + final boolean result = tester.keyboardManager.handleEvent(keyEvent); + + assertEquals(true, result); + assertEquals(calls.size(), 1); + assertChannelEventEquals(calls.get(0).channelObject, "keydown", 65); + + // Don't send the key event to the text plugin if the only primary responder + // hasn't responded. + verify(tester.mockView, times(0)).onTextInputKeyEvent(any(KeyEvent.class)); + verify(tester.mockView, times(0)).redispatch(any(KeyEvent.class)); + + // Neither the primary responders nor text input plugin handles the event. + tester.respondToTextInputWith(false); + calls.get(0).reply.accept(false); + + verify(tester.mockView, times(1)).onTextInputKeyEvent(keyEvent); + verify(tester.mockView, times(1)).redispatch(keyEvent); + } + + @Test + public void redispatchedEventsAreCorrectlySkipped() { + final KeyboardTester tester = new KeyboardTester(); + final ArrayList calls = new ArrayList<>(); + + tester.recordChannelCallsTo(calls); + + final KeyEvent keyEvent = new FakeKeyEvent(ACTION_DOWN, 65); + final boolean result = tester.keyboardManager.handleEvent(keyEvent); + + assertEquals(true, result); + assertEquals(calls.size(), 1); + assertChannelEventEquals(calls.get(0).channelObject, "keydown", 65); + + // Don't send the key event to the text plugin if the only primary responder + // hasn't responded. + verify(tester.mockView, times(0)).onTextInputKeyEvent(any(KeyEvent.class)); + verify(tester.mockView, times(0)).redispatch(any(KeyEvent.class)); + + // Neither the primary responders nor text input plugin handles the event. + tester.respondToTextInputWith(false); + calls.get(0).reply.accept(false); + + verify(tester.mockView, times(1)).onTextInputKeyEvent(keyEvent); + verify(tester.mockView, times(1)).redispatch(keyEvent); + + // It's redispatched to the keyboard manager, but no eventual key calls. + assertEquals(calls.size(), 1); + } + + @Test + public void tapLowerA() { + final KeyboardTester tester = new KeyboardTester(); + final ArrayList calls = new ArrayList<>(); + + tester.recordEmbedderCallsTo(calls); + tester.respondToTextInputWith(true); // Suppress redispatching + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_DOWN, SCAN_KEY_A, KEYCODE_A, 0, 'a', 0))); + + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData(Type.kDown, PHYSICAL_KEY_A, LOGICAL_KEY_A, "a", false, DeviceType.kKeyboard), + }); + calls.clear(); + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_DOWN, SCAN_KEY_A, KEYCODE_A, 1, 'a', 0))); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData( + Type.kRepeat, PHYSICAL_KEY_A, LOGICAL_KEY_A, "a", false, DeviceType.kKeyboard), + }); + calls.clear(); + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_UP, SCAN_KEY_A, KEYCODE_A, 0, 'a', 0))); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData(Type.kUp, PHYSICAL_KEY_A, LOGICAL_KEY_A, null, false, DeviceType.kKeyboard), + }); + calls.clear(); + } + + @Test + public void tapUpperA() { + final KeyboardTester tester = new KeyboardTester(); + final ArrayList calls = new ArrayList<>(); + + tester.recordEmbedderCallsTo(calls); + tester.respondToTextInputWith(true); // Suppress redispatching + + // ShiftLeft + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_DOWN, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', 0x41))); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData( + Type.kDown, + PHYSICAL_SHIFT_LEFT, + LOGICAL_SHIFT_LEFT, + null, + false, + DeviceType.kKeyboard), + }); + calls.clear(); + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_DOWN, SCAN_KEY_A, KEYCODE_A, 0, 'A', 0x41))); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData(Type.kDown, PHYSICAL_KEY_A, LOGICAL_KEY_A, "A", false, DeviceType.kKeyboard), + }); + calls.clear(); + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_UP, SCAN_KEY_A, KEYCODE_A, 0, 'A', 0x41))); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData(Type.kUp, PHYSICAL_KEY_A, LOGICAL_KEY_A, null, false, DeviceType.kKeyboard), + }); + calls.clear(); + + // ShiftLeft + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_UP, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', 0))); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData( + Type.kUp, PHYSICAL_SHIFT_LEFT, LOGICAL_SHIFT_LEFT, null, false, DeviceType.kKeyboard), + }); + calls.clear(); + } + + @Test + public void eventsWithMintedCodes() { + final KeyboardTester tester = new KeyboardTester(); + final ArrayList calls = new ArrayList<>(); + + tester.recordEmbedderCallsTo(calls); + tester.respondToTextInputWith(true); // Suppress redispatching + + // Zero scan code. + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_DOWN, 0, KEYCODE_ENTER, 0, '\n', 0))); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData(Type.kDown, 0x1100000042L, LOGICAL_ENTER, "\n", false, DeviceType.kKeyboard), + }); + calls.clear(); + + // Zero scan code and zero key code. + assertEquals( + true, tester.keyboardManager.handleEvent(new FakeKeyEvent(ACTION_DOWN, 0, 0, 0, '\0', 0))); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData(Type.kDown, 0, 0, null, true, DeviceType.kKeyboard), + }); + calls.clear(); + + // Unrecognized scan code. (Fictional test) + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_DOWN, 0xDEADBEEF, 0, 0, '\0', 0))); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData(Type.kDown, 0x11DEADBEEFL, 0x1100000000L, null, false, DeviceType.kKeyboard), + }); + calls.clear(); + + // Zero key code. (Fictional test; I have yet to find a real case.) + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_DOWN, SCAN_ARROW_LEFT, 0, 0, '\0', 0))); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData( + Type.kDown, PHYSICAL_ARROW_LEFT, 0x1100000000L, null, false, DeviceType.kKeyboard), + }); + calls.clear(); + + // Unrecognized key code. (Fictional test) + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_DOWN, SCAN_ARROW_RIGHT, 0xDEADBEEF, 0, '\0', 0))); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData( + Type.kDown, PHYSICAL_ARROW_RIGHT, 0x11DEADBEEFL, null, false, DeviceType.kKeyboard), + }); + calls.clear(); + } + + @Test + public void duplicateDownEventsArePrecededBySynthesizedUpEvents() { + final KeyboardTester tester = new KeyboardTester(); + final ArrayList calls = new ArrayList<>(); + + tester.recordEmbedderCallsTo(calls); + tester.respondToTextInputWith(true); // Suppress redispatching + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_DOWN, SCAN_KEY_A, KEYCODE_A, 0, 'a', 0))); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData(Type.kDown, PHYSICAL_KEY_A, LOGICAL_KEY_A, "a", false, DeviceType.kKeyboard), + }); + calls.clear(); + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_DOWN, SCAN_KEY_A, KEYCODE_A, 0, 'a', 0))); + assertEquals(calls.size(), 2); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kUp, + PHYSICAL_KEY_A, + LOGICAL_KEY_A, + null, + true, + DeviceType.kKeyboard); + assertEmbedderEventEquals( + calls.get(1).keyData, + Type.kDown, + PHYSICAL_KEY_A, + LOGICAL_KEY_A, + "a", + false, + DeviceType.kKeyboard); + calls.clear(); + } + + @Test + public void abruptUpEventsAreIgnored() { + final KeyboardTester tester = new KeyboardTester(); + final ArrayList calls = new ArrayList<>(); + + tester.recordEmbedderCallsTo(calls); + tester.respondToTextInputWith(true); // Suppress redispatching + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_UP, SCAN_KEY_A, KEYCODE_A, 0, 'a', 0))); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData(Type.kDown, 0l, 0l, null, true, DeviceType.kKeyboard), + }); + calls.clear(); + } + + @Test + public void modifierKeys() { + final KeyboardTester tester = new KeyboardTester(); + final ArrayList calls = new ArrayList<>(); + + tester.recordEmbedderCallsTo(calls); + tester.respondToTextInputWith(true); // Suppress redispatching + + // ShiftLeft + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_DOWN, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', 0x41)); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData( + Type.kDown, + PHYSICAL_SHIFT_LEFT, + LOGICAL_SHIFT_LEFT, + null, + false, + DeviceType.kKeyboard), + }); + calls.clear(); + + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_UP, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', 0)); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData( + Type.kUp, PHYSICAL_SHIFT_LEFT, LOGICAL_SHIFT_LEFT, null, false, DeviceType.kKeyboard), + }); + calls.clear(); + + // ShiftRight + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_DOWN, SCAN_SHIFT_RIGHT, KEYCODE_SHIFT_RIGHT, 0, '\0', 0x41)); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData( + Type.kDown, + PHYSICAL_SHIFT_RIGHT, + LOGICAL_SHIFT_RIGHT, + null, + false, + DeviceType.kKeyboard), + }); + calls.clear(); + + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_UP, SCAN_SHIFT_RIGHT, KEYCODE_SHIFT_RIGHT, 0, '\0', 0)); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData( + Type.kUp, + PHYSICAL_SHIFT_RIGHT, + LOGICAL_SHIFT_RIGHT, + null, + false, + DeviceType.kKeyboard), + }); + calls.clear(); + + // ControlLeft + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_DOWN, SCAN_CONTROL_LEFT, KEYCODE_CTRL_LEFT, 0, '\0', 0x3000)); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData( + Type.kDown, + PHYSICAL_CONTROL_LEFT, + LOGICAL_CONTROL_LEFT, + null, + false, + DeviceType.kKeyboard), + }); + calls.clear(); + + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_UP, SCAN_CONTROL_LEFT, KEYCODE_CTRL_LEFT, 0, '\0', 0)); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData( + Type.kUp, + PHYSICAL_CONTROL_LEFT, + LOGICAL_CONTROL_LEFT, + null, + false, + DeviceType.kKeyboard), + }); + calls.clear(); + + // ControlRight + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_DOWN, SCAN_CONTROL_RIGHT, KEYCODE_CTRL_RIGHT, 0, '\0', 0x3000)); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData( + Type.kDown, + PHYSICAL_CONTROL_RIGHT, + LOGICAL_CONTROL_RIGHT, + null, + false, + DeviceType.kKeyboard), + }); + calls.clear(); + + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_UP, SCAN_CONTROL_RIGHT, KEYCODE_CTRL_RIGHT, 0, '\0', 0)); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData( + Type.kUp, + PHYSICAL_CONTROL_RIGHT, + LOGICAL_CONTROL_RIGHT, + null, + false, + DeviceType.kKeyboard), + }); + calls.clear(); + + // AltLeft + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_DOWN, SCAN_ALT_LEFT, KEYCODE_ALT_LEFT, 0, '\0', 0x12)); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData( + Type.kDown, PHYSICAL_ALT_LEFT, LOGICAL_ALT_LEFT, null, false, DeviceType.kKeyboard), + }); + calls.clear(); + + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_UP, SCAN_ALT_LEFT, KEYCODE_ALT_LEFT, 0, '\0', 0)); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData( + Type.kUp, PHYSICAL_ALT_LEFT, LOGICAL_ALT_LEFT, null, false, DeviceType.kKeyboard), + }); + calls.clear(); + + // AltRight + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_DOWN, SCAN_ALT_RIGHT, KEYCODE_ALT_RIGHT, 0, '\0', 0x12)); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData( + Type.kDown, PHYSICAL_ALT_RIGHT, LOGICAL_ALT_RIGHT, null, false, DeviceType.kKeyboard), + }); + calls.clear(); + + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_UP, SCAN_ALT_RIGHT, KEYCODE_ALT_RIGHT, 0, '\0', 0)); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData( + Type.kUp, PHYSICAL_ALT_RIGHT, LOGICAL_ALT_RIGHT, null, false, DeviceType.kKeyboard), + }); + calls.clear(); + } + + @Test + public void nonUsKeys() { + final KeyboardTester tester = new KeyboardTester(); + final ArrayList calls = new ArrayList<>(); + + tester.recordEmbedderCallsTo(calls); + tester.respondToTextInputWith(true); // Suppress redispatching + + // French 1 + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_DOWN, SCAN_DIGIT1, KEYCODE_1, 0, '1', 0)); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData( + Type.kDown, PHYSICAL_DIGIT1, LOGICAL_DIGIT1, "1", false, DeviceType.kKeyboard), + }); + calls.clear(); + + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_UP, SCAN_DIGIT1, KEYCODE_1, 0, '1', 0)); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData( + Type.kUp, PHYSICAL_DIGIT1, LOGICAL_DIGIT1, null, false, DeviceType.kKeyboard), + }); + calls.clear(); + + // French Shift-1 + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_DOWN, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', 0x41)); + calls.clear(); + + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_DOWN, SCAN_DIGIT1, KEYCODE_1, 0, '&', 0x41)); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData( + Type.kDown, PHYSICAL_DIGIT1, LOGICAL_DIGIT1, "&", false, DeviceType.kKeyboard), + }); + calls.clear(); + + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_UP, SCAN_DIGIT1, KEYCODE_1, 0, '&', 0x41)); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData( + Type.kUp, PHYSICAL_DIGIT1, LOGICAL_DIGIT1, null, false, DeviceType.kKeyboard), + }); + calls.clear(); + + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_UP, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', 0)); + calls.clear(); + + // Russian lowerA + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_DOWN, SCAN_KEY_A, KEYCODE_A, 0, '\u0444', 0)); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData(Type.kDown, PHYSICAL_KEY_A, LOGICAL_KEY_A, "ф", false, DeviceType.kKeyboard), + }); + calls.clear(); + + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_UP, SCAN_KEY_A, KEYCODE_A, 0, '\u0444', 0)); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData(Type.kUp, PHYSICAL_KEY_A, LOGICAL_KEY_A, null, false, DeviceType.kKeyboard), + }); + calls.clear(); + } + + @Test + public void synchronizeShiftLeftDuringForeignKeyEvents() { + // Test if ShiftLeft can be synchronized during events of ArrowLeft. + final KeyboardTester tester = new KeyboardTester(); + final ArrayList calls = new ArrayList<>(); + + tester.recordEmbedderCallsTo(calls); + tester.respondToTextInputWith(true); // Suppress redispatching + + final int SHIFT_LEFT_ON = META_SHIFT_LEFT_ON | META_SHIFT_ON; + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent( + ACTION_DOWN, SCAN_ARROW_LEFT, KEYCODE_DPAD_LEFT, 0, '\0', SHIFT_LEFT_ON))); + assertEquals(calls.size(), 2); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kDown, + PHYSICAL_SHIFT_LEFT, + LOGICAL_SHIFT_LEFT, + null, + true, + DeviceType.kKeyboard); + calls.clear(); + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_UP, SCAN_ARROW_LEFT, KEYCODE_DPAD_LEFT, 0, '\0', 0))); + assertEquals(calls.size(), 2); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kUp, + PHYSICAL_SHIFT_LEFT, + LOGICAL_SHIFT_LEFT, + null, + true, + DeviceType.kKeyboard); + calls.clear(); + } + + @Test + public void synchronizeShiftLeftDuringSelfKeyEvents() { + // Test if ShiftLeft can be synchronized during events of ShiftLeft. + final KeyboardTester tester = new KeyboardTester(); + final ArrayList calls = new ArrayList<>(); + + tester.recordEmbedderCallsTo(calls); + tester.respondToTextInputWith(true); // Suppress redispatching + + final int SHIFT_LEFT_ON = META_SHIFT_LEFT_ON | META_SHIFT_ON; + // All 6 cases (3 types x 2 states) are arranged in the following order so that the starting + // states for each case are the desired states. + + // Repeat event when current state is 0. + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent( + ACTION_DOWN, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 1, '\0', SHIFT_LEFT_ON))); + assertEquals(calls.size(), 1); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kDown, + PHYSICAL_SHIFT_LEFT, + LOGICAL_SHIFT_LEFT, + null, + false, + DeviceType.kKeyboard); + calls.clear(); + + // Down event when the current state is 1. + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent( + ACTION_DOWN, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', SHIFT_LEFT_ON))); + assertEquals(calls.size(), 2); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kUp, + PHYSICAL_SHIFT_LEFT, + LOGICAL_SHIFT_LEFT, + null, + true, + DeviceType.kKeyboard); + assertEmbedderEventEquals( + calls.get(1).keyData, + Type.kDown, + PHYSICAL_SHIFT_LEFT, + LOGICAL_SHIFT_LEFT, + null, + false, + DeviceType.kKeyboard); + calls.clear(); + + // Up event when the current state is 1. + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_UP, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', 0))); + assertEquals(calls.size(), 1); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kUp, + PHYSICAL_SHIFT_LEFT, + LOGICAL_SHIFT_LEFT, + null, + false, + DeviceType.kKeyboard); + calls.clear(); + + // Up event when the current state is 0. + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_UP, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', 0))); + assertEquals(calls.size(), 1); + assertEmbedderEventEquals( + calls.get(0).keyData, Type.kDown, 0l, 0l, null, true, DeviceType.kKeyboard); + calls.clear(); + + // Down event when the current state is 0. + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent( + ACTION_DOWN, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', SHIFT_LEFT_ON))); + assertEquals(calls.size(), 1); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kDown, + PHYSICAL_SHIFT_LEFT, + LOGICAL_SHIFT_LEFT, + null, + false, + DeviceType.kKeyboard); + calls.clear(); + + // Repeat event when the current state is 1. + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent( + ACTION_DOWN, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 1, '\0', SHIFT_LEFT_ON))); + assertEquals(calls.size(), 1); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kRepeat, + PHYSICAL_SHIFT_LEFT, + LOGICAL_SHIFT_LEFT, + null, + false, + DeviceType.kKeyboard); + calls.clear(); + } + + @Test + public void synchronizeShiftLeftDuringSiblingKeyEvents() { + // Test if ShiftLeft can be synchronized during events of ShiftRight. The following events seem + // to have weird metaStates that don't follow Android's documentation (always using left masks) + // but are indeed observed on ChromeOS. + + // UP_EVENT, truePressed: false + + verifyEmbedderEvents(testShiftRightEvent(false, false, UP_EVENT, false), new KeyData[] {}); + verifyEmbedderEvents( + testShiftRightEvent(false, true, UP_EVENT, false), + new KeyData[] { + buildShiftKeyData(SHIFT_RIGHT_EVENT, UP_EVENT, false), + }); + verifyEmbedderEvents( + testShiftRightEvent(true, false, UP_EVENT, false), + new KeyData[] { + buildShiftKeyData(SHIFT_LEFT_EVENT, UP_EVENT, true), + }); + verifyEmbedderEvents( + testShiftRightEvent(true, true, UP_EVENT, false), + new KeyData[] { + buildShiftKeyData(SHIFT_LEFT_EVENT, UP_EVENT, true), + buildShiftKeyData(SHIFT_RIGHT_EVENT, UP_EVENT, false), + }); + + // UP_EVENT, truePressed: true + + verifyEmbedderEvents( + testShiftRightEvent(false, false, UP_EVENT, true), + new KeyData[] { + buildShiftKeyData(SHIFT_LEFT_EVENT, DOWN_EVENT, true), + }); + verifyEmbedderEvents( + testShiftRightEvent(false, true, UP_EVENT, true), + new KeyData[] { + buildShiftKeyData(SHIFT_LEFT_EVENT, DOWN_EVENT, true), + buildShiftKeyData(SHIFT_RIGHT_EVENT, UP_EVENT, false), + }); + verifyEmbedderEvents(testShiftRightEvent(true, false, UP_EVENT, true), new KeyData[] {}); + verifyEmbedderEvents( + testShiftRightEvent(true, true, UP_EVENT, true), + new KeyData[] { + buildShiftKeyData(SHIFT_RIGHT_EVENT, UP_EVENT, false), + }); + + // DOWN_EVENT, truePressed: false - skipped, because they're impossible. + + // DOWN_EVENT, truePressed: true + + verifyEmbedderEvents( + testShiftRightEvent(false, false, DOWN_EVENT, true), + new KeyData[] { + buildShiftKeyData(SHIFT_RIGHT_EVENT, DOWN_EVENT, false), + }); + verifyEmbedderEvents( + testShiftRightEvent(false, true, DOWN_EVENT, true), + new KeyData[] { + buildShiftKeyData(SHIFT_RIGHT_EVENT, UP_EVENT, true), + buildShiftKeyData(SHIFT_RIGHT_EVENT, DOWN_EVENT, false), + }); + verifyEmbedderEvents( + testShiftRightEvent(true, false, DOWN_EVENT, true), + new KeyData[] { + buildShiftKeyData(SHIFT_RIGHT_EVENT, DOWN_EVENT, false), + }); + verifyEmbedderEvents( + testShiftRightEvent(true, true, DOWN_EVENT, true), + new KeyData[] { + buildShiftKeyData(SHIFT_RIGHT_EVENT, UP_EVENT, true), + buildShiftKeyData(SHIFT_RIGHT_EVENT, DOWN_EVENT, false), + }); + } + + @Test + public void synchronizeOtherModifiers() { + // Test if other modifiers can be synchronized during events of ArrowLeft. Only the minimal + // cases are used here since the full logic has been tested on ShiftLeft. + final KeyboardTester tester = new KeyboardTester(); + final ArrayList calls = new ArrayList<>(); + + tester.recordEmbedderCallsTo(calls); + tester.respondToTextInputWith(true); // Suppress redispatching + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent( + ACTION_DOWN, SCAN_ARROW_LEFT, KEYCODE_DPAD_LEFT, 0, '\0', META_CTRL_ON))); + assertEquals(calls.size(), 2); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kDown, + PHYSICAL_CONTROL_LEFT, + LOGICAL_CONTROL_LEFT, + null, + true, + DeviceType.kKeyboard); + calls.clear(); + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_UP, SCAN_ARROW_LEFT, KEYCODE_DPAD_LEFT, 0, '\0', 0))); + assertEquals(calls.size(), 2); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kUp, + PHYSICAL_CONTROL_LEFT, + LOGICAL_CONTROL_LEFT, + null, + true, + DeviceType.kKeyboard); + calls.clear(); + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent( + ACTION_DOWN, SCAN_ARROW_LEFT, KEYCODE_DPAD_LEFT, 0, '\0', META_ALT_ON))); + assertEquals(calls.size(), 2); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kDown, + PHYSICAL_ALT_LEFT, + LOGICAL_ALT_LEFT, + null, + true, + DeviceType.kKeyboard); + calls.clear(); + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_UP, SCAN_ARROW_LEFT, KEYCODE_DPAD_LEFT, 0, '\0', 0))); + assertEquals(calls.size(), 2); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kUp, + PHYSICAL_ALT_LEFT, + LOGICAL_ALT_LEFT, + null, + true, + DeviceType.kKeyboard); + calls.clear(); + } + + // Regression test for https://github.com/flutter/flutter/issues/108124 + @Test + public void synchronizeModifiersForConflictingMetaState() { + // Test if ShiftLeft can be correctly synchronized during down events of + // ShiftLeft that have 0 for their metaState. + final KeyboardTester tester = new KeyboardTester(); + final ArrayList calls = new ArrayList<>(); + // Even though the event is for ShiftRight, we still set SHIFT | SHIFT_LEFT here. + // See the comment in synchronizePressingKey for the reason. + final int SHIFT_LEFT_ON = META_SHIFT_LEFT_ON | META_SHIFT_ON; + + tester.recordEmbedderCallsTo(calls); + tester.respondToTextInputWith(true); // Suppress redispatching + + // Test: Down event when the current state is 0. + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_DOWN, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', 0))); + assertEquals(calls.size(), 2); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kDown, + PHYSICAL_SHIFT_LEFT, + LOGICAL_SHIFT_LEFT, + null, + false, + DeviceType.kKeyboard); + assertEmbedderEventEquals( + calls.get(1).keyData, + Type.kUp, + PHYSICAL_SHIFT_LEFT, + LOGICAL_SHIFT_LEFT, + null, + true, + DeviceType.kKeyboard); + calls.clear(); + + // A normal down event. + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent( + ACTION_DOWN, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 0, '\0', SHIFT_LEFT_ON))); + assertEquals(calls.size(), 1); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kDown, + PHYSICAL_SHIFT_LEFT, + LOGICAL_SHIFT_LEFT, + null, + false, + DeviceType.kKeyboard); + calls.clear(); + + // Test: Repeat event when the current state is 0. + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_DOWN, SCAN_SHIFT_LEFT, KEYCODE_SHIFT_LEFT, 1, '\0', 0))); + assertEquals(calls.size(), 2); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kRepeat, + PHYSICAL_SHIFT_LEFT, + LOGICAL_SHIFT_LEFT, + null, + false, + DeviceType.kKeyboard); + assertEmbedderEventEquals( + calls.get(1).keyData, + Type.kUp, + PHYSICAL_SHIFT_LEFT, + LOGICAL_SHIFT_LEFT, + null, + true, + DeviceType.kKeyboard); + calls.clear(); + } + + // Regression test for https://github.com/flutter/flutter/issues/110640 + @Test + public void synchronizeModifiersForZeroedScanCode() { + // Test if ShiftLeft can be correctly synchronized during down events of + // ShiftLeft that have 0 for their metaState and 0 for their scanCode. + final KeyboardTester tester = new KeyboardTester(); + final ArrayList calls = new ArrayList<>(); + + tester.recordEmbedderCallsTo(calls); + tester.respondToTextInputWith(true); // Suppress redispatching + + // Test: DOWN event when the current state is 0 and scanCode is 0. + final KeyEvent keyEvent = new FakeKeyEvent(ACTION_DOWN, 0, KEYCODE_SHIFT_LEFT, 0, '\0', 0); + // Compute physicalKey in the same way as KeyboardManager.getPhysicalKey. + final Long physicalKey = KEYCODE_SHIFT_LEFT | KeyboardMap.kAndroidPlane; + + assertEquals(tester.keyboardManager.handleEvent(keyEvent), true); + assertEquals(calls.size(), 2); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kDown, + physicalKey, + LOGICAL_SHIFT_LEFT, + null, + false, + DeviceType.kKeyboard); + assertEmbedderEventEquals( + calls.get(1).keyData, + Type.kUp, + physicalKey, + LOGICAL_SHIFT_LEFT, + null, + true, + DeviceType.kKeyboard); + calls.clear(); + } + + // Regression test for https://github.com/flutter/flutter/issues/164626. + @Test + public void synchronizeModifiersForZeroedScanCodeOnRepeatEvent() { + // Test if ShiftLeft can be correctly synchronized during down events of + // ShiftLeft that have 0 for their metaState and 0 for their scanCode. + final KeyboardTester tester = new KeyboardTester(); + final ArrayList calls = new ArrayList<>(); + + tester.recordEmbedderCallsTo(calls); + tester.respondToTextInputWith(true); // Suppress redispatching + + // Test: repeat event when the meta state is 0 and scanCode is 0. + final KeyEvent shiftLeftKeyEvent = + new FakeKeyEvent(ACTION_DOWN, 0, KEYCODE_SHIFT_LEFT, 1, '\0', 0); + // Compute physicalKey in the same way as KeyboardManager.getPhysicalKey. + final Long shiftLeftPhysicalKey = KEYCODE_SHIFT_LEFT | KeyboardMap.kAndroidPlane; + + assertEquals(tester.keyboardManager.handleEvent(shiftLeftKeyEvent), true); + assertEquals(calls.size(), 2); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kDown, + shiftLeftPhysicalKey, + LOGICAL_SHIFT_LEFT, + null, + false, + DeviceType.kKeyboard); + assertEmbedderEventEquals( + calls.get(1).keyData, + Type.kUp, + shiftLeftPhysicalKey, + LOGICAL_SHIFT_LEFT, + null, + true, + DeviceType.kKeyboard); + calls.clear(); + + // Similar check for AltLeft. + final KeyEvent altLeftKeyEvent = new FakeKeyEvent(ACTION_DOWN, 0, KEYCODE_ALT_LEFT, 1, '\0', 0); + final Long altLeftPhysicalKey = KEYCODE_ALT_LEFT | KeyboardMap.kAndroidPlane; + + assertEquals(tester.keyboardManager.handleEvent(altLeftKeyEvent), true); + assertEquals(calls.size(), 2); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kDown, + altLeftPhysicalKey, + LOGICAL_ALT_LEFT, + null, + false, + DeviceType.kKeyboard); + assertEmbedderEventEquals( + calls.get(1).keyData, + Type.kUp, + altLeftPhysicalKey, + LOGICAL_ALT_LEFT, + null, + true, + DeviceType.kKeyboard); + calls.clear(); + } + + @Test + public void normalCapsLockEvents() { + final KeyboardTester tester = new KeyboardTester(); + final ArrayList calls = new ArrayList<>(); + + tester.recordEmbedderCallsTo(calls); + tester.respondToTextInputWith(true); // Suppress redispatching + + // The following two events seem to have weird metaStates that don't follow Android's + // documentation (CapsLock flag set on down events) but are indeed observed on ChromeOS. + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent( + ACTION_DOWN, SCAN_CAPS_LOCK, KEYCODE_CAPS_LOCK, 0, '\0', META_CAPS_LOCK_ON))); + assertEquals(calls.size(), 1); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kDown, + PHYSICAL_CAPS_LOCK, + LOGICAL_CAPS_LOCK, + null, + false, + DeviceType.kKeyboard); + calls.clear(); + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_UP, SCAN_CAPS_LOCK, KEYCODE_CAPS_LOCK, 0, '\0', 0))); + assertEquals(calls.size(), 1); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kUp, + PHYSICAL_CAPS_LOCK, + LOGICAL_CAPS_LOCK, + null, + false, + DeviceType.kKeyboard); + calls.clear(); + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent( + ACTION_DOWN, SCAN_ARROW_LEFT, KEYCODE_DPAD_LEFT, 0, '\0', META_CAPS_LOCK_ON))); + assertEquals(calls.size(), 1); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kDown, + PHYSICAL_ARROW_LEFT, + LOGICAL_ARROW_LEFT, + null, + false, + DeviceType.kKeyboard); + calls.clear(); + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent( + ACTION_UP, SCAN_ARROW_LEFT, KEYCODE_DPAD_LEFT, 0, '\0', META_CAPS_LOCK_ON))); + assertEquals(calls.size(), 1); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kUp, + PHYSICAL_ARROW_LEFT, + LOGICAL_ARROW_LEFT, + null, + false, + DeviceType.kKeyboard); + calls.clear(); + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent( + ACTION_DOWN, SCAN_CAPS_LOCK, KEYCODE_CAPS_LOCK, 0, '\0', META_CAPS_LOCK_ON))); + assertEquals(calls.size(), 1); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kDown, + PHYSICAL_CAPS_LOCK, + LOGICAL_CAPS_LOCK, + null, + false, + DeviceType.kKeyboard); + calls.clear(); + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_UP, SCAN_CAPS_LOCK, KEYCODE_CAPS_LOCK, 0, '\0', 0))); + assertEquals(calls.size(), 1); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kUp, + PHYSICAL_CAPS_LOCK, + LOGICAL_CAPS_LOCK, + null, + false, + DeviceType.kKeyboard); + calls.clear(); + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_DOWN, SCAN_ARROW_LEFT, KEYCODE_DPAD_LEFT, 0, '\0', 0))); + assertEquals(calls.size(), 1); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kDown, + PHYSICAL_ARROW_LEFT, + LOGICAL_ARROW_LEFT, + null, + false, + DeviceType.kKeyboard); + calls.clear(); + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_UP, SCAN_ARROW_LEFT, KEYCODE_DPAD_LEFT, 0, '\0', 0))); + assertEquals(calls.size(), 1); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kUp, + PHYSICAL_ARROW_LEFT, + LOGICAL_ARROW_LEFT, + null, + false, + DeviceType.kKeyboard); + calls.clear(); + } + + @Test + public void synchronizeCapsLock() { + final KeyboardTester tester = new KeyboardTester(); + final ArrayList calls = new ArrayList<>(); + + tester.recordEmbedderCallsTo(calls); + tester.respondToTextInputWith(true); // Suppress redispatching + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent( + ACTION_DOWN, SCAN_ARROW_LEFT, KEYCODE_DPAD_LEFT, 0, '\0', META_CAPS_LOCK_ON))); + assertEquals(calls.size(), 3); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kDown, + PHYSICAL_CAPS_LOCK, + LOGICAL_CAPS_LOCK, + null, + true, + DeviceType.kKeyboard); + assertEmbedderEventEquals( + calls.get(1).keyData, + Type.kUp, + PHYSICAL_CAPS_LOCK, + LOGICAL_CAPS_LOCK, + null, + true, + DeviceType.kKeyboard); + assertEmbedderEventEquals( + calls.get(2).keyData, + Type.kDown, + PHYSICAL_ARROW_LEFT, + LOGICAL_ARROW_LEFT, + null, + false, + DeviceType.kKeyboard); + calls.clear(); + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent( + ACTION_DOWN, SCAN_CAPS_LOCK, KEYCODE_CAPS_LOCK, 0, '\0', META_CAPS_LOCK_ON))); + assertEquals(calls.size(), 1); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kDown, + PHYSICAL_CAPS_LOCK, + LOGICAL_CAPS_LOCK, + null, + false, + DeviceType.kKeyboard); + calls.clear(); + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent( + ACTION_UP, SCAN_ARROW_LEFT, KEYCODE_DPAD_LEFT, 0, '\0', META_CAPS_LOCK_ON))); + assertEquals(calls.size(), 3); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kUp, + PHYSICAL_CAPS_LOCK, + LOGICAL_CAPS_LOCK, + null, + true, + DeviceType.kKeyboard); + assertEmbedderEventEquals( + calls.get(1).keyData, + Type.kDown, + PHYSICAL_CAPS_LOCK, + LOGICAL_CAPS_LOCK, + null, + true, + DeviceType.kKeyboard); + assertEmbedderEventEquals( + calls.get(2).keyData, + Type.kUp, + PHYSICAL_ARROW_LEFT, + LOGICAL_ARROW_LEFT, + null, + false, + DeviceType.kKeyboard); + calls.clear(); + + assertEquals( + true, + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_UP, SCAN_CAPS_LOCK, KEYCODE_CAPS_LOCK, 0, '\0', 0))); + assertEquals(calls.size(), 1); + assertEmbedderEventEquals( + calls.get(0).keyData, + Type.kUp, + PHYSICAL_CAPS_LOCK, + LOGICAL_CAPS_LOCK, + null, + false, + DeviceType.kKeyboard); + calls.clear(); + } + + @Test + public void getKeyboardState() { + final KeyboardTester tester = new KeyboardTester(); + + tester.respondToTextInputWith(true); // Suppress redispatching. + + // Initial pressed state is empty. + assertEquals(tester.keyboardManager.getKeyboardState(), Map.of()); + + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_DOWN, SCAN_KEY_A, KEYCODE_A, 1, 'a', 0)); + assertEquals(tester.keyboardManager.getKeyboardState(), Map.of(PHYSICAL_KEY_A, LOGICAL_KEY_A)); + + tester.keyboardManager.handleEvent( + new FakeKeyEvent(ACTION_UP, SCAN_KEY_A, KEYCODE_A, 0, 'a', 0)); + assertEquals(tester.keyboardManager.getKeyboardState(), Map.of()); + } + + @Test + public void deviceTypeFromInputDevice() { + final KeyboardTester tester = new KeyboardTester(); + final ArrayList calls = new ArrayList<>(); + + tester.recordEmbedderCallsTo(calls); + tester.respondToTextInputWith(true); + + // Keyboard + final KeyEvent keyboardEvent = + new FakeKeyEvent( + ACTION_DOWN, SCAN_KEY_A, KEYCODE_A, 0, 'a', 0, InputDevice.SOURCE_KEYBOARD); + assertEquals(true, tester.keyboardManager.handleEvent(keyboardEvent)); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData(Type.kDown, PHYSICAL_KEY_A, LOGICAL_KEY_A, "a", false, DeviceType.kKeyboard), + }); + calls.clear(); + + // Directional pad + final KeyEvent directionalPadEvent = + new FakeKeyEvent( + ACTION_DOWN, SCAN_ARROW_LEFT, KEYCODE_DPAD_LEFT, 0, '\0', 0, InputDevice.SOURCE_DPAD); + assertEquals(true, tester.keyboardManager.handleEvent(directionalPadEvent)); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData( + Type.kDown, + PHYSICAL_ARROW_LEFT, + LOGICAL_ARROW_LEFT, + null, + false, + DeviceType.kDirectionalPad), + }); + calls.clear(); + + // Gamepad + final KeyEvent gamepadEvent = + new FakeKeyEvent( + ACTION_DOWN, SCAN_ARROW_LEFT, KEYCODE_BUTTON_A, 0, '\0', 0, InputDevice.SOURCE_GAMEPAD); + assertEquals(true, tester.keyboardManager.handleEvent(gamepadEvent)); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData( + Type.kUp, PHYSICAL_ARROW_LEFT, LOGICAL_ARROW_LEFT, null, true, DeviceType.kKeyboard), + buildKeyData( + Type.kDown, + PHYSICAL_ARROW_LEFT, + LOGICAL_GAME_BUTTON_A, + null, + false, + DeviceType.kGamepad), + }); + calls.clear(); + + // HDMI + final KeyEvent hdmiEvent = + new FakeKeyEvent( + ACTION_DOWN, SCAN_ARROW_LEFT, KEYCODE_BUTTON_A, 0, '\0', 0, InputDevice.SOURCE_HDMI); + assertEquals(true, tester.keyboardManager.handleEvent(hdmiEvent)); + verifyEmbedderEvents( + calls, + new KeyData[] { + buildKeyData( + Type.kUp, + PHYSICAL_ARROW_LEFT, + LOGICAL_GAME_BUTTON_A, + null, + true, + DeviceType.kKeyboard), + buildKeyData( + Type.kDown, + PHYSICAL_ARROW_LEFT, + LOGICAL_GAME_BUTTON_A, + null, + false, + DeviceType.kHdmi), + }); + calls.clear(); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/RobolectricFlutterActivity.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/RobolectricFlutterActivity.java new file mode 100644 index 0000000000000000000000000000000000000000..dac9bb82e3a5414b5645b61b96a38301d9278dea --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/RobolectricFlutterActivity.java @@ -0,0 +1,40 @@ +// 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. + +package io.flutter.embedding.android; + +import android.content.Intent; +import androidx.annotation.NonNull; +import org.robolectric.Robolectric; +import org.robolectric.android.controller.ActivityController; + +/** + * Creates a {@code FlutterActivity} for use by test code that do not sit within the {@code + * io.flutter.embedding.android} package, and offers public access to some package private + * properties of {@code FlutterActivity} for testing purposes. + */ +public class RobolectricFlutterActivity { + /** + * Creates a {@code FlutterActivity} that is controlled by Robolectric, which otherwise can not be + * done in a test outside of the io.flutter.embedding.android package. + */ + @NonNull + public static FlutterActivity createFlutterActivity(@NonNull Intent intent) { + ActivityController activityController = + Robolectric.buildActivity(FlutterActivity.class, intent); + FlutterActivity flutterActivity = activityController.get(); + flutterActivity.setDelegate(new FlutterActivityAndFragmentDelegate(flutterActivity)); + return flutterActivity; + } + + /** + * Returns a given {@code FlutterActivity}'s {@code BackgroundMode} for use by tests that do not + * sit in the {@code io.flutter.embedding.android} package. + */ + @NonNull + public static FlutterActivityLaunchConfigs.BackgroundMode getBackgroundMode( + @NonNull FlutterActivity activity) { + return activity.getBackgroundMode(); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/SplashShadowResources.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/SplashShadowResources.java new file mode 100644 index 0000000000000000000000000000000000000000..16919f2f954d01bdc9b69fc40edf120aba8feb99 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/android/SplashShadowResources.java @@ -0,0 +1,60 @@ +// 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. + +package io.flutter.embedding.android; + +import static org.robolectric.util.reflector.Reflector.reflector; + +import android.content.res.Resources; +import android.graphics.Color; +import android.graphics.drawable.ColorDrawable; +import android.graphics.drawable.Drawable; +import androidx.annotation.Nullable; +import org.robolectric.annotation.Implementation; +import org.robolectric.annotation.Implements; +import org.robolectric.annotation.RealObject; +import org.robolectric.shadows.ShadowResources; +import org.robolectric.util.reflector.Direct; +import org.robolectric.util.reflector.ForType; + +@SuppressWarnings("deprecation") +// getDrawableInt +@Implements(Resources.class) +public class SplashShadowResources extends ShadowResources { + @RealObject private Resources resources; + + public static final int SPLASH_DRAWABLE_ID = 191919; + public static final int THEMED_SPLASH_DRAWABLE_ID = 212121; + + @ForType(Resources.class) + interface ResourcesReflector { + @Direct + Drawable getDrawable(int id, Resources.Theme theme); + + @Direct + Drawable getDrawable(int id); + } + + @Implementation + protected Drawable getDrawable(int id) { + if (id == SPLASH_DRAWABLE_ID) { + return new ColorDrawable(Color.BLUE); + } + return reflector(Resources.class, resources).getDrawable(id); + } + + @Implementation + protected Drawable getDrawable(int id, @Nullable Resources.Theme theme) { + if (id == THEMED_SPLASH_DRAWABLE_ID) { + // We pretend the drawable contains theme references. It can't be parsed without the app + // theme. + if (theme == null) { + throw new Resources.NotFoundException( + "Cannot parse drawable due to missing theme references."); + } + return new ColorDrawable(Color.GRAY); + } + return reflector(Resources.class, resources).getDrawable(id, theme); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/FlutterEngineCacheTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/FlutterEngineCacheTest.java new file mode 100644 index 0000000000000000000000000000000000000000..7872a2bbe9d8b7c9f2636a1e2ef11e6252a4d30b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/FlutterEngineCacheTest.java @@ -0,0 +1,84 @@ +// 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. + +package io.flutter.embedding.engine; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; + +import androidx.test.ext.junit.runners.AndroidJUnit4; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class FlutterEngineCacheTest { + @Test + public void itHoldsFlutterEngines() { + // --- Test Setup --- + FlutterEngine flutterEngine = mock(FlutterEngine.class); + FlutterEngineCache cache = new FlutterEngineCache(); + + // --- Execute Test --- + cache.put("my_flutter_engine", flutterEngine); + + // --- Verify Results --- + assertEquals(flutterEngine, cache.get("my_flutter_engine")); + } + + @Test + public void itQueriesFlutterEngineExistence() { + // --- Test Setup --- + FlutterEngine flutterEngine = mock(FlutterEngine.class); + FlutterEngineCache cache = new FlutterEngineCache(); + + // --- Execute Test --- + assertFalse(cache.contains("my_flutter_engine")); + + cache.put("my_flutter_engine", flutterEngine); + + // --- Verify Results --- + assertTrue(cache.contains("my_flutter_engine")); + } + + @Test + public void itRemovesFlutterEngines() { + // --- Test Setup --- + FlutterEngine flutterEngine = mock(FlutterEngine.class); + FlutterEngineCache cache = new FlutterEngineCache(); + + // --- Execute Test --- + cache.put("my_flutter_engine", flutterEngine); + cache.remove("my_flutter_engine"); + + // --- Verify Results --- + assertNull(cache.get("my_flutter_engine")); + } + + @Test + public void itRemovesAllFlutterEngines() { + // --- Test Setup --- + FlutterEngine flutterEngine = mock(FlutterEngine.class); + FlutterEngine flutterEngine2 = mock(FlutterEngine.class); + FlutterEngineCache cache = new FlutterEngineCache(); + + // --- Execute Test --- + cache.put("my_flutter_engine", flutterEngine); + cache.put("my_flutter_engine_2", flutterEngine2); + + // --- Verify Results --- + assertEquals(flutterEngine, cache.get("my_flutter_engine")); + assertEquals(flutterEngine2, cache.get("my_flutter_engine_2")); + + cache.clear(); + + // --- Verify Results --- + assertNull(cache.get("my_flutter_engine")); + assertNull(cache.get("my_flutter_engine_2")); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/FlutterEngineConnectionRegistryTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/FlutterEngineConnectionRegistryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..561f4bfe7536dc9e957b95750f8b4b6bb91ab6c5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/FlutterEngineConnectionRegistryTest.java @@ -0,0 +1,220 @@ +// 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. + +package io.flutter.embedding.engine; + +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import androidx.annotation.NonNull; +import androidx.lifecycle.Lifecycle; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.android.ExclusiveAppComponent; +import io.flutter.embedding.engine.loader.FlutterLoader; +import io.flutter.embedding.engine.plugins.FlutterPlugin; +import io.flutter.embedding.engine.plugins.activity.ActivityAware; +import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; +import io.flutter.plugin.common.PluginRegistry; +import io.flutter.plugin.platform.PlatformViewsController; +import io.flutter.plugin.platform.PlatformViewsController2; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +// Run with Robolectric so that Log calls don't crash. +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class FlutterEngineConnectionRegistryTest { + @Test + public void itDoesNotRegisterTheSamePluginTwice() { + Context context = mock(Context.class); + + FlutterEngine flutterEngine = mock(FlutterEngine.class); + PlatformViewsController platformViewsController = mock(PlatformViewsController.class); + when(flutterEngine.getPlatformViewsController()).thenReturn(platformViewsController); + PlatformViewsController2 platformViewsController2 = mock(PlatformViewsController2.class); + when(flutterEngine.getPlatformViewsController2()).thenReturn(platformViewsController2); + + FlutterLoader flutterLoader = mock(FlutterLoader.class); + + FakeFlutterPlugin fakePlugin1 = new FakeFlutterPlugin(); + FakeFlutterPlugin fakePlugin2 = new FakeFlutterPlugin(); + + FlutterEngineConnectionRegistry registry = + new FlutterEngineConnectionRegistry(context, flutterEngine, flutterLoader, null); + + // Verify that the registry doesn't think it contains our plugin yet. + assertFalse(registry.has(fakePlugin1.getClass())); + + // Add our plugin to the registry. + registry.add(fakePlugin1); + + // Verify that the registry now thinks it contains our plugin. + assertTrue(registry.has(fakePlugin1.getClass())); + assertEquals(1, fakePlugin1.attachmentCallCount); + + // Add a different instance of the same plugin class. + registry.add(fakePlugin2); + + // Verify that the registry did not detach the 1st plugin, and + // it did not attach the 2nd plugin. + assertEquals(1, fakePlugin1.attachmentCallCount); + assertEquals(0, fakePlugin1.detachmentCallCount); + + assertEquals(0, fakePlugin2.attachmentCallCount); + assertEquals(0, fakePlugin2.detachmentCallCount); + } + + @Test + public void activityResultListenerCanBeRemovedFromListener() { + Context context = mock(Context.class); + + FlutterEngine flutterEngine = mock(FlutterEngine.class); + PlatformViewsController platformViewsController = mock(PlatformViewsController.class); + when(flutterEngine.getPlatformViewsController()).thenReturn(platformViewsController); + PlatformViewsController2 platformViewsController2 = mock(PlatformViewsController2.class); + when(flutterEngine.getPlatformViewsController2()).thenReturn(platformViewsController2); + + FlutterLoader flutterLoader = mock(FlutterLoader.class); + + ExclusiveAppComponent appComponent = mock(ExclusiveAppComponent.class); + Activity activity = mock(Activity.class); + when(appComponent.getAppComponent()).thenReturn(activity); + + Intent intent = mock(Intent.class); + when(activity.getIntent()).thenReturn(intent); + + Lifecycle lifecycle = mock(Lifecycle.class); + AtomicBoolean isFirstCall = new AtomicBoolean(true); + + // Set up the environment to get the required internal data + FlutterEngineConnectionRegistry registry = + new FlutterEngineConnectionRegistry(context, flutterEngine, flutterLoader, null); + FakeActivityAwareFlutterPlugin fakePlugin = new FakeActivityAwareFlutterPlugin(); + registry.add(fakePlugin); + registry.attachToActivity(appComponent, lifecycle); + + // The binding is now available via `fakePlugin.binding`: Create and add the listeners + FakeActivityResultListener listener1 = + new FakeActivityResultListener(isFirstCall, fakePlugin.binding); + FakeActivityResultListener listener2 = + new FakeActivityResultListener(isFirstCall, fakePlugin.binding); + + fakePlugin.binding.addActivityResultListener(listener1); + fakePlugin.binding.addActivityResultListener(listener2); + + // fire the onActivityResult which should invoke both listeners + registry.onActivityResult(0, 0, intent); + + assertEquals(1, listener1.callCount); + assertEquals(1, listener2.callCount); + + // fire it again to check if the first called listener was removed + registry.onActivityResult(0, 0, intent); + + // The order of the listeners in the HashSet is random: So just check the sum of calls + assertEquals(3, listener1.callCount + listener2.callCount); + } + + @Test + public void softwareRendering() { + Context context = mock(Context.class); + + FlutterEngine flutterEngine = mock(FlutterEngine.class); + PlatformViewsController platformViewsController = mock(PlatformViewsController.class); + when(flutterEngine.getPlatformViewsController()).thenReturn(platformViewsController); + PlatformViewsController2 platformViewsController2 = mock(PlatformViewsController2.class); + when(flutterEngine.getPlatformViewsController2()).thenReturn(platformViewsController2); + + FlutterLoader flutterLoader = mock(FlutterLoader.class); + + ExclusiveAppComponent appComponent = mock(ExclusiveAppComponent.class); + Activity activity = mock(Activity.class); + when(appComponent.getAppComponent()).thenReturn(activity); + + // Test attachToActivity with an Activity that has no Intent. + FlutterEngineConnectionRegistry registry = + new FlutterEngineConnectionRegistry(context, flutterEngine, flutterLoader, null); + registry.attachToActivity(appComponent, mock(Lifecycle.class)); + verify(platformViewsController).setSoftwareRendering(false); + + Intent intent = mock(Intent.class); + when(intent.getBooleanExtra("enable-software-rendering", false)).thenReturn(false); + when(activity.getIntent()).thenReturn(intent); + + registry.attachToActivity(appComponent, mock(Lifecycle.class)); + verify(platformViewsController, times(2)).setSoftwareRendering(false); + + when(intent.getBooleanExtra("enable-software-rendering", false)).thenReturn(true); + + registry.attachToActivity(appComponent, mock(Lifecycle.class)); + verify(platformViewsController).setSoftwareRendering(true); + } + + private static class FakeFlutterPlugin implements FlutterPlugin { + public int attachmentCallCount = 0; + public int detachmentCallCount = 0; + + @Override + public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) { + attachmentCallCount += 1; + } + + @Override + public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { + detachmentCallCount += 1; + } + } + + private static class FakeActivityAwareFlutterPlugin implements FlutterPlugin, ActivityAware { + public ActivityPluginBinding binding; + + @Override + public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {} + + @Override + public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {} + + @Override + public void onAttachedToActivity(final ActivityPluginBinding binding) { + this.binding = binding; + } + + @Override + public void onDetachedFromActivityForConfigChanges() {} + + @Override + public void onReattachedToActivityForConfigChanges(final ActivityPluginBinding binding) {} + + @Override + public void onDetachedFromActivity() {} + } + + private static class FakeActivityResultListener implements PluginRegistry.ActivityResultListener { + public int callCount = 0; + private final AtomicBoolean isFirstCall; + private final ActivityPluginBinding binding; + + public FakeActivityResultListener(AtomicBoolean isFirstCall, ActivityPluginBinding binding) { + this.isFirstCall = isFirstCall; + this.binding = binding; + } + + @Override + public boolean onActivityResult( + final int requestCode, final int resultCode, final Intent data) { + callCount++; + if (isFirstCall.get()) { + isFirstCall.set(false); + binding.removeActivityResultListener(this); + } + return false; + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/FlutterEngineGroupCacheTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/FlutterEngineGroupCacheTest.java new file mode 100644 index 0000000000000000000000000000000000000000..28cd9b69a90038e8f851a633313f1c0f3a76ba39 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/FlutterEngineGroupCacheTest.java @@ -0,0 +1,102 @@ +// 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. + +package io.flutter.embedding.engine; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import androidx.test.core.app.ApplicationProvider; +import io.flutter.FlutterInjector; +import io.flutter.embedding.engine.loader.FlutterLoader; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(RobolectricTestRunner.class) +public class FlutterEngineGroupCacheTest { + + private FlutterEngineGroup flutterEngineGroup; + + @Before + public void setup() { + // Create a mocked FlutterEngineGroup that provided to run this test case + FlutterInjector.reset(); + FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); + when(mockFlutterLoader.findAppBundlePath()).thenReturn("default_flutter_assets/path"); + FlutterInjector.setInstance( + new FlutterInjector.Builder().setFlutterLoader(mockFlutterLoader).build()); + flutterEngineGroup = mock(FlutterEngineGroup.class); + } + + @Test + public void itHoldsFlutterEngineGroups() { + // --- Test Setup --- + FlutterEngineGroupCache cache = new FlutterEngineGroupCache(); + + // --- Execute Test --- + cache.put("my_flutter_engine_group", flutterEngineGroup); + + // --- Verify Results --- + assertEquals(flutterEngineGroup, cache.get("my_flutter_engine_group")); + } + + @Test + public void itQueriesFlutterEngineGroupExistence() { + // --- Test Setup --- + FlutterEngineGroupCache cache = new FlutterEngineGroupCache(); + + // --- Execute Test --- + assertFalse(cache.contains("my_flutter_engine_group")); + + cache.put("my_flutter_engine_group", flutterEngineGroup); + + // --- Verify Results --- + assertTrue(cache.contains("my_flutter_engine_group")); + } + + @Test + public void itRemovesFlutterEngineGroups() { + // --- Test Setup --- + FlutterEngineGroupCache cache = new FlutterEngineGroupCache(); + + // --- Execute Test --- + cache.put("my_flutter_engine_group", flutterEngineGroup); + cache.remove("my_flutter_engine_group"); + + // --- Verify Results --- + assertNull(cache.get("my_flutter_engine_group")); + } + + @Test + public void itRemovesAllFlutterEngineGroups() { + // --- Test Setup --- + FlutterEngineGroup flutterEngineGroup1 = + new FlutterEngineGroup(ApplicationProvider.getApplicationContext()); + FlutterEngineGroup flutterEngineGroup2 = + new FlutterEngineGroup(ApplicationProvider.getApplicationContext()); + FlutterEngineGroupCache cache = new FlutterEngineGroupCache(); + + // --- Execute Test --- + cache.put("my_flutter_engine_group", flutterEngineGroup1); + cache.put("my_flutter_engine_group_2", flutterEngineGroup2); + + // --- Verify Results --- + assertEquals(flutterEngineGroup1, cache.get("my_flutter_engine_group")); + assertEquals(flutterEngineGroup2, cache.get("my_flutter_engine_group_2")); + + cache.clear(); + + // --- Verify Results --- + assertNull(cache.get("my_flutter_engine_group")); + assertNull(cache.get("my_flutter_engine_group_2")); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/FlutterEngineGroupComponentTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/FlutterEngineGroupComponentTest.java new file mode 100644 index 0000000000000000000000000000000000000000..72693896e9a35f0f9c87406149380c5506ed535e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/FlutterEngineGroupComponentTest.java @@ -0,0 +1,362 @@ +// 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. + +package io.flutter.embedding.engine; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.nullable; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.content.Context; +import android.content.res.AssetManager; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.FlutterInjector; +import io.flutter.embedding.engine.dart.DartExecutor.DartEntrypoint; +import io.flutter.embedding.engine.loader.FlutterLoader; +import io.flutter.embedding.engine.systemchannels.NavigationChannel; +import io.flutter.plugin.platform.PlatformViewsController; +import io.flutter.plugins.GeneratedPluginRegistrant; +import java.util.ArrayList; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.robolectric.annotation.Config; + +// It's a component test because it tests the FlutterEngineGroup its components such as the +// FlutterEngine and the DartExecutor. +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class FlutterEngineGroupComponentTest { + private final Context ctx = ApplicationProvider.getApplicationContext(); + @Mock FlutterJNI mockFlutterJNI; + @Mock FlutterLoader mockFlutterLoader; + FlutterEngineGroup engineGroupUnderTest; + FlutterEngine firstEngineUnderTest; + boolean jniAttached; + + @Before + public void setUp() { + FlutterInjector.reset(); + + MockitoAnnotations.openMocks(this); + jniAttached = false; + when(mockFlutterJNI.isAttached()).thenAnswer(invocation -> jniAttached); + doAnswer(invocation -> jniAttached = true).when(mockFlutterJNI).attachToNative(); + GeneratedPluginRegistrant.clearRegisteredEngines(); + FlutterEngine.resetNextEngineId(); + + when(mockFlutterLoader.findAppBundlePath()).thenReturn("some/path/to/flutter_assets"); + + FlutterJNI.Factory jniFactory = + new FlutterJNI.Factory() { + @Override + public FlutterJNI provideFlutterJNI() { + // The default implementation is that `new FlutterJNI()` will report errors when + // creating the engine later, + // Change mockFlutterJNI to the default so that we can create the engine directly in + // later tests + return mockFlutterJNI; + } + }; + + FlutterInjector.setInstance( + new FlutterInjector.Builder() + .setFlutterLoader(mockFlutterLoader) + .setFlutterJNIFactory(jniFactory) + .build()); + + firstEngineUnderTest = + spy( + new FlutterEngine( + ctx, + mock(FlutterLoader.class), + mockFlutterJNI, + /*dartVmArgs=*/ new String[] {}, + /*automaticallyRegisterPlugins=*/ false)); + engineGroupUnderTest = + new FlutterEngineGroup(ctx) { + @Override + FlutterEngine createEngine( + Context context, + PlatformViewsController platformViewsController, + boolean automaticallyRegisterPlugins, + boolean waitForRestorationData) { + return firstEngineUnderTest; + } + }; + } + + @After + public void tearDown() { + GeneratedPluginRegistrant.clearRegisteredEngines(); + engineGroupUnderTest = null; + firstEngineUnderTest = null; + } + + @Test + public void listensToEngineDestruction() { + FlutterEngine firstEngine = + engineGroupUnderTest.createAndRunEngine(ctx, mock(DartEntrypoint.class)); + assertEquals(1, engineGroupUnderTest.activeEngines.size()); + + firstEngine.destroy(); + assertEquals(0, engineGroupUnderTest.activeEngines.size()); + } + + @Test + public void canRecreateEngines() { + FlutterEngine firstEngine = + engineGroupUnderTest.createAndRunEngine(ctx, mock(DartEntrypoint.class)); + assertEquals(1, engineGroupUnderTest.activeEngines.size()); + + firstEngine.destroy(); + assertEquals(0, engineGroupUnderTest.activeEngines.size()); + + FlutterEngine secondEngine = + engineGroupUnderTest.createAndRunEngine(ctx, mock(DartEntrypoint.class)); + assertEquals(1, engineGroupUnderTest.activeEngines.size()); + // They happen to be equal in our test since we mocked it to be so. + assertEquals(firstEngine, secondEngine); + } + + @Test + public void canSpawnMoreEngines() { + FlutterEngine firstEngine = + engineGroupUnderTest.createAndRunEngine(ctx, mock(DartEntrypoint.class)); + assertEquals(1, engineGroupUnderTest.activeEngines.size()); + + doReturn(mock(FlutterEngine.class)) + .when(firstEngine) + .spawn( + any(Context.class), + any(DartEntrypoint.class), + nullable(String.class), + nullable(List.class), + any(PlatformViewsController.class), + any(Boolean.class), + any(Boolean.class)); + + FlutterEngine secondEngine = + engineGroupUnderTest.createAndRunEngine(ctx, mock(DartEntrypoint.class)); + assertEquals(2, engineGroupUnderTest.activeEngines.size()); + + firstEngine.destroy(); + assertEquals(1, engineGroupUnderTest.activeEngines.size()); + + // Now the second spawned engine is the only one left and it will be called to spawn the next + // engine in the chain. + when(secondEngine.spawn( + any(Context.class), + any(DartEntrypoint.class), + nullable(String.class), + nullable(List.class), + any(PlatformViewsController.class), + any(Boolean.class), + any(Boolean.class))) + .thenReturn(mock(FlutterEngine.class)); + + FlutterEngine thirdEngine = + engineGroupUnderTest.createAndRunEngine(ctx, mock(DartEntrypoint.class)); + assertEquals(2, engineGroupUnderTest.activeEngines.size()); + } + + @Test + public void canCreateAndRunCustomEntrypoints() { + FlutterEngine firstEngine = + engineGroupUnderTest.createAndRunEngine( + ctx, + new DartEntrypoint( + FlutterInjector.instance().flutterLoader().findAppBundlePath(), + "other entrypoint")); + assertEquals(1, engineGroupUnderTest.activeEngines.size()); + verify(mockFlutterJNI, times(1)) + .runBundleAndSnapshotFromLibrary( + eq("some/path/to/flutter_assets"), + eq("other entrypoint"), + isNull(), + any(AssetManager.class), + nullable(List.class), + eq(1l)); + } + + @Test + public void canCreateAndRunWithCustomInitialRoute() { + when(firstEngineUnderTest.getNavigationChannel()).thenReturn(mock(NavigationChannel.class)); + + FlutterEngine firstEngine = + engineGroupUnderTest.createAndRunEngine(ctx, mock(DartEntrypoint.class), "/foo"); + assertEquals(1, engineGroupUnderTest.activeEngines.size()); + verify(firstEngine.getNavigationChannel(), times(1)).setInitialRoute("/foo"); + + when(mockFlutterJNI.isAttached()).thenReturn(true); + jniAttached = false; + FlutterJNI secondMockFlutterJNI = mock(FlutterJNI.class); + when(secondMockFlutterJNI.isAttached()).thenAnswer(invocation -> jniAttached); + doAnswer(invocation -> jniAttached = true).when(secondMockFlutterJNI).attachToNative(); + doReturn(secondMockFlutterJNI) + .when(mockFlutterJNI) + .spawn( + nullable(String.class), + nullable(String.class), + nullable(String.class), + nullable(List.class), + eq(2l)); + + FlutterEngine secondEngine = + engineGroupUnderTest.createAndRunEngine(ctx, mock(DartEntrypoint.class), "/bar"); + + assertEquals(2, engineGroupUnderTest.activeEngines.size()); + verify(mockFlutterJNI, times(1)) + .spawn( + nullable(String.class), + nullable(String.class), + eq("/bar"), + nullable(List.class), + eq(2l)); + } + + @Test + public void canCreateAndRunWithCustomEntrypointArgs() { + List firstDartEntrypointArgs = new ArrayList(); + FlutterEngine firstEngine = + engineGroupUnderTest.createAndRunEngine( + new FlutterEngineGroup.Options(ctx) + .setDartEntrypoint(mock(DartEntrypoint.class)) + .setDartEntrypointArgs(firstDartEntrypointArgs)); + assertEquals(1, engineGroupUnderTest.activeEngines.size()); + verify(mockFlutterJNI, times(1)) + .runBundleAndSnapshotFromLibrary( + nullable(String.class), + nullable(String.class), + isNull(), + any(AssetManager.class), + eq(firstDartEntrypointArgs), + eq(1l)); + + when(mockFlutterJNI.isAttached()).thenReturn(true); + jniAttached = false; + FlutterJNI secondMockFlutterJNI = mock(FlutterJNI.class); + when(secondMockFlutterJNI.isAttached()).thenAnswer(invocation -> jniAttached); + doAnswer(invocation -> jniAttached = true).when(secondMockFlutterJNI).attachToNative(); + doReturn(secondMockFlutterJNI) + .when(mockFlutterJNI) + .spawn( + nullable(String.class), + nullable(String.class), + nullable(String.class), + nullable(List.class), + eq(2l)); + List secondDartEntrypointArgs = new ArrayList(); + FlutterEngine secondEngine = + engineGroupUnderTest.createAndRunEngine( + new FlutterEngineGroup.Options(ctx) + .setDartEntrypoint(mock(DartEntrypoint.class)) + .setDartEntrypointArgs(secondDartEntrypointArgs)); + + assertEquals(2, engineGroupUnderTest.activeEngines.size()); + verify(mockFlutterJNI, times(1)) + .spawn( + nullable(String.class), + nullable(String.class), + nullable(String.class), + eq(secondDartEntrypointArgs), + eq(2l)); + } + + @Test + public void createEngineSupportMoreParams() { + // Create a new FlutterEngineGroup because the first engine created in engineGroupUnderTest was + // changed to firstEngineUnderTest in `setUp()`, so can't use it to validate params. + FlutterEngineGroup engineGroup = new FlutterEngineGroup(ctx); + + PlatformViewsController controller = new PlatformViewsController(); + boolean waitForRestorationData = true; + boolean automaticallyRegisterPlugins = true; + + when(FlutterInjector.instance().flutterLoader().automaticallyRegisterPlugins()) + .thenReturn(true); + assertTrue(FlutterInjector.instance().flutterLoader().automaticallyRegisterPlugins()); + assertEquals(0, GeneratedPluginRegistrant.getRegisteredEngines().size()); + + FlutterEngine firstEngine = + engineGroup.createAndRunEngine( + new FlutterEngineGroup.Options(ctx) + .setDartEntrypoint(mock(DartEntrypoint.class)) + .setPlatformViewsController(controller) + .setWaitForRestorationData(waitForRestorationData) + .setAutomaticallyRegisterPlugins(automaticallyRegisterPlugins)); + + assertEquals(1, GeneratedPluginRegistrant.getRegisteredEngines().size()); + assertEquals(controller, firstEngine.getPlatformViewsController()); + assertEquals( + waitForRestorationData, firstEngine.getRestorationChannel().waitForRestorationData); + } + + @Test + public void spawnEngineSupportMoreParams() { + FlutterEngine firstEngine = + engineGroupUnderTest.createAndRunEngine( + new FlutterEngineGroup.Options(ctx).setDartEntrypoint(mock(DartEntrypoint.class))); + assertEquals(1, engineGroupUnderTest.activeEngines.size()); + verify(mockFlutterJNI, times(1)) + .runBundleAndSnapshotFromLibrary( + nullable(String.class), + nullable(String.class), + isNull(), + any(AssetManager.class), + nullable(List.class), + eq(1l)); + + when(mockFlutterJNI.isAttached()).thenReturn(true); + jniAttached = false; + FlutterJNI secondMockFlutterJNI = mock(FlutterJNI.class); + when(secondMockFlutterJNI.isAttached()).thenAnswer(invocation -> jniAttached); + doAnswer(invocation -> jniAttached = true).when(secondMockFlutterJNI).attachToNative(); + doReturn(secondMockFlutterJNI) + .when(mockFlutterJNI) + .spawn( + nullable(String.class), + nullable(String.class), + nullable(String.class), + nullable(List.class), + eq(2l)); + + PlatformViewsController controller = new PlatformViewsController(); + boolean waitForRestorationData = false; + boolean automaticallyRegisterPlugins = false; + + when(FlutterInjector.instance().flutterLoader().automaticallyRegisterPlugins()) + .thenReturn(true); + assertTrue(FlutterInjector.instance().flutterLoader().automaticallyRegisterPlugins()); + assertEquals(0, GeneratedPluginRegistrant.getRegisteredEngines().size()); + + FlutterEngine secondEngine = + engineGroupUnderTest.createAndRunEngine( + new FlutterEngineGroup.Options(ctx) + .setDartEntrypoint(mock(DartEntrypoint.class)) + .setWaitForRestorationData(waitForRestorationData) + .setPlatformViewsController(controller) + .setAutomaticallyRegisterPlugins(automaticallyRegisterPlugins)); + + assertEquals( + waitForRestorationData, secondEngine.getRestorationChannel().waitForRestorationData); + assertEquals(controller, secondEngine.getPlatformViewsController()); + assertEquals(0, GeneratedPluginRegistrant.getRegisteredEngines().size()); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/FlutterEngineTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/FlutterEngineTest.java new file mode 100644 index 0000000000000000000000000000000000000000..dc339860b1972eeb5d0312edb840eeb60e63719a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/FlutterEngineTest.java @@ -0,0 +1,394 @@ +package test.io.flutter.embedding.engine; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyInt; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.app.Activity; +import android.content.Context; +import android.content.pm.PackageManager.NameNotFoundException; +import android.content.res.Configuration; +import android.content.res.Resources; +import android.os.LocaleList; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.FlutterInjector; +import io.flutter.embedding.engine.FlutterEngine; +import io.flutter.embedding.engine.FlutterEngine.EngineLifecycleListener; +import io.flutter.embedding.engine.FlutterEngineGroup; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.loader.FlutterLoader; +import io.flutter.embedding.engine.plugins.FlutterPlugin; +import io.flutter.embedding.engine.plugins.PluginRegistry; +import io.flutter.plugin.platform.PlatformViewsController; +import io.flutter.plugins.GeneratedPluginRegistrant; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.robolectric.Robolectric; +import org.robolectric.android.controller.ActivityController; +import org.robolectric.annotation.Config; +import org.robolectric.shadows.ShadowLog; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class FlutterEngineTest { + private final Context ctx = ApplicationProvider.getApplicationContext(); + private final Context mockContext = mock(Context.class); + @Mock FlutterJNI flutterJNI; + boolean jniAttached; + + @Before + public void setUp() { + MockitoAnnotations.openMocks(this); + + Resources mockResources = mock(Resources.class); + Configuration mockConfiguration = mock(Configuration.class); + doReturn(mockResources).when(mockContext).getResources(); + doReturn(mockConfiguration).when(mockResources).getConfiguration(); + doReturn(LocaleList.getEmptyLocaleList()).when(mockConfiguration).getLocales(); + + jniAttached = false; + when(flutterJNI.isAttached()).thenAnswer(invocation -> jniAttached); + doAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + jniAttached = true; + return null; + } + }) + .when(flutterJNI) + .attachToNative(); + GeneratedPluginRegistrant.clearRegisteredEngines(); + FlutterEngine.resetNextEngineId(); + } + + @After + public void tearDown() { + GeneratedPluginRegistrant.clearRegisteredEngines(); + // Make sure to not forget to remove the mock exception in the generated plugin registration + // mock, or everything subsequent will break. + GeneratedPluginRegistrant.pluginRegistrationException = null; + } + + @Test + public void itAutomaticallyRegistersPluginsByDefault() { + assertTrue(GeneratedPluginRegistrant.getRegisteredEngines().isEmpty()); + FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); + when(mockFlutterLoader.automaticallyRegisterPlugins()).thenReturn(true); + FlutterEngine flutterEngine = new FlutterEngine(ctx, mockFlutterLoader, flutterJNI); + + List registeredEngines = GeneratedPluginRegistrant.getRegisteredEngines(); + assertEquals(1, registeredEngines.size()); + assertEquals(flutterEngine, registeredEngines.get(0)); + } + + @Test + public void itUpdatesDisplayMetricsOnConstructionWithActivityContext() { + // Needs an activity. ApplicationContext won't work for this. + ActivityController activityController = Robolectric.buildActivity(Activity.class); + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + when(mockFlutterJNI.isAttached()).thenReturn(true); + + FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); + FlutterEngine flutterEngine = + new FlutterEngine(activityController.get(), mockFlutterLoader, mockFlutterJNI); + + verify(mockFlutterJNI, times(1)) + .updateDisplayMetrics(eq(0), any(Float.class), any(Float.class), any(Float.class)); + } + + @Test + public void itSendLocalesOnEngineInit() { + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + when(mockFlutterJNI.isAttached()).thenReturn(true); + + assertTrue(GeneratedPluginRegistrant.getRegisteredEngines().isEmpty()); + FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); + when(mockFlutterLoader.automaticallyRegisterPlugins()).thenReturn(true); + FlutterEngine flutterEngine = new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJNI); + + verify(mockFlutterJNI, times(1)) + .dispatchPlatformMessage(eq("flutter/localization"), any(), anyInt(), anyInt()); + } + + @Test + public void itCanBeRetrievedByHandle() { + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + when(mockFlutterJNI.isAttached()).thenReturn(true); + FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); + when(mockFlutterLoader.automaticallyRegisterPlugins()).thenReturn(true); + FlutterEngine flutterEngine1 = new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJNI); + FlutterEngine flutterEngine2 = new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJNI); + assertEquals(flutterEngine1, FlutterEngine.engineForId(1)); + assertEquals(flutterEngine2, FlutterEngine.engineForId(2)); + flutterEngine1.destroy(); + assertEquals(null, FlutterEngine.engineForId(1)); + assertEquals(flutterEngine2, FlutterEngine.engineForId(2)); + flutterEngine2.destroy(); + assertEquals(null, FlutterEngine.engineForId(2)); + } + + // Helps show the root cause of MissingPluginException type errors like + // https://github.com/flutter/flutter/issues/78625. + @Test + public void itCatchesAndDisplaysRegistrationExceptions() { + assertTrue(GeneratedPluginRegistrant.getRegisteredEngines().isEmpty()); + GeneratedPluginRegistrant.pluginRegistrationException = + new RuntimeException("I'm a bug in the plugin"); + FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); + when(mockFlutterLoader.automaticallyRegisterPlugins()).thenReturn(true); + FlutterEngine flutterEngine = new FlutterEngine(ctx, mockFlutterLoader, flutterJNI); + + List registeredEngines = GeneratedPluginRegistrant.getRegisteredEngines(); + // When it crashes, it doesn't end up registering anything. + assertEquals(0, registeredEngines.size()); + + // Check the logs actually says registration failed, so a subsequent MissingPluginException + // isn't mysterious. + assertTrue( + ShadowLog.getLogsForTag("GeneratedPluginsRegister") + .get(0) + .msg + .contains("Tried to automatically register plugins")); + assertEquals( + GeneratedPluginRegistrant.pluginRegistrationException, + ShadowLog.getLogsForTag("GeneratedPluginsRegister").get(1).throwable.getCause()); + + GeneratedPluginRegistrant.pluginRegistrationException = null; + } + + @Test + public void itDoesNotAutomaticallyRegistersPluginsWhenFlutterLoaderDisablesIt() { + assertTrue(GeneratedPluginRegistrant.getRegisteredEngines().isEmpty()); + FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); + when(mockFlutterLoader.automaticallyRegisterPlugins()).thenReturn(false); + new FlutterEngine(ctx, mockFlutterLoader, flutterJNI); + + List registeredEngines = GeneratedPluginRegistrant.getRegisteredEngines(); + assertTrue(registeredEngines.isEmpty()); + } + + @Test + public void itDoesNotAutomaticallyRegistersPluginsWhenFlutterEngineDisablesIt() { + assertTrue(GeneratedPluginRegistrant.getRegisteredEngines().isEmpty()); + FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); + when(mockFlutterLoader.automaticallyRegisterPlugins()).thenReturn(true); + new FlutterEngine( + ctx, + mockFlutterLoader, + flutterJNI, + /*dartVmArgs=*/ new String[] {}, + /*automaticallyRegisterPlugins=*/ false); + + List registeredEngines = GeneratedPluginRegistrant.getRegisteredEngines(); + assertTrue(registeredEngines.isEmpty()); + } + + @Test + public void itNotifiesPlatformViewsControllerWhenDevHotRestart() { + // Setup test. + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + when(mockFlutterJNI.isAttached()).thenReturn(true); + + PlatformViewsController platformViewsController = mock(PlatformViewsController.class); + + ArgumentCaptor engineLifecycleListenerArgumentCaptor = + ArgumentCaptor.forClass(FlutterEngine.EngineLifecycleListener.class); + + // Execute behavior under test. + new FlutterEngine( + ctx, + mock(FlutterLoader.class), + mockFlutterJNI, + platformViewsController, + /*dartVmArgs=*/ new String[] {}, + /*automaticallyRegisterPlugins=*/ false); + + // Obtain the EngineLifecycleListener within FlutterEngine that was given to FlutterJNI. + verify(mockFlutterJNI) + .addEngineLifecycleListener(engineLifecycleListenerArgumentCaptor.capture()); + FlutterEngine.EngineLifecycleListener engineLifecycleListener = + engineLifecycleListenerArgumentCaptor.getValue(); + assertNotNull(engineLifecycleListener); + + // Simulate a pre-engine restart, AKA hot restart. + engineLifecycleListener.onPreEngineRestart(); + + // Verify that FlutterEngine notified PlatformViewsController of the pre-engine restart, + // AKA hot restart. + verify(platformViewsController, times(1)).onPreEngineRestart(); + } + + @Test + public void itNotifiesPlatformViewsControllerAboutJNILifecycle() { + PlatformViewsController platformViewsController = mock(PlatformViewsController.class); + + // Execute behavior under test. + FlutterEngine engine = + new FlutterEngine( + ctx, + mock(FlutterLoader.class), + flutterJNI, + platformViewsController, + /*dartVmArgs=*/ new String[] {}, + /*automaticallyRegisterPlugins=*/ false); + + engine.destroy(); + verify(platformViewsController, times(1)).onDetachedFromJNI(); + } + + @Test + public void itUsesApplicationContext() throws NameNotFoundException { + Context packageContext = mock(Context.class); + + when(mockContext.createPackageContext(any(), anyInt())).thenReturn(packageContext); + + new FlutterEngine( + mockContext, + mock(FlutterLoader.class), + flutterJNI, + /*dartVmArgs=*/ new String[] {}, + /*automaticallyRegisterPlugins=*/ false); + + verify(mockContext, atLeast(1)).getApplicationContext(); + } + + @Test + public void itUsesPackageContextForAssetManager() throws NameNotFoundException { + Context packageContext = mock(Context.class); + when(mockContext.createPackageContext(any(), anyInt())).thenReturn(packageContext); + + new FlutterEngine( + mockContext, + mock(FlutterLoader.class), + flutterJNI, + /*dartVmArgs=*/ new String[] {}, + /*automaticallyRegisterPlugins=*/ false); + + verify(packageContext, atLeast(1)).getAssets(); + verify(mockContext, times(0)).getAssets(); + } + + @Test + public void itCanUseFlutterLoaderInjectionViaFlutterInjector() throws NameNotFoundException { + FlutterInjector.reset(); + FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); + FlutterInjector.setInstance( + new FlutterInjector.Builder().setFlutterLoader(mockFlutterLoader).build()); + Context packageContext = mock(Context.class); + + when(mockContext.createPackageContext(any(), anyInt())).thenReturn(packageContext); + + new FlutterEngine(mockContext, null, flutterJNI); + + verify(mockFlutterLoader, times(1)).startInitialization(any()); + verify(mockFlutterLoader, times(1)).ensureInitializationComplete(any(), any()); + FlutterInjector.reset(); + } + + @Test + public void itNotifiesListenersForDestruction() throws NameNotFoundException { + Context packageContext = mock(Context.class); + + when(mockContext.createPackageContext(any(), anyInt())).thenReturn(packageContext); + + FlutterEngine engineUnderTest = + new FlutterEngine( + mockContext, + mock(FlutterLoader.class), + flutterJNI, + /*dartVmArgs=*/ new String[] {}, + /*automaticallyRegisterPlugins=*/ false); + + EngineLifecycleListener listener = mock(EngineLifecycleListener.class); + engineUnderTest.addEngineLifecycleListener(listener); + engineUnderTest.destroy(); + verify(listener, times(1)).onEngineWillDestroy(); + } + + @Test + public void itDoesNotAttachAgainWhenBuiltWithAnAttachedJNI() throws NameNotFoundException { + Context packageContext = mock(Context.class); + + when(mockContext.createPackageContext(any(), anyInt())).thenReturn(packageContext); + when(flutterJNI.isAttached()).thenReturn(true); + + FlutterEngine engineUnderTest = + new FlutterEngine( + mockContext, + mock(FlutterLoader.class), + flutterJNI, + /*dartVmArgs=*/ new String[] {}, + /*automaticallyRegisterPlugins=*/ false); + + verify(flutterJNI, never()).attachToNative(); + } + + @Test + public void itComesWithARunningDartExecutorIfJNIIsAlreadyAttached() throws NameNotFoundException { + Context packageContext = mock(Context.class); + + when(mockContext.createPackageContext(any(), anyInt())).thenReturn(packageContext); + when(flutterJNI.isAttached()).thenReturn(true); + + FlutterEngine engineUnderTest = + new FlutterEngine( + mockContext, + mock(FlutterLoader.class), + flutterJNI, + /*dartVmArgs=*/ new String[] {}, + /*automaticallyRegisterPlugins=*/ false); + + assertTrue(engineUnderTest.getDartExecutor().isExecutingDart()); + } + + @Test + public void passesEngineGroupToPlugins() throws NameNotFoundException { + Context packageContext = mock(Context.class); + + when(mockContext.createPackageContext(any(), anyInt())).thenReturn(packageContext); + when(flutterJNI.isAttached()).thenReturn(true); + + FlutterEngineGroup mockGroup = mock(FlutterEngineGroup.class); + + FlutterEngine engineUnderTest = + new FlutterEngine( + mockContext, + mock(FlutterLoader.class), + flutterJNI, + new PlatformViewsController(), + /*dartVmArgs=*/ new String[] {}, + /*automaticallyRegisterPlugins=*/ false, + /*waitForRestorationData=*/ false, + mockGroup); + + PluginRegistry registry = engineUnderTest.getPlugins(); + FlutterPlugin mockPlugin = mock(FlutterPlugin.class); + ArgumentCaptor pluginBindingCaptor = + ArgumentCaptor.forClass(FlutterPlugin.FlutterPluginBinding.class); + registry.add(mockPlugin); + verify(mockPlugin).onAttachedToEngine(pluginBindingCaptor.capture()); + assertNotNull(pluginBindingCaptor.getValue()); + assertEquals(mockGroup, pluginBindingCaptor.getValue().getEngineGroup()); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/FlutterJNITest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/FlutterJNITest.java new file mode 100644 index 0000000000000000000000000000000000000000..a0809d5f22e2074aabdbe29810353f6170c700a6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/FlutterJNITest.java @@ -0,0 +1,316 @@ +// 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. + +package io.flutter.embedding.engine; + +import static io.flutter.Build.API_LEVELS; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.annotation.TargetApi; +import android.content.Context; +import android.content.res.Configuration; +import android.content.res.Resources; +import android.os.LocaleList; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.dart.DartExecutor; +import io.flutter.embedding.engine.mutatorsstack.FlutterMutatorsStack; +import io.flutter.embedding.engine.renderer.FlutterUiDisplayListener; +import io.flutter.embedding.engine.systemchannels.LocalizationChannel; +import io.flutter.plugin.localization.LocalizationPlugin; +import io.flutter.plugin.platform.PlatformViewsController; +import java.nio.ByteBuffer; +import java.util.Locale; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +@TargetApi(API_LEVELS.API_24) // LocaleList and scriptCode are API 24+. +public class FlutterJNITest { + @Test + public void itAllowsFirstFrameListenersToRemoveThemselvesInline() { + // --- Test Setup --- + FlutterJNI flutterJNI = new FlutterJNI(); + + AtomicInteger callbackInvocationCount = new AtomicInteger(0); + FlutterUiDisplayListener callback = + new FlutterUiDisplayListener() { + @Override + public void onFlutterUiDisplayed() { + callbackInvocationCount.incrementAndGet(); + flutterJNI.removeIsDisplayingFlutterUiListener(this); + } + + @Override + public void onFlutterUiNoLongerDisplayed() {} + }; + flutterJNI.addIsDisplayingFlutterUiListener(callback); + + // --- Execute Test --- + flutterJNI.onFirstFrame(); + + // --- Verify Results --- + assertEquals(1, callbackInvocationCount.get()); + + // --- Execute Test --- + // The callback removed itself from the listener list. A second call doesn't call the callback. + flutterJNI.onFirstFrame(); + + // --- Verify Results --- + assertEquals(1, callbackInvocationCount.get()); + } + + @Test + public void computePlatformResolvedLocaleCallsLocalizationPluginProperly() { + // --- Test Setup --- + FlutterJNI flutterJNI = new FlutterJNI(); + + Context context = mock(Context.class); + Resources resources = mock(Resources.class); + Configuration config = mock(Configuration.class); + DartExecutor dartExecutor = mock(DartExecutor.class); + LocaleList localeList = + new LocaleList(new Locale("es", "MX"), new Locale("zh", "CN"), new Locale("en", "US")); + when(context.getResources()).thenReturn(resources); + when(resources.getConfiguration()).thenReturn(config); + when(config.getLocales()).thenReturn(localeList); + + flutterJNI.setLocalizationPlugin( + new LocalizationPlugin(context, new LocalizationChannel(dartExecutor))); + String[] supportedLocales = + new String[] { + "fr", "FR", "", + "zh", "", "", + "en", "CA", "" + }; + String[] result = flutterJNI.computePlatformResolvedLocale(supportedLocales); + assertEquals(result.length, 3); + assertEquals(result[0], "zh"); + assertEquals(result[1], ""); + assertEquals(result[2], ""); + + supportedLocales = + new String[] { + "fr", "FR", "", + "ar", "", "", + "en", "CA", "" + }; + result = flutterJNI.computePlatformResolvedLocale(supportedLocales); + assertEquals(result.length, 3); + assertEquals(result[0], "en"); + assertEquals(result[1], "CA"); + assertEquals(result[2], ""); + + supportedLocales = + new String[] { + "fr", "FR", "", + "ar", "", "", + "en", "US", "" + }; + result = flutterJNI.computePlatformResolvedLocale(supportedLocales); + assertEquals(result.length, 3); + assertEquals(result[0], "en"); + assertEquals(result[1], "US"); + assertEquals(result[2], ""); + + supportedLocales = + new String[] { + "ar", "", "", + "es", "MX", "", + "en", "US", "" + }; + result = flutterJNI.computePlatformResolvedLocale(supportedLocales); + assertEquals(result.length, 3); + assertEquals(result[0], "es"); + assertEquals(result[1], "MX"); + assertEquals(result[2], ""); + + // Empty supportedLocales. + supportedLocales = new String[] {}; + result = flutterJNI.computePlatformResolvedLocale(supportedLocales); + assertEquals(result.length, 0); + + // Empty preferredLocales. + supportedLocales = + new String[] { + "fr", "FR", "", + "zh", "", "", + "en", "CA", "" + }; + localeList = new LocaleList(); + when(config.getLocales()).thenReturn(localeList); + result = flutterJNI.computePlatformResolvedLocale(supportedLocales); + // The first locale is default. + assertEquals(result.length, 3); + assertEquals(result[0], "fr"); + assertEquals(result[1], "FR"); + assertEquals(result[2], ""); + } + + @Test + public void setAccessibilityIfAttached() { + // --- Test Setup --- + FlutterJNITester flutterJNI = new FlutterJNITester(true); + int expectedFlag = 100; + + flutterJNI.setAccessibilityFeatures(expectedFlag); + assertEquals(flutterJNI.flags, expectedFlag); + + flutterJNI.setSemanticsEnabled(true); + assertTrue(flutterJNI.semanticsEnabled); + } + + @Test + public void doesNotSetAccessibilityIfNotAttached() { + // --- Test Setup --- + FlutterJNITester flutterJNI = new FlutterJNITester(false); + int flags = 100; + + flutterJNI.setAccessibilityFeatures(flags); + assertEquals(flutterJNI.flags, 0); + + flutterJNI.setSemanticsEnabled(true); + assertFalse(flutterJNI.semanticsEnabled); + } + + public void onDisplayPlatformView_callsPlatformViewsController() { + PlatformViewsController platformViewsController = mock(PlatformViewsController.class); + + FlutterJNI flutterJNI = new FlutterJNI(); + flutterJNI.setPlatformViewsController(platformViewsController); + FlutterMutatorsStack stack = new FlutterMutatorsStack(); + // --- Execute Test --- + flutterJNI.onDisplayPlatformView( + /*viewId=*/ 1, + /*x=*/ 10, + /*y=*/ 20, + /*width=*/ 100, + /*height=*/ 200, + /*viewWidth=*/ 100, + /*viewHeight=*/ 200, + /*mutatorsStack=*/ stack); + + // --- Verify Results --- + verify(platformViewsController, times(1)) + .onDisplayPlatformView( + /*viewId=*/ 1, + /*x=*/ 10, + /*y=*/ 20, + /*width=*/ 100, + /*height=*/ 200, + /*viewWidth=*/ 100, + /*viewHeight=*/ 200, + /*mutatorsStack=*/ stack); + } + + @Test + public void onDisplayOverlaySurface_callsPlatformViewsController() { + PlatformViewsController platformViewsController = mock(PlatformViewsController.class); + + FlutterJNI flutterJNI = new FlutterJNI(); + flutterJNI.setPlatformViewsController(platformViewsController); + + // --- Execute Test --- + flutterJNI.onDisplayOverlaySurface( + /*id=*/ 1, /*x=*/ 10, /*y=*/ 20, /*width=*/ 100, /*height=*/ 200); + + // --- Verify Results --- + verify(platformViewsController, times(1)) + .onDisplayOverlaySurface(/*id=*/ 1, /*x=*/ 10, /*y=*/ 20, /*width=*/ 100, /*height=*/ 200); + } + + @Test + public void onBeginFrame_callsPlatformViewsController() { + PlatformViewsController platformViewsController = mock(PlatformViewsController.class); + + // --- Test Setup --- + FlutterJNI flutterJNI = new FlutterJNI(); + flutterJNI.setPlatformViewsController(platformViewsController); + + // --- Execute Test --- + flutterJNI.onBeginFrame(); + + // --- Verify Results --- + verify(platformViewsController, times(1)).onBeginFrame(); + } + + @Test + public void onEndFrame_callsPlatformViewsController() { + PlatformViewsController platformViewsController = mock(PlatformViewsController.class); + + // --- Test Setup --- + FlutterJNI flutterJNI = new FlutterJNI(); + flutterJNI.setPlatformViewsController(platformViewsController); + + // --- Execute Test --- + flutterJNI.onEndFrame(); + + // --- Verify Results --- + verify(platformViewsController, times(1)).onEndFrame(); + } + + @Test + public void createOverlaySurface_callsPlatformViewsController() { + PlatformViewsController platformViewsController = mock(PlatformViewsController.class); + + FlutterJNI flutterJNI = new FlutterJNI(); + flutterJNI.setPlatformViewsController(platformViewsController); + + // --- Execute Test --- + flutterJNI.createOverlaySurface(); + + // --- Verify Results --- + verify(platformViewsController, times(1)).createOverlaySurface(); + } + + @Test(expected = IllegalArgumentException.class) + public void invokePlatformMessageResponseCallback_wantsDirectBuffer() { + FlutterJNI flutterJNI = new FlutterJNI(); + ByteBuffer buffer = ByteBuffer.allocate(4); + flutterJNI.invokePlatformMessageResponseCallback(0, buffer, buffer.position()); + } + + @Test + public void setRefreshRateFPS_callsUpdateRefreshRate() { + FlutterJNI flutterJNI = spy(new FlutterJNI()); + // --- Execute Test --- + flutterJNI.setRefreshRateFPS(120.0f); + // --- Verify Results --- + verify(flutterJNI, times(1)).updateRefreshRate(); + } + + static class FlutterJNITester extends FlutterJNI { + FlutterJNITester(boolean attached) { + this.isAttached = attached; + } + + final boolean isAttached; + boolean semanticsEnabled = false; + int flags = 0; + + @Override + public boolean isAttached() { + return isAttached; + } + + @Override + public void setSemanticsEnabledInNative(boolean enabled) { + semanticsEnabled = enabled; + } + + @Override + public void setAccessibilityFeaturesInNative(int flags) { + this.flags = flags; + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/FlutterShellArgsTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/FlutterShellArgsTest.java new file mode 100644 index 0000000000000000000000000000000000000000..55d18f3647b1f2a5ad55e695485a47c25a8de59f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/FlutterShellArgsTest.java @@ -0,0 +1,38 @@ +// 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. + +package test.io.flutter.embedding.engine; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import android.content.Intent; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.FlutterShellArgs; +import java.util.Arrays; +import java.util.HashSet; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class FlutterShellArgsTest { + @Test + public void itProcessesShellFlags() { + // Setup the test. + Intent intent = new Intent(); + intent.putExtra("dart-flags", "--observe --no-hot --no-pub"); + intent.putExtra("trace-skia-allowlist", "skia.a,skia.b"); + + // Execute the behavior under test. + FlutterShellArgs args = FlutterShellArgs.fromIntent(intent); + HashSet argValues = new HashSet(Arrays.asList(args.toArray())); + + // Verify results. + assertEquals(2, argValues.size()); + assertTrue(argValues.contains("--dart-flags=--observe --no-hot --no-pub")); + assertTrue(argValues.contains("--trace-skia-allowlist=skia.a,skia.b")); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/PluginComponentTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/PluginComponentTest.java new file mode 100644 index 0000000000000000000000000000000000000000..187355a7acf3dfd8188020c90c46d796ef4a4934 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/PluginComponentTest.java @@ -0,0 +1,100 @@ +// 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. + +package test.io.flutter.embedding.engine; + +import static junit.framework.TestCase.assertEquals; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import androidx.annotation.NonNull; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.FlutterEngine; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.loader.FlutterLoader; +import io.flutter.embedding.engine.plugins.FlutterPlugin; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class PluginComponentTest { + boolean jniAttached; + + @Test + public void pluginsCanAccessFlutterAssetPaths() { + // Setup test. + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + FlutterJNI flutterJNI = mock(FlutterJNI.class); + jniAttached = false; + when(flutterJNI.isAttached()).thenAnswer(invocation -> jniAttached); + doAnswer(invocation -> jniAttached = true).when(flutterJNI).attachToNative(); + + FlutterLoader flutterLoader = new FlutterLoader(mockFlutterJNI); + + // Execute behavior under test. + FlutterEngine flutterEngine = + new FlutterEngine(ApplicationProvider.getApplicationContext(), flutterLoader, flutterJNI); + + // As soon as our plugin is registered it will look up asset paths and store them + // for our verification. + PluginThatAccessesAssets plugin = new PluginThatAccessesAssets(); + flutterEngine.getPlugins().add(plugin); + + // Verify results. + assertEquals("flutter_assets/fake_asset.jpg", plugin.getAssetPathBasedOnName()); + assertEquals( + "flutter_assets/packages/fakepackage/fake_asset.jpg", + plugin.getAssetPathBasedOnNameAndPackage()); + assertEquals("flutter_assets/some/path/fake_asset.jpg", plugin.getAssetPathBasedOnSubpath()); + assertEquals( + "flutter_assets/packages/fakepackage/some/path/fake_asset.jpg", + plugin.getAssetPathBasedOnSubpathAndPackage()); + } + + private static class PluginThatAccessesAssets implements FlutterPlugin { + private String assetPathBasedOnName; + private String assetPathBasedOnNameAndPackage; + private String assetPathBasedOnSubpath; + private String assetPathBasedOnSubpathAndPackage; + + public String getAssetPathBasedOnName() { + return assetPathBasedOnName; + } + + public String getAssetPathBasedOnNameAndPackage() { + return assetPathBasedOnNameAndPackage; + } + + public String getAssetPathBasedOnSubpath() { + return assetPathBasedOnSubpath; + } + + public String getAssetPathBasedOnSubpathAndPackage() { + return assetPathBasedOnSubpathAndPackage; + } + + @Override + public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) { + assetPathBasedOnName = binding.getFlutterAssets().getAssetFilePathByName("fake_asset.jpg"); + + assetPathBasedOnNameAndPackage = + binding.getFlutterAssets().getAssetFilePathByName("fake_asset.jpg", "fakepackage"); + + assetPathBasedOnSubpath = + binding.getFlutterAssets().getAssetFilePathByName("some/path/fake_asset.jpg"); + + assetPathBasedOnSubpathAndPackage = + binding + .getFlutterAssets() + .getAssetFilePathByName("some/path/fake_asset.jpg", "fakepackage"); + } + + @Override + public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {} + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/RenderingComponentTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/RenderingComponentTest.java new file mode 100644 index 0000000000000000000000000000000000000000..297411237452240a94a7eb03257a0616d145d4bf --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/RenderingComponentTest.java @@ -0,0 +1,96 @@ +// 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. + +package io.flutter.embedding.engine; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.renderer.FlutterRenderer; +import io.flutter.embedding.engine.renderer.FlutterUiDisplayListener; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class RenderingComponentTest { + @Test + public void flutterUiDisplayListenersCanRemoveThemselvesWhenInvoked() { + // Setup test. + FlutterJNI flutterJNI = new FlutterJNI(); + FlutterRenderer flutterRenderer = new FlutterRenderer(flutterJNI); + + AtomicInteger listenerInvocationCount = new AtomicInteger(0); + FlutterUiDisplayListener listener = + new FlutterUiDisplayListener() { + @Override + public void onFlutterUiDisplayed() { + // This is the behavior we're testing, but we also verify that this method + // was invoked to ensure that this test behavior executed. + flutterRenderer.removeIsDisplayingFlutterUiListener(this); + + // Track the invocation to ensure this method is called once, and only once. + listenerInvocationCount.incrementAndGet(); + } + + @Override + public void onFlutterUiNoLongerDisplayed() {} + }; + flutterRenderer.addIsDisplayingFlutterUiListener(listener); + + // Execute behavior under test. + // Pretend we are the native side and tell FlutterJNI that Flutter has rendered a frame. + flutterJNI.onFirstFrame(); + + // Verify results. + // If we got to this point without an exception, and if our listener was called one time, + // then the behavior under test is correct. + assertEquals(1, listenerInvocationCount.get()); + } + + @Test + public void flutterUiDisplayListenersAddedAfterFirstFrameAreAutomaticallyInvoked() { + // Setup test. + FlutterJNI flutterJNI = new FlutterJNI(); + FlutterRenderer flutterRenderer = new FlutterRenderer(flutterJNI); + + FlutterUiDisplayListener listener = mock(FlutterUiDisplayListener.class); + + // Pretend we are the native side and tell FlutterJNI that Flutter has rendered a frame. + flutterJNI.onFirstFrame(); + + // Execute behavior under test. + flutterRenderer.addIsDisplayingFlutterUiListener(listener); + + // Verify results. + verify(listener, times(1)).onFlutterUiDisplayed(); + } + + @Test + public void flutterUiDisplayListenersAddedAfterFlutterUiDisappearsAreNotInvoked() { + // Setup test. + FlutterJNI flutterJNI = new FlutterJNI(); + FlutterRenderer flutterRenderer = new FlutterRenderer(flutterJNI); + + FlutterUiDisplayListener listener = mock(FlutterUiDisplayListener.class); + + // Pretend we are the native side and tell FlutterJNI that Flutter has rendered a frame. + flutterJNI.onFirstFrame(); + + // Pretend that rendering has stopped. + flutterJNI.onRenderingStopped(); + + // Execute behavior under test. + flutterRenderer.addIsDisplayingFlutterUiListener(listener); + + // Verify results. + verify(listener, never()).onFlutterUiDisplayed(); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/dart/DartExecutorTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/dart/DartExecutorTest.java new file mode 100644 index 0000000000000000000000000000000000000000..bba9911521345bab74c969c17802eff965effeef --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/dart/DartExecutorTest.java @@ -0,0 +1,91 @@ +// 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. + +package io.flutter.embedding.engine.dart; + +import static junit.framework.TestCase.assertNotNull; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.content.res.AssetManager; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.FlutterInjector; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.dart.DartExecutor.DartEntrypoint; +import io.flutter.embedding.engine.loader.FlutterLoader; +import java.nio.ByteBuffer; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class DartExecutorTest { + @Mock FlutterLoader mockFlutterLoader; + + @Before + public void setUp() { + FlutterInjector.reset(); + MockitoAnnotations.openMocks(this); + } + + @Test + public void itSendsBinaryMessages() { + // Setup test. + FlutterJNI fakeFlutterJni = mock(FlutterJNI.class); + + // Create object under test. + DartExecutor dartExecutor = new DartExecutor(fakeFlutterJni, mock(AssetManager.class)); + + // Verify a BinaryMessenger exists. + assertNotNull(dartExecutor.getBinaryMessenger()); + + // Execute the behavior under test. + ByteBuffer fakeMessage = mock(ByteBuffer.class); + dartExecutor.getBinaryMessenger().send("fake_channel", fakeMessage); + + // Verify that DartExecutor sent our message to FlutterJNI. + verify(fakeFlutterJni, times(1)) + .dispatchPlatformMessage(eq("fake_channel"), eq(fakeMessage), anyInt(), anyInt()); + } + + @Test + public void itNotifiesLowMemoryWarning() { + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + when(mockFlutterJNI.isAttached()).thenReturn(true); + + DartExecutor dartExecutor = new DartExecutor(mockFlutterJNI, mock(AssetManager.class)); + dartExecutor.notifyLowMemoryWarning(); + verify(mockFlutterJNI, times(1)).notifyLowMemoryWarning(); + } + + @Test + public void itThrowsWhenCreatingADefaultDartEntrypointWithAnUninitializedFlutterLoader() { + assertThrows( + AssertionError.class, + () -> { + DartEntrypoint.createDefault(); + }); + } + + @Test + public void itHasReasonableDefaultsWhenFlutterLoaderIsInitialized() { + when(mockFlutterLoader.initialized()).thenReturn(true); + when(mockFlutterLoader.findAppBundlePath()).thenReturn("my/custom/path"); + FlutterInjector.setInstance( + new FlutterInjector.Builder().setFlutterLoader(mockFlutterLoader).build()); + DartEntrypoint entrypoint = DartEntrypoint.createDefault(); + assertEquals(entrypoint.pathToBundle, "my/custom/path"); + assertEquals(entrypoint.dartEntrypointFunctionName, "main"); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/dart/DartMessengerTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/dart/DartMessengerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..ecd602c06bdbaa8b31fa9d8ea70702e828a8e72e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/dart/DartMessengerTest.java @@ -0,0 +1,359 @@ +// 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. + +package io.flutter.embedding.engine.dart; + +import static android.os.Looper.getMainLooper; +import static junit.framework.TestCase.assertEquals; +import static junit.framework.TestCase.assertNotNull; +import static junit.framework.TestCase.assertTrue; +import static org.junit.Assert.assertArrayEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.robolectric.Shadows.shadowOf; + +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.dart.DartMessenger.DartMessengerTaskQueue; +import io.flutter.plugin.common.BinaryMessenger; +import io.flutter.plugin.common.BinaryMessenger.BinaryMessageHandler; +import java.nio.ByteBuffer; +import java.util.LinkedList; +import java.util.Random; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class DartMessengerTest { + SynchronousTaskQueue synchronousTaskQueue = new SynchronousTaskQueue(); + + private static class ReportingUncaughtExceptionHandler + implements Thread.UncaughtExceptionHandler { + public Throwable latestException; + + @Override + public void uncaughtException(Thread t, Throwable e) { + latestException = e; + } + } + + private static class SynchronousTaskQueue implements DartMessengerTaskQueue { + public void dispatch(Runnable runnable) { + runnable.run(); + } + } + + @Test + public void itHandlesErrors() { + // Setup test. + final FlutterJNI fakeFlutterJni = mock(FlutterJNI.class); + final Thread currentThread = Thread.currentThread(); + final Thread.UncaughtExceptionHandler savedHandler = + currentThread.getUncaughtExceptionHandler(); + final ReportingUncaughtExceptionHandler reportingHandler = + new ReportingUncaughtExceptionHandler(); + currentThread.setUncaughtExceptionHandler(reportingHandler); + + // Create object under test. + final DartMessenger messenger = + new DartMessenger(fakeFlutterJni, (options) -> synchronousTaskQueue); + final BinaryMessageHandler throwingHandler = mock(BinaryMessageHandler.class); + Mockito.doThrow(AssertionError.class) + .when(throwingHandler) + .onMessage(any(ByteBuffer.class), any(DartMessenger.Reply.class)); + BinaryMessenger.TaskQueue taskQueue = messenger.makeBackgroundTaskQueue(); + messenger.setMessageHandler("test", throwingHandler, taskQueue); + messenger.handleMessageFromDart("test", ByteBuffer.allocate(0), 0, 0); + assertNotNull(reportingHandler.latestException); + assertTrue(reportingHandler.latestException instanceof AssertionError); + currentThread.setUncaughtExceptionHandler(savedHandler); + } + + @Test + public void givesDirectByteBuffer() { + // Setup test. + final FlutterJNI fakeFlutterJni = mock(FlutterJNI.class); + final DartMessenger messenger = + new DartMessenger(fakeFlutterJni, (options) -> synchronousTaskQueue); + final String channel = "foobar"; + final boolean[] wasDirect = {false}; + final BinaryMessenger.BinaryMessageHandler handler = + (message, reply) -> { + wasDirect[0] = message.isDirect(); + }; + BinaryMessenger.TaskQueue taskQueue = messenger.makeBackgroundTaskQueue(); + messenger.setMessageHandler(channel, handler, taskQueue); + final ByteBuffer message = ByteBuffer.allocateDirect(4 * 2); + message.rewind(); + message.putChar('a'); + message.putChar('b'); + message.putChar('c'); + message.putChar('d'); + messenger.handleMessageFromDart(channel, message, /*replyId=*/ 123, 0); + assertTrue(wasDirect[0]); + } + + @Test + public void directByteBufferLimitZeroAfterUsage() { + // Setup test. + final FlutterJNI fakeFlutterJni = mock(FlutterJNI.class); + final DartMessenger messenger = + new DartMessenger(fakeFlutterJni, (options) -> synchronousTaskQueue); + final String channel = "foobar"; + final ByteBuffer[] byteBuffers = {null}; + final int bufferSize = 4 * 2; + final BinaryMessenger.BinaryMessageHandler handler = + (message, reply) -> { + byteBuffers[0] = message; + assertEquals(bufferSize, byteBuffers[0].limit()); + }; + BinaryMessenger.TaskQueue taskQueue = messenger.makeBackgroundTaskQueue(); + messenger.setMessageHandler(channel, handler, taskQueue); + final ByteBuffer message = ByteBuffer.allocateDirect(bufferSize); + message.rewind(); + message.putChar('a'); + message.putChar('b'); + message.putChar('c'); + message.putChar('d'); + messenger.handleMessageFromDart(channel, message, /*replyId=*/ 123, 0); + assertNotNull(byteBuffers[0]); + assertTrue(byteBuffers[0].isDirect()); + assertEquals(0, byteBuffers[0].limit()); + } + + @Test + public void directByteBufferLimitZeroAfterReply() { + // Setup test. + final FlutterJNI fakeFlutterJni = mock(FlutterJNI.class); + final DartMessenger messenger = new DartMessenger(fakeFlutterJni); + final ByteBuffer message = ByteBuffer.allocateDirect(4 * 2); + final String channel = "foobar"; + message.rewind(); + message.putChar('a'); + message.putChar('b'); + message.putChar('c'); + message.putChar('d'); + final ByteBuffer[] byteBuffers = {null}; + BinaryMessenger.BinaryReply callback = + (reply) -> { + assertTrue(reply.isDirect()); + byteBuffers[0] = reply; + }; + messenger.send(channel, null, callback); + messenger.handlePlatformMessageResponse(1, message); + assertEquals(0, byteBuffers[0].limit()); + } + + @Test + public void replyIdIncrementsOnNullReply() { + /// Setup test. + final FlutterJNI fakeFlutterJni = mock(FlutterJNI.class); + final DartMessenger messenger = new DartMessenger(fakeFlutterJni); + final String channel = "foobar"; + messenger.send(channel, null, null); + verify(fakeFlutterJni, times(1)).dispatchEmptyPlatformMessage(eq("foobar"), eq(1)); + messenger.send(channel, null, null); + verify(fakeFlutterJni, times(1)).dispatchEmptyPlatformMessage(eq("foobar"), eq(2)); + } + + @Test + public void cleansUpMessageData() throws InterruptedException { + final FlutterJNI fakeFlutterJni = mock(FlutterJNI.class); + final DartMessenger messenger = + new DartMessenger(fakeFlutterJni, (options) -> synchronousTaskQueue); + BinaryMessenger.TaskQueue taskQueue = messenger.makeBackgroundTaskQueue(); + String channel = "foobar"; + BinaryMessenger.BinaryMessageHandler handler = + (ByteBuffer message, BinaryMessenger.BinaryReply reply) -> { + reply.reply(null); + }; + messenger.setMessageHandler(channel, handler, taskQueue); + final ByteBuffer message = ByteBuffer.allocateDirect(4 * 2); + final int replyId = 1; + final long messageData = 1234; + messenger.handleMessageFromDart(channel, message, replyId, messageData); + verify(fakeFlutterJni).cleanupMessageData(eq(messageData)); + } + + @Test + public void cleansUpMessageDataOnError() throws InterruptedException { + final FlutterJNI fakeFlutterJni = mock(FlutterJNI.class); + final DartMessenger messenger = + new DartMessenger(fakeFlutterJni, (options) -> synchronousTaskQueue); + BinaryMessenger.TaskQueue taskQueue = messenger.makeBackgroundTaskQueue(); + String channel = "foobar"; + BinaryMessenger.BinaryMessageHandler handler = + (ByteBuffer message, BinaryMessenger.BinaryReply reply) -> { + throw new RuntimeException("hello"); + }; + messenger.setMessageHandler(channel, handler, taskQueue); + final ByteBuffer message = ByteBuffer.allocateDirect(4 * 2); + final int replyId = 1; + final long messageData = 1234; + + messenger.handleMessageFromDart(channel, message, replyId, messageData); + verify(fakeFlutterJni).cleanupMessageData(eq(messageData)); + } + + @Test + public void emptyResponseWhenHandlerIsNotSet() throws InterruptedException { + final FlutterJNI fakeFlutterJni = mock(FlutterJNI.class); + final DartMessenger messenger = + new DartMessenger(fakeFlutterJni, (options) -> synchronousTaskQueue); + final String channel = "foobar"; + final ByteBuffer message = ByteBuffer.allocateDirect(4 * 2); + final int replyId = 1; + final long messageData = 1234; + + messenger.handleMessageFromDart(channel, message, replyId, messageData); + shadowOf(getMainLooper()).idle(); + verify(fakeFlutterJni).invokePlatformMessageEmptyResponseCallback(replyId); + } + + @Test + public void buffersResponseWhenHandlerIsNotSet() throws InterruptedException { + final FlutterJNI fakeFlutterJni = mock(FlutterJNI.class); + final DartMessenger messenger = + new DartMessenger(fakeFlutterJni, (options) -> synchronousTaskQueue); + final BinaryMessenger.TaskQueue taskQueue = messenger.makeBackgroundTaskQueue(); + final String channel = "foobar"; + final ByteBuffer message = ByteBuffer.allocateDirect(4 * 2); + final int replyId = 1; + final long messageData = 1234; + + messenger.enableBufferingIncomingMessages(); + messenger.handleMessageFromDart(channel, message, replyId, messageData); + + shadowOf(getMainLooper()).idle(); + verify(fakeFlutterJni, never()).invokePlatformMessageEmptyResponseCallback(eq(replyId)); + + final BinaryMessenger.BinaryMessageHandler handler = + (ByteBuffer msg, BinaryMessenger.BinaryReply reply) -> { + reply.reply(ByteBuffer.wrap("done".getBytes())); + }; + messenger.setMessageHandler(channel, handler, taskQueue); + + shadowOf(getMainLooper()).idle(); + verify(fakeFlutterJni, never()).invokePlatformMessageEmptyResponseCallback(eq(replyId)); + + final ArgumentCaptor response = ArgumentCaptor.forClass(ByteBuffer.class); + verify(fakeFlutterJni) + .invokePlatformMessageResponseCallback(anyInt(), response.capture(), anyInt()); + assertArrayEquals("done".getBytes(), response.getValue().array()); + } + + @Test + public void disableBufferingTriggersEmptyResponseForPendingMessages() + throws InterruptedException { + final FlutterJNI fakeFlutterJni = mock(FlutterJNI.class); + final DartMessenger messenger = + new DartMessenger(fakeFlutterJni, (options) -> synchronousTaskQueue); + final String channel = "foobar"; + final ByteBuffer message = ByteBuffer.allocateDirect(4 * 2); + final int replyId = 1; + final long messageData = 1234; + + messenger.enableBufferingIncomingMessages(); + messenger.handleMessageFromDart(channel, message, replyId, messageData); + shadowOf(getMainLooper()).idle(); + verify(fakeFlutterJni, never()).invokePlatformMessageEmptyResponseCallback(replyId); + + messenger.disableBufferingIncomingMessages(); + shadowOf(getMainLooper()).idle(); + verify(fakeFlutterJni).invokePlatformMessageEmptyResponseCallback(replyId); + } + + @Test + public void emptyResponseWhenHandlerIsUnregistered() throws InterruptedException { + final FlutterJNI fakeFlutterJni = mock(FlutterJNI.class); + final DartMessenger messenger = + new DartMessenger(fakeFlutterJni, (options) -> synchronousTaskQueue); + final BinaryMessenger.TaskQueue taskQueue = messenger.makeBackgroundTaskQueue(); + final String channel = "foobar"; + final ByteBuffer message = ByteBuffer.allocateDirect(4 * 2); + final int replyId = 1; + final long messageData = 1234; + + messenger.enableBufferingIncomingMessages(); + messenger.handleMessageFromDart(channel, message, replyId, messageData); + + shadowOf(getMainLooper()).idle(); + verify(fakeFlutterJni, never()).invokePlatformMessageEmptyResponseCallback(eq(replyId)); + + final BinaryMessenger.BinaryMessageHandler handler = + (ByteBuffer msg, BinaryMessenger.BinaryReply reply) -> { + reply.reply(ByteBuffer.wrap("done".getBytes())); + }; + messenger.setMessageHandler(channel, handler, taskQueue); + + shadowOf(getMainLooper()).idle(); + verify(fakeFlutterJni, never()).invokePlatformMessageEmptyResponseCallback(eq(replyId)); + + final ArgumentCaptor response = ArgumentCaptor.forClass(ByteBuffer.class); + verify(fakeFlutterJni) + .invokePlatformMessageResponseCallback(anyInt(), response.capture(), anyInt()); + assertArrayEquals("done".getBytes(), response.getValue().array()); + + messenger.disableBufferingIncomingMessages(); + messenger.setMessageHandler(channel, null, null); // Unregister handler. + + messenger.handleMessageFromDart(channel, message, replyId, messageData); + shadowOf(getMainLooper()).idle(); + verify(fakeFlutterJni).invokePlatformMessageEmptyResponseCallback(replyId); + } + + @Test + public void testSerialTaskQueue() throws InterruptedException { + final FlutterJNI fakeFlutterJni = mock(FlutterJNI.class); + final DartMessenger messenger = new DartMessenger(fakeFlutterJni); + final ExecutorService taskQueuePool = Executors.newFixedThreadPool(4); + final DartMessengerTaskQueue taskQueue = new DartMessenger.SerialTaskQueue(taskQueuePool); + final int count = 5000; + final LinkedList ints = new LinkedList<>(); + Random rand = new Random(); + for (int i = 0; i < count; ++i) { + final int value = i; + taskQueue.dispatch( + () -> { + try { + Thread.sleep(rand.nextInt(10)); + } catch (InterruptedException ex) { + System.out.println(ex.toString()); + } + ints.add(value); + }); + taskQueuePool.execute( + () -> { + // Add some extra noise to make sure we aren't always handling on the same thread. + try { + Thread.sleep(rand.nextInt(10)); + } catch (InterruptedException ex) { + System.out.println(ex.toString()); + } + }); + } + CountDownLatch latch = new CountDownLatch(1); + taskQueue.dispatch( + () -> { + latch.countDown(); + }); + latch.await(); + assertEquals(count, ints.size()); + for (int i = 0; i < count - 1; ++i) { + assertEquals((int) ints.get(i), (int) (ints.get(i + 1)) - 1); + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/deferredcomponents/PlayStoreDeferredComponentManagerTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/deferredcomponents/PlayStoreDeferredComponentManagerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..735382b21cdb2085277b3745822fd2dbb4eaa888 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/deferredcomponents/PlayStoreDeferredComponentManagerTest.java @@ -0,0 +1,349 @@ +// 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. + +package io.flutter.embedding.engine.deferredcomponents; + +import static junit.framework.TestCase.assertEquals; +import static junit.framework.TestCase.assertFalse; +import static junit.framework.TestCase.assertTrue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyInt; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import android.content.Context; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; +import android.content.pm.PackageManager.NameNotFoundException; +import android.content.res.AssetManager; +import android.os.Bundle; +import androidx.annotation.NonNull; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.loader.ApplicationInfoLoader; +import java.io.File; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class PlayStoreDeferredComponentManagerTest { + private class TestFlutterJNI extends FlutterJNI { + public int loadDartDeferredLibraryCalled = 0; + public int updateAssetManagerCalled = 0; + public int deferredComponentInstallFailureCalled = 0; + public String[] searchPaths; + public int loadingUnitId; + public AssetManager assetManager; + public String assetBundlePath; + + public TestFlutterJNI() {} + + @Override + public void loadDartDeferredLibrary(int loadingUnitId, @NonNull String[] searchPaths) { + loadDartDeferredLibraryCalled++; + this.searchPaths = searchPaths; + this.loadingUnitId = loadingUnitId; + } + + @Override + public void updateJavaAssetManager( + @NonNull AssetManager assetManager, @NonNull String assetBundlePath) { + updateAssetManagerCalled++; + this.loadingUnitId = loadingUnitId; + this.assetManager = assetManager; + this.assetBundlePath = assetBundlePath; + } + + @Override + public void deferredComponentInstallFailure( + int loadingUnitId, @NonNull String error, boolean isTransient) { + deferredComponentInstallFailureCalled++; + } + } + + // Skips the download process to directly call the loadAssets and loadDartLibrary methods. + private class TestPlayStoreDeferredComponentManager extends PlayStoreDeferredComponentManager { + public TestPlayStoreDeferredComponentManager(Context context, FlutterJNI jni) { + super(context, jni); + } + + @Override + public void installDeferredComponent(int loadingUnitId, String componentName) { + // Override this to skip the online SplitInstallManager portion. + loadAssets(loadingUnitId, componentName); + loadDartLibrary(loadingUnitId, componentName); + } + } + + @SuppressWarnings("deprecation") + // getApplicationInfo + private Context createSpyContext(Bundle metadata) throws NameNotFoundException { + Context spyContext = spy(ApplicationProvider.getApplicationContext()); + doReturn(spyContext).when(spyContext).createPackageContext(any(), anyInt()); + if (metadata == null) { + metadata = new Bundle(); + } + PackageManager packageManager = mock(PackageManager.class); + ApplicationInfo applicationInfo = mock(ApplicationInfo.class); + applicationInfo.metaData = metadata; + applicationInfo.splitSourceDirs = new String[1]; + applicationInfo.splitSourceDirs[0] = "some.invalid.apk"; + when(packageManager.getApplicationInfo(any(String.class), any(int.class))) + .thenReturn(applicationInfo); + doReturn(packageManager).when(spyContext).getPackageManager(); + doReturn(applicationInfo).when(spyContext).getApplicationInfo(); + return spyContext; + } + + @Test + public void downloadCallsJNIFunctions() throws NameNotFoundException { + TestFlutterJNI jni = new TestFlutterJNI(); + Context spyContext = createSpyContext(null); + doReturn(null).when(spyContext).getAssets(); + String soTestFilename = "libapp.so-123.part.so"; + String soTestPath = "test/path/" + soTestFilename; + doReturn(new File(soTestPath)).when(spyContext).getFilesDir(); + TestPlayStoreDeferredComponentManager playStoreManager = + new TestPlayStoreDeferredComponentManager(spyContext, jni); + jni.setDeferredComponentManager(playStoreManager); + assertEquals(jni.loadingUnitId, 0); + + playStoreManager.installDeferredComponent(123, "TestModuleName"); + assertEquals(jni.loadDartDeferredLibraryCalled, 1); + assertEquals(jni.updateAssetManagerCalled, 1); + assertEquals(jni.deferredComponentInstallFailureCalled, 0); + + assertEquals(jni.searchPaths[0], soTestFilename); + assertTrue(jni.searchPaths[1].endsWith(soTestPath)); + assertEquals(jni.searchPaths.length, 2); + assertEquals(jni.loadingUnitId, 123); + assertEquals(jni.assetBundlePath, "flutter_assets"); + } + + @Test + public void downloadCallsJNIFunctionsWithFilenameFromManifest() throws NameNotFoundException { + TestFlutterJNI jni = new TestFlutterJNI(); + + Bundle bundle = new Bundle(); + bundle.putString(ApplicationInfoLoader.PUBLIC_AOT_SHARED_LIBRARY_NAME, "custom_name.so"); + bundle.putString(ApplicationInfoLoader.PUBLIC_FLUTTER_ASSETS_DIR_KEY, "custom_assets"); + + Context spyContext = createSpyContext(bundle); + doReturn(null).when(spyContext).getAssets(); + + String soTestFilename = "custom_name.so-123.part.so"; + String soTestPath = "test/path/" + soTestFilename; + doReturn(new File(soTestPath)).when(spyContext).getFilesDir(); + TestPlayStoreDeferredComponentManager playStoreManager = + new TestPlayStoreDeferredComponentManager(spyContext, jni); + jni.setDeferredComponentManager(playStoreManager); + assertEquals(jni.loadingUnitId, 0); + + playStoreManager.installDeferredComponent(123, "TestModuleName"); + assertEquals(jni.loadDartDeferredLibraryCalled, 1); + assertEquals(jni.updateAssetManagerCalled, 1); + assertEquals(jni.deferredComponentInstallFailureCalled, 0); + + assertEquals(jni.searchPaths[0], soTestFilename); + assertTrue(jni.searchPaths[1].endsWith(soTestPath)); + assertEquals(jni.searchPaths.length, 2); + assertEquals(jni.loadingUnitId, 123); + assertEquals(jni.assetBundlePath, "custom_assets"); + } + + @Test + public void downloadCallsJNIFunctionsWithSharedLibraryNameFromManifest() + throws NameNotFoundException { + TestFlutterJNI jni = new TestFlutterJNI(); + + Bundle bundle = new Bundle(); + bundle.putString(PlayStoreDeferredComponentManager.MAPPING_KEY, "123:module:custom_name.so"); + bundle.putString(ApplicationInfoLoader.PUBLIC_FLUTTER_ASSETS_DIR_KEY, "custom_assets"); + + Context spyContext = createSpyContext(bundle); + doReturn(null).when(spyContext).getAssets(); + + String soTestFilename = "custom_name.so"; + String soTestPath = "test/path/" + soTestFilename; + doReturn(new File(soTestPath)).when(spyContext).getFilesDir(); + TestPlayStoreDeferredComponentManager playStoreManager = + new TestPlayStoreDeferredComponentManager(spyContext, jni); + jni.setDeferredComponentManager(playStoreManager); + assertEquals(jni.loadingUnitId, 0); + + playStoreManager.installDeferredComponent(123, "TestModuleName"); + assertEquals(jni.loadDartDeferredLibraryCalled, 1); + assertEquals(jni.updateAssetManagerCalled, 1); + assertEquals(jni.deferredComponentInstallFailureCalled, 0); + + assertEquals(jni.searchPaths[0], soTestFilename); + assertTrue(jni.searchPaths[1].endsWith(soTestPath)); + assertEquals(jni.searchPaths.length, 2); + assertEquals(jni.loadingUnitId, 123); + assertEquals(jni.assetBundlePath, "custom_assets"); + } + + @Test + public void manifestMappingHandlesBaseModuleEmptyString() throws NameNotFoundException { + TestFlutterJNI jni = new TestFlutterJNI(); + + Bundle bundle = new Bundle(); + bundle.putString( + PlayStoreDeferredComponentManager.MAPPING_KEY, "123:module:custom_name.so,3:,4:"); + bundle.putString(ApplicationInfoLoader.PUBLIC_FLUTTER_ASSETS_DIR_KEY, "custom_assets"); + + Context spyContext = createSpyContext(bundle); + doReturn(null).when(spyContext).getAssets(); + + String soTestFilename = "libapp.so-3.part.so"; + String soTestPath = "test/path/" + soTestFilename; + doReturn(new File(soTestPath)).when(spyContext).getFilesDir(); + PlayStoreDeferredComponentManager playStoreManager = + new PlayStoreDeferredComponentManager(spyContext, jni); + jni.setDeferredComponentManager(playStoreManager); + assertEquals(jni.loadingUnitId, 0); + + playStoreManager.installDeferredComponent(3, null); + assertEquals(jni.loadDartDeferredLibraryCalled, 1); + assertEquals(jni.updateAssetManagerCalled, 0); // no assets to load for base + assertEquals(jni.deferredComponentInstallFailureCalled, 0); + + assertEquals(jni.searchPaths[0], soTestFilename); + assertTrue(jni.searchPaths[1].endsWith(soTestPath)); + assertEquals(jni.searchPaths.length, 2); + assertEquals(jni.loadingUnitId, 3); + } + + @Test + public void searchPathsAddsApks() throws NameNotFoundException { + TestFlutterJNI jni = new TestFlutterJNI(); + Context spyContext = createSpyContext(null); + doReturn(null).when(spyContext).getAssets(); + String apkTestPath = "test/path/TestModuleName_armeabi_v7a.apk"; + doReturn(new File(apkTestPath)).when(spyContext).getFilesDir(); + TestPlayStoreDeferredComponentManager playStoreManager = + new TestPlayStoreDeferredComponentManager(spyContext, jni); + jni.setDeferredComponentManager(playStoreManager); + + assertEquals(jni.loadingUnitId, 0); + + playStoreManager.installDeferredComponent(123, "TestModuleName"); + assertEquals(jni.loadDartDeferredLibraryCalled, 1); + assertEquals(jni.updateAssetManagerCalled, 1); + assertEquals(jni.deferredComponentInstallFailureCalled, 0); + + assertEquals(jni.searchPaths[0], "libapp.so-123.part.so"); + assertTrue(jni.searchPaths[1].endsWith(apkTestPath + "!lib/armeabi-v7a/libapp.so-123.part.so")); + assertEquals(jni.searchPaths.length, 2); + assertEquals(jni.loadingUnitId, 123); + } + + @Test + public void searchPathsSearchesSplitConfig() throws NameNotFoundException { + TestFlutterJNI jni = new TestFlutterJNI(); + Context spyContext = createSpyContext(null); + doReturn(null).when(spyContext).getAssets(); + String apkTestPath = "test/path/split_config.armeabi_v7a.apk"; + doReturn(new File(apkTestPath)).when(spyContext).getFilesDir(); + TestPlayStoreDeferredComponentManager playStoreManager = + new TestPlayStoreDeferredComponentManager(spyContext, jni); + jni.setDeferredComponentManager(playStoreManager); + + assertEquals(jni.loadingUnitId, 0); + + playStoreManager.installDeferredComponent(123, "TestModuleName"); + assertEquals(jni.loadDartDeferredLibraryCalled, 1); + assertEquals(jni.updateAssetManagerCalled, 1); + assertEquals(jni.deferredComponentInstallFailureCalled, 0); + + assertEquals(jni.searchPaths[0], "libapp.so-123.part.so"); + assertTrue(jni.searchPaths[1].endsWith(apkTestPath + "!lib/armeabi-v7a/libapp.so-123.part.so")); + assertEquals(jni.searchPaths.length, 2); + assertEquals(jni.loadingUnitId, 123); + } + + @Test + public void invalidSearchPathsAreIgnored() throws NameNotFoundException { + TestFlutterJNI jni = new TestFlutterJNI(); + Context spyContext = createSpyContext(null); + doReturn(null).when(spyContext).getAssets(); + String apkTestPath = "test/path/invalidpath.apk"; + doReturn(new File(apkTestPath)).when(spyContext).getFilesDir(); + TestPlayStoreDeferredComponentManager playStoreManager = + new TestPlayStoreDeferredComponentManager(spyContext, jni); + jni.setDeferredComponentManager(playStoreManager); + + assertEquals(jni.loadingUnitId, 0); + + playStoreManager.installDeferredComponent(123, "TestModuleName"); + assertEquals(jni.loadDartDeferredLibraryCalled, 1); + assertEquals(jni.updateAssetManagerCalled, 1); + assertEquals(jni.deferredComponentInstallFailureCalled, 0); + + assertEquals(jni.searchPaths[0], "libapp.so-123.part.so"); + assertEquals(jni.searchPaths.length, 1); + assertEquals(jni.loadingUnitId, 123); + } + + @Test + public void assetManagerUpdateInvoked() throws NameNotFoundException { + TestFlutterJNI jni = new TestFlutterJNI(); + Context spyContext = createSpyContext(null); + doReturn(null).when(spyContext).getAssets(); + AssetManager assetManager = spyContext.getAssets(); + String apkTestPath = "blah doesn't matter here"; + doReturn(new File(apkTestPath)).when(spyContext).getFilesDir(); + TestPlayStoreDeferredComponentManager playStoreManager = + new TestPlayStoreDeferredComponentManager(spyContext, jni); + jni.setDeferredComponentManager(playStoreManager); + + assertEquals(jni.loadingUnitId, 0); + + playStoreManager.installDeferredComponent(123, "TestModuleName"); + assertEquals(jni.loadDartDeferredLibraryCalled, 1); + assertEquals(jni.updateAssetManagerCalled, 1); + assertEquals(jni.deferredComponentInstallFailureCalled, 0); + + assertEquals(jni.assetManager, assetManager); + } + + @Test + public void stateGetterReturnsUnknowByDefault() throws NameNotFoundException { + TestFlutterJNI jni = new TestFlutterJNI(); + Context spyContext = createSpyContext(null); + doReturn(null).when(spyContext).getAssets(); + TestPlayStoreDeferredComponentManager playStoreManager = + new TestPlayStoreDeferredComponentManager(spyContext, jni); + assertEquals(playStoreManager.getDeferredComponentInstallState(-1, "invalidName"), "unknown"); + } + + @Test + public void loadingUnitMappingFindsMatch() throws NameNotFoundException { + TestFlutterJNI jni = new TestFlutterJNI(); + Bundle bundle = new Bundle(); + bundle.putString(PlayStoreDeferredComponentManager.MAPPING_KEY, "2:module1,5:module2"); + Context spyContext = createSpyContext(bundle); + TestPlayStoreDeferredComponentManager playStoreManager = + new TestPlayStoreDeferredComponentManager(spyContext, jni); + + assertTrue(playStoreManager.uninstallDeferredComponent(5, null)); + assertTrue(playStoreManager.uninstallDeferredComponent(2, null)); + assertFalse(playStoreManager.uninstallDeferredComponent(3, null)); + } + + @Test + public void assetOnlyMappingParses() throws NameNotFoundException { + TestFlutterJNI jni = new TestFlutterJNI(); + Bundle bundle = new Bundle(); + bundle.putString(PlayStoreDeferredComponentManager.MAPPING_KEY, ""); + Context spyContext = createSpyContext(bundle); + TestPlayStoreDeferredComponentManager playStoreManager = + new TestPlayStoreDeferredComponentManager(spyContext, jni); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/loader/ApplicationInfoLoaderTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/loader/ApplicationInfoLoaderTest.java new file mode 100644 index 0000000000000000000000000000000000000000..6a9e4424f31827df7734997f733f8928e8a4acdd --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/loader/ApplicationInfoLoaderTest.java @@ -0,0 +1,178 @@ +// 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. + +package io.flutter.embedding.engine.loader; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyBoolean; +import static org.mockito.Mockito.anyInt; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import android.content.Context; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; +import android.content.res.Resources; +import android.content.res.XmlResourceParser; +import android.os.Bundle; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import java.io.StringReader; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.stubbing.Answer; +import org.robolectric.annotation.Config; +import org.xmlpull.v1.XmlPullParser; +import org.xmlpull.v1.XmlPullParserFactory; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class ApplicationInfoLoaderTest { + + @Test + public void itGeneratesCorrectApplicationInfoWithDefaultManifest() { + FlutterApplicationInfo info = + ApplicationInfoLoader.load(ApplicationProvider.getApplicationContext()); + assertNotNull(info); + assertEquals("libapp.so", info.aotSharedLibraryName); + assertEquals("vm_snapshot_data", info.vmSnapshotData); + assertEquals("isolate_snapshot_data", info.isolateSnapshotData); + assertEquals("flutter_assets", info.flutterAssetsDir); + assertEquals("", info.domainNetworkPolicy); + assertNull(info.nativeLibraryDir); + } + + @SuppressWarnings("deprecation") + // getApplicationInfo + private Context generateMockContext(Bundle metadata, String networkPolicyXml) throws Exception { + Context context = mock(Context.class); + PackageManager packageManager = mock(PackageManager.class); + ApplicationInfo applicationInfo = mock(ApplicationInfo.class); + applicationInfo.metaData = metadata; + Resources resources = mock(Resources.class); + when(context.getPackageManager()).thenReturn(packageManager); + when(context.getResources()).thenReturn(resources); + when(context.getPackageName()).thenReturn(""); + when(packageManager.getApplicationInfo(anyString(), anyInt())).thenReturn(applicationInfo); + if (networkPolicyXml != null) { + metadata.putInt(ApplicationInfoLoader.NETWORK_POLICY_METADATA_KEY, 5); + doAnswer(invocationOnMock -> createMockResourceParser(networkPolicyXml)) + .when(resources) + .getXml(5); + } + return context; + } + + @Test + public void itGeneratesCorrectApplicationInfoWithCustomValues() throws Exception { + Bundle bundle = new Bundle(); + bundle.putString(ApplicationInfoLoader.PUBLIC_AOT_SHARED_LIBRARY_NAME, "testaot"); + bundle.putString(ApplicationInfoLoader.PUBLIC_VM_SNAPSHOT_DATA_KEY, "testvmsnapshot"); + bundle.putString(ApplicationInfoLoader.PUBLIC_ISOLATE_SNAPSHOT_DATA_KEY, "testisolatesnapshot"); + bundle.putString(ApplicationInfoLoader.PUBLIC_FLUTTER_ASSETS_DIR_KEY, "testassets"); + Context context = generateMockContext(bundle, null); + FlutterApplicationInfo info = ApplicationInfoLoader.load(context); + assertNotNull(info); + assertEquals("testaot", info.aotSharedLibraryName); + assertEquals("testvmsnapshot", info.vmSnapshotData); + assertEquals("testisolatesnapshot", info.isolateSnapshotData); + assertEquals("testassets", info.flutterAssetsDir); + assertNull(info.nativeLibraryDir); + assertEquals("", info.domainNetworkPolicy); + } + + @Test + public void itGeneratesCorrectNetworkPolicy() throws Exception { + Bundle bundle = new Bundle(); + String networkPolicyXml = + "" + + "" + + "secure.example.com" + + "" + + ""; + Context context = generateMockContext(bundle, networkPolicyXml); + FlutterApplicationInfo info = ApplicationInfoLoader.load(context); + assertNotNull(info); + assertEquals("[[\"secure.example.com\",true,false]]", info.domainNetworkPolicy); + } + + @Test + public void itHandlesBogusInformationInNetworkPolicy() throws Exception { + Bundle bundle = new Bundle(); + String networkPolicyXml = + "" + + "" + + "secure.example.com" + + "" + + "7HIpactkIAq2Y49orFOOQKurWxmmSFZhBCoQYcRhJ3Y=" + + "" + + "fwza0LRMXouZHRC8Ei+4PyuldPDcf3UKgO/04cDM1oE=" + + "" + + "" + + ""; + Context context = generateMockContext(bundle, networkPolicyXml); + FlutterApplicationInfo info = ApplicationInfoLoader.load(context); + assertNotNull(info); + assertEquals("[[\"secure.example.com\",true,false]]", info.domainNetworkPolicy); + } + + @Test + public void itHandlesNestedSubDomains() throws Exception { + Bundle bundle = new Bundle(); + String networkPolicyXml = + "" + + "" + + "example.com" + + "" + + "insecure.example.com" + + "" + + "" + + "secure.example.com" + + "" + + "" + + ""; + Context context = generateMockContext(bundle, networkPolicyXml); + FlutterApplicationInfo info = ApplicationInfoLoader.load(context); + assertNotNull(info); + assertEquals( + "[[\"example.com\",true,true],[\"insecure.example.com\",true,true],[\"secure.example.com\",true,false]]", + info.domainNetworkPolicy); + } + + // The following ridiculousness is needed because Android gives no way for us + // to customize XmlResourceParser. We have to mock it and tie each method + // we use to an actual Xml parser. + private XmlResourceParser createMockResourceParser(String xml) throws Exception { + final XmlPullParser xpp = XmlPullParserFactory.newInstance().newPullParser(); + xpp.setInput(new StringReader(xml)); + XmlResourceParser resourceParser = mock(XmlResourceParser.class); + final Answer invokeMethodOnRealParser = + invocation -> invocation.getMethod().invoke(xpp, invocation.getArguments()); + when(resourceParser.next()).thenAnswer(invokeMethodOnRealParser); + when(resourceParser.getName()).thenAnswer(invokeMethodOnRealParser); + when(resourceParser.getEventType()).thenAnswer(invokeMethodOnRealParser); + when(resourceParser.getText()).thenAnswer(invokeMethodOnRealParser); + when(resourceParser.getAttributeCount()).thenAnswer(invokeMethodOnRealParser); + when(resourceParser.getAttributeName(anyInt())).thenAnswer(invokeMethodOnRealParser); + when(resourceParser.getAttributeValue(anyInt())).thenAnswer(invokeMethodOnRealParser); + when(resourceParser.getAttributeValue(anyString(), anyString())) + .thenAnswer(invokeMethodOnRealParser); + when(resourceParser.getAttributeBooleanValue(any(), anyString(), anyBoolean())) + .thenAnswer( + invocation -> { + Object[] args = invocation.getArguments(); + String result = xpp.getAttributeValue((String) args[0], (String) args[1]); + if (result == null) { + return (Boolean) args[2]; + } + return Boolean.parseBoolean(result); + }); + return resourceParser; + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/loader/FlutterLoaderTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/loader/FlutterLoaderTest.java new file mode 100644 index 0000000000000000000000000000000000000000..c7bfc8406bcd4802734c6f69e4e958e6ae2dc96b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/loader/FlutterLoaderTest.java @@ -0,0 +1,360 @@ +// 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. + +package io.flutter.embedding.engine.loader; + +import static android.os.Looper.getMainLooper; +import static io.flutter.Build.API_LEVELS; +import static junit.framework.TestCase.assertFalse; +import static junit.framework.TestCase.assertTrue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyInt; +import static org.mockito.Mockito.anyLong; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.robolectric.Shadows.shadowOf; + +import android.annotation.TargetApi; +import android.app.ActivityManager; +import android.content.Context; +import android.os.Bundle; +import android.util.DisplayMetrics; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.FlutterJNI; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class FlutterLoaderTest { + private final Context ctx = ApplicationProvider.getApplicationContext(); + + @Test + public void itReportsUninitializedAfterCreating() { + FlutterLoader flutterLoader = new FlutterLoader(); + assertFalse(flutterLoader.initialized()); + } + + @Test + public void itReportsInitializedAfterInitializing() { + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + FlutterLoader flutterLoader = new FlutterLoader(mockFlutterJNI); + + assertFalse(flutterLoader.initialized()); + flutterLoader.startInitialization(ctx); + flutterLoader.ensureInitializationComplete(ctx, null); + shadowOf(getMainLooper()).idle(); + assertTrue(flutterLoader.initialized()); + verify(mockFlutterJNI, times(1)).loadLibrary(ctx); + verify(mockFlutterJNI, times(1)).updateRefreshRate(); + } + + @Test + public void unsatisfiedLinkErrorPathDoesNotExist() { + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + ctx.getApplicationInfo().nativeLibraryDir = "/path/that/doesnt/exist"; + FlutterLoader flutterLoader = new FlutterLoader(mockFlutterJNI); + + Mockito.doThrow(new UnsatisfiedLinkError("couldn't find \"libflutter.so\"")) + .when(mockFlutterJNI) + .loadLibrary(ctx); + try { + flutterLoader.startInitialization(ctx); + } catch (UnsupportedOperationException e) { + assertTrue( + e.getMessage() + .contains( + "and the native libraries directory (with path /path/that/doesnt/exist) does not exist.")); + } + } + + @Test + public void itDefaultsTheOldGenHeapSizeAppropriately() { + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + FlutterLoader flutterLoader = new FlutterLoader(mockFlutterJNI); + + assertFalse(flutterLoader.initialized()); + flutterLoader.startInitialization(ctx); + flutterLoader.ensureInitializationComplete(ctx, null); + shadowOf(getMainLooper()).idle(); + + ActivityManager activityManager = + (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE); + ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo(); + activityManager.getMemoryInfo(memInfo); + int oldGenHeapSizeMegaBytes = (int) (memInfo.totalMem / 1e6 / 2); + final String oldGenHeapArg = "--old-gen-heap-size=" + oldGenHeapSizeMegaBytes; + ArgumentCaptor shellArgsCaptor = ArgumentCaptor.forClass(String[].class); + verify(mockFlutterJNI, times(1)) + .init( + eq(ctx), + shellArgsCaptor.capture(), + anyString(), + anyString(), + anyString(), + anyLong(), + anyInt()); + List arguments = Arrays.asList(shellArgsCaptor.getValue()); + assertTrue(arguments.contains(oldGenHeapArg)); + } + + @Test + public void itDefaultsTheResourceCacheMaxBytesThresholdAppropriately() { + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + FlutterLoader flutterLoader = new FlutterLoader(mockFlutterJNI); + + assertFalse(flutterLoader.initialized()); + flutterLoader.startInitialization(ctx); + flutterLoader.ensureInitializationComplete(ctx, null); + shadowOf(getMainLooper()).idle(); + + DisplayMetrics displayMetrics = ctx.getResources().getDisplayMetrics(); + int screenWidth = displayMetrics.widthPixels; + int screenHeight = displayMetrics.heightPixels; + int resourceCacheMaxBytesThreshold = screenWidth * screenHeight * 12 * 4; + final String resourceCacheMaxBytesThresholdArg = + "--resource-cache-max-bytes-threshold=" + resourceCacheMaxBytesThreshold; + ArgumentCaptor shellArgsCaptor = ArgumentCaptor.forClass(String[].class); + verify(mockFlutterJNI, times(1)) + .init( + eq(ctx), + shellArgsCaptor.capture(), + anyString(), + anyString(), + anyString(), + anyLong(), + anyInt()); + List arguments = Arrays.asList(shellArgsCaptor.getValue()); + assertTrue(arguments.contains(resourceCacheMaxBytesThresholdArg)); + } + + @Test + public void itSetsLeakVMToTrueByDefault() { + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + FlutterLoader flutterLoader = new FlutterLoader(mockFlutterJNI); + + assertFalse(flutterLoader.initialized()); + flutterLoader.startInitialization(ctx); + flutterLoader.ensureInitializationComplete(ctx, null); + shadowOf(getMainLooper()).idle(); + + final String leakVMArg = "--leak-vm=true"; + ArgumentCaptor shellArgsCaptor = ArgumentCaptor.forClass(String[].class); + verify(mockFlutterJNI, times(1)) + .init( + eq(ctx), + shellArgsCaptor.capture(), + anyString(), + anyString(), + anyString(), + anyLong(), + anyInt()); + List arguments = Arrays.asList(shellArgsCaptor.getValue()); + assertTrue(arguments.contains(leakVMArg)); + } + + @Test + public void itSetsTheLeakVMFromMetaData() { + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + FlutterLoader flutterLoader = new FlutterLoader(mockFlutterJNI); + Bundle metaData = new Bundle(); + metaData.putBoolean("io.flutter.embedding.android.LeakVM", false); + ctx.getApplicationInfo().metaData = metaData; + + FlutterLoader.Settings settings = new FlutterLoader.Settings(); + assertFalse(flutterLoader.initialized()); + flutterLoader.startInitialization(ctx, settings); + flutterLoader.ensureInitializationComplete(ctx, null); + shadowOf(getMainLooper()).idle(); + + final String leakVMArg = "--leak-vm=false"; + ArgumentCaptor shellArgsCaptor = ArgumentCaptor.forClass(String[].class); + verify(mockFlutterJNI, times(1)) + .init( + eq(ctx), + shellArgsCaptor.capture(), + anyString(), + anyString(), + anyString(), + anyLong(), + anyInt()); + List arguments = Arrays.asList(shellArgsCaptor.getValue()); + assertTrue(arguments.contains(leakVMArg)); + } + + @Test + public void itUsesCorrectExecutorService() { + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + ExecutorService mockExecutorService = mock(ExecutorService.class); + FlutterLoader flutterLoader = new FlutterLoader(mockFlutterJNI, mockExecutorService); + + assertFalse(flutterLoader.initialized()); + flutterLoader.startInitialization(ctx); + verify(mockExecutorService, times(1)).submit(any(Callable.class)); + } + + @Test + public void itDoesNotSetEnableImpellerByDefault() { + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + FlutterLoader flutterLoader = new FlutterLoader(mockFlutterJNI); + + assertFalse(flutterLoader.initialized()); + flutterLoader.startInitialization(ctx); + flutterLoader.ensureInitializationComplete(ctx, null); + shadowOf(getMainLooper()).idle(); + + final String enableImpellerArg = "--enable-impeller"; + ArgumentCaptor shellArgsCaptor = ArgumentCaptor.forClass(String[].class); + verify(mockFlutterJNI, times(1)) + .init( + eq(ctx), + shellArgsCaptor.capture(), + anyString(), + anyString(), + anyString(), + anyLong(), + anyInt()); + List arguments = Arrays.asList(shellArgsCaptor.getValue()); + assertFalse(arguments.contains(enableImpellerArg)); + } + + @Test + public void itDoesNotSetEnableVulkanValidationByDefault() { + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + FlutterLoader flutterLoader = new FlutterLoader(mockFlutterJNI); + + assertFalse(flutterLoader.initialized()); + flutterLoader.startInitialization(ctx); + flutterLoader.ensureInitializationComplete(ctx, null); + shadowOf(getMainLooper()).idle(); + + final String enableVulkanValidationArg = "--enable-vulkan-validation"; + ArgumentCaptor shellArgsCaptor = ArgumentCaptor.forClass(String[].class); + verify(mockFlutterJNI, times(1)) + .init( + eq(ctx), + shellArgsCaptor.capture(), + anyString(), + anyString(), + anyString(), + anyLong(), + anyInt()); + List arguments = Arrays.asList(shellArgsCaptor.getValue()); + assertFalse(arguments.contains(enableVulkanValidationArg)); + } + + @Test + public void itSetsEnableImpellerFromMetaData() { + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + FlutterLoader flutterLoader = new FlutterLoader(mockFlutterJNI); + Bundle metaData = new Bundle(); + metaData.putBoolean("io.flutter.embedding.android.EnableImpeller", true); + ctx.getApplicationInfo().metaData = metaData; + + FlutterLoader.Settings settings = new FlutterLoader.Settings(); + assertFalse(flutterLoader.initialized()); + flutterLoader.startInitialization(ctx, settings); + flutterLoader.ensureInitializationComplete(ctx, null); + shadowOf(getMainLooper()).idle(); + + final String enableImpellerArg = "--enable-impeller=true"; + ArgumentCaptor shellArgsCaptor = ArgumentCaptor.forClass(String[].class); + verify(mockFlutterJNI, times(1)) + .init( + eq(ctx), + shellArgsCaptor.capture(), + anyString(), + anyString(), + anyString(), + anyLong(), + anyInt()); + List arguments = Arrays.asList(shellArgsCaptor.getValue()); + assertTrue(arguments.contains(enableImpellerArg)); + } + + @Test + public void itSetsEnableSurfaceControlFromMetaData() { + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + FlutterLoader flutterLoader = new FlutterLoader(mockFlutterJNI); + Bundle metaData = new Bundle(); + metaData.putBoolean("io.flutter.embedding.android.EnableSurfaceControl", true); + ctx.getApplicationInfo().metaData = metaData; + + FlutterLoader.Settings settings = new FlutterLoader.Settings(); + assertFalse(flutterLoader.initialized()); + flutterLoader.startInitialization(ctx, settings); + flutterLoader.ensureInitializationComplete(ctx, null); + shadowOf(getMainLooper()).idle(); + + final String disabledControlArg = "--enable-surface-control"; + ArgumentCaptor shellArgsCaptor = ArgumentCaptor.forClass(String[].class); + verify(mockFlutterJNI, times(1)) + .init( + eq(ctx), + shellArgsCaptor.capture(), + anyString(), + anyString(), + anyString(), + anyLong(), + anyInt()); + List arguments = Arrays.asList(shellArgsCaptor.getValue()); + assertTrue(arguments.contains(disabledControlArg)); + } + + @Test + public void itSetsShaderInitModeFromMetaData() { + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + FlutterLoader flutterLoader = new FlutterLoader(mockFlutterJNI); + Bundle metaData = new Bundle(); + metaData.putBoolean("io.flutter.embedding.android.ImpellerLazyShaderInitialization", true); + ctx.getApplicationInfo().metaData = metaData; + + FlutterLoader.Settings settings = new FlutterLoader.Settings(); + assertFalse(flutterLoader.initialized()); + flutterLoader.startInitialization(ctx, settings); + flutterLoader.ensureInitializationComplete(ctx, null); + shadowOf(getMainLooper()).idle(); + + final String shaderModeArg = "--impeller-lazy-shader-mode"; + ArgumentCaptor shellArgsCaptor = ArgumentCaptor.forClass(String[].class); + verify(mockFlutterJNI, times(1)) + .init( + eq(ctx), + shellArgsCaptor.capture(), + anyString(), + anyString(), + anyString(), + anyLong(), + anyInt()); + List arguments = Arrays.asList(shellArgsCaptor.getValue()); + assertTrue(arguments.contains(shaderModeArg)); + } + + @Test + @TargetApi(API_LEVELS.API_23) + @Config(sdk = API_LEVELS.API_23) + public void itReportsFpsToVsyncWaiterAndroidM() { + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + FlutterLoader flutterLoader = new FlutterLoader(mockFlutterJNI); + + Context appContextSpy = spy(ctx); + + assertFalse(flutterLoader.initialized()); + flutterLoader.startInitialization(appContextSpy); + verify(appContextSpy, never()).getSystemService(anyString()); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/mutatorsstack/FlutterMutatorViewTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/mutatorsstack/FlutterMutatorViewTest.java new file mode 100644 index 0000000000000000000000000000000000000000..a434aae980f2ec92cf58ba24aeed4c65de9de5d5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/mutatorsstack/FlutterMutatorViewTest.java @@ -0,0 +1,249 @@ +// 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. + +package io.flutter.embedding.engine.mutatorsstack; + +import static android.view.View.OnFocusChangeListener; +import static junit.framework.TestCase.*; +import static org.mockito.Mockito.*; + +import android.content.Context; +import android.graphics.Matrix; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewGroup; +import android.view.ViewTreeObserver; +import android.view.accessibility.AccessibilityEvent; +import android.widget.FrameLayout; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.android.AndroidTouchProcessor; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.robolectric.annotation.Config; +import org.robolectric.annotation.Implementation; +import org.robolectric.annotation.Implements; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class FlutterMutatorViewTest { + private final Context ctx = ApplicationProvider.getApplicationContext(); + + @Test + public void canDragViews() { + final AndroidTouchProcessor touchProcessor = mock(AndroidTouchProcessor.class); + final FlutterMutatorView view = new FlutterMutatorView(ctx, 1.0f, touchProcessor); + final FlutterMutatorsStack mutatorStack = mock(FlutterMutatorsStack.class); + + assertTrue(view.onInterceptTouchEvent(mock(MotionEvent.class))); + + { + view.readyToDisplay(mutatorStack, /*left=*/ 1, /*top=*/ 2, /*width=*/ 0, /*height=*/ 0); + view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, 0.0f, 0.0f, 0)); + final ArgumentCaptor matrixCaptor = ArgumentCaptor.forClass(Matrix.class); + verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture()); + + final Matrix screenMatrix = new Matrix(); + screenMatrix.postTranslate(1, 2); + assertTrue(matrixCaptor.getValue().equals(screenMatrix)); + } + + reset(touchProcessor); + + { + view.readyToDisplay(mutatorStack, /*left=*/ 3, /*top=*/ 4, /*width=*/ 0, /*height=*/ 0); + view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_MOVE, 0.0f, 0.0f, 0)); + final ArgumentCaptor matrixCaptor = ArgumentCaptor.forClass(Matrix.class); + verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture()); + + final Matrix screenMatrix = new Matrix(); + screenMatrix.postTranslate(1, 2); + assertTrue(matrixCaptor.getValue().equals(screenMatrix)); + } + + reset(touchProcessor); + + { + view.readyToDisplay(mutatorStack, /*left=*/ 5, /*top=*/ 6, /*width=*/ 0, /*height=*/ 0); + view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_MOVE, 0.0f, 0.0f, 0)); + final ArgumentCaptor matrixCaptor = ArgumentCaptor.forClass(Matrix.class); + verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture()); + + final Matrix screenMatrix = new Matrix(); + screenMatrix.postTranslate(3, 4); + assertTrue(matrixCaptor.getValue().equals(screenMatrix)); + } + + reset(touchProcessor); + + { + view.readyToDisplay(mutatorStack, /*left=*/ 7, /*top=*/ 8, /*width=*/ 0, /*height=*/ 0); + view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, 0.0f, 0.0f, 0)); + final ArgumentCaptor matrixCaptor = ArgumentCaptor.forClass(Matrix.class); + verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture()); + + final Matrix screenMatrix = new Matrix(); + screenMatrix.postTranslate(7, 8); + assertTrue(matrixCaptor.getValue().equals(screenMatrix)); + } + } + + @Test + public void focusChangeListener_hasFocus() { + final ViewTreeObserver viewTreeObserver = mock(ViewTreeObserver.class); + when(viewTreeObserver.isAlive()).thenReturn(true); + + final FlutterMutatorView view = + new FlutterMutatorView(ctx) { + @Override + public ViewTreeObserver getViewTreeObserver() { + return viewTreeObserver; + } + + @Override + public boolean hasFocus() { + return true; + } + }; + + final OnFocusChangeListener focusListener = mock(OnFocusChangeListener.class); + view.setOnDescendantFocusChangeListener(focusListener); + + final ArgumentCaptor focusListenerCaptor = + ArgumentCaptor.forClass(ViewTreeObserver.OnGlobalFocusChangeListener.class); + verify(viewTreeObserver).addOnGlobalFocusChangeListener(focusListenerCaptor.capture()); + + focusListenerCaptor.getValue().onGlobalFocusChanged(null, null); + verify(focusListener).onFocusChange(view, true); + } + + @Test + public void focusChangeListener_doesNotHaveFocus() { + final ViewTreeObserver viewTreeObserver = mock(ViewTreeObserver.class); + when(viewTreeObserver.isAlive()).thenReturn(true); + + final FlutterMutatorView view = + new FlutterMutatorView(ctx) { + @Override + public ViewTreeObserver getViewTreeObserver() { + return viewTreeObserver; + } + + @Override + public boolean hasFocus() { + return false; + } + }; + + final OnFocusChangeListener focusListener = mock(OnFocusChangeListener.class); + view.setOnDescendantFocusChangeListener(focusListener); + + final ArgumentCaptor focusListenerCaptor = + ArgumentCaptor.forClass(ViewTreeObserver.OnGlobalFocusChangeListener.class); + verify(viewTreeObserver).addOnGlobalFocusChangeListener(focusListenerCaptor.capture()); + + focusListenerCaptor.getValue().onGlobalFocusChanged(null, null); + verify(focusListener).onFocusChange(view, false); + } + + @Test + public void focusChangeListener_viewTreeObserverIsAliveFalseDoesNotThrow() { + final FlutterMutatorView view = + new FlutterMutatorView(ctx) { + @Override + public ViewTreeObserver getViewTreeObserver() { + final ViewTreeObserver viewTreeObserver = mock(ViewTreeObserver.class); + when(viewTreeObserver.isAlive()).thenReturn(false); + return viewTreeObserver; + } + }; + view.setOnDescendantFocusChangeListener(mock(OnFocusChangeListener.class)); + } + + @Test + public void setOnDescendantFocusChangeListener_keepsSingleListener() { + final ViewTreeObserver viewTreeObserver = mock(ViewTreeObserver.class); + when(viewTreeObserver.isAlive()).thenReturn(true); + + final FlutterMutatorView view = + new FlutterMutatorView(ctx) { + @Override + public ViewTreeObserver getViewTreeObserver() { + return viewTreeObserver; + } + }; + + assertNull(view.activeFocusListener); + + view.setOnDescendantFocusChangeListener(mock(OnFocusChangeListener.class)); + assertNotNull(view.activeFocusListener); + + final ViewTreeObserver.OnGlobalFocusChangeListener activeFocusListener = + view.activeFocusListener; + + view.setOnDescendantFocusChangeListener(mock(OnFocusChangeListener.class)); + assertNotNull(view.activeFocusListener); + + verify(viewTreeObserver, times(1)).removeOnGlobalFocusChangeListener(activeFocusListener); + } + + @Test + public void unsetOnDescendantFocusChangeListener_removesActiveListener() { + final ViewTreeObserver viewTreeObserver = mock(ViewTreeObserver.class); + when(viewTreeObserver.isAlive()).thenReturn(true); + + final FlutterMutatorView view = + new FlutterMutatorView(ctx) { + @Override + public ViewTreeObserver getViewTreeObserver() { + return viewTreeObserver; + } + }; + + assertNull(view.activeFocusListener); + + view.setOnDescendantFocusChangeListener(mock(OnFocusChangeListener.class)); + assertNotNull(view.activeFocusListener); + + final ViewTreeObserver.OnGlobalFocusChangeListener activeFocusListener = + view.activeFocusListener; + + view.unsetOnDescendantFocusChangeListener(); + assertNull(view.activeFocusListener); + + view.unsetOnDescendantFocusChangeListener(); + verify(viewTreeObserver, times(1)).removeOnGlobalFocusChangeListener(activeFocusListener); + } + + @Test + @Config( + shadows = { + ShadowViewGroup.class, + }) + public void ignoreAccessibilityEvents() { + final FlutterMutatorView wrapperView = new FlutterMutatorView(ctx); + + final View embeddedView = mock(View.class); + wrapperView.addView(embeddedView); + + when(embeddedView.getImportantForAccessibility()) + .thenReturn(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); + final boolean eventSent = + wrapperView.requestSendAccessibilityEvent(embeddedView, mock(AccessibilityEvent.class)); + assertFalse(eventSent); + } + + @Implements(ViewGroup.class) + public static class ShadowViewGroup extends org.robolectric.shadows.ShadowViewGroup { + @Implementation + protected boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { + return true; + } + } + + @Implements(FrameLayout.class) + public static class ShadowFrameLayout + extends io.flutter.plugin.platform.PlatformViewWrapperTest.ShadowViewGroup {} +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/renderer/FlutterEngineRule.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/renderer/FlutterEngineRule.java new file mode 100644 index 0000000000000000000000000000000000000000..d771a7f1296c2a99d21d6e35b871f9d348680800 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/renderer/FlutterEngineRule.java @@ -0,0 +1,88 @@ +// 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. + +package io.flutter.embedding.engine.renderer; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import android.content.Context; +import android.content.Intent; +import androidx.test.core.app.ApplicationProvider; +import io.flutter.embedding.android.FlutterActivity; +import io.flutter.embedding.engine.FlutterEngine; +import io.flutter.embedding.engine.FlutterEngineCache; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.loader.FlutterLoader; +import org.junit.rules.TestWatcher; +import org.junit.runner.Description; + +/** + * Prepares and returns a {@link FlutterEngine} and {@link Intent} primed with an engine for tests. + */ +public final class FlutterEngineRule extends TestWatcher { + private static final String cachedEngineId = "flutter_engine_rule_cached_engine"; + private final Context ctx = ApplicationProvider.getApplicationContext(); + private FlutterJNI flutterJNI; + private FlutterEngine flutterEngine; + private boolean jniIsAttached = true; + + @Override + protected void starting(Description description) { + // Setup mock JNI. + flutterJNI = mock(FlutterJNI.class); + when(flutterJNI.isAttached()).thenAnswer(i -> jniIsAttached); + + // We will not try to load plugins in these tests. + FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); + when(mockFlutterLoader.automaticallyRegisterPlugins()).thenReturn(false); + + // Create an engine. + flutterEngine = new FlutterEngine(ctx, mockFlutterLoader, flutterJNI); + + // Place it in the engine cache. + FlutterEngineCache.getInstance().put(cachedEngineId, flutterEngine); + } + + @Override + protected void finished(Description description) { + FlutterEngineCache.getInstance().clear(); + } + + /** + * Returns a Mockito-mocked version of {@link FlutterJNI}. + * + * @return an instance that is already considered attached. + */ + FlutterJNI getFlutterJNI() { + return this.flutterJNI; + } + + /** + * Returns a pre-configured engine. + * + * @return flutter engine using the mock provided by {{@link #getFlutterJNI()}}. + */ + FlutterEngine getFlutterEngine() { + return this.flutterEngine; + } + + /** + * Sets what {@link FlutterJNI#isAttached()} returns. If not invoked, defaults to true. + * + * @param isAttached whether to consider JNI attached. + */ + void setJniIsAttached(boolean isAttached) { + this.jniIsAttached = isAttached; + } + + /** + * Creates an intent with {@link FlutterEngine} instance already provided. + * + * @return intent, i.e. to use with {@link androidx.test.ext.junit.rules.ActivityScenarioRule}. + */ + Intent makeIntent() { + return FlutterActivity.withCachedEngine(cachedEngineId).build(ctx); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/renderer/FlutterRendererTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/renderer/FlutterRendererTest.java new file mode 100644 index 0000000000000000000000000000000000000000..3ea0c4df9f5192f5e2471a3d5273b12d61969cb4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/renderer/FlutterRendererTest.java @@ -0,0 +1,1019 @@ +// 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. + +package io.flutter.embedding.engine.renderer; + +import static android.content.ComponentCallbacks2.TRIM_MEMORY_BACKGROUND; +import static android.content.ComponentCallbacks2.TRIM_MEMORY_COMPLETE; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyFloat; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.robolectric.Shadows.shadowOf; + +import android.graphics.Canvas; +import android.graphics.Rect; +import android.graphics.SurfaceTexture; +import android.media.Image; +import android.os.Looper; +import android.view.Surface; +import androidx.lifecycle.Lifecycle; +import androidx.lifecycle.LifecycleRegistry; +import androidx.lifecycle.ProcessLifecycleOwner; +import androidx.test.ext.junit.rules.ActivityScenarioRule; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.android.FlutterActivity; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.view.TextureRegistry; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class FlutterRendererTest { + @Rule(order = 1) + public final FlutterEngineRule engineRule = new FlutterEngineRule(); + + @Rule(order = 2) + public final ActivityScenarioRule scenarioRule = + new ActivityScenarioRule<>(engineRule.makeIntent()); + + private FlutterJNI fakeFlutterJNI; + + @Before + public void init() { + // Uncomment the following line to enable logging output in test. + // ShadowLog.stream = System.out; + } + + @Before + public void setup() { + fakeFlutterJNI = engineRule.getFlutterJNI(); + } + + @Test + public void itForwardsSurfaceCreationNotificationToFlutterJNI() { + // Setup the test. + Surface fakeSurface = mock(Surface.class); + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + + // Execute the behavior under test. + flutterRenderer.startRenderingToSurface(fakeSurface, false); + + // Verify the behavior under test. + verify(fakeFlutterJNI, times(1)).onSurfaceCreated(eq(fakeSurface)); + } + + @Test + public void itForwardsSurfaceChangeNotificationToFlutterJNI() { + // Setup the test. + Surface fakeSurface = mock(Surface.class); + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + + flutterRenderer.startRenderingToSurface(fakeSurface, false); + + // Execute the behavior under test. + flutterRenderer.surfaceChanged(100, 50); + + // Verify the behavior under test. + verify(fakeFlutterJNI, times(1)).onSurfaceChanged(eq(100), eq(50)); + } + + @Test + public void itForwardsSurfaceDestructionNotificationToFlutterJNI() { + // Setup the test. + Surface fakeSurface = mock(Surface.class); + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + + flutterRenderer.startRenderingToSurface(fakeSurface, false); + + // Execute the behavior under test. + flutterRenderer.stopRenderingToSurface(); + + // Verify the behavior under test. + verify(fakeFlutterJNI, times(1)).onSurfaceDestroyed(); + } + + @Test + public void itStopsRenderingToOneSurfaceBeforeRenderingToANewSurface() { + // Setup the test. + Surface fakeSurface = mock(Surface.class); + Surface fakeSurface2 = mock(Surface.class); + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + + flutterRenderer.startRenderingToSurface(fakeSurface, false); + + // Execute behavior under test. + flutterRenderer.startRenderingToSurface(fakeSurface2, false); + + // Verify behavior under test. + verify(fakeFlutterJNI, times(1)).onSurfaceDestroyed(); // notification of 1st surface's removal. + } + + @Test + public void itStopsRenderingToSurfaceWhenRequested() { + // Setup the test. + Surface fakeSurface = mock(Surface.class); + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + + flutterRenderer.startRenderingToSurface(fakeSurface, false); + + // Execute the behavior under test. + flutterRenderer.stopRenderingToSurface(); + + // Verify behavior under test. + verify(fakeFlutterJNI, times(1)).onSurfaceDestroyed(); + } + + @Test + public void iStopsRenderingToSurfaceWhenSurfaceAlreadySet() { + // Setup the test. + Surface fakeSurface = mock(Surface.class); + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + + flutterRenderer.startRenderingToSurface(fakeSurface, false); + flutterRenderer.startRenderingToSurface(fakeSurface, false); + + // Verify behavior under test. + verify(fakeFlutterJNI, times(1)).onSurfaceDestroyed(); + } + + @Test + public void itNeverStopsRenderingToSurfaceWhenRequested() { + // Setup the test. + Surface fakeSurface = mock(Surface.class); + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + + flutterRenderer.startRenderingToSurface(fakeSurface, false); + flutterRenderer.startRenderingToSurface(fakeSurface, true); + + // Verify behavior under test. + verify(fakeFlutterJNI, never()).onSurfaceDestroyed(); + } + + @Test + public void itStopsSurfaceTextureCallbackWhenDetached() { + // Setup the test. + Surface fakeSurface = mock(Surface.class); + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + + FlutterRenderer.SurfaceTextureRegistryEntry entry = + (FlutterRenderer.SurfaceTextureRegistryEntry) flutterRenderer.createSurfaceTexture(); + flutterRenderer.startRenderingToSurface(fakeSurface, false); + + // Execute the behavior under test. + flutterRenderer.stopRenderingToSurface(); + + // Verify behavior under test. + verify(fakeFlutterJNI, times(0)).markTextureFrameAvailable(eq(entry.id())); + } + + @Test + public void itRegistersExistingSurfaceTexture() { + // Setup the test. + Surface fakeSurface = mock(Surface.class); + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + + SurfaceTexture surfaceTexture = new SurfaceTexture(0); + + // Execute the behavior under test. + FlutterRenderer.SurfaceTextureRegistryEntry entry = + (FlutterRenderer.SurfaceTextureRegistryEntry) + flutterRenderer.registerSurfaceTexture(surfaceTexture); + + flutterRenderer.startRenderingToSurface(fakeSurface, false); + + // Verify behavior under test. + assertEquals(surfaceTexture, entry.surfaceTexture()); + + verify(fakeFlutterJNI, times(1)).registerTexture(eq(entry.id()), eq(entry.textureWrapper())); + } + + @Test + public void itUnregistersTextureWhenSurfaceTextureFinalized() { + // Setup the test. + Surface fakeSurface = mock(Surface.class); + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + + FlutterRenderer.SurfaceTextureRegistryEntry entry = + (FlutterRenderer.SurfaceTextureRegistryEntry) flutterRenderer.createSurfaceTexture(); + long id = entry.id(); + + flutterRenderer.startRenderingToSurface(fakeSurface, false); + + // Execute the behavior under test. + runFinalization(entry); + + shadowOf(Looper.getMainLooper()).idle(); + + flutterRenderer.stopRenderingToSurface(); + + // Verify behavior under test. + verify(fakeFlutterJNI, times(1)).unregisterTexture(eq(id)); + } + + @Test + public void itStopsUnregisteringTextureWhenDetached() { + // Setup the test. + Surface fakeSurface = mock(Surface.class); + engineRule.setJniIsAttached(false); + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + + FlutterRenderer.SurfaceTextureRegistryEntry entry = + (FlutterRenderer.SurfaceTextureRegistryEntry) flutterRenderer.createSurfaceTexture(); + long id = entry.id(); + + flutterRenderer.startRenderingToSurface(fakeSurface, false); + flutterRenderer.stopRenderingToSurface(); + + // Execute the behavior under test. + runFinalization(entry); + + shadowOf(Looper.getMainLooper()).idle(); + + // Verify behavior under test. + verify(fakeFlutterJNI, times(0)).unregisterTexture(eq(id)); + } + + /** @noinspection FinalizeCalledExplicitly */ + void runFinalization(FlutterRenderer.SurfaceTextureRegistryEntry entry) { + CountDownLatch latch = new CountDownLatch(1); + Thread fakeFinalizer = + new Thread( + () -> { + try { + entry.finalize(); + latch.countDown(); + } catch (Throwable e) { + // do nothing + } + }); + fakeFinalizer.start(); + try { + latch.await(); + } catch (InterruptedException e) { + // do nothing + } + } + + @Test + public void itConvertsDisplayFeatureArrayToPrimitiveArrays() { + // Intentionally do not use 'engineRule' in this test, because we are testing a very narrow + // API (the side-effects of 'setViewportMetrics'). Under normal construction, the engine will + // invoke 'setViewportMetrics' a number of times automatically, making testing the side-effects + // of the method call more difficult than needed. + FlutterJNI fakeFlutterJNI = mock(FlutterJNI.class); + FlutterRenderer flutterRenderer = new FlutterRenderer(fakeFlutterJNI); + + // Setup the test. + FlutterRenderer.ViewportMetrics metrics = new FlutterRenderer.ViewportMetrics(); + metrics.width = 1000; + metrics.height = 1000; + metrics.devicePixelRatio = 2; + metrics + .getDisplayFeatures() + .add( + new FlutterRenderer.DisplayFeature( + new Rect(10, 20, 30, 40), + FlutterRenderer.DisplayFeatureType.FOLD, + FlutterRenderer.DisplayFeatureState.POSTURE_HALF_OPENED)); + metrics + .getDisplayCutouts() + .add( + new FlutterRenderer.DisplayFeature( + new Rect(50, 60, 70, 80), + FlutterRenderer.DisplayFeatureType.CUTOUT, + FlutterRenderer.DisplayFeatureState.UNKNOWN)); + + // Execute the behavior under test. + flutterRenderer.setViewportMetrics(metrics); + + // Verify behavior under test. + ArgumentCaptor boundsCaptor = ArgumentCaptor.forClass(int[].class); + ArgumentCaptor typeCaptor = ArgumentCaptor.forClass(int[].class); + ArgumentCaptor stateCaptor = ArgumentCaptor.forClass(int[].class); + verify(fakeFlutterJNI) + .setViewportMetrics( + anyFloat(), + anyInt(), + anyInt(), + anyInt(), + anyInt(), + anyInt(), + anyInt(), + anyInt(), + anyInt(), + anyInt(), + anyInt(), + anyInt(), + anyInt(), + anyInt(), + anyInt(), + anyInt(), + boundsCaptor.capture(), + typeCaptor.capture(), + stateCaptor.capture()); + + assertArrayEquals(new int[] {10, 20, 30, 40, 50, 60, 70, 80}, boundsCaptor.getValue()); + assertArrayEquals( + new int[] { + FlutterRenderer.DisplayFeatureType.FOLD.encodedValue, + FlutterRenderer.DisplayFeatureType.CUTOUT.encodedValue + }, + typeCaptor.getValue()); + assertArrayEquals( + new int[] { + FlutterRenderer.DisplayFeatureState.POSTURE_HALF_OPENED.encodedValue, + FlutterRenderer.DisplayFeatureState.UNKNOWN.encodedValue + }, + stateCaptor.getValue()); + } + + @Test + public void itNotifyImageFrameListener() { + // Setup the test. + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + + AtomicInteger invocationCount = new AtomicInteger(0); + final TextureRegistry.OnFrameConsumedListener listener = invocationCount::incrementAndGet; + + FlutterRenderer.SurfaceTextureRegistryEntry entry = + (FlutterRenderer.SurfaceTextureRegistryEntry) flutterRenderer.createSurfaceTexture(); + entry.setOnFrameConsumedListener(listener); + + // Execute the behavior under test. + entry.textureWrapper().updateTexImage(); + + // Verify behavior under test. + assertEquals(1, invocationCount.get()); + } + + @Test + public void itAddsListenerWhenSurfaceTextureEntryCreated() { + // Setup the test. + FlutterRenderer flutterRenderer = spy(engineRule.getFlutterEngine().getRenderer()); + + // Execute the behavior under test. + FlutterRenderer.SurfaceTextureRegistryEntry entry = + (FlutterRenderer.SurfaceTextureRegistryEntry) flutterRenderer.createSurfaceTexture(); + + // Verify behavior under test. + verify(flutterRenderer, times(1)).addOnTrimMemoryListener(entry); + } + + @Test + public void itRemovesListenerWhenSurfaceTextureEntryReleased() { + // Setup the test. + FlutterRenderer flutterRenderer = spy(engineRule.getFlutterEngine().getRenderer()); + FlutterRenderer.SurfaceTextureRegistryEntry entry = + (FlutterRenderer.SurfaceTextureRegistryEntry) flutterRenderer.createSurfaceTexture(); + + // Execute the behavior under test. + entry.release(); + + // Verify behavior under test. + verify(flutterRenderer, times(1)).removeOnTrimMemoryListener(entry); + } + + @Test + @SuppressWarnings("deprecation") + // TRIM_MEMORY_COMPLETE + public void itNotifySurfaceTextureEntryWhenMemoryPressureWarning() { + // Setup the test. + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + + AtomicInteger invocationCount = new AtomicInteger(0); + final TextureRegistry.OnTrimMemoryListener listener = + level -> invocationCount.incrementAndGet(); + + FlutterRenderer.SurfaceTextureRegistryEntry entry = + (FlutterRenderer.SurfaceTextureRegistryEntry) flutterRenderer.createSurfaceTexture(); + entry.setOnTrimMemoryListener(listener); + + // Execute the behavior under test. + flutterRenderer.onTrimMemory(TRIM_MEMORY_COMPLETE); + + // Verify behavior under test. + assertEquals(1, invocationCount.get()); + } + + @Test + public void itDoesDispatchSurfaceDestructionNotificationOnlyOnce() { + // Setup the test. + Surface fakeSurface = mock(Surface.class); + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + + flutterRenderer.startRenderingToSurface(fakeSurface, false); + + // Execute the behavior under test. + // Simulate calling |FlutterRenderer#stopRenderingToSurface| twice with different code paths. + flutterRenderer.stopRenderingToSurface(); + flutterRenderer.stopRenderingToSurface(); + + // Verify behavior under test. + verify(fakeFlutterJNI, times(1)).onSurfaceDestroyed(); + } + + @Test + public void itInvokesCreatesSurfaceWhenStartingRendering() { + Surface fakeSurface = mock(Surface.class); + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + + flutterRenderer.startRenderingToSurface(fakeSurface, false); + verify(fakeFlutterJNI, times(1)).onSurfaceCreated(eq(fakeSurface)); + } + + @Test + public void itDoesNotInvokeCreatesSurfaceWhenResumingRendering() { + Surface fakeSurface = mock(Surface.class); + Surface fakeSurface2 = mock(Surface.class); + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + + // The following call sequence mimics the behaviour of FlutterView when it exits from hybrid + // composition mode. + + // Install initial rendering surface. + flutterRenderer.startRenderingToSurface(fakeSurface, false); + verify(fakeFlutterJNI, times(1)).onSurfaceCreated(eq(fakeSurface)); + verify(fakeFlutterJNI, times(0)).onSurfaceWindowChanged(eq(fakeSurface)); + + // Install the image view. + flutterRenderer.startRenderingToSurface(fakeSurface2, true); + verify(fakeFlutterJNI, times(1)).onSurfaceCreated(eq(fakeSurface)); + verify(fakeFlutterJNI, times(0)).onSurfaceWindowChanged(eq(fakeSurface)); + verify(fakeFlutterJNI, times(0)).onSurfaceCreated(eq(fakeSurface2)); + verify(fakeFlutterJNI, times(1)).onSurfaceWindowChanged(eq(fakeSurface2)); + + flutterRenderer.startRenderingToSurface(fakeSurface, true); + verify(fakeFlutterJNI, times(1)).onSurfaceCreated(eq(fakeSurface)); + verify(fakeFlutterJNI, times(1)).onSurfaceWindowChanged(eq(fakeSurface)); + verify(fakeFlutterJNI, times(0)).onSurfaceCreated(eq(fakeSurface2)); + verify(fakeFlutterJNI, times(1)).onSurfaceWindowChanged(eq(fakeSurface2)); + } + + @Test + public void ImageReaderSurfaceProducerProducesImageOfCorrectSize() { + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + TextureRegistry.SurfaceProducer producer = flutterRenderer.createSurfaceProducer(); + FlutterRenderer.ImageReaderSurfaceProducer texture = + (FlutterRenderer.ImageReaderSurfaceProducer) producer; + texture.disableFenceForTest(); + + // Returns a null image when one hasn't been produced. + assertNull(texture.acquireLatestImage()); + + // Give the texture an initial size. + texture.setSize(1, 1); + + // Render a frame. + Surface surface = texture.getSurface(); + assertNotNull(surface); + Canvas canvas = surface.lockHardwareCanvas(); + canvas.drawARGB(255, 255, 0, 0); + surface.unlockCanvasAndPost(canvas); + + // Let callbacks run. + shadowOf(Looper.getMainLooper()).idle(); + + // Extract the image and check its size. + Image image = texture.acquireLatestImage(); + assert image != null; + assertEquals(1, image.getWidth()); + assertEquals(1, image.getHeight()); + image.close(); + + // Resize the texture. + texture.setSize(5, 5); + + // Render a frame. + surface = texture.getSurface(); + assertNotNull(surface); + canvas = surface.lockHardwareCanvas(); + canvas.drawARGB(255, 255, 0, 0); + surface.unlockCanvasAndPost(canvas); + + // Let callbacks run. + shadowOf(Looper.getMainLooper()).idle(); + + // Extract the image and check its size. + image = texture.acquireLatestImage(); + assert image != null; + assertEquals(5, image.getWidth()); + assertEquals(5, image.getHeight()); + image.close(); + + assertNull(texture.acquireLatestImage()); + + texture.release(); + } + + @Test + public void ImageReaderSurfaceProducerDoesNotDropFramesWhenResizeInFlight() { + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + TextureRegistry.SurfaceProducer producer = flutterRenderer.createSurfaceProducer(); + FlutterRenderer.ImageReaderSurfaceProducer texture = + (FlutterRenderer.ImageReaderSurfaceProducer) producer; + texture.disableFenceForTest(); + + // Returns a null image when one hasn't been produced. + assertNull(texture.acquireLatestImage()); + + // Give the texture an initial size. + texture.setSize(1, 1); + + // Render a frame. + Surface surface = texture.getSurface(); + assertNotNull(surface); + Canvas canvas = surface.lockHardwareCanvas(); + canvas.drawARGB(255, 255, 0, 0); + surface.unlockCanvasAndPost(canvas); + + // Resize. + texture.setSize(4, 4); + + // Let callbacks run. The rendered frame will manifest here. + shadowOf(Looper.getMainLooper()).idle(); + + // We acquired the frame produced above. + assertNotNull(texture.acquireLatestImage()); + } + + @Test + public void ImageReaderSurfaceProducerImageReadersAndImagesCount() { + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + TextureRegistry.SurfaceProducer producer = flutterRenderer.createSurfaceProducer(); + FlutterRenderer.ImageReaderSurfaceProducer texture = + (FlutterRenderer.ImageReaderSurfaceProducer) producer; + texture.disableFenceForTest(); + + // Returns a null image when one hasn't been produced. + assertNull(texture.acquireLatestImage()); + + // Give the texture an initial size. + texture.setSize(1, 1); + + // Grab the surface so we can render a frame at 1x1 after resizing. + Surface surface = texture.getSurface(); + assertNotNull(surface); + Canvas canvas = surface.lockHardwareCanvas(); + canvas.drawARGB(255, 255, 0, 0); + surface.unlockCanvasAndPost(canvas); + + // Let callbacks run, this will produce a single frame. + shadowOf(Looper.getMainLooper()).idle(); + + assertEquals(1, texture.numImageReaders()); + assertEquals(1, texture.numImages()); + assertEquals(0, texture.pendingDequeuedImages()); + + // Resize. + texture.setSize(4, 4); + + // Render a frame at the old size (by using the pre-resized Surface) + canvas = surface.lockHardwareCanvas(); + canvas.drawARGB(255, 255, 0, 0); + surface.unlockCanvasAndPost(canvas); + + // Let callbacks run. + shadowOf(Looper.getMainLooper()).idle(); + + assertEquals(1, texture.numImageReaders()); + assertEquals(2, texture.numImages()); + assertEquals(0, texture.pendingDequeuedImages()); + + // Render a new frame with the current size. + surface = texture.getSurface(); + assertNotNull(surface); + canvas = surface.lockHardwareCanvas(); + canvas.drawARGB(255, 255, 0, 0); + surface.unlockCanvasAndPost(canvas); + + // Let callbacks run. + shadowOf(Looper.getMainLooper()).idle(); + + assertEquals(2, texture.numImageReaders()); + assertEquals(3, texture.numImages()); + assertEquals(0, texture.pendingDequeuedImages()); + + // Acquire first frame. + Image produced = texture.acquireLatestImage(); + assertNotNull(produced); + assertEquals(1, produced.getWidth()); + assertEquals(1, produced.getHeight()); + assertEquals(2, texture.numImageReaders()); + assertEquals(2, texture.numImages()); + assertEquals(1, texture.pendingDequeuedImages()); + + // Acquire second frame. This won't result in the first reader being closed because it has + // an active image from it. + produced = texture.acquireLatestImage(); + assertNotNull(produced); + assertEquals(1, produced.getWidth()); + assertEquals(1, produced.getHeight()); + assertEquals(2, texture.numImageReaders()); + assertEquals(1, texture.numImages()); + assertEquals(2, texture.pendingDequeuedImages()); + + // Acquire third frame. We will now close the first reader. + produced = texture.acquireLatestImage(); + assertNotNull(produced); + assertEquals(4, produced.getWidth()); + assertEquals(4, produced.getHeight()); + assertEquals(1, texture.numImageReaders()); + assertEquals(0, texture.numImages()); + assertEquals(3, texture.pendingDequeuedImages()); + + // Returns null image when no more images are queued. + assertNull(texture.acquireLatestImage()); + assertEquals(1, texture.numImageReaders()); + assertEquals(0, texture.numImages()); + assertEquals(3, texture.pendingDequeuedImages()); + } + + @Test + public void ImageReaderSurfaceProducerDequeueManyImages() { + // Demonstrates maximum dequeued image count. + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + TextureRegistry.SurfaceProducer producer = flutterRenderer.createSurfaceProducer(); + FlutterRenderer.ImageReaderSurfaceProducer texture = + (FlutterRenderer.ImageReaderSurfaceProducer) producer; + texture.disableFenceForTest(); + + // Give the texture an initial size. + texture.setSize(1, 1); + + Surface surface = texture.getSurface(); + Canvas canvas = surface.lockHardwareCanvas(); + canvas.drawARGB(255, 255, 0, 0); + surface.unlockCanvasAndPost(canvas); + shadowOf(Looper.getMainLooper()).idle(); + + // Acquire first frame. + Image produced = texture.acquireLatestImage(); + assertNotNull(produced); + assertEquals(1, texture.pendingDequeuedImages()); + + canvas = surface.lockHardwareCanvas(); + canvas.drawARGB(255, 255, 0, 0); + surface.unlockCanvasAndPost(canvas); + shadowOf(Looper.getMainLooper()).idle(); + + // 2 + produced = texture.acquireLatestImage(); + assertEquals(2, texture.pendingDequeuedImages()); + + canvas = surface.lockHardwareCanvas(); + canvas.drawARGB(255, 255, 0, 0); + surface.unlockCanvasAndPost(canvas); + shadowOf(Looper.getMainLooper()).idle(); + + // 3 + produced = texture.acquireLatestImage(); + assertEquals(3, texture.pendingDequeuedImages()); + + canvas = surface.lockHardwareCanvas(); + canvas.drawARGB(255, 255, 0, 0); + surface.unlockCanvasAndPost(canvas); + shadowOf(Looper.getMainLooper()).idle(); + + // 4 + produced = texture.acquireLatestImage(); + assertEquals(3, texture.pendingDequeuedImages()); + } + + @Test + public void ImageReaderSurfaceProducerTrimMemoryCallback() { + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + TextureRegistry.SurfaceProducer producer = flutterRenderer.createSurfaceProducer(); + FlutterRenderer.ImageReaderSurfaceProducer texture = + (FlutterRenderer.ImageReaderSurfaceProducer) producer; + + texture.disableFenceForTest(); + + // Returns a null image when one hasn't been produced. + assertNull(texture.acquireLatestImage()); + + // Give the texture an initial size. + texture.setSize(1, 1); + + // Grab the surface so we can render a frame at 1x1 after resizing. + Surface surface = texture.getSurface(); + assertNotNull(surface); + Canvas canvas = surface.lockHardwareCanvas(); + canvas.drawARGB(255, 255, 0, 0); + surface.unlockCanvasAndPost(canvas); + + // Let callbacks run, this will produce a single frame. + shadowOf(Looper.getMainLooper()).idle(); + + assertEquals(1, texture.numImageReaders()); + assertEquals(1, texture.numImages()); + + // Invoke the onTrimMemory callback with level 0. + // This should do nothing. + texture.onTrimMemory(0); + shadowOf(Looper.getMainLooper()).idle(); + + assertEquals(1, texture.numImageReaders()); + assertEquals(1, texture.numImages()); + assertEquals(0, texture.numTrims()); + + // Invoke the onTrimMemory callback with level 40. + // This should result in a trim. + texture.onTrimMemory(TRIM_MEMORY_BACKGROUND); + shadowOf(Looper.getMainLooper()).idle(); + + assertEquals(0, texture.numImageReaders()); + assertEquals(0, texture.numImages()); + assertEquals(1, texture.numTrims()); + + // Request the surface, this should result in a new image reader. + surface = texture.getSurface(); + assertEquals(1, texture.numImageReaders()); + assertEquals(0, texture.numImages()); + assertEquals(1, texture.numTrims()); + + // Render an image. + canvas = surface.lockHardwareCanvas(); + canvas.drawARGB(255, 255, 0, 0); + surface.unlockCanvasAndPost(canvas); + + // Let callbacks run, this will produce a single frame. + shadowOf(Looper.getMainLooper()).idle(); + + assertEquals(1, texture.numImageReaders()); + assertEquals(1, texture.numImages()); + assertEquals(1, texture.numTrims()); + } + + // A 0x0 ImageReader is a runtime error. + @Test + public void ImageReaderSurfaceProducerClampsWidthAndHeightTo1() { + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + TextureRegistry.SurfaceProducer producer = flutterRenderer.createSurfaceProducer(); + + // Default values. + assertEquals(producer.getWidth(), 1); + assertEquals(producer.getHeight(), 1); + + // Try setting width and height to 0. + producer.setSize(0, 0); + + // Ensure we can still create/get a surface without an exception being raised. + assertNotNull(producer.getSurface()); + + // Expect clamp to 1. + assertEquals(producer.getWidth(), 1); + assertEquals(producer.getHeight(), 1); + } + + @Test + public void SurfaceTextureSurfaceProducerCreatesAConnectedTexture() { + // Force creating a SurfaceTextureSurfaceProducer regardless of Android API version. + Surface fakeSurface = mock(Surface.class); + try { + FlutterRenderer.debugForceSurfaceProducerGlTextures = true; + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + TextureRegistry.SurfaceProducer producer = flutterRenderer.createSurfaceProducer(); + + flutterRenderer.startRenderingToSurface(fakeSurface, false); + + // Verify behavior under test. + assertEquals(producer.id(), 0); + verify(fakeFlutterJNI, times(1)).registerTexture(eq(producer.id()), any()); + } finally { + FlutterRenderer.debugForceSurfaceProducerGlTextures = false; + } + } + + @Test + public void SurfaceTextureSurfaceProducerDoesNotCropOrRotate() { + try { + FlutterRenderer.debugForceSurfaceProducerGlTextures = true; + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + TextureRegistry.SurfaceProducer producer = flutterRenderer.createSurfaceProducer(); + + assertTrue(producer.handlesCropAndRotation()); + } finally { + FlutterRenderer.debugForceSurfaceProducerGlTextures = false; + } + } + + @Test + public void ImageReaderSurfaceProducerDoesNotCropOrRotate() { + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + TextureRegistry.SurfaceProducer producer = flutterRenderer.createSurfaceProducer(); + + assertFalse(producer.handlesCropAndRotation()); + } + + @Test + @SuppressWarnings({"deprecation", "removal"}) + public void ImageReaderSurfaceProducerIsCleanedUpOnTrimMemory() { + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + TextureRegistry.SurfaceProducer producer = + flutterRenderer.createSurfaceProducer(TextureRegistry.SurfaceLifecycle.resetInBackground); + + // Create and set a mock callback. + TextureRegistry.SurfaceProducer.Callback callback = + mock(TextureRegistry.SurfaceProducer.Callback.class); + producer.setCallback(callback); + + // Trim memory. + flutterRenderer.onTrimMemory(TRIM_MEMORY_BACKGROUND); + + // Verify. + verify(callback).onSurfaceCleanup(); + } + + private static class TestSurfaceState { + Surface beingDestroyed; + } + + @Test + public void ImageReaderSurfaceProducerSignalsCleanupBeforeDestroying() throws Exception { + // Regression test for https://github.com/flutter/flutter/issues/160933. + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + TextureRegistry.SurfaceProducer producer = + flutterRenderer.createSurfaceProducer(TextureRegistry.SurfaceLifecycle.resetInBackground); + + // Ensure the callbacks were actually called. + // Note this needs to be an object in order to be accessed in the callback. + final TestSurfaceState state = new TestSurfaceState(); + state.beingDestroyed = producer.getSurface(); + + // Create and set a callback that ensures the surface is not yet released. + CountDownLatch latch = new CountDownLatch(1); + producer.setCallback( + new TextureRegistry.SurfaceProducer.Callback() { + @Override + public void onSurfaceCleanup() { + state.beingDestroyed = producer.getSurface(); + assertTrue("Not released yet", state.beingDestroyed.isValid()); + + state.beingDestroyed.release(); + latch.countDown(); + } + }); + + // Trim. + flutterRenderer.onTrimMemory(TRIM_MEMORY_BACKGROUND); + latch.await(); + + // Destroy. + assertFalse("Should be destroyed", state.beingDestroyed.isValid()); + } + + @Test + @SuppressWarnings({"deprecation", "removal"}) + public void ImageReaderSurfaceProducerSignalsCleanupCallsDestroy() throws Exception { + CountDownLatch latch = new CountDownLatch(1); + TextureRegistry.SurfaceProducer.Callback callback = + new TextureRegistry.SurfaceProducer.Callback() { + @Override + public void onSurfaceDestroyed() { + latch.countDown(); + } + }; + + // Tests that cleanup, if not provided, just calls destroyed. + callback.onSurfaceCleanup(); + latch.await(); + } + + @Test + @SuppressWarnings({"deprecation", "removal"}) + public void ImageReaderSurfaceProducerUnsubscribesWhenReleased() { + // Regression test for https://github.com/flutter/flutter/issues/156434. + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + TextureRegistry.SurfaceProducer producer = + flutterRenderer.createSurfaceProducer(TextureRegistry.SurfaceLifecycle.resetInBackground); + + // Create and set a mock callback. + TextureRegistry.SurfaceProducer.Callback callback = + mock(TextureRegistry.SurfaceProducer.Callback.class); + producer.setCallback(callback); + + // Release the surface. + producer.release(); + + // Call trim memory. + flutterRenderer.onTrimMemory(TRIM_MEMORY_BACKGROUND); + + // Verify was not called. + verify(callback, never()).onSurfaceCleanup(); + verify(callback, never()).onSurfaceDestroyed(); + } + + @Test + @SuppressWarnings({"deprecation", "removal"}) + public void ImageReaderSurfaceProducerIsCreatedOnLifecycleResume() throws Exception { + FlutterRenderer flutterRenderer = engineRule.getFlutterEngine().getRenderer(); + TextureRegistry.SurfaceProducer producer = + flutterRenderer.createSurfaceProducer(TextureRegistry.SurfaceLifecycle.resetInBackground); + + // Create a callback. + CountDownLatch latch = new CountDownLatch(1); + TextureRegistry.SurfaceProducer.Callback callback = + new TextureRegistry.SurfaceProducer.Callback() { + @Override + public void onSurfaceAvailable() { + latch.countDown(); + } + + @Override + public void onSurfaceDestroyed() {} + }; + producer.setCallback(callback); + + // Trim memory. + flutterRenderer.onTrimMemory(TRIM_MEMORY_BACKGROUND); + + // Trigger a resume. + ((LifecycleRegistry) ProcessLifecycleOwner.get().getLifecycle()) + .setCurrentState(Lifecycle.State.RESUMED); + + // Verify. + latch.await(); + } + + @Test + public void ImageReaderSurfaceProducerSchedulesFrameIfQueueNotEmpty() throws Exception { + FlutterRenderer flutterRenderer = spy(engineRule.getFlutterEngine().getRenderer()); + TextureRegistry.SurfaceProducer producer = flutterRenderer.createSurfaceProducer(); + FlutterRenderer.ImageReaderSurfaceProducer texture = + (FlutterRenderer.ImageReaderSurfaceProducer) producer; + texture.disableFenceForTest(); + texture.setSize(1, 1); + + // Render two frames. + for (int i = 0; i < 2; i++) { + Surface surface = texture.getSurface(); + assertNotNull(surface); + Canvas canvas = surface.lockHardwareCanvas(); + canvas.drawARGB(255, 255, 0, 0); + surface.unlockCanvasAndPost(canvas); + shadowOf(Looper.getMainLooper()).idle(); + } + + // Each enqueue of an image should result in a call to scheduleEngineFrame. + verify(flutterRenderer, times(2)).scheduleEngineFrame(); + + // Consume the first image. + Image image = texture.acquireLatestImage(); + shadowOf(Looper.getMainLooper()).idle(); + + // The dequeue should call scheduleEngineFrame because another image + // remains in the queue. + verify(flutterRenderer, times(3)).scheduleEngineFrame(); + + // Consume the second image. + image = texture.acquireLatestImage(); + shadowOf(Looper.getMainLooper()).idle(); + + // The dequeue should not call scheduleEngineFrame because the queue + // is now empty. + verify(flutterRenderer, times(3)).scheduleEngineFrame(); + } + + @Test + public void getForcedNewSurface_returnsNewSurface() { + FlutterRenderer flutterRenderer = spy(engineRule.getFlutterEngine().getRenderer()); + TextureRegistry.SurfaceProducer producer = flutterRenderer.createSurfaceProducer(); + + Surface firstSurface = producer.getSurface(); + Surface secondSurface = producer.getForcedNewSurface(); + + assertNotEquals(firstSurface, secondSurface); + } + + @Test + public void getSurface_doesNotReturnNewSurface() { + FlutterRenderer flutterRenderer = spy(engineRule.getFlutterEngine().getRenderer()); + TextureRegistry.SurfaceProducer producer = flutterRenderer.createSurfaceProducer(); + + Surface firstSurface = producer.getSurface(); + Surface secondSurface = producer.getSurface(); + + assertEquals(firstSurface, secondSurface); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/renderer/SurfaceTextureSurfaceProducerTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/renderer/SurfaceTextureSurfaceProducerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..639d338ece4899ae04b7e41a3c361dcf6e450708 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/renderer/SurfaceTextureSurfaceProducerTest.java @@ -0,0 +1,116 @@ +// 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. + +package io.flutter.embedding.engine.renderer; + +import static io.flutter.Build.API_LEVELS; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.robolectric.Shadows.shadowOf; + +import android.annotation.TargetApi; +import android.graphics.Canvas; +import android.graphics.SurfaceTexture; +import android.os.Handler; +import android.os.Looper; +import android.view.Surface; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.FlutterJNI; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(AndroidJUnit4.class) +@TargetApi(API_LEVELS.API_26) +public final class SurfaceTextureSurfaceProducerTest { + private final FlutterJNI fakeJNI = mock(FlutterJNI.class); + + @Test + public void createsSurfaceTextureOfGivenSizeAndResizesWhenRequested() { + final FlutterRenderer flutterRenderer = new FlutterRenderer(fakeJNI); + + // Create a surface and set the initial size. + final Handler handler = new Handler(Looper.getMainLooper()); + final SurfaceTextureSurfaceProducer producer = + new SurfaceTextureSurfaceProducer( + 0, handler, fakeJNI, flutterRenderer.registerSurfaceTexture(new SurfaceTexture(0))); + final Surface surface = producer.getSurface(); + AtomicInteger frames = new AtomicInteger(); + producer + .getSurfaceTexture() + .setOnFrameAvailableListener( + (texture) -> { + if (texture.isReleased()) { + return; + } + frames.getAndIncrement(); + }); + producer.setSize(100, 200); + + // Draw. + Canvas canvas = surface.lockHardwareCanvas(); + canvas.drawARGB(255, 255, 0, 0); + surface.unlockCanvasAndPost(canvas); + shadowOf(Looper.getMainLooper()).idle(); + assertEquals(frames.get(), 1); + + // Resize and redraw. + producer.setSize(400, 800); + canvas = surface.lockHardwareCanvas(); + canvas.drawARGB(255, 255, 0, 0); + surface.unlockCanvasAndPost(canvas); + shadowOf(Looper.getMainLooper()).idle(); + assertEquals(frames.get(), 2); + + // Done. + fakeJNI.detachFromNativeAndReleaseResources(); + producer.release(); + } + + @Test + public void releaseWillReleaseSurface() { + final FlutterRenderer flutterRenderer = new FlutterRenderer(fakeJNI); + + // Create a surface and set the initial size. + final Handler handler = new Handler(Looper.getMainLooper()); + final SurfaceTextureSurfaceProducer producer = + new SurfaceTextureSurfaceProducer( + 0, handler, fakeJNI, flutterRenderer.registerSurfaceTexture(new SurfaceTexture(0))); + final Surface surface = producer.getSurface(); + assertTrue(surface.isValid()); + producer.release(); + assertFalse(surface.isValid()); + } + + @Test + public void getForcedNewSurface_returnsNewSurface() { + final FlutterRenderer flutterRenderer = new FlutterRenderer(fakeJNI); + final Handler handler = new Handler(Looper.getMainLooper()); + final SurfaceTextureSurfaceProducer producer = + new SurfaceTextureSurfaceProducer( + 0, handler, fakeJNI, flutterRenderer.registerSurfaceTexture(new SurfaceTexture(0))); + + final Surface firstSurface = producer.getSurface(); + final Surface secondSurface = producer.getForcedNewSurface(); + + assertNotEquals(firstSurface, secondSurface); + } + + @Test + public void getSurface_doesNotReturnNewSurface() { + final FlutterRenderer flutterRenderer = new FlutterRenderer(fakeJNI); + final Handler handler = new Handler(Looper.getMainLooper()); + final SurfaceTextureSurfaceProducer producer = + new SurfaceTextureSurfaceProducer( + 0, handler, fakeJNI, flutterRenderer.registerSurfaceTexture(new SurfaceTexture(0))); + + Surface firstSurface = producer.getSurface(); + Surface secondSurface = producer.getSurface(); + + assertEquals(firstSurface, secondSurface); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/renderer/SurfaceTextureWrapperTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/renderer/SurfaceTextureWrapperTest.java new file mode 100644 index 0000000000000000000000000000000000000000..859b024b888b6585791c56289944fad889338e12 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/renderer/SurfaceTextureWrapperTest.java @@ -0,0 +1,86 @@ +// 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. + +package io.flutter.embedding.engine.renderer; + +import static junit.framework.TestCase.*; +import static org.mockito.Mockito.*; + +import android.graphics.SurfaceTexture; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(AndroidJUnit4.class) +public class SurfaceTextureWrapperTest { + + @Test + public void attachToGLContext() { + final SurfaceTexture tx = mock(SurfaceTexture.class); + final SurfaceTextureWrapper wrapper = new SurfaceTextureWrapper(tx); + + wrapper.attachToGLContext(0); + verify(tx, times(1)).attachToGLContext(0); + verifyNoMoreInteractions(tx); + } + + @Test + public void attachToGLContext_detachesFromCurrentContext() { + final SurfaceTexture tx = mock(SurfaceTexture.class); + final SurfaceTextureWrapper wrapper = new SurfaceTextureWrapper(tx); + + wrapper.attachToGLContext(0); + + reset(tx); + + wrapper.attachToGLContext(0); + verify(tx, times(1)).detachFromGLContext(); + verify(tx, times(1)).attachToGLContext(0); + verifyNoMoreInteractions(tx); + } + + @Test + public void attachToGLContext_doesNotDetacheFromCurrentContext() { + final SurfaceTexture tx = mock(SurfaceTexture.class); + final SurfaceTextureWrapper wrapper = new SurfaceTextureWrapper(tx); + + wrapper.attachToGLContext(0); + + wrapper.detachFromGLContext(); + + reset(tx); + + wrapper.attachToGLContext(0); + verify(tx, times(1)).attachToGLContext(0); + verifyNoMoreInteractions(tx); + } + + @Test + public void detachFromGLContext() { + final SurfaceTexture tx = mock(SurfaceTexture.class); + final SurfaceTextureWrapper wrapper = new SurfaceTextureWrapper(tx); + + wrapper.attachToGLContext(0); + reset(tx); + + wrapper.detachFromGLContext(); + verify(tx, times(1)).detachFromGLContext(); + verifyNoMoreInteractions(tx); + } + + @Test + public void release() { + final SurfaceTexture tx = mock(SurfaceTexture.class); + final SurfaceTextureWrapper wrapper = new SurfaceTextureWrapper(tx); + + wrapper.release(); + + verify(tx, times(1)).release(); + reset(tx); + + wrapper.detachFromGLContext(); + wrapper.attachToGLContext(0); + verifyNoMoreInteractions(tx); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/AccessibilityChannelTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/AccessibilityChannelTest.java new file mode 100644 index 0000000000000000000000000000000000000000..93d84759927915a510564a8bb591ebc94d134bc8 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/AccessibilityChannelTest.java @@ -0,0 +1,54 @@ +// 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. + +package io.flutter.embedding.engine.systemchannels; + +import static io.flutter.Build.API_LEVELS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import android.annotation.TargetApi; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.dart.DartExecutor; +import io.flutter.plugin.common.BasicMessageChannel; +import java.util.HashMap; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.annotation.Config; + +@Config( + manifest = Config.NONE, + shadows = {}) +@RunWith(RobolectricTestRunner.class) +@TargetApi(API_LEVELS.API_24) +public class AccessibilityChannelTest { + @Test + public void repliesWhenNoAccessibilityHandler() throws JSONException { + AccessibilityChannel accessibilityChannel = + new AccessibilityChannel(mock(DartExecutor.class), mock(FlutterJNI.class)); + JSONObject arguments = new JSONObject(); + arguments.put("type", "announce"); + BasicMessageChannel.Reply reply = mock(BasicMessageChannel.Reply.class); + accessibilityChannel.parsingMessageHandler.onMessage(arguments, reply); + verify(reply).reply(null); + } + + @Test + public void handleFocus() throws JSONException { + AccessibilityChannel accessibilityChannel = + new AccessibilityChannel(mock(DartExecutor.class), mock(FlutterJNI.class)); + HashMap arguments = new HashMap<>(); + arguments.put("type", "focus"); + arguments.put("nodeId", 123); + AccessibilityChannel.AccessibilityMessageHandler handler = + mock(AccessibilityChannel.AccessibilityMessageHandler.class); + accessibilityChannel.setAccessibilityMessageHandler(handler); + BasicMessageChannel.Reply reply = mock(BasicMessageChannel.Reply.class); + accessibilityChannel.parsingMessageHandler.onMessage(arguments, reply); + verify(handler).onFocus(123); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/DeferredComponentChannelTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/DeferredComponentChannelTest.java new file mode 100644 index 0000000000000000000000000000000000000000..c24b12697f9f2cabc7049c13faff1d7500bcb270 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/DeferredComponentChannelTest.java @@ -0,0 +1,127 @@ +// 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. + +package io.flutter.embedding.engine.systemchannels; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import android.content.res.AssetManager; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.dart.DartExecutor; +import io.flutter.embedding.engine.deferredcomponents.DeferredComponentManager; +import io.flutter.plugin.common.MethodCall; +import io.flutter.plugin.common.MethodChannel; +import java.util.HashMap; +import java.util.Map; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +class TestDeferredComponentManager implements DeferredComponentManager { + DeferredComponentChannel channel; + String componentName; + + public void setJNI(FlutterJNI flutterJNI) {} + + public void setDeferredComponentChannel(DeferredComponentChannel channel) { + this.channel = channel; + } + + public void installDeferredComponent(int loadingUnitId, String componentName) { + this.componentName = componentName; + } + + public void completeInstall() { + channel.completeInstallSuccess(componentName); + } + + public String getDeferredComponentInstallState(int loadingUnitId, String componentName) { + return "installed"; + } + + public void loadAssets(int loadingUnitId, String componentName) {} + + public void loadDartLibrary(int loadingUnitId, String componentName) {} + + public boolean uninstallDeferredComponent(int loadingUnitId, String componentName) { + return true; + } + + public void destroy() {} +} + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class DeferredComponentChannelTest { + @Test + public void deferredComponentChannel_installCompletesResults() { + MethodChannel rawChannel = mock(MethodChannel.class); + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + DartExecutor dartExecutor = new DartExecutor(mockFlutterJNI, mock(AssetManager.class), 0); + TestDeferredComponentManager testDeferredComponentManager = new TestDeferredComponentManager(); + DeferredComponentChannel fakeDeferredComponentChannel = + new DeferredComponentChannel(dartExecutor); + fakeDeferredComponentChannel.setDeferredComponentManager(testDeferredComponentManager); + testDeferredComponentManager.setDeferredComponentChannel(fakeDeferredComponentChannel); + + Map args = new HashMap<>(); + args.put("loadingUnitId", -1); + args.put("componentName", "hello"); + MethodCall methodCall = new MethodCall("installDeferredComponent", args); + MethodChannel.Result mockResult = mock(MethodChannel.Result.class); + fakeDeferredComponentChannel.parsingMethodHandler.onMethodCall(methodCall, mockResult); + + testDeferredComponentManager.completeInstall(); + verify(mockResult).success(null); + } + + @Test + public void deferredComponentChannel_installCompletesMultipleResults() { + MethodChannel rawChannel = mock(MethodChannel.class); + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + DartExecutor dartExecutor = new DartExecutor(mockFlutterJNI, mock(AssetManager.class)); + TestDeferredComponentManager testDeferredComponentManager = new TestDeferredComponentManager(); + DeferredComponentChannel fakeDeferredComponentChannel = + new DeferredComponentChannel(dartExecutor); + fakeDeferredComponentChannel.setDeferredComponentManager(testDeferredComponentManager); + testDeferredComponentManager.setDeferredComponentChannel(fakeDeferredComponentChannel); + + Map args = new HashMap<>(); + args.put("loadingUnitId", -1); + args.put("componentName", "hello"); + MethodCall methodCall = new MethodCall("installDeferredComponent", args); + MethodChannel.Result mockResult1 = mock(MethodChannel.Result.class); + MethodChannel.Result mockResult2 = mock(MethodChannel.Result.class); + fakeDeferredComponentChannel.parsingMethodHandler.onMethodCall(methodCall, mockResult1); + fakeDeferredComponentChannel.parsingMethodHandler.onMethodCall(methodCall, mockResult2); + + testDeferredComponentManager.completeInstall(); + verify(mockResult1).success(null); + verify(mockResult2).success(null); + } + + @Test + public void deferredComponentChannel_getInstallState() { + MethodChannel rawChannel = mock(MethodChannel.class); + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + DartExecutor dartExecutor = new DartExecutor(mockFlutterJNI, mock(AssetManager.class)); + TestDeferredComponentManager testDeferredComponentManager = new TestDeferredComponentManager(); + DeferredComponentChannel fakeDeferredComponentChannel = + new DeferredComponentChannel(dartExecutor); + fakeDeferredComponentChannel.setDeferredComponentManager(testDeferredComponentManager); + testDeferredComponentManager.setDeferredComponentChannel(fakeDeferredComponentChannel); + + Map args = new HashMap<>(); + args.put("loadingUnitId", -1); + args.put("componentName", "hello"); + MethodCall methodCall = new MethodCall("getDeferredComponentInstallState", args); + MethodChannel.Result mockResult = mock(MethodChannel.Result.class); + fakeDeferredComponentChannel.parsingMethodHandler.onMethodCall(methodCall, mockResult); + + testDeferredComponentManager.completeInstall(); + verify(mockResult).success("installed"); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/KeyEventChannelTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/KeyEventChannelTest.java new file mode 100644 index 0000000000000000000000000000000000000000..815adfc11ebe187cd0be7658aedc9f4510e59699 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/KeyEventChannelTest.java @@ -0,0 +1,114 @@ +// 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. + +package io.flutter.embedding.engine.systemchannels; + +import static io.flutter.Build.API_LEVELS; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import android.annotation.TargetApi; +import android.view.KeyEvent; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.plugin.common.BinaryMessenger; +import io.flutter.plugin.common.JSONMessageCodec; +import io.flutter.util.FakeKeyEvent; +import java.nio.ByteBuffer; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +@TargetApi(API_LEVELS.API_35) +public class KeyEventChannelTest { + + KeyEvent keyEvent; + @Mock BinaryMessenger fakeMessenger; + boolean[] handled; + KeyEventChannel keyEventChannel; + + private void sendReply(boolean handled, BinaryMessenger.BinaryReply messengerReply) + throws JSONException { + JSONObject reply = new JSONObject(); + reply.put("handled", true); + ByteBuffer binaryReply = JSONMessageCodec.INSTANCE.encodeMessage(reply); + assertNotNull(binaryReply); + binaryReply.rewind(); + messengerReply.reply(binaryReply); + } + + @Before + public void setUp() { + MockitoAnnotations.openMocks(this); + keyEvent = new FakeKeyEvent(KeyEvent.ACTION_DOWN, 65); + handled = new boolean[] {false}; + keyEventChannel = new KeyEventChannel(fakeMessenger); + } + + @Test + public void keyDownEventIsSentToFramework() throws JSONException { + KeyEventChannel.FlutterKeyEvent flutterKeyEvent = + new KeyEventChannel.FlutterKeyEvent(keyEvent, null); + keyEventChannel.sendFlutterKeyEvent( + flutterKeyEvent, + false, + (isHandled) -> { + handled[0] = isHandled; + }); + + ArgumentCaptor byteBufferArgumentCaptor = ArgumentCaptor.forClass(ByteBuffer.class); + ArgumentCaptor replyArgumentCaptor = + ArgumentCaptor.forClass(BinaryMessenger.BinaryReply.class); + verify(fakeMessenger, times(1)) + .send(any(), byteBufferArgumentCaptor.capture(), replyArgumentCaptor.capture()); + ByteBuffer capturedMessage = byteBufferArgumentCaptor.getValue(); + capturedMessage.rewind(); + JSONObject message = (JSONObject) JSONMessageCodec.INSTANCE.decodeMessage(capturedMessage); + assertNotNull(message); + assertEquals("keydown", message.get("type")); + + // Simulate a reply, and see that it is handled. + sendReply(true, replyArgumentCaptor.getValue()); + assertTrue(handled[0]); + } + + @Test + public void keyUpEventIsSentToFramework() throws JSONException { + keyEvent = new FakeKeyEvent(KeyEvent.ACTION_UP, 65); + KeyEventChannel.FlutterKeyEvent flutterKeyEvent = + new KeyEventChannel.FlutterKeyEvent(keyEvent, null); + keyEventChannel.sendFlutterKeyEvent( + flutterKeyEvent, + false, + (isHandled) -> { + handled[0] = isHandled; + }); + + ArgumentCaptor byteBufferArgumentCaptor = ArgumentCaptor.forClass(ByteBuffer.class); + ArgumentCaptor replyArgumentCaptor = + ArgumentCaptor.forClass(BinaryMessenger.BinaryReply.class); + verify(fakeMessenger, times(1)) + .send(any(), byteBufferArgumentCaptor.capture(), replyArgumentCaptor.capture()); + ByteBuffer capturedMessage = byteBufferArgumentCaptor.getValue(); + capturedMessage.rewind(); + JSONObject message = (JSONObject) JSONMessageCodec.INSTANCE.decodeMessage(capturedMessage); + assertNotNull(message); + assertEquals("keydown", message.get("type")); + + // Simulate a reply, and see that it is handled. + sendReply(true, replyArgumentCaptor.getValue()); + assertTrue(handled[0]); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/KeyboardChannelTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/KeyboardChannelTest.java new file mode 100644 index 0000000000000000000000000000000000000000..383a1f7552b3f7fb0620a5dd597d9a551e87cd53 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/KeyboardChannelTest.java @@ -0,0 +1,73 @@ +// 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. + +package io.flutter.embedding.android; + +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.dart.DartExecutor; +import io.flutter.embedding.engine.systemchannels.KeyboardChannel; +import io.flutter.plugin.common.BinaryMessenger; +import io.flutter.plugin.common.MethodCall; +import io.flutter.plugin.common.MethodChannel; +import io.flutter.plugin.common.StandardMethodCodec; +import java.nio.ByteBuffer; +import java.util.HashMap; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class KeyboardChannelTest { + + private static BinaryMessenger.BinaryReply sendToBinaryMessageHandler( + BinaryMessenger.BinaryMessageHandler binaryMessageHandler, String method, Object args) { + MethodCall methodCall = new MethodCall(method, args); + ByteBuffer encodedMethodCall = StandardMethodCodec.INSTANCE.encodeMethodCall(methodCall); + BinaryMessenger.BinaryReply reply = mock(BinaryMessenger.BinaryReply.class); + binaryMessageHandler.onMessage((ByteBuffer) encodedMethodCall.flip(), reply); + return reply; + } + + @SuppressWarnings("deprecation") + // setMessageHandler is deprecated. + @Test + public void respondsToGetKeyboardStateChannelMessage() { + ArgumentCaptor binaryMessageHandlerCaptor = + ArgumentCaptor.forClass(BinaryMessenger.BinaryMessageHandler.class); + DartExecutor mockBinaryMessenger = mock(DartExecutor.class); + KeyboardChannel.KeyboardMethodHandler mockHandler = + mock(KeyboardChannel.KeyboardMethodHandler.class); + KeyboardChannel keyboardChannel = new KeyboardChannel(mockBinaryMessenger); + + verify(mockBinaryMessenger, times(1)) + .setMessageHandler(any(String.class), binaryMessageHandlerCaptor.capture()); + + BinaryMessenger.BinaryMessageHandler binaryMessageHandler = + binaryMessageHandlerCaptor.getValue(); + + keyboardChannel.setKeyboardMethodHandler(mockHandler); + sendToBinaryMessageHandler(binaryMessageHandler, "getKeyboardState", null); + + verify(mockHandler, times(1)).getKeyboardState(); + } + + @Test + public void repliesWhenNoKeyboardChannelHandler() { + // Regression test for https://github.com/flutter/flutter/issues/122441#issuecomment-1582052616. + + KeyboardChannel keyboardChannel = new KeyboardChannel(mock(DartExecutor.class)); + MethodCall methodCall = new MethodCall("getKeyboardState", null); + MethodChannel.Result result = mock(MethodChannel.Result.class); + keyboardChannel.parsingMethodHandler.onMethodCall(methodCall, result); + + verify(result).success(new HashMap()); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/LifecycleChannelTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/LifecycleChannelTest.java new file mode 100644 index 0000000000000000000000000000000000000000..c064961244ddff543383ed2f6e767a9548f541ca --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/LifecycleChannelTest.java @@ -0,0 +1,137 @@ +// 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. + +package io.flutter.embedding.engine.systemchannels; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.plugin.common.BasicMessageChannel; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class LifecycleChannelTest { + LifecycleChannel lifecycleChannel; + BasicMessageChannel mockChannel; + + @Before + public void setUp() { + mockChannel = mock(BasicMessageChannel.class); + lifecycleChannel = new LifecycleChannel(mockChannel); + } + + @Test + public void lifecycleChannel_handlesResumed() { + lifecycleChannel.appIsResumed(); + ArgumentCaptor stringArgumentCaptor = ArgumentCaptor.forClass(String.class); + verify(mockChannel, times(1)).send(stringArgumentCaptor.capture()); + assertEquals("AppLifecycleState.resumed", stringArgumentCaptor.getValue()); + + lifecycleChannel.noWindowsAreFocused(); + stringArgumentCaptor = ArgumentCaptor.forClass(String.class); + verify(mockChannel, times(2)).send(stringArgumentCaptor.capture()); + assertEquals("AppLifecycleState.inactive", stringArgumentCaptor.getValue()); + + lifecycleChannel.aWindowIsFocused(); + stringArgumentCaptor = ArgumentCaptor.forClass(String.class); + verify(mockChannel, times(3)).send(stringArgumentCaptor.capture()); + assertEquals("AppLifecycleState.resumed", stringArgumentCaptor.getValue()); + + // Stays inactive, so no event is sent. + lifecycleChannel.appIsInactive(); + verify(mockChannel, times(4)).send(any(String.class)); + + // Stays inactive, so no event is sent. + lifecycleChannel.appIsResumed(); + verify(mockChannel, times(5)).send(any(String.class)); + + lifecycleChannel.aWindowIsFocused(); + stringArgumentCaptor = ArgumentCaptor.forClass(String.class); + verify(mockChannel, times(5)).send(stringArgumentCaptor.capture()); + assertEquals("AppLifecycleState.resumed", stringArgumentCaptor.getValue()); + } + + @Test + public void lifecycleChannel_handlesInactive() { + lifecycleChannel.appIsInactive(); + ArgumentCaptor stringArgumentCaptor = ArgumentCaptor.forClass(String.class); + verify(mockChannel, times(1)).send(stringArgumentCaptor.capture()); + assertEquals("AppLifecycleState.inactive", stringArgumentCaptor.getValue()); + + // Stays inactive, so no event is sent. + lifecycleChannel.aWindowIsFocused(); + verify(mockChannel, times(1)).send(any(String.class)); + + // Stays inactive, so no event is sent. + lifecycleChannel.noWindowsAreFocused(); + verify(mockChannel, times(1)).send(any(String.class)); + + lifecycleChannel.appIsResumed(); + lifecycleChannel.aWindowIsFocused(); + stringArgumentCaptor = ArgumentCaptor.forClass(String.class); + verify(mockChannel, times(2)).send(stringArgumentCaptor.capture()); + assertEquals("AppLifecycleState.resumed", stringArgumentCaptor.getValue()); + } + + @Test + public void lifecycleChannel_handlesPaused() { + // Stays inactive, so no event is sent. + lifecycleChannel.appIsPaused(); + ArgumentCaptor stringArgumentCaptor = ArgumentCaptor.forClass(String.class); + verify(mockChannel, times(1)).send(stringArgumentCaptor.capture()); + assertEquals("AppLifecycleState.paused", stringArgumentCaptor.getValue()); + + // Stays paused, so no event is sent. + lifecycleChannel.aWindowIsFocused(); + verify(mockChannel, times(1)).send(any(String.class)); + + lifecycleChannel.noWindowsAreFocused(); + verify(mockChannel, times(1)).send(any(String.class)); + + lifecycleChannel.appIsResumed(); + stringArgumentCaptor = ArgumentCaptor.forClass(String.class); + verify(mockChannel, times(2)).send(stringArgumentCaptor.capture()); + assertEquals("AppLifecycleState.inactive", stringArgumentCaptor.getValue()); + + lifecycleChannel.aWindowIsFocused(); + stringArgumentCaptor = ArgumentCaptor.forClass(String.class); + verify(mockChannel, times(3)).send(stringArgumentCaptor.capture()); + assertEquals("AppLifecycleState.resumed", stringArgumentCaptor.getValue()); + } + + @Test + public void lifecycleChannel_handlesDetached() { + // Stays inactive, so no event is sent. + lifecycleChannel.appIsDetached(); + ArgumentCaptor stringArgumentCaptor = ArgumentCaptor.forClass(String.class); + verify(mockChannel, times(1)).send(stringArgumentCaptor.capture()); + assertEquals("AppLifecycleState.detached", stringArgumentCaptor.getValue()); + + // Stays paused, so no event is sent. + lifecycleChannel.aWindowIsFocused(); + verify(mockChannel, times(1)).send(any(String.class)); + + lifecycleChannel.noWindowsAreFocused(); + verify(mockChannel, times(1)).send(any(String.class)); + + lifecycleChannel.appIsResumed(); + stringArgumentCaptor = ArgumentCaptor.forClass(String.class); + verify(mockChannel, times(2)).send(stringArgumentCaptor.capture()); + assertEquals("AppLifecycleState.inactive", stringArgumentCaptor.getValue()); + + lifecycleChannel.aWindowIsFocused(); + stringArgumentCaptor = ArgumentCaptor.forClass(String.class); + verify(mockChannel, times(3)).send(stringArgumentCaptor.capture()); + assertEquals("AppLifecycleState.resumed", stringArgumentCaptor.getValue()); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/PlatformChannelTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/PlatformChannelTest.java new file mode 100644 index 0000000000000000000000000000000000000000..076f89d5dbb66595b9793d4ea850925750dc3cbb --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/PlatformChannelTest.java @@ -0,0 +1,74 @@ +// 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. + +package io.flutter.embedding.engine.systemchannels; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.refEq; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.content.res.AssetManager; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.dart.DartExecutor; +import io.flutter.plugin.common.MethodCall; +import io.flutter.plugin.common.MethodChannel; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class PlatformChannelTest { + @Test + public void platformChannel_hasStringsMessage() { + MethodChannel rawChannel = mock(MethodChannel.class); + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + DartExecutor dartExecutor = new DartExecutor(mockFlutterJNI, mock(AssetManager.class)); + PlatformChannel fakePlatformChannel = new PlatformChannel(dartExecutor); + PlatformChannel.PlatformMessageHandler mockMessageHandler = + mock(PlatformChannel.PlatformMessageHandler.class); + fakePlatformChannel.setPlatformMessageHandler(mockMessageHandler); + Boolean returnValue = true; + when(mockMessageHandler.clipboardHasStrings()).thenReturn(returnValue); + MethodCall methodCall = new MethodCall("Clipboard.hasStrings", null); + MethodChannel.Result mockResult = mock(MethodChannel.Result.class); + fakePlatformChannel.parsingMethodCallHandler.onMethodCall(methodCall, mockResult); + + JSONObject expected = new JSONObject(); + try { + expected.put("value", returnValue); + } catch (JSONException e) { + } + verify(mockResult).success(refEq(expected)); + } + + @Test + public void platformChannel_shareInvokeMessage() { + MethodChannel rawChannel = mock(MethodChannel.class); + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + DartExecutor dartExecutor = new DartExecutor(mockFlutterJNI, mock(AssetManager.class)); + PlatformChannel fakePlatformChannel = new PlatformChannel(dartExecutor); + PlatformChannel.PlatformMessageHandler mockMessageHandler = + mock(PlatformChannel.PlatformMessageHandler.class); + fakePlatformChannel.setPlatformMessageHandler(mockMessageHandler); + + ArgumentCaptor valueCapture = ArgumentCaptor.forClass(String.class); + doNothing().when(mockMessageHandler).share(valueCapture.capture()); + + final String expectedContent = "Flutter"; + MethodCall methodCall = new MethodCall("Share.invoke", expectedContent); + MethodChannel.Result mockResult = mock(MethodChannel.Result.class); + fakePlatformChannel.parsingMethodCallHandler.onMethodCall(methodCall, mockResult); + + assertEquals(valueCapture.getValue(), expectedContent); + verify(mockResult).success(null); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/RestorationChannelTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/RestorationChannelTest.java new file mode 100644 index 0000000000000000000000000000000000000000..b121b5a95b394792c8080248bf9f7874e5e2122b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/RestorationChannelTest.java @@ -0,0 +1,118 @@ +// 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. + +package io.flutter.embedding.engine.systemchannels; + +import static io.flutter.Build.API_LEVELS; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; + +import android.annotation.TargetApi; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.plugin.common.MethodCall; +import io.flutter.plugin.common.MethodChannel; +import java.util.HashMap; +import java.util.Map; +import org.json.JSONException; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.robolectric.annotation.Config; + +@Config( + manifest = Config.NONE, + shadows = {}) +@RunWith(AndroidJUnit4.class) +@TargetApi(API_LEVELS.API_24) +public class RestorationChannelTest { + @Test + public void itDoesNotDoAnythingWhenRestorationDataIsSetBeforeFrameworkAsks() + throws JSONException { + MethodChannel rawChannel = mock(MethodChannel.class); + RestorationChannel restorationChannel = + new RestorationChannel(rawChannel, /*waitForRestorationData=*/ false); + restorationChannel.setRestorationData("Any String you want".getBytes()); + verify(rawChannel, times(0)).invokeMethod(any(), any()); + } + + @Test + public void itSendsDataOverWhenRequestIsPending() throws JSONException { + byte[] data = "Any String you want".getBytes(); + + MethodChannel rawChannel = mock(MethodChannel.class); + RestorationChannel restorationChannel = + new RestorationChannel(rawChannel, /*waitForRestorationData=*/ true); + ArgumentCaptor argumentCaptor = + ArgumentCaptor.forClass(MethodChannel.MethodCallHandler.class); + verify(rawChannel).setMethodCallHandler(argumentCaptor.capture()); + + MethodChannel.Result result = mock(MethodChannel.Result.class); + argumentCaptor.getValue().onMethodCall(new MethodCall("get", null), result); + verifyNoInteractions(result); + + restorationChannel.setRestorationData(data); + verify(rawChannel, times(0)).invokeMethod(any(), any()); + Map expected = new HashMap<>(); + expected.put("enabled", true); + expected.put("data", data); + verify(result).success(expected); + + // Next get request is answered right away. + MethodChannel.Result result2 = mock(MethodChannel.Result.class); + argumentCaptor.getValue().onMethodCall(new MethodCall("get", null), result2); + verify(result2).success(expected); + } + + @Test + public void itPushesNewData() throws JSONException { + byte[] data = "Any String you want".getBytes(); + + MethodChannel rawChannel = mock(MethodChannel.class); + RestorationChannel restorationChannel = + new RestorationChannel(rawChannel, /*waitForRestorationData=*/ false); + ArgumentCaptor argumentCaptor = + ArgumentCaptor.forClass(MethodChannel.MethodCallHandler.class); + verify(rawChannel).setMethodCallHandler(argumentCaptor.capture()); + + MethodChannel.Result result = mock(MethodChannel.Result.class); + argumentCaptor.getValue().onMethodCall(new MethodCall("get", null), result); + Map expected = new HashMap<>(); + expected.put("enabled", true); + expected.put("data", null); + verify(result).success(expected); + + restorationChannel.setRestorationData(data); + assertEquals(restorationChannel.getRestorationData(), null); + + ArgumentCaptor resultCapture = + ArgumentCaptor.forClass(MethodChannel.Result.class); + Map expected2 = new HashMap<>(); + expected2.put("enabled", true); + expected2.put("data", data); + verify(rawChannel).invokeMethod(eq("push"), eq(expected2), resultCapture.capture()); + resultCapture.getValue().success(null); + assertEquals(restorationChannel.getRestorationData(), data); + } + + @Test + public void itHoldsOnToDataFromFramework() throws JSONException { + byte[] data = "Any String you want".getBytes(); + + MethodChannel rawChannel = mock(MethodChannel.class); + RestorationChannel restorationChannel = + new RestorationChannel(rawChannel, /*waitForRestorationData=*/ false); + ArgumentCaptor argumentCaptor = + ArgumentCaptor.forClass(MethodChannel.MethodCallHandler.class); + verify(rawChannel).setMethodCallHandler(argumentCaptor.capture()); + + MethodChannel.Result result = mock(MethodChannel.Result.class); + argumentCaptor.getValue().onMethodCall(new MethodCall("put", data), result); + assertEquals(restorationChannel.getRestorationData(), data); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/ScribeChannelTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/ScribeChannelTest.java new file mode 100644 index 0000000000000000000000000000000000000000..c69f624300fcded76bec97e5d524928ed286df8a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/ScribeChannelTest.java @@ -0,0 +1,202 @@ +// 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. + +package io.flutter.embedding.engine.systemchannels; + +import static io.flutter.Build.API_LEVELS; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.argThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import android.annotation.TargetApi; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.dart.DartExecutor; +import io.flutter.plugin.common.BinaryMessenger; +import io.flutter.plugin.common.FlutterException; +import io.flutter.plugin.common.JSONMethodCodec; +import io.flutter.plugin.common.MethodCall; +import java.nio.ByteBuffer; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.robolectric.annotation.Config; + +@RunWith(AndroidJUnit4.class) +public class ScribeChannelTest { + private static BinaryMessenger.BinaryReply sendToBinaryMessageHandler( + BinaryMessenger.BinaryMessageHandler binaryMessageHandler, String method) { + MethodCall methodCall = new MethodCall(method, null); + ByteBuffer encodedMethodCall = JSONMethodCodec.INSTANCE.encodeMethodCall(methodCall); + BinaryMessenger.BinaryReply mockReply = mock(BinaryMessenger.BinaryReply.class); + binaryMessageHandler.onMessage((ByteBuffer) encodedMethodCall.flip(), mockReply); + return mockReply; + } + + ScribeChannel.ScribeMethodHandler mockHandler; + BinaryMessenger.BinaryMessageHandler binaryMessageHandler; + + @Before + public void setUp() { + ArgumentCaptor binaryMessageHandlerCaptor = + ArgumentCaptor.forClass(BinaryMessenger.BinaryMessageHandler.class); + DartExecutor mockBinaryMessenger = mock(DartExecutor.class); + mockHandler = mock(ScribeChannel.ScribeMethodHandler.class); + ScribeChannel scribeChannel = new ScribeChannel(mockBinaryMessenger); + + scribeChannel.setScribeMethodHandler(mockHandler); + + verify((BinaryMessenger) mockBinaryMessenger, times(1)) + .setMessageHandler(any(String.class), binaryMessageHandlerCaptor.capture()); + + binaryMessageHandler = binaryMessageHandlerCaptor.getValue(); + } + + @Config(minSdk = API_LEVELS.API_34) + @TargetApi(API_LEVELS.API_34) + @Test + public void respondsToStartStylusHandwriting() { + BinaryMessenger.BinaryReply mockReply = + sendToBinaryMessageHandler( + binaryMessageHandler, ScribeChannel.METHOD_START_STYLUS_HANDWRITING); + + verify(mockReply) + .reply( + argThat( + (ByteBuffer reply) -> { + reply.flip(); + try { + final Object decodedReply = JSONMethodCodec.INSTANCE.decodeEnvelope(reply); + return decodedReply == null; + } catch (FlutterException e) { + return false; + } + })); + verify(mockHandler).startStylusHandwriting(); + } + + @Config(minSdk = API_LEVELS.API_34) + @TargetApi(API_LEVELS.API_34) + @Test + public void respondsToIsFeatureAvailable() { + BinaryMessenger.BinaryReply mockReply = + sendToBinaryMessageHandler(binaryMessageHandler, ScribeChannel.METHOD_IS_FEATURE_AVAILABLE); + + verify(mockReply) + .reply( + argThat( + (ByteBuffer reply) -> { + reply.flip(); + try { + final Object decodedReply = JSONMethodCodec.INSTANCE.decodeEnvelope(reply); + // Should succeed and should tell whether or not Scribe is available by + // using a boolean. + return decodedReply.getClass() == java.lang.Boolean.class; + } catch (FlutterException e) { + return false; + } + })); + verify(mockHandler).isFeatureAvailable(); + } + + @Config(minSdk = API_LEVELS.API_34) + @TargetApi(API_LEVELS.API_34) + @Test + public void respondsToIsStylusHandwritingAvailable() { + BinaryMessenger.BinaryReply mockReply = + sendToBinaryMessageHandler( + binaryMessageHandler, ScribeChannel.METHOD_IS_STYLUS_HANDWRITING_AVAILABLE); + + verify(mockReply) + .reply( + argThat( + (ByteBuffer reply) -> { + reply.flip(); + try { + final Object decodedReply = JSONMethodCodec.INSTANCE.decodeEnvelope(reply); + // Should succeed and should tell whether or not Scribe is available by + // using a boolean. + return decodedReply.getClass() == java.lang.Boolean.class; + } catch (FlutterException e) { + return false; + } + })); + verify(mockHandler).isStylusHandwritingAvailable(); + } + + @Config(sdk = API_LEVELS.API_32) + @TargetApi(API_LEVELS.API_32) + @Test + public void respondsToStartStylusHandwritingWhenAPILevelUnsupported() { + BinaryMessenger.BinaryReply mockReply = + sendToBinaryMessageHandler( + binaryMessageHandler, ScribeChannel.METHOD_START_STYLUS_HANDWRITING); + + verify(mockReply) + .reply( + argThat( + (ByteBuffer reply) -> { + reply.flip(); + try { + final Object decodedReply = JSONMethodCodec.INSTANCE.decodeEnvelope(reply); + return false; + } catch (FlutterException e) { + // Should fail because the API version is too low. + return true; + } + })); + verify(mockHandler, never()).startStylusHandwriting(); + } + + @Config(sdk = API_LEVELS.API_33) + @TargetApi(API_LEVELS.API_33) + @Test + public void respondsToIsFeatureAvailableWhenAPILevelUnsupported() { + BinaryMessenger.BinaryReply mockReply = + sendToBinaryMessageHandler(binaryMessageHandler, ScribeChannel.METHOD_IS_FEATURE_AVAILABLE); + + verify(mockReply) + .reply( + argThat( + (ByteBuffer reply) -> { + reply.flip(); + try { + final Object decodedReply = JSONMethodCodec.INSTANCE.decodeEnvelope(reply); + // Should succeed and indicate that Scribe is not available. + return decodedReply.getClass() == java.lang.Boolean.class + && !((boolean) decodedReply); + } catch (FlutterException e) { + return false; + } + })); + verify(mockHandler).isFeatureAvailable(); + } + + @Config(sdk = API_LEVELS.API_33) + @TargetApi(API_LEVELS.API_33) + @Test + public void respondsToIsStylusHandwritingAvailableWhenAPILevelUnsupported() { + BinaryMessenger.BinaryReply mockReply = + sendToBinaryMessageHandler( + binaryMessageHandler, ScribeChannel.METHOD_IS_STYLUS_HANDWRITING_AVAILABLE); + + verify(mockReply) + .reply( + argThat( + (ByteBuffer reply) -> { + reply.flip(); + try { + final Object decodedReply = JSONMethodCodec.INSTANCE.decodeEnvelope(reply); + return false; + } catch (FlutterException e) { + // Should fail because the API version is too low. + return true; + } + })); + verify(mockHandler, never()).isStylusHandwritingAvailable(); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/SettingsChannelTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/SettingsChannelTest.java new file mode 100644 index 0000000000000000000000000000000000000000..ada7154dff0b8d5ea2a9c134a724be2bddaed8c7 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/SettingsChannelTest.java @@ -0,0 +1,80 @@ +// 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. + +package io.flutter.embedding.engine.systemchannels; + +import static io.flutter.Build.API_LEVELS; +import static junit.framework.TestCase.assertEquals; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import android.annotation.TargetApi; +import android.util.DisplayMetrics; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.dart.DartExecutor; +import io.flutter.plugin.common.BasicMessageChannel; +import java.nio.ByteBuffer; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class SettingsChannelTest { + @Test + @TargetApi(API_LEVELS.API_33) + @Config(sdk = API_LEVELS.API_33) + @SuppressWarnings("deprecation") + // DartExecutor.send is deprecated. + public void setDisplayMetricsDoesNothingOnAPILevel33() { + final DartExecutor executor = mock(DartExecutor.class); + executor.onAttachedToJNI(); + final SettingsChannel settingsChannel = new SettingsChannel(executor); + + final ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(ByteBuffer.class); + + settingsChannel.startMessage().setDisplayMetrics(mock(DisplayMetrics.class)).send(); + + verify(executor).send(eq("flutter/settings"), messageCaptor.capture(), isNull()); + } + + @Test + public void configurationQueueWorks() { + final SettingsChannel.ConfigurationQueue queue = new SettingsChannel.ConfigurationQueue(); + final int baseId = Integer.MIN_VALUE; + + queue.enqueueConfiguration( + new SettingsChannel.ConfigurationQueue.SentConfiguration(mock(DisplayMetrics.class))); + queue.enqueueConfiguration( + new SettingsChannel.ConfigurationQueue.SentConfiguration(mock(DisplayMetrics.class))); + assertEquals(baseId + 0, queue.getConfiguration(baseId + 0).generationNumber); + assertEquals(baseId + 1, queue.getConfiguration(baseId + 1).generationNumber); + assertEquals(baseId + 1, queue.getConfiguration(baseId + 1).generationNumber); + + queue.enqueueConfiguration( + new SettingsChannel.ConfigurationQueue.SentConfiguration(mock(DisplayMetrics.class))); + queue.enqueueConfiguration( + new SettingsChannel.ConfigurationQueue.SentConfiguration(mock(DisplayMetrics.class))); + assertEquals(baseId + 3, queue.getConfiguration(baseId + 3).generationNumber); + // Can get the same configuration more than once. + assertEquals(baseId + 3, queue.getConfiguration(baseId + 3).generationNumber); + + final BasicMessageChannel.Reply replyFor4 = + queue.enqueueConfiguration( + new SettingsChannel.ConfigurationQueue.SentConfiguration(mock(DisplayMetrics.class))); + final BasicMessageChannel.Reply replyFor5 = + queue.enqueueConfiguration( + new SettingsChannel.ConfigurationQueue.SentConfiguration(mock(DisplayMetrics.class))); + replyFor4.reply(null); + replyFor5.reply(null); + assertEquals(baseId + 5, queue.getConfiguration(baseId + 5).generationNumber); + assertEquals(baseId + 5, queue.getConfiguration(baseId + 5).generationNumber); + } + + // TODO(LongCatIsLooong): add tests for API 34 code path. + // https://github.com/flutter/flutter/issues/128825 +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/TextInputChannelTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/TextInputChannelTest.java new file mode 100644 index 0000000000000000000000000000000000000000..0d914a3b996c232549902a80f2c911762d4589f9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/TextInputChannelTest.java @@ -0,0 +1,42 @@ +// 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. + +package io.flutter.embedding.engine.systemchannels; + +import static io.flutter.Build.API_LEVELS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import android.annotation.TargetApi; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.dart.DartExecutor; +import io.flutter.plugin.common.MethodCall; +import io.flutter.plugin.common.MethodChannel; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +@Config( + manifest = Config.NONE, + shadows = {}) +@RunWith(AndroidJUnit4.class) +@TargetApi(API_LEVELS.API_24) +public class TextInputChannelTest { + @Test + public void setEditableSizeAndTransformCompletes() throws JSONException { + TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); + textInputChannel.setTextInputMethodHandler(mock(TextInputChannel.TextInputMethodHandler.class)); + JSONObject arguments = new JSONObject(); + arguments.put("width", 100.0); + arguments.put("height", 20.0); + arguments.put("transform", new JSONArray(new double[16])); + MethodCall call = new MethodCall("TextInput.setEditableSizeAndTransform", arguments); + MethodChannel.Result result = mock(MethodChannel.Result.class); + textInputChannel.parsingMethodHandler.onMethodCall(call, result); + verify(result).success(null); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/external/FlutterLaunchTests.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/external/FlutterLaunchTests.java new file mode 100644 index 0000000000000000000000000000000000000000..b77bdbf712b3dad52910ee043ff5f8bcdfa20b85 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/external/FlutterLaunchTests.java @@ -0,0 +1,40 @@ +package io.flutter.external; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import android.content.Intent; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.android.FlutterActivity; +import io.flutter.embedding.android.FlutterActivityLaunchConfigs.BackgroundMode; +import io.flutter.embedding.android.RenderMode; +import io.flutter.embedding.android.RobolectricFlutterActivity; +import io.flutter.embedding.android.TransparencyMode; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class FlutterLaunchTests { + @Test + public void launchFlutterActivity_with_defaultIntent_expect_defaultConfiguration() { + Intent intent = + FlutterActivity.createDefaultIntent(ApplicationProvider.getApplicationContext()); + FlutterActivity flutterActivity = RobolectricFlutterActivity.createFlutterActivity(intent); + + assertEquals("main", flutterActivity.getDartEntrypointFunctionName()); + assertEquals("/", flutterActivity.getInitialRoute()); + assertArrayEquals(new String[] {}, flutterActivity.getFlutterShellArgs().toArray()); + assertTrue(flutterActivity.shouldAttachEngineToActivity()); + assertNull(flutterActivity.getCachedEngineId()); + assertTrue(flutterActivity.shouldDestroyEngineWithHost()); + assertEquals( + BackgroundMode.opaque, RobolectricFlutterActivity.getBackgroundMode(flutterActivity)); + assertEquals(RenderMode.surface, flutterActivity.getRenderMode()); + assertEquals(TransparencyMode.opaque, flutterActivity.getTransparencyMode()); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/external/README.md b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/external/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9fbf87159289e3599cf5ff5e86c97982a566ed8a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/external/README.md @@ -0,0 +1 @@ +This `external` package exists to run tests in a package other than where the code under test is defined. This is offered for tests that need to verify that app devs, with their own packages, can reference and execute APIs that Flutter intends to be public. \ No newline at end of file diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/common/BinaryCodecTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/common/BinaryCodecTest.java new file mode 100644 index 0000000000000000000000000000000000000000..e57631254a925f0541b19f466c751772133fe81f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/common/BinaryCodecTest.java @@ -0,0 +1,17 @@ +package io.flutter.plugin.common; + +import static org.junit.Assert.assertNull; + +import androidx.test.ext.junit.runners.AndroidJUnit4; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class BinaryCodecTest { + @Test + public void decodeNull() { + assertNull(BinaryCodec.INSTANCE.decodeMessage(null)); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/common/MethodChannelTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/common/MethodChannelTest.java new file mode 100644 index 0000000000000000000000000000000000000000..df1fa2108c296250fc429c1ac6f90e29d13d3dee --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/common/MethodChannelTest.java @@ -0,0 +1,97 @@ +package io.flutter.plugin.common; + +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import android.content.res.AssetManager; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.dart.DartExecutor; +import java.nio.ByteBuffer; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatcher; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class MethodChannelTest { + @Test + public void resizeChannelBufferMessageIsWellformed() { + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + DartExecutor dartExecutor = new DartExecutor(mockFlutterJNI, mock(AssetManager.class)); + String channel = "flutter/test"; + MethodChannel rawChannel = new MethodChannel(dartExecutor, channel); + + int newSize = 3; + rawChannel.resizeChannelBuffer(newSize); + + // Created from the following Dart code: + // MethodCall methodCall = const MethodCall('resize', ['flutter/test', 3]); + // const StandardMethodCodec().encodeMethodCall(methodCall).buffer.asUint8List(); + final byte[] expected = { + 7, 6, 114, 101, 115, 105, 122, 101, 12, 2, 7, 12, 102, 108, 117, 116, 116, 101, 114, 47, 116, + 101, 115, 116, 3, 3, 0, 0, 0 + }; + + // Verify that the correct message was sent to FlutterJNI. + ArgumentMatcher packetMatcher = + new ByteBufferContentMatcher(ByteBuffer.wrap(expected)); + verify(mockFlutterJNI, times(1)) + .dispatchPlatformMessage( + eq(BasicMessageChannel.CHANNEL_BUFFERS_CHANNEL), + argThat(packetMatcher), + anyInt(), + anyInt()); + } + + @Test + public void overflowChannelBufferMessageIsWellformed() { + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + DartExecutor dartExecutor = new DartExecutor(mockFlutterJNI, mock(AssetManager.class)); + String channel = "flutter/test"; + MethodChannel rawChannel = new MethodChannel(dartExecutor, channel); + + rawChannel.setWarnsOnChannelOverflow(false); + + // Created from the following Dart code: + // MethodCall methodCall = const MethodCall('overflow', ['flutter/test', true]); + // const StandardMethodCodec().encodeMethodCall(methodCall).buffer.asUint8List(); + final byte[] expected = { + 7, 8, 111, 118, 101, 114, 102, 108, 111, 119, 12, 2, 7, 12, 102, 108, 117, 116, 116, 101, 114, + 47, 116, 101, 115, 116, 1 + }; + + // Verify that the correct message was sent to FlutterJNI. + ArgumentMatcher packetMatcher = + new ByteBufferContentMatcher(ByteBuffer.wrap(expected)); + verify(mockFlutterJNI, times(1)) + .dispatchPlatformMessage( + eq(BasicMessageChannel.CHANNEL_BUFFERS_CHANNEL), + argThat(packetMatcher), + anyInt(), + anyInt()); + } +} + +// Custom ByteBuffer matcher which calls rewind on both buffers before calling equals. +// ByteBuffer.equals might return true when comparing byte buffers with different content if +// both have no remaining elements. +class ByteBufferContentMatcher implements ArgumentMatcher { + private ByteBuffer expected; + + public ByteBufferContentMatcher(ByteBuffer expected) { + this.expected = expected; + } + + @Override + public boolean matches(ByteBuffer received) { + expected.rewind(); + received.rewind(); + return received.equals(expected); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/common/StandardMessageCodecTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/common/StandardMessageCodecTest.java new file mode 100644 index 0000000000000000000000000000000000000000..d1ffb5204e8089297c6b5c6c38a8c251a01eb72e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/common/StandardMessageCodecTest.java @@ -0,0 +1,147 @@ +package io.flutter.plugin.common; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import android.text.SpannableString; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class StandardMessageCodecTest { + // Data types defined as per StandardMessageCodec.Java + // XXX Please consider exposing these so that tests can access them + private static final byte NULL = 0; + private static final byte TRUE = 1; + private static final byte FALSE = 2; + private static final byte INT = 3; + private static final byte LONG = 4; + private static final byte BIGINT = 5; + private static final byte DOUBLE = 6; + private static final byte STRING = 7; + private static final byte BYTE_ARRAY = 8; + private static final byte INT_ARRAY = 9; + private static final byte LONG_ARRAY = 10; + private static final byte DOUBLE_ARRAY = 11; + private static final byte LIST = 12; + private static final byte MAP = 13; + private static final byte FLOAT_ARRAY = 14; + + @Test + public void itEncodesNullLiterals() { + // Setup message codec + StandardMessageCodec codec = new StandardMessageCodec(); + + // Attempt to encode message with a null literal inside a list + // A list with a null is used instead of just a null literal because if + // only null is encoded, then no message is returned; null is returned instead + ArrayList messageContent = new ArrayList(); + messageContent.add(null); + ByteBuffer message = codec.encodeMessage(messageContent); + message.flip(); + ByteBuffer expected = ByteBuffer.allocateDirect(3); + expected.put(new byte[] {LIST, 1, NULL}); + expected.flip(); + assertEquals(expected, message); + } + + @Test + public void itEncodesNullObjects() { + // An example class that equals null + class ExampleNullObject { + @Override + public boolean equals(Object other) { + return other == null || other == this; + } + + @Override + public int hashCode() { + return 0; + } + } + + // Setup message codec + StandardMessageCodec codec = new StandardMessageCodec(); + + // Same as itEncodesNullLiterals but with objects that equal null instead + ArrayList messageContent = new ArrayList(); + messageContent.add(new ExampleNullObject()); + ByteBuffer message = codec.encodeMessage(messageContent); + message.flip(); + ByteBuffer expected = ByteBuffer.allocateDirect(3); + expected.put(new byte[] {LIST, 1, NULL}); + expected.flip(); + assertEquals(expected, message); + } + + @Test + @SuppressWarnings("deprecation") + public void itEncodesBooleans() { + // Setup message codec + StandardMessageCodec codec = new StandardMessageCodec(); + + ArrayList messageContent = new ArrayList(); + // Test handling of Boolean objects other than the static TRUE and FALSE constants. + messageContent.add(new Boolean(true)); + messageContent.add(new Boolean(false)); + ByteBuffer message = codec.encodeMessage(messageContent); + message.flip(); + ByteBuffer expected = ByteBuffer.allocateDirect(4); + expected.put(new byte[] {LIST, 2, TRUE, FALSE}); + expected.flip(); + assertEquals(expected, message); + } + + @Test + public void itEncodesFloatArrays() { + StandardMessageCodec codec = new StandardMessageCodec(); + + float[] expectedValues = new float[] {1.0f, 2.2f, 5.3f}; + + ByteBuffer message = codec.encodeMessage(expectedValues); + message.flip(); + + float[] values = (float[]) codec.decodeMessage(message); + assertArrayEquals(expectedValues, values, 0.01f); + } + + @Test + public void itEncodesCharSequences() { + StandardMessageCodec codec = new StandardMessageCodec(); + + CharSequence cs = new SpannableString("hello world"); + + ByteBuffer message = codec.encodeMessage(cs); + message.flip(); + + String value = (String) codec.decodeMessage(message); + assertEquals(value, "hello world"); + } + + private static class NotEncodable { + @Override + public String toString() { + return "not encodable"; + } + } + + @Test + public void errorHasType() { + StandardMessageCodec codec = new StandardMessageCodec(); + NotEncodable notEncodable = new NotEncodable(); + Exception exception = + assertThrows( + IllegalArgumentException.class, + () -> { + codec.encodeMessage(notEncodable); + }); + assertTrue(exception.getMessage().contains("NotEncodable")); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/common/StandardMethodCodecTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/common/StandardMethodCodecTest.java new file mode 100644 index 0000000000000000000000000000000000000000..81d545ea13901a0035216e6d0ddfead46d300d16 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/common/StandardMethodCodecTest.java @@ -0,0 +1,116 @@ +package io.flutter.plugin.common; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import androidx.test.ext.junit.runners.AndroidJUnit4; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.HashMap; +import java.util.Map; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class StandardMethodCodecTest { + + @Test + public void encodeMethodTest() { + final Map args = new HashMap<>(); + args.put("testArg", "testValue"); + MethodCall call = new MethodCall("testMethod", args); + final ByteBuffer buffer = StandardMethodCodec.INSTANCE.encodeMethodCall(call); + assertNotNull(buffer); + buffer.flip(); + final MethodCall result = StandardMethodCodec.INSTANCE.decodeMethodCall(buffer); + assertEquals(call.method, result.method); + assertEquals(call.arguments, result.arguments); + } + + @Test + public void encodeSuccessEnvelopeTest() { + final Map success = new HashMap<>(); + success.put("result", 1); + final ByteBuffer buffer = StandardMethodCodec.INSTANCE.encodeSuccessEnvelope(success); + assertNotNull(buffer); + buffer.flip(); + final Object result = StandardMethodCodec.INSTANCE.decodeEnvelope(buffer); + assertEquals(success, result); + } + + @Test + public void encodeSuccessEnvelopeUnsupportedObjectTest() { + final StandardMethodCodecTest joke = new StandardMethodCodecTest(); + try { + final ByteBuffer buffer = StandardMethodCodec.INSTANCE.encodeSuccessEnvelope(joke); + fail("Should have failed to convert unsupported type."); + } catch (IllegalArgumentException e) { + // pass. + } + } + + @Test + public void encodeErrorEnvelopeWithNullDetailsTest() { + final ByteBuffer buffer = + StandardMethodCodec.INSTANCE.encodeErrorEnvelope("code", "error", null); + assertNotNull(buffer); + buffer.flip(); + try { + StandardMethodCodec.INSTANCE.decodeEnvelope(buffer); + fail("Should have thrown a FlutterException since this is an error envelope."); + } catch (FlutterException result) { + assertEquals("code", result.code); + assertEquals("error", result.getMessage()); + assertNull(result.details); + } + } + + @Test + public void encodeErrorEnvelopeWithThrowableTest() { + final Exception e = new IllegalArgumentException("foo"); + final ByteBuffer buffer = + StandardMethodCodec.INSTANCE.encodeErrorEnvelope("code", e.getMessage(), e); + assertNotNull(buffer); + buffer.flip(); + try { + StandardMethodCodec.INSTANCE.decodeEnvelope(buffer); + fail("Should have thrown a FlutterException since this is an error envelope."); + } catch (FlutterException result) { + assertEquals("code", result.code); + assertEquals("foo", result.getMessage()); + // Must contain part of a stack. + String stack = (String) result.details; + assertTrue( + stack.contains( + "at io.flutter.plugin.common.StandardMethodCodecTest.encodeErrorEnvelopeWithThrowableTest(StandardMethodCodecTest.java:")); + } + } + + @Test + public void encodeErrorEnvelopeWithStacktraceTest() { + final Exception e = new IllegalArgumentException("foo"); + final ByteBuffer buffer = + StandardMethodCodec.INSTANCE.encodeErrorEnvelopeWithStacktrace( + "code", e.getMessage(), e, "error stacktrace"); + assertNotNull(buffer); + buffer.flip(); + buffer.order(ByteOrder.nativeOrder()); + final byte flag = buffer.get(); + final Object code = StandardMessageCodec.INSTANCE.readValue(buffer); + final Object message = StandardMessageCodec.INSTANCE.readValue(buffer); + final Object details = StandardMessageCodec.INSTANCE.readValue(buffer); + final Object stacktrace = StandardMessageCodec.INSTANCE.readValue(buffer); + assertEquals("code", (String) code); + assertEquals("foo", (String) message); + String stack = (String) details; + assertTrue( + stack.contains( + "at io.flutter.plugin.common.StandardMethodCodecTest.encodeErrorEnvelopeWithStacktraceTest(StandardMethodCodecTest.java:")); + assertEquals("error stacktrace", (String) stacktrace); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/editing/InputConnectionAdaptorTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/editing/InputConnectionAdaptorTest.java new file mode 100644 index 0000000000000000000000000000000000000000..8ca3469498c24abc2c7836d18c2cd66920bdec61 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/editing/InputConnectionAdaptorTest.java @@ -0,0 +1,1433 @@ +package io.flutter.plugin.editing; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.content.ClipDescription; +import android.content.ClipboardManager; +import android.content.ContentResolver; +import android.content.Context; +import android.content.res.AssetManager; +import android.net.Uri; +import android.os.Bundle; +import android.text.InputType; +import android.text.Selection; +import android.text.SpannableStringBuilder; +import android.view.KeyEvent; +import android.view.View; +import android.view.inputmethod.CursorAnchorInfo; +import android.view.inputmethod.EditorInfo; +import android.view.inputmethod.ExtractedText; +import android.view.inputmethod.ExtractedTextRequest; +import android.view.inputmethod.InputConnection; +import android.view.inputmethod.InputContentInfo; +import android.view.inputmethod.InputMethodManager; +import androidx.core.view.inputmethod.InputConnectionCompat; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import com.ibm.icu.lang.UCharacter; +import com.ibm.icu.lang.UProperty; +import io.flutter.embedding.android.KeyboardManager; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.dart.DartExecutor; +import io.flutter.embedding.engine.systemchannels.ScribeChannel; +import io.flutter.embedding.engine.systemchannels.TextInputChannel; +import io.flutter.plugin.common.JSONMethodCodec; +import io.flutter.plugin.common.MethodCall; +import io.flutter.util.FakeKeyEvent; +import java.io.ByteArrayInputStream; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import org.json.JSONArray; +import org.json.JSONException; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.robolectric.Shadows; +import org.robolectric.annotation.Config; +import org.robolectric.annotation.Implementation; +import org.robolectric.annotation.Implements; +import org.robolectric.shadow.api.Shadow; +import org.robolectric.shadows.ShadowContentResolver; +import org.robolectric.shadows.ShadowInputMethodManager; + +@Config( + manifest = Config.NONE, + shadows = {InputConnectionAdaptorTest.TestImm.class}) +@RunWith(AndroidJUnit4.class) +public class InputConnectionAdaptorTest { + private final Context ctx = ApplicationProvider.getApplicationContext(); + private ContentResolver contentResolver; + private ShadowContentResolver shadowContentResolver; + + @Mock KeyboardManager mockKeyboardManager; + // Verifies the method and arguments for a captured method call. + private void verifyMethodCall(ByteBuffer buffer, String methodName, String[] expectedArgs) + throws JSONException { + buffer.rewind(); + MethodCall methodCall = JSONMethodCodec.INSTANCE.decodeMethodCall(buffer); + assertEquals(methodName, methodCall.method); + if (expectedArgs != null) { + JSONArray args = methodCall.arguments(); + assertEquals(expectedArgs.length, args.length()); + for (int i = 0; i < args.length(); i++) { + assertEquals(expectedArgs[i], args.get(i).toString()); + } + } + } + + @Before + public void setUp() { + MockitoAnnotations.openMocks(this); + contentResolver = ctx.getContentResolver(); + shadowContentResolver = Shadows.shadowOf(contentResolver); + } + + @Test + public void inputConnectionAdaptor_ReceivesEnter() throws NullPointerException { + View testView = new View(ctx); + FlutterJNI mockFlutterJni = mock(FlutterJNI.class); + DartExecutor dartExecutor = spy(new DartExecutor(mockFlutterJni, mock(AssetManager.class))); + int inputTargetId = 0; + TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); + ScribeChannel scribeChannel = new ScribeChannel(dartExecutor); + ListenableEditingState mEditable = new ListenableEditingState(null, testView); + Selection.setSelection(mEditable, 0, 0); + ListenableEditingState spyEditable = spy(mEditable); + EditorInfo outAttrs = new EditorInfo(); + outAttrs.inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE; + + InputConnectionAdaptor inputConnectionAdaptor = + new InputConnectionAdaptor( + testView, + inputTargetId, + textInputChannel, + scribeChannel, + mockKeyboardManager, + spyEditable, + outAttrs); + + // Send an enter key and make sure the Editable received it. + FakeKeyEvent keyEvent = new FakeKeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER, '\n'); + inputConnectionAdaptor.handleKeyEvent(keyEvent); + verify(spyEditable, times(1)).insert(eq(0), anyString()); + } + + @Test + public void testPerformContextMenuAction_selectAll() { + int selStart = 5; + ListenableEditingState editable = sampleEditable(selStart, selStart); + InputConnectionAdaptor adaptor = sampleInputConnectionAdaptor(editable); + + boolean didConsume = adaptor.performContextMenuAction(android.R.id.selectAll); + + assertTrue(didConsume); + assertEquals(0, Selection.getSelectionStart(editable)); + assertEquals(editable.length(), Selection.getSelectionEnd(editable)); + } + + @SuppressWarnings("deprecation") + // ClipboardManager.hasText is deprecated. + @Test + public void testPerformContextMenuAction_cut() { + ClipboardManager clipboardManager = ctx.getSystemService(ClipboardManager.class); + int selStart = 6; + int selEnd = 11; + ListenableEditingState editable = sampleEditable(selStart, selEnd); + CharSequence textToBeCut = editable.subSequence(selStart, selEnd); + InputConnectionAdaptor adaptor = sampleInputConnectionAdaptor(editable); + + boolean didConsume = adaptor.performContextMenuAction(android.R.id.cut); + + assertTrue(didConsume); + assertTrue(clipboardManager.hasText()); + assertEquals(textToBeCut, clipboardManager.getPrimaryClip().getItemAt(0).getText()); + assertFalse(editable.toString().contains(textToBeCut)); + } + + @SuppressWarnings("deprecation") + // ClipboardManager.hasText is deprecated. + @Test + public void testPerformContextMenuAction_copy() { + ClipboardManager clipboardManager = ctx.getSystemService(ClipboardManager.class); + int selStart = 6; + int selEnd = 11; + ListenableEditingState editable = sampleEditable(selStart, selEnd); + InputConnectionAdaptor adaptor = sampleInputConnectionAdaptor(editable); + + assertFalse(clipboardManager.hasText()); + + boolean didConsume = adaptor.performContextMenuAction(android.R.id.copy); + + assertTrue(didConsume); + assertTrue(clipboardManager.hasText()); + assertEquals( + editable.subSequence(selStart, selEnd), + clipboardManager.getPrimaryClip().getItemAt(0).getText()); + } + + @SuppressWarnings("deprecation") + // ClipboardManager.setText is deprecated. + @Test + public void testPerformContextMenuAction_paste() { + ClipboardManager clipboardManager = ctx.getSystemService(ClipboardManager.class); + String textToBePasted = "deadbeef"; + clipboardManager.setText(textToBePasted); + ListenableEditingState editable = sampleEditable(0, 0); + InputConnectionAdaptor adaptor = sampleInputConnectionAdaptor(editable); + + boolean didConsume = adaptor.performContextMenuAction(android.R.id.paste); + + assertTrue(didConsume); + assertTrue(editable.toString().startsWith(textToBePasted)); + } + + @SuppressWarnings("deprecation") + // DartExecutor.send is deprecated. + @Test + public void testCommitContent() throws JSONException { + View testView = new View(ctx); + int client = 0; + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + DartExecutor dartExecutor = spy(new DartExecutor(mockFlutterJNI, mock(AssetManager.class))); + TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); + ScribeChannel scribeChannel = new ScribeChannel(dartExecutor); + ListenableEditingState editable = sampleEditable(0, 0); + InputConnectionAdaptor adaptor = + new InputConnectionAdaptor( + testView, + client, + textInputChannel, + scribeChannel, + mockKeyboardManager, + editable, + null, + mockFlutterJNI); + + String uri = "content://mock/uri/test/commitContent"; + Charset charset = Charset.forName("UTF-8"); + String fakeImageData = "fake image data"; + byte[] fakeImageDataBytes = fakeImageData.getBytes(charset); + shadowContentResolver.registerInputStream( + Uri.parse(uri), new ByteArrayInputStream(fakeImageDataBytes)); + + boolean commitContentSuccess = + adaptor.commitContent( + new InputContentInfo( + Uri.parse(uri), + new ClipDescription("commitContent test", new String[] {"image/png"})), + InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION, + null); + assertTrue(commitContentSuccess); + + ArgumentCaptor channelCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor bufferCaptor = ArgumentCaptor.forClass(ByteBuffer.class); + verify(dartExecutor, times(1)).send(channelCaptor.capture(), bufferCaptor.capture(), isNull()); + assertEquals("flutter/textinput", channelCaptor.getValue()); + + String fakeImageDataIntString = ""; + for (int i = 0; i < fakeImageDataBytes.length; i++) { + int byteAsInt = fakeImageDataBytes[i]; + fakeImageDataIntString += byteAsInt; + if (i < (fakeImageDataBytes.length - 1)) { + fakeImageDataIntString += ","; + } + } + verifyMethodCall( + bufferCaptor.getValue(), + "TextInputClient.performAction", + new String[] { + "0", + "TextInputAction.commitContent", + "{\"data\":[" + + fakeImageDataIntString + + "],\"mimeType\":\"image\\/png\",\"uri\":\"content:\\/\\/mock\\/uri\\/test\\/commitContent\"}" + }); + } + + @SuppressWarnings("deprecation") + // DartExecutor.send is deprecated. + @Test + public void testPerformPrivateCommand_dataIsNull() throws JSONException { + View testView = new View(ctx); + int client = 0; + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + DartExecutor dartExecutor = spy(new DartExecutor(mockFlutterJNI, mock(AssetManager.class))); + TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); + ScribeChannel scribeChannel = new ScribeChannel(dartExecutor); + ListenableEditingState editable = sampleEditable(0, 0); + InputConnectionAdaptor adaptor = + new InputConnectionAdaptor( + testView, + client, + textInputChannel, + scribeChannel, + mockKeyboardManager, + editable, + null, + mockFlutterJNI); + adaptor.performPrivateCommand("actionCommand", null); + + ArgumentCaptor channelCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor bufferCaptor = ArgumentCaptor.forClass(ByteBuffer.class); + verify(dartExecutor, times(1)).send(channelCaptor.capture(), bufferCaptor.capture(), isNull()); + assertEquals("flutter/textinput", channelCaptor.getValue()); + verifyMethodCall( + bufferCaptor.getValue(), + "TextInputClient.performPrivateCommand", + new String[] {"0", "{\"action\":\"actionCommand\"}"}); + } + + @SuppressWarnings("deprecation") + // DartExecutor.send is deprecated. + @Test + public void testPerformPrivateCommand_dataIsByteArray() throws JSONException { + View testView = new View(ctx); + int client = 0; + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + DartExecutor dartExecutor = spy(new DartExecutor(mockFlutterJNI, mock(AssetManager.class))); + TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); + ScribeChannel scribeChannel = new ScribeChannel(dartExecutor); + ListenableEditingState editable = sampleEditable(0, 0); + InputConnectionAdaptor adaptor = + new InputConnectionAdaptor( + testView, + client, + textInputChannel, + scribeChannel, + mockKeyboardManager, + editable, + null, + mockFlutterJNI); + + Bundle bundle = new Bundle(); + byte[] buffer = new byte[] {'a', 'b', 'c', 'd'}; + bundle.putByteArray("keyboard_layout", buffer); + adaptor.performPrivateCommand("actionCommand", bundle); + + ArgumentCaptor channelCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor bufferCaptor = ArgumentCaptor.forClass(ByteBuffer.class); + verify(dartExecutor, times(1)).send(channelCaptor.capture(), bufferCaptor.capture(), isNull()); + assertEquals("flutter/textinput", channelCaptor.getValue()); + verifyMethodCall( + bufferCaptor.getValue(), + "TextInputClient.performPrivateCommand", + new String[] { + "0", "{\"data\":{\"keyboard_layout\":[97,98,99,100]},\"action\":\"actionCommand\"}" + }); + } + + @SuppressWarnings("deprecation") + // DartExecutor.send is deprecated. + @Test + public void testPerformPrivateCommand_dataIsByte() throws JSONException { + View testView = new View(ctx); + int client = 0; + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + DartExecutor dartExecutor = spy(new DartExecutor(mockFlutterJNI, mock(AssetManager.class))); + TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); + ScribeChannel scribeChannel = new ScribeChannel(dartExecutor); + ListenableEditingState editable = sampleEditable(0, 0); + InputConnectionAdaptor adaptor = + new InputConnectionAdaptor( + testView, + client, + textInputChannel, + scribeChannel, + mockKeyboardManager, + editable, + null, + mockFlutterJNI); + + Bundle bundle = new Bundle(); + byte b = 3; + bundle.putByte("keyboard_layout", b); + adaptor.performPrivateCommand("actionCommand", bundle); + + ArgumentCaptor channelCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor bufferCaptor = ArgumentCaptor.forClass(ByteBuffer.class); + verify(dartExecutor, times(1)).send(channelCaptor.capture(), bufferCaptor.capture(), isNull()); + assertEquals("flutter/textinput", channelCaptor.getValue()); + verifyMethodCall( + bufferCaptor.getValue(), + "TextInputClient.performPrivateCommand", + new String[] {"0", "{\"data\":{\"keyboard_layout\":3},\"action\":\"actionCommand\"}"}); + } + + @SuppressWarnings("deprecation") + // DartExecutor.send is deprecated. + @Test + public void testPerformPrivateCommand_dataIsCharArray() throws JSONException { + View testView = new View(ctx); + int client = 0; + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + DartExecutor dartExecutor = spy(new DartExecutor(mockFlutterJNI, mock(AssetManager.class))); + TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); + ScribeChannel scribeChannel = new ScribeChannel(dartExecutor); + ListenableEditingState editable = sampleEditable(0, 0); + InputConnectionAdaptor adaptor = + new InputConnectionAdaptor( + testView, + client, + textInputChannel, + scribeChannel, + mockKeyboardManager, + editable, + null, + mockFlutterJNI); + + Bundle bundle = new Bundle(); + char[] buffer = new char[] {'a', 'b', 'c', 'd'}; + bundle.putCharArray("keyboard_layout", buffer); + adaptor.performPrivateCommand("actionCommand", bundle); + + ArgumentCaptor channelCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor bufferCaptor = ArgumentCaptor.forClass(ByteBuffer.class); + verify(dartExecutor, times(1)).send(channelCaptor.capture(), bufferCaptor.capture(), isNull()); + assertEquals("flutter/textinput", channelCaptor.getValue()); + verifyMethodCall( + bufferCaptor.getValue(), + "TextInputClient.performPrivateCommand", + new String[] { + "0", + "{\"data\":{\"keyboard_layout\":[\"a\",\"b\",\"c\",\"d\"]},\"action\":\"actionCommand\"}" + }); + } + + @SuppressWarnings("deprecation") + // DartExecutor.send is deprecated. + @Test + public void testPerformPrivateCommand_dataIsChar() throws JSONException { + View testView = new View(ctx); + int client = 0; + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + DartExecutor dartExecutor = spy(new DartExecutor(mockFlutterJNI, mock(AssetManager.class))); + TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); + ScribeChannel scribeChannel = new ScribeChannel(dartExecutor); + ListenableEditingState editable = sampleEditable(0, 0); + InputConnectionAdaptor adaptor = + new InputConnectionAdaptor( + testView, + client, + textInputChannel, + scribeChannel, + mockKeyboardManager, + editable, + null, + mockFlutterJNI); + + Bundle bundle = new Bundle(); + char b = 'a'; + bundle.putChar("keyboard_layout", b); + adaptor.performPrivateCommand("actionCommand", bundle); + + ArgumentCaptor channelCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor bufferCaptor = ArgumentCaptor.forClass(ByteBuffer.class); + verify(dartExecutor, times(1)).send(channelCaptor.capture(), bufferCaptor.capture(), isNull()); + assertEquals("flutter/textinput", channelCaptor.getValue()); + verifyMethodCall( + bufferCaptor.getValue(), + "TextInputClient.performPrivateCommand", + new String[] {"0", "{\"data\":{\"keyboard_layout\":\"a\"},\"action\":\"actionCommand\"}"}); + } + + @SuppressWarnings("deprecation") + // DartExecutor.send is deprecated. + @Test + public void testPerformPrivateCommand_dataIsCharSequenceArray() throws JSONException { + View testView = new View(ctx); + int client = 0; + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + DartExecutor dartExecutor = spy(new DartExecutor(mockFlutterJNI, mock(AssetManager.class))); + TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); + ScribeChannel scribeChannel = new ScribeChannel(dartExecutor); + ListenableEditingState editable = sampleEditable(0, 0); + InputConnectionAdaptor adaptor = + new InputConnectionAdaptor( + testView, + client, + textInputChannel, + scribeChannel, + mockKeyboardManager, + editable, + null, + mockFlutterJNI); + + Bundle bundle = new Bundle(); + CharSequence charSequence1 = new StringBuffer("abc"); + CharSequence charSequence2 = new StringBuffer("efg"); + CharSequence[] value = {charSequence1, charSequence2}; + bundle.putCharSequenceArray("keyboard_layout", value); + adaptor.performPrivateCommand("actionCommand", bundle); + + ArgumentCaptor channelCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor bufferCaptor = ArgumentCaptor.forClass(ByteBuffer.class); + verify(dartExecutor, times(1)).send(channelCaptor.capture(), bufferCaptor.capture(), isNull()); + assertEquals("flutter/textinput", channelCaptor.getValue()); + verifyMethodCall( + bufferCaptor.getValue(), + "TextInputClient.performPrivateCommand", + new String[] { + "0", "{\"data\":{\"keyboard_layout\":[\"abc\",\"efg\"]},\"action\":\"actionCommand\"}" + }); + } + + @SuppressWarnings("deprecation") + // DartExecutor.send is deprecated. + @Test + public void testPerformPrivateCommand_dataIsCharSequence() throws JSONException { + View testView = new View(ctx); + int client = 0; + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + DartExecutor dartExecutor = spy(new DartExecutor(mockFlutterJNI, mock(AssetManager.class))); + TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); + ScribeChannel scribeChannel = new ScribeChannel(dartExecutor); + ListenableEditingState editable = sampleEditable(0, 0); + InputConnectionAdaptor adaptor = + new InputConnectionAdaptor( + testView, + client, + textInputChannel, + scribeChannel, + mockKeyboardManager, + editable, + null, + mockFlutterJNI); + + Bundle bundle = new Bundle(); + CharSequence charSequence = new StringBuffer("abc"); + bundle.putCharSequence("keyboard_layout", charSequence); + adaptor.performPrivateCommand("actionCommand", bundle); + + ArgumentCaptor channelCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor bufferCaptor = ArgumentCaptor.forClass(ByteBuffer.class); + verify(dartExecutor, times(1)).send(channelCaptor.capture(), bufferCaptor.capture(), isNull()); + assertEquals("flutter/textinput", channelCaptor.getValue()); + verifyMethodCall( + bufferCaptor.getValue(), + "TextInputClient.performPrivateCommand", + new String[] { + "0", "{\"data\":{\"keyboard_layout\":\"abc\"},\"action\":\"actionCommand\"}" + }); + } + + @SuppressWarnings("deprecation") + // DartExecutor.send is deprecated. + @Test + public void testPerformPrivateCommand_dataIsFloat() throws JSONException { + View testView = new View(ctx); + int client = 0; + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + DartExecutor dartExecutor = spy(new DartExecutor(mockFlutterJNI, mock(AssetManager.class))); + TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); + ScribeChannel scribeChannel = new ScribeChannel(dartExecutor); + ListenableEditingState editable = sampleEditable(0, 0); + InputConnectionAdaptor adaptor = + new InputConnectionAdaptor( + testView, + client, + textInputChannel, + scribeChannel, + mockKeyboardManager, + editable, + null, + mockFlutterJNI); + + Bundle bundle = new Bundle(); + float value = 0.5f; + bundle.putFloat("keyboard_layout", value); + adaptor.performPrivateCommand("actionCommand", bundle); + + ArgumentCaptor channelCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor bufferCaptor = ArgumentCaptor.forClass(ByteBuffer.class); + verify(dartExecutor, times(1)).send(channelCaptor.capture(), bufferCaptor.capture(), isNull()); + assertEquals("flutter/textinput", channelCaptor.getValue()); + verifyMethodCall( + bufferCaptor.getValue(), + "TextInputClient.performPrivateCommand", + new String[] {"0", "{\"data\":{\"keyboard_layout\":0.5},\"action\":\"actionCommand\"}"}); + } + + @SuppressWarnings("deprecation") + // DartExecutor.send is deprecated. + @Test + public void testPerformPrivateCommand_dataIsFloatArray() throws JSONException { + View testView = new View(ctx); + int client = 0; + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + DartExecutor dartExecutor = spy(new DartExecutor(mockFlutterJNI, mock(AssetManager.class))); + TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); + ScribeChannel scribeChannel = new ScribeChannel(dartExecutor); + ListenableEditingState editable = sampleEditable(0, 0); + InputConnectionAdaptor adaptor = + new InputConnectionAdaptor( + testView, + client, + textInputChannel, + scribeChannel, + mockKeyboardManager, + editable, + null, + mockFlutterJNI); + + Bundle bundle = new Bundle(); + float[] value = {0.5f, 0.6f}; + bundle.putFloatArray("keyboard_layout", value); + adaptor.performPrivateCommand("actionCommand", bundle); + + ArgumentCaptor channelCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor bufferCaptor = ArgumentCaptor.forClass(ByteBuffer.class); + verify(dartExecutor, times(1)).send(channelCaptor.capture(), bufferCaptor.capture(), isNull()); + assertEquals("flutter/textinput", channelCaptor.getValue()); + verifyMethodCall( + bufferCaptor.getValue(), + "TextInputClient.performPrivateCommand", + new String[] { + "0", "{\"data\":{\"keyboard_layout\":[0.5,0.6]},\"action\":\"actionCommand\"}" + }); + } + + @Test + public void testSendKeyEvent_shiftKeyUpDoesNotCancelSelection() { + // Regression test for https://github.com/flutter/flutter/issues/101569. + int selStart = 5; + int selEnd = 10; + ListenableEditingState editable = sampleEditable(selStart, selEnd); + InputConnectionAdaptor adaptor = sampleInputConnectionAdaptor(editable); + + KeyEvent shiftKeyUp = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_SHIFT_LEFT); + boolean didConsume = adaptor.handleKeyEvent(shiftKeyUp); + + assertFalse(didConsume); + assertEquals(selStart, Selection.getSelectionStart(editable)); + assertEquals(selEnd, Selection.getSelectionEnd(editable)); + } + + @Test + public void testSendKeyEvent_leftKeyMovesCaretLeft() { + int selStart = 5; + ListenableEditingState editable = sampleEditable(selStart, selStart); + InputConnectionAdaptor adaptor = sampleInputConnectionAdaptor(editable); + + KeyEvent leftKeyDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT); + boolean didConsume = adaptor.handleKeyEvent(leftKeyDown); + + assertTrue(didConsume); + assertEquals(selStart - 1, Selection.getSelectionStart(editable)); + assertEquals(selStart - 1, Selection.getSelectionEnd(editable)); + } + + @Test + public void testSendKeyEvent_leftKeyMovesCaretLeftComplexEmoji() { + int selStart = 75; + ListenableEditingState editable = sampleEditable(selStart, selStart, SAMPLE_EMOJI_TEXT); + InputConnectionAdaptor adaptor = sampleInputConnectionAdaptor(editable); + + KeyEvent downKeyDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT); + boolean didConsume; + + // Normal Character + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 74); + + // Non-Spacing Mark + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 73); + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 72); + + // Keycap + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 69); + + // Keycap with invalid base + adaptor.setSelection(68, 68); + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 66); + adaptor.setSelection(67, 67); + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 66); + + // Zero Width Joiner + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 55); + + // Zero Width Joiner with invalid base + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 53); + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 52); + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 51); + + // ----- Start Emoji Tag Sequence with invalid base testing ---- + // Delete base tag + adaptor.setSelection(39, 39); + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 37); + + // Delete the sequence + adaptor.setSelection(49, 49); + for (int i = 0; i < 6; i++) { + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + } + assertEquals(Selection.getSelectionStart(editable), 37); + // ----- End Emoji Tag Sequence with invalid base testing ---- + + // Emoji Tag Sequence + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 23); + + // Variation Selector with invalid base + adaptor.setSelection(22, 22); + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 21); + adaptor.setSelection(22, 22); + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 21); + + // Variation Selector + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 19); + + // Emoji Modifier + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 16); + + // Emoji Modifier with invalid base + adaptor.setSelection(14, 14); + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 13); + adaptor.setSelection(14, 14); + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 13); + + // Line Feed + adaptor.setSelection(12, 12); + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 11); + + // Carriage Return + adaptor.setSelection(12, 12); + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 11); + + // Carriage Return and Line Feed + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 9); + + // Regional Indicator Symbol odd + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 7); + + // Regional Indicator Symbol even + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 3); + + // Simple Emoji + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 1); + + // First CodePoint + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 0); + } + + @Test + public void testSendKeyEvent_leftKeyExtendsSelectionLeft() { + int selStart = 5; + int selEnd = 40; + ListenableEditingState editable = sampleEditable(selStart, selEnd); + InputConnectionAdaptor adaptor = sampleInputConnectionAdaptor(editable); + + KeyEvent leftKeyDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT); + boolean didConsume = adaptor.handleKeyEvent(leftKeyDown); + + assertTrue(didConsume); + assertEquals(selStart, Selection.getSelectionStart(editable)); + assertEquals(selEnd - 1, Selection.getSelectionEnd(editable)); + } + + @Test + public void testSendKeyEvent_shiftLeftKeyStartsSelectionLeft() { + int selStart = 5; + ListenableEditingState editable = sampleEditable(selStart, selStart); + InputConnectionAdaptor adaptor = sampleInputConnectionAdaptor(editable); + + KeyEvent shiftLeftKeyDown = + new KeyEvent( + 0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT, 0, KeyEvent.META_SHIFT_ON); + boolean didConsume = adaptor.handleKeyEvent(shiftLeftKeyDown); + + assertTrue(didConsume); + assertEquals(selStart, Selection.getSelectionStart(editable)); + assertEquals(selStart - 1, Selection.getSelectionEnd(editable)); + } + + @Test + public void testSendKeyEvent_rightKeyMovesCaretRight() { + int selStart = 5; + ListenableEditingState editable = sampleEditable(selStart, selStart); + InputConnectionAdaptor adaptor = sampleInputConnectionAdaptor(editable); + + KeyEvent rightKeyDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT); + boolean didConsume = adaptor.handleKeyEvent(rightKeyDown); + + assertTrue(didConsume); + assertEquals(selStart + 1, Selection.getSelectionStart(editable)); + assertEquals(selStart + 1, Selection.getSelectionEnd(editable)); + } + + @Test + public void testSendKeyEvent_rightKeyMovesCaretRightComplexRegion() { + int selStart = 0; + // Seven region indicator characters. The first six should be considered as + // three region indicators, and the final seventh character should be + // considered to be on its own because it has no partner. + String SAMPLE_REGION_TEXT = "🇷🇷🇷🇷🇷🇷🇷"; + ListenableEditingState editable = sampleEditable(selStart, selStart, SAMPLE_REGION_TEXT); + InputConnectionAdaptor adaptor = sampleInputConnectionAdaptor(editable); + + KeyEvent downKeyDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT); + boolean didConsume; + + // The cursor moves over two region indicators at a time. + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 4); + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 8); + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 12); + + // When there is only one region indicator left with no pair, the cursor + // moves over that single region indicator. + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 14); + + // If the cursor is placed in the middle of a region indicator pair, it + // moves over only the second half of the pair. + adaptor.setSelection(6, 6); + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 8); + } + + @Test + public void testSendKeyEvent_rightKeyMovesCaretRightComplexEmoji() { + int selStart = 0; + ListenableEditingState editable = sampleEditable(selStart, selStart, SAMPLE_EMOJI_TEXT); + InputConnectionAdaptor adaptor = sampleInputConnectionAdaptor(editable); + + KeyEvent downKeyDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT); + boolean didConsume; + + // First CodePoint + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 1); + + // Simple Emoji + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 3); + + // Regional Indicator Symbol even + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 7); + + // Regional Indicator Symbol odd + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 9); + + // Carriage Return + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 10); + + // Line Feed and Carriage Return + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 12); + + // Line Feed + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 13); + + // Modified Emoji + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 16); + + // Emoji Modifier + adaptor.setSelection(14, 14); + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 16); + + // Emoji Modifier with invalid base + adaptor.setSelection(18, 18); + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 19); + + // Variation Selector + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 21); + + // Variation Selector with invalid base + adaptor.setSelection(22, 22); + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 23); + + // Emoji Tag Sequence + for (int i = 0; i < 7; i++) { + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 25 + 2 * i); + } + assertEquals(Selection.getSelectionStart(editable), 37); + + // ----- Start Emoji Tag Sequence with invalid base testing ---- + // Pass the sequence + adaptor.setSelection(39, 39); + for (int i = 0; i < 6; i++) { + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 41 + 2 * i); + } + assertEquals(Selection.getSelectionStart(editable), 51); + // ----- End Emoji Tag Sequence with invalid base testing ---- + + // Zero Width Joiner with invalid base + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 52); + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 53); + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 55); + + // Zero Width Joiner + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 66); + + // Keycap with invalid base + adaptor.setSelection(67, 67); + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 68); + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 69); + + // Keycap + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 72); + + // Non-Spacing Mark + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 73); + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 74); + + // Normal Character + didConsume = adaptor.handleKeyEvent(downKeyDown); + assertTrue(didConsume); + assertEquals(Selection.getSelectionStart(editable), 75); + } + + @Test + public void testSendKeyEvent_rightKeyExtendsSelectionRight() { + int selStart = 5; + int selEnd = 40; + ListenableEditingState editable = sampleEditable(selStart, selEnd); + InputConnectionAdaptor adaptor = sampleInputConnectionAdaptor(editable); + + KeyEvent rightKeyDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT); + boolean didConsume = adaptor.handleKeyEvent(rightKeyDown); + + assertTrue(didConsume); + assertEquals(selStart, Selection.getSelectionStart(editable)); + assertEquals(selEnd + 1, Selection.getSelectionEnd(editable)); + } + + @Test + public void testSendKeyEvent_shiftRightKeyStartsSelectionRight() { + int selStart = 5; + ListenableEditingState editable = sampleEditable(selStart, selStart); + InputConnectionAdaptor adaptor = sampleInputConnectionAdaptor(editable); + + KeyEvent shiftRightKeyDown = + new KeyEvent( + 0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT, 0, KeyEvent.META_SHIFT_ON); + boolean didConsume = adaptor.handleKeyEvent(shiftRightKeyDown); + + assertTrue(didConsume); + assertEquals(selStart, Selection.getSelectionStart(editable)); + assertEquals(selStart + 1, Selection.getSelectionEnd(editable)); + } + + @Test + public void testSendKeyEvent_upKeyMovesCaretUp() { + int selStart = SAMPLE_TEXT.indexOf('\n') + 4; + ListenableEditingState editable = sampleEditable(selStart, selStart); + InputConnectionAdaptor adaptor = sampleInputConnectionAdaptor(editable); + + KeyEvent upKeyDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_UP); + boolean didConsume = adaptor.handleKeyEvent(upKeyDown); + + assertTrue(didConsume); + // Checks the caret moved left (to some previous character). Selection.moveUp() behaves + // different in tests than on a real device, we can't verify the exact position. + assertTrue(Selection.getSelectionStart(editable) < selStart); + } + + @Test + public void testSendKeyEvent_downKeyMovesCaretDown() { + int selStart = 4; + ListenableEditingState editable = sampleEditable(selStart, selStart); + InputConnectionAdaptor adaptor = sampleInputConnectionAdaptor(editable); + + KeyEvent downKeyDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_DOWN); + boolean didConsume = adaptor.handleKeyEvent(downKeyDown); + + assertTrue(didConsume); + // Checks the caret moved right (to some following character). Selection.moveDown() behaves + // different in tests than on a real device, we can't verify the exact position. + assertTrue(Selection.getSelectionStart(editable) > selStart); + } + + @Test + public void testSendKeyEvent_MovementKeysAreNopWhenNoSelection() { + // Regression test for https://github.com/flutter/flutter/issues/76283. + ListenableEditingState editable = sampleEditable(-1, -1); + InputConnectionAdaptor adaptor = sampleInputConnectionAdaptor(editable); + + KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_DOWN); + boolean didConsume = adaptor.handleKeyEvent(keyEvent); + assertFalse(didConsume); + assertEquals(Selection.getSelectionStart(editable), -1); + assertEquals(Selection.getSelectionEnd(editable), -1); + + keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_UP); + didConsume = adaptor.handleKeyEvent(keyEvent); + assertFalse(didConsume); + assertEquals(Selection.getSelectionStart(editable), -1); + assertEquals(Selection.getSelectionEnd(editable), -1); + + keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT); + didConsume = adaptor.handleKeyEvent(keyEvent); + assertFalse(didConsume); + assertEquals(Selection.getSelectionStart(editable), -1); + assertEquals(Selection.getSelectionEnd(editable), -1); + + keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT); + didConsume = adaptor.handleKeyEvent(keyEvent); + assertFalse(didConsume); + assertEquals(Selection.getSelectionStart(editable), -1); + assertEquals(Selection.getSelectionEnd(editable), -1); + } + + @Test + public void testMethod_getExtractedText() { + int selStart = 5; + + ListenableEditingState editable = sampleEditable(selStart, selStart); + InputConnectionAdaptor adaptor = sampleInputConnectionAdaptor(editable); + + ExtractedText extractedText = adaptor.getExtractedText(null, 0); + + assertEquals(extractedText.text, SAMPLE_TEXT); + assertEquals(extractedText.selectionStart, selStart); + assertEquals(extractedText.selectionEnd, selStart); + } + + @Test + public void testExtractedText_monitoring() { + ListenableEditingState editable = sampleEditable(5, 5); + View testView = new View(ctx); + InputConnectionAdaptor adaptor = + new InputConnectionAdaptor( + testView, + 1, + mock(TextInputChannel.class), + mock(ScribeChannel.class), + mockKeyboardManager, + editable, + new EditorInfo()); + TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); + + testImm.resetStates(); + + ExtractedTextRequest request = new ExtractedTextRequest(); + request.token = 123; + + ExtractedText extractedText = adaptor.getExtractedText(request, 0); + assertEquals(5, extractedText.selectionStart); + assertEquals(5, extractedText.selectionEnd); + assertFalse(extractedText.text instanceof SpannableStringBuilder); + + // Move the cursor. Should not report extracted text. + adaptor.setSelection(2, 3); + assertNull(testImm.lastExtractedText); + + // Now request monitoring, and update the request text flag. + request.flags = InputConnection.GET_TEXT_WITH_STYLES; + extractedText = adaptor.getExtractedText(request, InputConnection.GET_EXTRACTED_TEXT_MONITOR); + assertEquals(2, extractedText.selectionStart); + assertEquals(3, extractedText.selectionEnd); + assertTrue(extractedText.text instanceof SpannableStringBuilder); + + adaptor.setSelection(3, 5); + assertEquals(3, testImm.lastExtractedText.selectionStart); + assertEquals(5, testImm.lastExtractedText.selectionEnd); + assertTrue(testImm.lastExtractedText.text instanceof SpannableStringBuilder); + + // Stop monitoring. + testImm.resetStates(); + extractedText = adaptor.getExtractedText(request, 0); + assertEquals(3, extractedText.selectionStart); + assertEquals(5, extractedText.selectionEnd); + assertTrue(extractedText.text instanceof SpannableStringBuilder); + + adaptor.setSelection(1, 3); + assertNull(testImm.lastExtractedText); + } + + @Test + public void testCursorAnchorInfo() { + ListenableEditingState editable = sampleEditable(5, 5); + View testView = new View(ctx); + InputConnectionAdaptor adaptor = + new InputConnectionAdaptor( + testView, + 1, + mock(TextInputChannel.class), + mock(ScribeChannel.class), + mockKeyboardManager, + editable, + new EditorInfo()); + TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); + + testImm.resetStates(); + + // Monitoring only. Does not send update immediately. + adaptor.requestCursorUpdates(InputConnection.CURSOR_UPDATE_MONITOR); + assertNull(testImm.lastCursorAnchorInfo); + + // Monitor selection changes. + adaptor.setSelection(0, 1); + CursorAnchorInfo cursorAnchorInfo = testImm.lastCursorAnchorInfo; + assertEquals(0, cursorAnchorInfo.getSelectionStart()); + assertEquals(1, cursorAnchorInfo.getSelectionEnd()); + + // Turn monitoring off. + testImm.resetStates(); + assertNull(testImm.lastCursorAnchorInfo); + adaptor.requestCursorUpdates(InputConnection.CURSOR_UPDATE_IMMEDIATE); + cursorAnchorInfo = testImm.lastCursorAnchorInfo; + assertEquals(0, cursorAnchorInfo.getSelectionStart()); + assertEquals(1, cursorAnchorInfo.getSelectionEnd()); + + // No more updates. + testImm.resetStates(); + adaptor.setSelection(1, 3); + assertNull(testImm.lastCursorAnchorInfo); + } + + @Test + public void testSendKeyEvent_sendSoftKeyEvents() { + ListenableEditingState editable = sampleEditable(5, 5); + InputConnectionAdaptor adaptor = sampleInputConnectionAdaptor(editable, mockKeyboardManager); + + KeyEvent shiftKeyDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT); + + boolean didConsume = adaptor.handleKeyEvent(shiftKeyDown); + assertFalse(didConsume); + verify(mockKeyboardManager, never()).handleEvent(shiftKeyDown); + } + + @Test + public void testSendKeyEvent_sendHardwareKeyEvents() { + ListenableEditingState editable = sampleEditable(5, 5); + when(mockKeyboardManager.handleEvent(any())).thenReturn(true); + InputConnectionAdaptor adaptor = sampleInputConnectionAdaptor(editable, mockKeyboardManager); + + KeyEvent shiftKeyDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT); + + // Call sendKeyEvent instead of handleKeyEvent. + boolean didConsume = adaptor.sendKeyEvent(shiftKeyDown); + assertTrue(didConsume); + verify(mockKeyboardManager, times(1)).handleEvent(shiftKeyDown); + } + + @Test + public void testSendKeyEvent_delKeyNotConsumed() { + ListenableEditingState editable = sampleEditable(5, 5); + InputConnectionAdaptor adaptor = sampleInputConnectionAdaptor(editable); + + KeyEvent downKeyDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL); + + for (int i = 0; i < 4; i++) { + boolean didConsume = adaptor.handleKeyEvent(downKeyDown); + assertFalse(didConsume); + } + assertEquals(5, Selection.getSelectionStart(editable)); + } + + @Test + public void testDoesNotConsumeBackButton() { + ListenableEditingState editable = sampleEditable(0, 0); + InputConnectionAdaptor adaptor = sampleInputConnectionAdaptor(editable); + + FakeKeyEvent keyEvent = new FakeKeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK, '\b'); + boolean didConsume = adaptor.handleKeyEvent(keyEvent); + + assertFalse(didConsume); + } + + @Test + public void testCleanUpBatchEndsOnCloseConnection() { + final ListenableEditingState editable = sampleEditable(0, 0); + InputConnectionAdaptor adaptor = spy(sampleInputConnectionAdaptor(editable)); + for (int i = 0; i < 5; i++) { + adaptor.beginBatchEdit(); + } + adaptor.endBatchEdit(); + verify(adaptor, times(1)).endBatchEdit(); + adaptor.closeConnection(); + verify(adaptor, times(4)).endBatchEdit(); + } + + private static final String SAMPLE_TEXT = + "Lorem ipsum dolor sit amet," + "\nconsectetur adipiscing elit."; + + private static final String SAMPLE_EMOJI_TEXT = + "a" // First CodePoint + + "😂" // Simple Emoji + + "🇮🇷" // Regional Indicator Symbol even + + "🇷" // Regional Indicator Symbol odd + + "\r\n" // Carriage Return and Line Feed + + "\r\n" + + "✋🏿" // Emoji Modifier + + "✋🏿" + + "⚠️" // Variant Selector + + "⚠️" + + "🏴󠁧󠁢󠁥󠁮󠁧󠁿" // Emoji Tag Sequence + + "🏴󠁧󠁢󠁥󠁮󠁧󠁿" + + "a‍👨" // Zero Width Joiner + + "👨‍👩‍👧‍👦" + + "5️⃣" // Keycap + + "5️⃣" + + "عَ" // Non-Spacing Mark + + "a"; // Normal Character + + private static final String SAMPLE_RTL_TEXT = "متن ساختگی" + "\nبرای تستfor test😊"; + + private static ListenableEditingState sampleEditable(int selStart, int selEnd) { + ListenableEditingState sample = + new ListenableEditingState(null, new View(ApplicationProvider.getApplicationContext())); + sample.replace(0, 0, SAMPLE_TEXT); + Selection.setSelection(sample, selStart, selEnd); + return sample; + } + + private static ListenableEditingState sampleEditable(int selStart, int selEnd, String text) { + ListenableEditingState sample = + new ListenableEditingState(null, new View(ApplicationProvider.getApplicationContext())); + sample.replace(0, 0, text); + Selection.setSelection(sample, selStart, selEnd); + return sample; + } + + private static InputConnectionAdaptor sampleInputConnectionAdaptor( + ListenableEditingState editable) { + return sampleInputConnectionAdaptor(editable, mock(KeyboardManager.class)); + } + + private static InputConnectionAdaptor sampleInputConnectionAdaptor( + ListenableEditingState editable, KeyboardManager mockKeyboardManager) { + View testView = new View(ApplicationProvider.getApplicationContext()); + int client = 0; + TextInputChannel textInputChannel = mock(TextInputChannel.class); + ScribeChannel scribeChannel = mock(ScribeChannel.class); + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + when(mockFlutterJNI.isCodePointEmoji(anyInt())) + .thenAnswer((invocation) -> Emoji.isEmoji((int) invocation.getArguments()[0])); + when(mockFlutterJNI.isCodePointEmojiModifier(anyInt())) + .thenAnswer((invocation) -> Emoji.isEmojiModifier((int) invocation.getArguments()[0])); + when(mockFlutterJNI.isCodePointEmojiModifierBase(anyInt())) + .thenAnswer((invocation) -> Emoji.isEmojiModifierBase((int) invocation.getArguments()[0])); + when(mockFlutterJNI.isCodePointVariantSelector(anyInt())) + .thenAnswer((invocation) -> Emoji.isVariationSelector((int) invocation.getArguments()[0])); + when(mockFlutterJNI.isCodePointRegionalIndicator(anyInt())) + .thenAnswer( + (invocation) -> Emoji.isRegionalIndicatorSymbol((int) invocation.getArguments()[0])); + return new InputConnectionAdaptor( + testView, + client, + textInputChannel, + scribeChannel, + mockKeyboardManager, + editable, + null, + mockFlutterJNI); + } + + private static class Emoji { + public static boolean isEmoji(int codePoint) { + return UCharacter.hasBinaryProperty(codePoint, UProperty.EMOJI); + } + + public static boolean isEmojiModifier(int codePoint) { + return UCharacter.hasBinaryProperty(codePoint, UProperty.EMOJI_MODIFIER); + } + + public static boolean isEmojiModifierBase(int codePoint) { + return UCharacter.hasBinaryProperty(codePoint, UProperty.EMOJI_MODIFIER_BASE); + } + + public static boolean isRegionalIndicatorSymbol(int codePoint) { + return UCharacter.hasBinaryProperty(codePoint, UProperty.REGIONAL_INDICATOR); + } + + public static boolean isVariationSelector(int codePoint) { + return UCharacter.hasBinaryProperty(codePoint, UProperty.VARIATION_SELECTOR); + } + } + + private class TestTextInputChannel extends TextInputChannel { + public TestTextInputChannel(DartExecutor dartExecutor) { + super(dartExecutor); + } + + public int inputClientId; + public String text; + public int selectionStart; + public int selectionEnd; + public int composingStart; + public int composingEnd; + public int updateEditingStateInvocations = 0; + + @Override + public void updateEditingState( + int inputClientId, + String text, + int selectionStart, + int selectionEnd, + int composingStart, + int composingEnd) { + this.inputClientId = inputClientId; + this.text = text; + this.selectionStart = selectionStart; + this.selectionEnd = selectionEnd; + this.composingStart = composingStart; + this.composingEnd = composingEnd; + updateEditingStateInvocations++; + } + } + + @Implements(InputMethodManager.class) + public static class TestImm extends ShadowInputMethodManager { + public static int empty = -999; + CursorAnchorInfo lastCursorAnchorInfo; + int lastExtractedTextToken = empty; + ExtractedText lastExtractedText; + + int lastSelectionStart = empty; + int lastSelectionEnd = empty; + int lastCandidatesStart = empty; + int lastCandidatesEnd = empty; + + public TestImm() {} + + @Implementation + public void updateCursorAnchorInfo(View view, CursorAnchorInfo cursorAnchorInfo) { + lastCursorAnchorInfo = cursorAnchorInfo; + } + + @Implementation + public void updateExtractedText(View view, int token, ExtractedText text) { + lastExtractedTextToken = token; + lastExtractedText = text; + } + + @Implementation + public void updateSelection( + View view, int selStart, int selEnd, int candidatesStart, int candidatesEnd) { + lastSelectionStart = selStart; + lastSelectionEnd = selEnd; + lastCandidatesStart = candidatesStart; + lastCandidatesEnd = candidatesEnd; + } + + public void resetStates() { + lastExtractedText = null; + lastExtractedTextToken = empty; + + lastSelectionStart = empty; + lastSelectionEnd = empty; + lastCandidatesStart = empty; + lastCandidatesEnd = empty; + + lastCursorAnchorInfo = null; + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/editing/ListenableEditingStateTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/editing/ListenableEditingStateTest.java new file mode 100644 index 0000000000000000000000000000000000000000..e867dd587b90030b30b826f48695e75ba678f090 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/editing/ListenableEditingStateTest.java @@ -0,0 +1,442 @@ +package io.flutter.plugin.editing; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; + +import android.content.Context; +import android.text.Editable; +import android.text.Selection; +import android.view.View; +import android.view.inputmethod.BaseInputConnection; +import android.view.inputmethod.EditorInfo; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.android.KeyboardManager; +import io.flutter.embedding.engine.systemchannels.ScribeChannel; +import io.flutter.embedding.engine.systemchannels.TextInputChannel; +import java.util.ArrayList; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class ListenableEditingStateTest { + private final Context ctx = ApplicationProvider.getApplicationContext(); + @Mock KeyboardManager mockKeyboardManager; + + private BaseInputConnection getTestInputConnection(View view, Editable mEditable) { + new View(ctx); + return new BaseInputConnection(view, true) { + @Override + public Editable getEditable() { + return mEditable; + } + }; + } + + @Before + public void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + public void testConstructor() { + // When provided valid composing range, should not fail + new ListenableEditingState( + new TextInputChannel.TextEditState("hello", 1, 4, 1, 4), new View(ctx)); + } + + // -------- Start: Test BatchEditing ------- + @Test + public void testBatchEditing() { + final ListenableEditingState editingState = new ListenableEditingState(null, new View(ctx)); + final Listener listener = new Listener(); + final View testView = new View(ctx); + final BaseInputConnection inputConnection = getTestInputConnection(testView, editingState); + + editingState.addEditingStateListener(listener); + + editingState.replace(0, editingState.length(), "update"); + assertTrue(listener.isCalled()); + assertTrue(listener.textChanged); + assertFalse(listener.selectionChanged); + assertFalse(listener.composingRegionChanged); + + assertEquals(-1, editingState.getSelectionStart()); + assertEquals(-1, editingState.getSelectionEnd()); + + listener.reset(); + + // Batch edit depth = 1. + editingState.beginBatchEdit(); + editingState.replace(0, editingState.length(), "update1"); + assertFalse(listener.isCalled()); + // Batch edit depth = 2. + editingState.beginBatchEdit(); + editingState.replace(0, editingState.length(), "update2"); + inputConnection.setComposingRegion(0, editingState.length()); + assertFalse(listener.isCalled()); + // Batch edit depth = 1. + editingState.endBatchEdit(); + assertFalse(listener.isCalled()); + + // Batch edit depth = 2. + editingState.beginBatchEdit(); + assertFalse(listener.isCalled()); + inputConnection.setSelection(0, 0); + assertFalse(listener.isCalled()); + // Batch edit depth = 1. + editingState.endBatchEdit(); + assertFalse(listener.isCalled()); + + // Remove composing region. + inputConnection.finishComposingText(); + + // Batch edit depth = 0. Last endBatchEdit. + editingState.endBatchEdit(); + + // Now notify the listener. + assertTrue(listener.isCalled()); + assertTrue(listener.textChanged); + assertFalse(listener.composingRegionChanged); + } + + @Test + public void testBatchingEditing_callEndBeforeBegin() { + final ListenableEditingState editingState = new ListenableEditingState(null, new View(ctx)); + final Listener listener = new Listener(); + editingState.addEditingStateListener(listener); + + editingState.endBatchEdit(); + assertFalse(listener.isCalled()); + + editingState.replace(0, editingState.length(), "text"); + assertTrue(listener.isCalled()); + assertTrue(listener.textChanged); + + listener.reset(); + // Does not disrupt the followup events. + editingState.beginBatchEdit(); + editingState.replace(0, editingState.length(), "more text"); + assertFalse(listener.isCalled()); + editingState.endBatchEdit(); + assertTrue(listener.isCalled()); + } + + @Test + public void testBatchingEditing_addListenerDuringBatchEdit() { + final ListenableEditingState editingState = new ListenableEditingState(null, new View(ctx)); + final Listener listener = new Listener(); + + editingState.beginBatchEdit(); + editingState.addEditingStateListener(listener); + editingState.replace(0, editingState.length(), "update"); + editingState.endBatchEdit(); + + assertTrue(listener.isCalled()); + assertTrue(listener.textChanged); + assertTrue(listener.selectionChanged); + assertTrue(listener.composingRegionChanged); + + listener.reset(); + + // Verifies the listener is officially added. + editingState.replace(0, editingState.length(), "more updates"); + assertTrue(listener.isCalled()); + assertTrue(listener.textChanged); + editingState.removeEditingStateListener(listener); + + listener.reset(); + // Now remove before endBatchEdit(); + editingState.beginBatchEdit(); + editingState.addEditingStateListener(listener); + editingState.replace(0, editingState.length(), "update"); + editingState.removeEditingStateListener(listener); + editingState.endBatchEdit(); + + assertFalse(listener.isCalled()); + } + + @Test + public void testBatchingEditing_removeListenerDuringBatchEdit() { + final ListenableEditingState editingState = new ListenableEditingState(null, new View(ctx)); + final Listener listener = new Listener(); + editingState.addEditingStateListener(listener); + + editingState.beginBatchEdit(); + editingState.replace(0, editingState.length(), "update"); + editingState.removeEditingStateListener(listener); + editingState.endBatchEdit(); + + assertFalse(listener.isCalled()); + } + + @Test + public void testBatchingEditing_listenerCallsReplaceWhenBatchEditEnds() { + final ListenableEditingState editingState = new ListenableEditingState(null, new View(ctx)); + + final Listener listener = + new Listener() { + @Override + public void didChangeEditingState( + boolean textChanged, boolean selectionChanged, boolean composingRegionChanged) { + super.didChangeEditingState(textChanged, selectionChanged, composingRegionChanged); + editingState.replace( + 0, editingState.length(), "one does not simply replace the text in the listener"); + } + }; + editingState.addEditingStateListener(listener); + + editingState.beginBatchEdit(); + editingState.replace(0, editingState.length(), "update"); + editingState.endBatchEdit(); + + assertTrue(listener.isCalled()); + assertEquals(1, listener.timesCalled); + assertEquals("one does not simply replace the text in the listener", editingState.toString()); + } + // -------- End: Test BatchEditing ------- + + @Test + public void testSetComposingRegion() { + final ListenableEditingState editingState = new ListenableEditingState(null, new View(ctx)); + editingState.replace(0, editingState.length(), "text"); + + // (-1, -1) clears the composing region. + editingState.setComposingRange(-1, -1); + assertEquals(-1, editingState.getComposingStart()); + assertEquals(-1, editingState.getComposingEnd()); + + editingState.setComposingRange(-1, 5); + assertEquals(-1, editingState.getComposingStart()); + assertEquals(-1, editingState.getComposingEnd()); + + editingState.setComposingRange(2, 3); + assertEquals(2, editingState.getComposingStart()); + assertEquals(3, editingState.getComposingEnd()); + + // Empty range is invalid. Clears composing region. + editingState.setComposingRange(1, 1); + assertEquals(-1, editingState.getComposingStart()); + assertEquals(-1, editingState.getComposingEnd()); + + // Covers everything. + editingState.setComposingRange(0, editingState.length()); + assertEquals(0, editingState.getComposingStart()); + assertEquals(editingState.length(), editingState.getComposingEnd()); + } + + @Test + public void testClearBatchDeltas() { + final ListenableEditingState editingState = new ListenableEditingState(null, new View(ctx)); + editingState.replace(0, editingState.length(), "text"); + editingState.delete(0, 1); + editingState.insert(0, "This is t"); + editingState.clearBatchDeltas(); + assertEquals(0, editingState.extractBatchTextEditingDeltas().size()); + } + + @Test + public void testExtractBatchTextEditingDeltas() { + final ListenableEditingState editingState = new ListenableEditingState(null, new View(ctx)); + + // Creating some deltas. + editingState.replace(0, editingState.length(), "test"); + editingState.delete(0, 1); + editingState.insert(0, "This is a t"); + + ArrayList batchDeltas = editingState.extractBatchTextEditingDeltas(); + assertEquals(3, batchDeltas.size()); + } + + // -------- Start: Test InputMethods actions ------- + @Test + public void inputMethod_batchEditingBeginAndEnd() { + final ArrayList batchMarkers = new ArrayList<>(); + final ListenableEditingState editingState = + new ListenableEditingState(null, new View(ctx)) { + @Override + public final void beginBatchEdit() { + super.beginBatchEdit(); + batchMarkers.add("begin"); + } + + @Override + public void endBatchEdit() { + super.endBatchEdit(); + batchMarkers.add("end"); + } + }; + + final Listener listener = new Listener(); + final View testView = new View(ctx); + final InputConnectionAdaptor inputConnection = + new InputConnectionAdaptor( + testView, + 0, + mock(TextInputChannel.class), + mock(ScribeChannel.class), + mockKeyboardManager, + editingState, + new EditorInfo()); + + // Make sure begin/endBatchEdit is called on the Editable when the input method calls + // InputConnection#begin/endBatchEdit. + inputConnection.beginBatchEdit(); + assertEquals(1, batchMarkers.size()); + assertEquals("begin", batchMarkers.get(0)); + + inputConnection.endBatchEdit(); + assertEquals(2, batchMarkers.size()); + assertEquals("end", batchMarkers.get(1)); + } + + @Test + public void inputMethod_testSetSelection() { + final ListenableEditingState editingState = new ListenableEditingState(null, new View(ctx)); + final Listener listener = new Listener(); + final View testView = new View(ctx); + final InputConnectionAdaptor inputConnection = + new InputConnectionAdaptor( + testView, + 0, + mock(TextInputChannel.class), + mock(ScribeChannel.class), + mockKeyboardManager, + editingState, + new EditorInfo()); + editingState.replace(0, editingState.length(), "initial text"); + + editingState.addEditingStateListener(listener); + + inputConnection.setSelection(0, 0); + + assertTrue(listener.isCalled()); + assertFalse(listener.textChanged); + assertTrue(listener.selectionChanged); + assertFalse(listener.composingRegionChanged); + + listener.reset(); + + inputConnection.setSelection(5, 5); + + assertTrue(listener.isCalled()); + assertFalse(listener.textChanged); + assertTrue(listener.selectionChanged); + assertFalse(listener.composingRegionChanged); + } + + @Test + public void inputMethod_testSetComposition() { + final ListenableEditingState editingState = new ListenableEditingState(null, new View(ctx)); + final Listener listener = new Listener(); + final View testView = new View(ctx); + final InputConnectionAdaptor inputConnection = + new InputConnectionAdaptor( + testView, + 0, + mock(TextInputChannel.class), + mock(ScribeChannel.class), + mockKeyboardManager, + editingState, + new EditorInfo()); + editingState.replace(0, editingState.length(), "initial text"); + + editingState.addEditingStateListener(listener); + + // setComposingRegion test. + inputConnection.setComposingRegion(1, 3); + assertTrue(listener.isCalled()); + assertFalse(listener.textChanged); + assertFalse(listener.selectionChanged); + assertTrue(listener.composingRegionChanged); + + Selection.setSelection(editingState, 0, 0); + listener.reset(); + + // setComposingText test: non-empty text, does not move cursor. + inputConnection.setComposingText("composing", -1); + assertTrue(listener.isCalled()); + assertTrue(listener.textChanged); + assertFalse(listener.selectionChanged); + assertTrue(listener.composingRegionChanged); + + listener.reset(); + // setComposingText test: non-empty text, moves cursor. + inputConnection.setComposingText("composing2", 1); + assertTrue(listener.isCalled()); + assertTrue(listener.textChanged); + assertTrue(listener.selectionChanged); + assertTrue(listener.composingRegionChanged); + + listener.reset(); + // setComposingText test: empty text. + inputConnection.setComposingText("", 1); + assertTrue(listener.isCalled()); + assertTrue(listener.textChanged); + assertTrue(listener.selectionChanged); + assertTrue(listener.composingRegionChanged); + + // finishComposingText test. + inputConnection.setComposingText("composing text", 1); + listener.reset(); + inputConnection.finishComposingText(); + assertTrue(listener.isCalled()); + assertFalse(listener.textChanged); + assertFalse(listener.selectionChanged); + assertTrue(listener.composingRegionChanged); + } + + @Test + public void inputMethod_testCommitText() { + final ListenableEditingState editingState = new ListenableEditingState(null, new View(ctx)); + final Listener listener = new Listener(); + final View testView = new View(ctx); + final InputConnectionAdaptor inputConnection = + new InputConnectionAdaptor( + testView, + 0, + mock(TextInputChannel.class), + mock(ScribeChannel.class), + mockKeyboardManager, + editingState, + new EditorInfo()); + editingState.replace(0, editingState.length(), "initial text"); + + editingState.addEditingStateListener(listener); + } + // -------- End: Test InputMethods actions ------- + + public static class Listener implements ListenableEditingState.EditingStateWatcher { + public boolean isCalled() { + return timesCalled > 0; + } + + int timesCalled = 0; + boolean textChanged = false; + boolean selectionChanged = false; + boolean composingRegionChanged = false; + + @Override + public void didChangeEditingState( + boolean textChanged, boolean selectionChanged, boolean composingRegionChanged) { + timesCalled++; + this.textChanged = textChanged; + this.selectionChanged = selectionChanged; + this.composingRegionChanged = composingRegionChanged; + } + + public void reset() { + timesCalled = 0; + textChanged = false; + selectionChanged = false; + composingRegionChanged = false; + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/editing/ScribePluginTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/editing/ScribePluginTest.java new file mode 100644 index 0000000000000000000000000000000000000000..386c75a35c79ffa8ad3243ae798d95adc0855579 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/editing/ScribePluginTest.java @@ -0,0 +1,106 @@ +// 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. + +package io.flutter.plugin.editing; + +import static io.flutter.Build.API_LEVELS; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.annotation.TargetApi; +import android.content.Context; +import android.os.Build; +import android.view.View; +import android.view.inputmethod.InputMethodManager; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.systemchannels.ScribeChannel; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +@RunWith(AndroidJUnit4.class) +public class ScribePluginTest { + private final Context ctx = ApplicationProvider.getApplicationContext(); + + ScribePlugin scribePlugin; + InputMethodManager mockImm; + View testView; + + @Before + public void setUp() { + ScribeChannel mockScribeChannel = mock(ScribeChannel.class); + testView = new View(ctx); + mockImm = mock(InputMethodManager.class); + if (Build.VERSION.SDK_INT >= API_LEVELS.API_34) { + when(mockImm.isStylusHandwritingAvailable()).thenReturn(true); + } + scribePlugin = new ScribePlugin(testView, mockImm, mockScribeChannel); + } + + @Config(minSdk = API_LEVELS.API_34) + @TargetApi(API_LEVELS.API_34) + @Test + public void scribePluginIsFeatureAvailable() { + assertEquals(scribePlugin.isFeatureAvailable(), true); + + verify(mockImm).isStylusHandwritingAvailable(); + } + + @Config(minSdk = API_LEVELS.API_34) + @TargetApi(API_LEVELS.API_34) + @Test + public void scribePluginIsStylusHandwritingAvailable() { + assertEquals(scribePlugin.isStylusHandwritingAvailable(), true); + + verify(mockImm).isStylusHandwritingAvailable(); + } + + @Config(minSdk = API_LEVELS.API_34) + @TargetApi(API_LEVELS.API_34) + @Test + public void scribePluginStartStylusHandwriting() { + scribePlugin.startStylusHandwriting(); + + verify(mockImm).startStylusHandwriting(testView); + } + + @Config(sdk = API_LEVELS.API_32) + @TargetApi(API_LEVELS.API_32) + @Test + public void scribePluginStartStylusHandwritingWhenAPILevelUnsupported() { + assertNotNull(scribePlugin); + + assertThrows( + NoSuchMethodError.class, + () -> { + scribePlugin.startStylusHandwriting(); + }); + } + + @Config(sdk = API_LEVELS.API_33) + @TargetApi(API_LEVELS.API_33) + @Test + public void scribePluginIsFeatureAvailableWhenAPILevelUnsupported() { + assertEquals(scribePlugin.isFeatureAvailable(), false); + } + + @Config(sdk = API_LEVELS.API_33) + @TargetApi(API_LEVELS.API_33) + @Test + public void scribePluginIsStylusHandwritingAvailableWhenAPILevelUnsupported() { + assertNotNull(scribePlugin); + + assertThrows( + NoSuchMethodError.class, + () -> { + scribePlugin.isStylusHandwritingAvailable(); + }); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/editing/SpellCheckPluginTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/editing/SpellCheckPluginTest.java new file mode 100644 index 0000000000000000000000000000000000000000..fd291b291ada0467dda039e2a6767384f4830979 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/editing/SpellCheckPluginTest.java @@ -0,0 +1,270 @@ +package io.flutter.plugin.editing; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.content.Context; +import android.view.textservice.SentenceSuggestionsInfo; +import android.view.textservice.SpellCheckerSession; +import android.view.textservice.SuggestionsInfo; +import android.view.textservice.TextInfo; +import android.view.textservice.TextServicesManager; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.dart.DartExecutor; +import io.flutter.embedding.engine.systemchannels.SpellCheckChannel; +import io.flutter.plugin.common.BinaryMessenger; +import io.flutter.plugin.common.MethodCall; +import io.flutter.plugin.common.MethodChannel; +import io.flutter.plugin.common.StandardMethodCodec; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Locale; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; + +@RunWith(AndroidJUnit4.class) +public class SpellCheckPluginTest { + + private static void sendToBinaryMessageHandler( + BinaryMessenger.BinaryMessageHandler binaryMessageHandler, String method, Object args) { + MethodCall methodCall = new MethodCall(method, args); + ByteBuffer encodedMethodCall = StandardMethodCodec.INSTANCE.encodeMethodCall(methodCall); + binaryMessageHandler.onMessage( + (ByteBuffer) encodedMethodCall.flip(), mock(BinaryMessenger.BinaryReply.class)); + } + + @SuppressWarnings("deprecation") + // setMessageHandler is deprecated. + @Test + public void respondsToSpellCheckChannelMessage() { + ArgumentCaptor binaryMessageHandlerCaptor = + ArgumentCaptor.forClass(BinaryMessenger.BinaryMessageHandler.class); + DartExecutor mockBinaryMessenger = mock(DartExecutor.class); + SpellCheckChannel.SpellCheckMethodHandler mockHandler = + mock(SpellCheckChannel.SpellCheckMethodHandler.class); + SpellCheckChannel spellCheckChannel = new SpellCheckChannel(mockBinaryMessenger); + + spellCheckChannel.setSpellCheckMethodHandler(mockHandler); + + verify(mockBinaryMessenger, times(1)) + .setMessageHandler(any(String.class), binaryMessageHandlerCaptor.capture()); + + BinaryMessenger.BinaryMessageHandler binaryMessageHandler = + binaryMessageHandlerCaptor.getValue(); + + sendToBinaryMessageHandler( + binaryMessageHandler, + "SpellCheck.initiateSpellCheck", + Arrays.asList("en-US", "Hello, wrold!")); + + verify(mockHandler) + .initiateSpellCheck(eq("en-US"), eq("Hello, wrold!"), any(MethodChannel.Result.class)); + } + + @Test + public void initiateSpellCheckPerformsSpellCheckWhenNoResultPending() { + SpellCheckChannel fakeSpellCheckChannel = mock(SpellCheckChannel.class); + TextServicesManager fakeTextServicesManager = mock(TextServicesManager.class); + SpellCheckPlugin spellCheckPlugin = + spy(new SpellCheckPlugin(fakeTextServicesManager, fakeSpellCheckChannel)); + MethodChannel.Result mockResult = mock(MethodChannel.Result.class); + SpellCheckerSession fakeSpellCheckerSession = mock(SpellCheckerSession.class); + + when(fakeTextServicesManager.newSpellCheckerSession( + null, new Locale("en", "US"), spellCheckPlugin, true)) + .thenReturn(fakeSpellCheckerSession); + + spellCheckPlugin.initiateSpellCheck("en-US", "Hello, wrold!", mockResult); + + verify(spellCheckPlugin).performSpellCheck("en-US", "Hello, wrold!"); + } + + @Test + public void initiateSpellCheckThrowsErrorWhenResultPending() { + SpellCheckChannel fakeSpellCheckChannel = mock(SpellCheckChannel.class); + TextServicesManager fakeTextServicesManager = mock(TextServicesManager.class); + SpellCheckPlugin spellCheckPlugin = + spy(new SpellCheckPlugin(fakeTextServicesManager, fakeSpellCheckChannel)); + MethodChannel.Result mockPendingResult = mock(MethodChannel.Result.class); + MethodChannel.Result mockResult = mock(MethodChannel.Result.class); + spellCheckPlugin.pendingResult = mockPendingResult; + + spellCheckPlugin.initiateSpellCheck("en-US", "Hello, wrold!", mockResult); + + verify(mockResult).error("error", "Previous spell check request still pending.", null); + verify(spellCheckPlugin, never()).performSpellCheck("en-US", "Hello, wrold!"); + } + + @Test + public void destroyClosesSpellCheckerSessionAndClearsSpellCheckMethodHandler() { + Context fakeContext = mock(Context.class); + SpellCheckChannel fakeSpellCheckChannel = mock(SpellCheckChannel.class); + TextServicesManager fakeTextServicesManager = mock(TextServicesManager.class); + when(fakeContext.getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE)) + .thenReturn(fakeTextServicesManager); + SpellCheckPlugin spellCheckPlugin = + spy(new SpellCheckPlugin(fakeTextServicesManager, fakeSpellCheckChannel)); + SpellCheckerSession fakeSpellCheckerSession = mock(SpellCheckerSession.class); + + when(fakeTextServicesManager.newSpellCheckerSession( + null, new Locale("en", "US"), spellCheckPlugin, true)) + .thenReturn(fakeSpellCheckerSession); + + spellCheckPlugin.performSpellCheck("en-US", "Hello, wrold!"); + spellCheckPlugin.destroy(); + + verify(fakeSpellCheckChannel).setSpellCheckMethodHandler(isNull()); + verify(fakeSpellCheckerSession).close(); + } + + @Test + public void performSpellCheckSendsRequestToAndroidSpellCheckService() { + Context fakeContext = mock(Context.class); + SpellCheckChannel fakeSpellCheckChannel = mock(SpellCheckChannel.class); + TextServicesManager fakeTextServicesManager = mock(TextServicesManager.class); + when(fakeContext.getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE)) + .thenReturn(fakeTextServicesManager); + SpellCheckPlugin spellCheckPlugin = + spy(new SpellCheckPlugin(fakeTextServicesManager, fakeSpellCheckChannel)); + SpellCheckerSession fakeSpellCheckerSession = mock(SpellCheckerSession.class); + Locale english_US = new Locale("en", "US"); + + when(fakeTextServicesManager.newSpellCheckerSession(null, english_US, spellCheckPlugin, true)) + .thenReturn(fakeSpellCheckerSession); + + int maxSuggestions = 5; + ArgumentCaptor textInfosCaptor = ArgumentCaptor.forClass(TextInfo[].class); + ArgumentCaptor maxSuggestionsCaptor = ArgumentCaptor.forClass(Integer.class); + + spellCheckPlugin.performSpellCheck("en-US", "Hello, wrold!"); + + verify(fakeSpellCheckerSession) + .getSentenceSuggestions(textInfosCaptor.capture(), maxSuggestionsCaptor.capture()); + assertEquals("Hello, wrold!", textInfosCaptor.getValue()[0].getText()); + assertEquals(Integer.valueOf(maxSuggestions), maxSuggestionsCaptor.getValue()); + } + + @Test + public void performSpellCheckCreatesNewSpellCheckerSession() { + Context fakeContext = mock(Context.class); + SpellCheckChannel fakeSpellCheckChannel = mock(SpellCheckChannel.class); + TextServicesManager fakeTextServicesManager = mock(TextServicesManager.class); + when(fakeContext.getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE)) + .thenReturn(fakeTextServicesManager); + SpellCheckPlugin spellCheckPlugin = + spy(new SpellCheckPlugin(fakeTextServicesManager, fakeSpellCheckChannel)); + SpellCheckerSession fakeSpellCheckerSession = mock(SpellCheckerSession.class); + Locale english_US = new Locale("en", "US"); + + when(fakeTextServicesManager.newSpellCheckerSession(null, english_US, spellCheckPlugin, true)) + .thenReturn(fakeSpellCheckerSession); + + spellCheckPlugin.performSpellCheck("en-US", "Hello, worl!"); + spellCheckPlugin.performSpellCheck("en-US", "Hello, world!"); + + verify(fakeTextServicesManager, times(1)) + .newSpellCheckerSession(null, english_US, spellCheckPlugin, true); + } + + @Test + public void onGetSentenceSuggestionsResultsWithSuccessAndNoResultsProperly() { + TextServicesManager fakeTextServicesManager = mock(TextServicesManager.class); + SpellCheckChannel fakeSpellCheckChannel = mock(SpellCheckChannel.class); + SpellCheckPlugin spellCheckPlugin = + spy(new SpellCheckPlugin(fakeTextServicesManager, fakeSpellCheckChannel)); + MethodChannel.Result mockResult = mock(MethodChannel.Result.class); + spellCheckPlugin.pendingResult = mockResult; + + spellCheckPlugin.onGetSentenceSuggestions(new SentenceSuggestionsInfo[] {}); + + verify(mockResult).success(new ArrayList>()); + } + + @Test + public void onGetSentenceSuggestionsResultsWithSuccessAndResultsProperly() { + TextServicesManager fakeTextServicesManager = mock(TextServicesManager.class); + SpellCheckChannel fakeSpellCheckChannel = mock(SpellCheckChannel.class); + SpellCheckPlugin spellCheckPlugin = + spy(new SpellCheckPlugin(fakeTextServicesManager, fakeSpellCheckChannel)); + MethodChannel.Result mockResult = mock(MethodChannel.Result.class); + spellCheckPlugin.pendingResult = mockResult; + + spellCheckPlugin.onGetSentenceSuggestions( + new SentenceSuggestionsInfo[] { + new SentenceSuggestionsInfo( + (new SuggestionsInfo[] { + new SuggestionsInfo( + SuggestionsInfo.RESULT_ATTR_LOOKS_LIKE_TYPO, + new String[] {"world", "word", "old"}) + }), + new int[] {7}, + new int[] {5}) + }); + + ArrayList> expectedResults = new ArrayList>(); + HashMap expectedResult = new HashMap(); + + expectedResult.put(SpellCheckPlugin.START_INDEX_KEY, 7); + expectedResult.put(SpellCheckPlugin.END_INDEX_KEY, 12); + expectedResult.put( + SpellCheckPlugin.SUGGESTIONS_KEY, + new ArrayList(Arrays.asList("world", "word", "old"))); + expectedResults.add(expectedResult); + + verify(mockResult).success(expectedResults); + } + + @Test + public void onGetSentenceSuggestionsResultsWithSuccessAndNoResultsWhenSuggestionsAreInvalid() { + TextServicesManager fakeTextServicesManager = mock(TextServicesManager.class); + SpellCheckChannel fakeSpellCheckChannel = mock(SpellCheckChannel.class); + SpellCheckPlugin spellCheckPlugin = + spy(new SpellCheckPlugin(fakeTextServicesManager, fakeSpellCheckChannel)); + MethodChannel.Result mockResult = mock(MethodChannel.Result.class); + spellCheckPlugin.pendingResult = mockResult; + + spellCheckPlugin.onGetSentenceSuggestions( + new SentenceSuggestionsInfo[] { + new SentenceSuggestionsInfo( + (new SuggestionsInfo[] { + new SuggestionsInfo( + SuggestionsInfo.RESULT_ATTR_LOOKS_LIKE_TYPO, + // This is the suggestion that may be provided by the Samsung spell checker: + new String[] {""}) + }), + new int[] {7}, + new int[] {5}) + }); + + verify(mockResult).success(new ArrayList>()); + } + + @Test + public void onGetSentenceSuggestionsResultsWithSuccessAndNoResultsWhenSuggestionsAreInvalid2() { + TextServicesManager fakeTextServicesManager = mock(TextServicesManager.class); + SpellCheckChannel fakeSpellCheckChannel = mock(SpellCheckChannel.class); + SpellCheckPlugin spellCheckPlugin = + spy(new SpellCheckPlugin(fakeTextServicesManager, fakeSpellCheckChannel)); + MethodChannel.Result mockResult = mock(MethodChannel.Result.class); + spellCheckPlugin.pendingResult = mockResult; + + spellCheckPlugin.onGetSentenceSuggestions( + new SentenceSuggestionsInfo[] { + // This "suggestion" may be provided by the Samsung spell checker: + null + }); + + verify(mockResult).success(new ArrayList>()); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/editing/TextEditingDeltaTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/editing/TextEditingDeltaTest.java new file mode 100644 index 0000000000000000000000000000000000000000..cf7d127d3700f7be85150e93b3ce05f80a9f070d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/editing/TextEditingDeltaTest.java @@ -0,0 +1,79 @@ +package io.flutter.plugin.editing; + +import static org.junit.Assert.assertEquals; + +import androidx.test.ext.junit.runners.AndroidJUnit4; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.MockitoAnnotations; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class TextEditingDeltaTest { + @Before + public void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + public void testConstructorTextEditingDelta() { + final CharSequence oldText = "hell"; + final CharSequence textAfterChange = "hello"; + + final int oldComposingStart = 0; + final int oldComposingEnd = 4; + + final int startOfReplacementText = 0; + final int endOfReplacementText = textAfterChange.length(); + + final int newSelectionStart = 5; + final int newSelectionEnd = 5; + final int newComposingStart = 0; + final int newComposingEnd = 5; + + final TextEditingDelta delta = + new TextEditingDelta( + oldText, + oldComposingStart, + oldComposingEnd, + textAfterChange, + newSelectionStart, + newSelectionEnd, + newComposingStart, + newComposingEnd); + + assertEquals(oldText, delta.getOldText()); + assertEquals(textAfterChange, delta.getDeltaText()); + assertEquals(oldComposingStart, delta.getDeltaStart()); + assertEquals(oldComposingEnd, delta.getDeltaEnd()); + assertEquals(newSelectionStart, delta.getNewSelectionStart()); + assertEquals(newSelectionEnd, delta.getNewSelectionEnd()); + assertEquals(newComposingStart, delta.getNewComposingStart()); + assertEquals(newComposingEnd, delta.getNewComposingEnd()); + } + + @Test + public void testNonTextUpdateConstructorTextEditingDelta() { + final CharSequence oldText = "hello"; + + final int newSelectionStart = 3; + final int newSelectionEnd = 3; + final int newComposingStart = 0; + final int newComposingEnd = 5; + + final TextEditingDelta delta = + new TextEditingDelta( + oldText, newSelectionStart, newSelectionEnd, newComposingStart, newComposingEnd); + + assertEquals(oldText, delta.getOldText()); + assertEquals("", delta.getDeltaText()); + assertEquals(-1, delta.getDeltaStart()); + assertEquals(-1, delta.getDeltaEnd()); + assertEquals(newSelectionStart, delta.getNewSelectionStart()); + assertEquals(newSelectionEnd, delta.getNewSelectionEnd()); + assertEquals(newComposingStart, delta.getNewComposingStart()); + assertEquals(newComposingEnd, delta.getNewComposingEnd()); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/editing/TextInputPluginTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/editing/TextInputPluginTest.java new file mode 100644 index 0000000000000000000000000000000000000000..8276b3fdf99e72f73449013db13cd92e7db90b4e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/editing/TextInputPluginTest.java @@ -0,0 +1,2827 @@ +package io.flutter.plugin.editing; + +import static io.flutter.Build.API_LEVELS; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.AdditionalMatchers.aryEq; +import static org.mockito.AdditionalMatchers.gt; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.isNotNull; +import static org.mockito.Mockito.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.annotation.TargetApi; +import android.app.Activity; +import android.content.Context; +import android.content.res.AssetManager; +import android.graphics.Insets; +import android.graphics.Rect; +import android.os.Build; +import android.os.Bundle; +import android.provider.Settings; +import android.text.InputType; +import android.text.Selection; +import android.util.SparseArray; +import android.util.SparseIntArray; +import android.view.KeyEvent; +import android.view.View; +import android.view.ViewStructure; +import android.view.WindowInsets; +import android.view.WindowInsetsAnimation; +import android.view.autofill.AutofillManager; +import android.view.autofill.AutofillValue; +import android.view.inputmethod.CursorAnchorInfo; +import android.view.inputmethod.EditorInfo; +import android.view.inputmethod.InputConnection; +import android.view.inputmethod.InputMethodManager; +import android.view.inputmethod.InputMethodSubtype; +import androidx.core.view.inputmethod.EditorInfoCompat; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.android.FlutterView; +import io.flutter.embedding.android.KeyboardManager; +import io.flutter.embedding.engine.FlutterEngine; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.dart.DartExecutor; +import io.flutter.embedding.engine.loader.FlutterLoader; +import io.flutter.embedding.engine.renderer.FlutterRenderer; +import io.flutter.embedding.engine.systemchannels.ScribeChannel; +import io.flutter.embedding.engine.systemchannels.TextInputChannel; +import io.flutter.embedding.engine.systemchannels.TextInputChannel.TextEditState; +import io.flutter.plugin.common.BinaryMessenger; +import io.flutter.plugin.common.JSONMethodCodec; +import io.flutter.plugin.common.MethodCall; +import io.flutter.plugin.platform.PlatformViewsController; +import io.flutter.plugin.platform.PlatformViewsController2; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.robolectric.Robolectric; +import org.robolectric.annotation.Config; +import org.robolectric.annotation.Implementation; +import org.robolectric.annotation.Implements; +import org.robolectric.shadow.api.Shadow; +import org.robolectric.shadows.ShadowAutofillManager; +import org.robolectric.shadows.ShadowBuild; +import org.robolectric.shadows.ShadowInputMethodManager; + +@Config( + manifest = Config.NONE, + shadows = {TextInputPluginTest.TestImm.class, TextInputPluginTest.TestAfm.class}) +@RunWith(AndroidJUnit4.class) +public class TextInputPluginTest { + private final Context ctx = ApplicationProvider.getApplicationContext(); + @Mock FlutterJNI mockFlutterJni; + @Mock FlutterLoader mockFlutterLoader; + + @Before + public void setUp() { + MockitoAnnotations.openMocks(this); + when(mockFlutterJni.isAttached()).thenReturn(true); + } + + // Verifies the method and arguments for a captured method call. + private void verifyMethodCall(ByteBuffer buffer, String methodName, String[] expectedArgs) + throws JSONException { + buffer.rewind(); + MethodCall methodCall = JSONMethodCodec.INSTANCE.decodeMethodCall(buffer); + assertEquals(methodName, methodCall.method); + if (expectedArgs != null) { + JSONArray args = methodCall.arguments(); + assertEquals(expectedArgs.length, args.length()); + for (int i = 0; i < args.length(); i++) { + assertEquals(expectedArgs[i], args.get(i).toString()); + } + } + } + + private static void sendToBinaryMessageHandler( + BinaryMessenger.BinaryMessageHandler binaryMessageHandler, String method, Object args) { + MethodCall methodCall = new MethodCall(method, args); + ByteBuffer encodedMethodCall = JSONMethodCodec.INSTANCE.encodeMethodCall(methodCall); + binaryMessageHandler.onMessage( + (ByteBuffer) encodedMethodCall.flip(), mock(BinaryMessenger.BinaryReply.class)); + } + + @SuppressWarnings("deprecation") + // DartExecutor.send is deprecated. + @Test + public void textInputPlugin_RequestsReattachOnCreation() throws JSONException { + // Initialize a general TextInputPlugin. + InputMethodSubtype inputMethodSubtype = mock(InputMethodSubtype.class); + TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); + testImm.setCurrentInputMethodSubtype(inputMethodSubtype); + View testView = new View(ctx); + + FlutterJNI mockFlutterJni = mock(FlutterJNI.class); + DartExecutor dartExecutor = spy(new DartExecutor(mockFlutterJni, mock(AssetManager.class))); + TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + + ArgumentCaptor channelCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor bufferCaptor = ArgumentCaptor.forClass(ByteBuffer.class); + + verify(dartExecutor, times(1)).send(channelCaptor.capture(), bufferCaptor.capture(), isNull()); + assertEquals("flutter/textinput", channelCaptor.getValue()); + verifyMethodCall(bufferCaptor.getValue(), "TextInputClient.requestExistingInputState", null); + } + + @Test + public void setTextInputEditingState_doesNotInvokeUpdateEditingState() { + // Initialize a general TextInputPlugin. + InputMethodSubtype inputMethodSubtype = mock(InputMethodSubtype.class); + TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); + testImm.setCurrentInputMethodSubtype(inputMethodSubtype); + View testView = new View(ctx); + TextInputChannel textInputChannel = spy(new TextInputChannel(mock(DartExecutor.class))); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + textInputPlugin.setTextInputClient( + 0, + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + null, + null, + null, + null, + null, + null)); + + textInputPlugin.setTextInputEditingState( + testView, new TextInputChannel.TextEditState("initial input from framework", 0, 0, -1, -1)); + assertTrue(textInputPlugin.getEditable().toString().equals("initial input from framework")); + + verify(textInputChannel, times(0)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + + textInputPlugin.setTextInputEditingState( + testView, + new TextInputChannel.TextEditState("more update from the framework", 1, 2, -1, -1)); + + assertTrue(textInputPlugin.getEditable().toString().equals("more update from the framework")); + verify(textInputChannel, times(0)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + } + + @Test + public void setTextInputEditingState_willNotThrowWithoutSetTextInputClient() { + // Initialize a general TextInputPlugin. + InputMethodSubtype inputMethodSubtype = mock(InputMethodSubtype.class); + TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); + testImm.setCurrentInputMethodSubtype(inputMethodSubtype); + View testView = new View(ctx); + TextInputChannel textInputChannel = spy(new TextInputChannel(mock(DartExecutor.class))); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + + // Here's no textInputPlugin.setTextInputClient() + textInputPlugin.setTextInputEditingState( + testView, new TextInputChannel.TextEditState("initial input from framework", 0, 0, -1, -1)); + assertTrue(textInputPlugin.getEditable().toString().equals("initial input from framework")); + } + + @Test + public void setTextInputEditingState_doesNotInvokeUpdateEditingStateWithDeltas() { + // Initialize a general TextInputPlugin. + InputMethodSubtype inputMethodSubtype = mock(InputMethodSubtype.class); + TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); + testImm.setCurrentInputMethodSubtype(inputMethodSubtype); + View testView = new View(ctx); + TextInputChannel textInputChannel = spy(new TextInputChannel(mock(DartExecutor.class))); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + textInputPlugin.setTextInputClient( + 0, + new TextInputChannel.Configuration( + false, + false, + true, + true, + true, // Enable delta model. + TextInputChannel.TextCapitalization.NONE, + null, + null, + null, + null, + null, + null)); + + textInputPlugin.setTextInputEditingState( + testView, + new TextInputChannel.TextEditState("receiving initial input from framework", 0, 0, -1, -1)); + assertTrue( + textInputPlugin.getEditable().toString().equals("receiving initial input from framework")); + + verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); + + textInputPlugin.setTextInputEditingState( + testView, + new TextInputChannel.TextEditState( + "receiving more updates from the framework", 1, 2, -1, -1)); + + assertTrue( + textInputPlugin + .getEditable() + .toString() + .equals("receiving more updates from the framework")); + verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); + } + + @Test + public void textEditingDelta_TestUpdateEditingValueWithDeltasIsNotInvokedWhenDeltaModelDisabled() + throws NullPointerException { + // Initialize a general TextInputPlugin. + InputMethodSubtype inputMethodSubtype = mock(InputMethodSubtype.class); + TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); + testImm.setCurrentInputMethodSubtype(inputMethodSubtype); + View testView = new View(ctx); + EditorInfo outAttrs = new EditorInfo(); + outAttrs.inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE; + TextInputChannel textInputChannel = spy(new TextInputChannel(mock(DartExecutor.class))); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + CharSequence newText = "I do not fear computers. I fear the lack of them."; + + // Change InputTarget to FRAMEWORK_CLIENT. + textInputPlugin.setTextInputClient( + 0, + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, // Delta model is disabled. + TextInputChannel.TextCapitalization.NONE, + new TextInputChannel.InputType(TextInputChannel.TextInputType.TEXT, false, false), + null, + null, + null, + null, + null)); + + // There's a pending restart since we initialized the text input client. Flush that now. + textInputPlugin.setTextInputEditingState( + testView, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); + verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); + verify(textInputChannel, times(0)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + assertEquals( + 0, + ((ListenableEditingState) textInputPlugin.getEditable()) + .extractBatchTextEditingDeltas() + .size()); + + InputConnection inputConnection = + textInputPlugin.createInputConnection(testView, mock(KeyboardManager.class), outAttrs); + + inputConnection.beginBatchEdit(); + verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); + verify(textInputChannel, times(0)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + inputConnection.setComposingText(newText, newText.length()); + verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); + verify(textInputChannel, times(0)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + inputConnection.endBatchEdit(); + + assertEquals( + 0, + ((ListenableEditingState) textInputPlugin.getEditable()) + .extractBatchTextEditingDeltas() + .size()); + + verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); + verify(textInputChannel, times(1)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + + inputConnection.beginBatchEdit(); + + verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); + verify(textInputChannel, times(1)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + + inputConnection.endBatchEdit(); + + assertEquals( + 0, + ((ListenableEditingState) textInputPlugin.getEditable()) + .extractBatchTextEditingDeltas() + .size()); + + verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); + verify(textInputChannel, times(1)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + + inputConnection.beginBatchEdit(); + + verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); + verify(textInputChannel, times(1)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + + // Selection changes so this will trigger an update to the framework through + // updateEditingStateWithDeltas after the batch edit has completed and notified all listeners + // of the editing state. + inputConnection.setSelection(3, 4); + assertEquals(Selection.getSelectionStart(textInputPlugin.getEditable()), 3); + assertEquals(Selection.getSelectionEnd(textInputPlugin.getEditable()), 4); + + verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); + verify(textInputChannel, times(1)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + + verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); + verify(textInputChannel, times(1)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + + inputConnection.endBatchEdit(); + + verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); + verify(textInputChannel, times(2)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + } + + @Test + public void textEditingDelta_TestUpdateEditingValueIsNotInvokedWhenDeltaModelEnabled() + throws NullPointerException { + // Initialize a general TextInputPlugin. + InputMethodSubtype inputMethodSubtype = mock(InputMethodSubtype.class); + TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); + testImm.setCurrentInputMethodSubtype(inputMethodSubtype); + View testView = new View(ctx); + EditorInfo outAttrs = new EditorInfo(); + outAttrs.inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE; + TextInputChannel textInputChannel = spy(new TextInputChannel(mock(DartExecutor.class))); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + CharSequence newText = "I do not fear computers. I fear the lack of them."; + final TextEditingDelta expectedDelta = + new TextEditingDelta("", 0, 0, newText, newText.length(), newText.length(), 0, 49); + + // Change InputTarget to FRAMEWORK_CLIENT. + textInputPlugin.setTextInputClient( + 0, + new TextInputChannel.Configuration( + false, + false, + true, + true, + true, // Enable delta model. + TextInputChannel.TextCapitalization.NONE, + new TextInputChannel.InputType(TextInputChannel.TextInputType.TEXT, false, false), + null, + null, + null, + null, + null)); + + // There's a pending restart since we initialized the text input client. Flush that now. + textInputPlugin.setTextInputEditingState( + testView, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); + verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); + verify(textInputChannel, times(0)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + assertEquals( + 0, + ((ListenableEditingState) textInputPlugin.getEditable()) + .extractBatchTextEditingDeltas() + .size()); + + InputConnection inputConnection = + textInputPlugin.createInputConnection(testView, mock(KeyboardManager.class), outAttrs); + + inputConnection.beginBatchEdit(); + verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); + verify(textInputChannel, times(0)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + inputConnection.setComposingText(newText, newText.length()); + final ArrayList actualDeltas = + ((ListenableEditingState) textInputPlugin.getEditable()).extractBatchTextEditingDeltas(); + assertEquals(2, actualDeltas.size()); + final TextEditingDelta delta = actualDeltas.get(1); + verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); + verify(textInputChannel, times(0)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + inputConnection.endBatchEdit(); + + assertEquals( + 0, + ((ListenableEditingState) textInputPlugin.getEditable()) + .extractBatchTextEditingDeltas() + .size()); + + // Verify delta is what we expect. + assertEquals(expectedDelta.getOldText(), delta.getOldText()); + assertEquals(expectedDelta.getDeltaText(), delta.getDeltaText()); + assertEquals(expectedDelta.getDeltaStart(), delta.getDeltaStart()); + assertEquals(expectedDelta.getDeltaEnd(), delta.getDeltaEnd()); + assertEquals(expectedDelta.getNewSelectionStart(), delta.getNewSelectionStart()); + assertEquals(expectedDelta.getNewSelectionEnd(), delta.getNewSelectionEnd()); + assertEquals(expectedDelta.getNewComposingStart(), delta.getNewComposingStart()); + assertEquals(expectedDelta.getNewComposingEnd(), delta.getNewComposingEnd()); + + verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); + verify(textInputChannel, times(0)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + + inputConnection.beginBatchEdit(); + + verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); + verify(textInputChannel, times(0)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + + inputConnection.endBatchEdit(); + + assertEquals( + 0, + ((ListenableEditingState) textInputPlugin.getEditable()) + .extractBatchTextEditingDeltas() + .size()); + + verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); + verify(textInputChannel, times(0)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + + inputConnection.beginBatchEdit(); + + verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); + verify(textInputChannel, times(0)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + + // Selection changes so this will trigger an update to the framework through + // updateEditingStateWithDeltas after the batch edit has completed and notified all listeners + // of the editing state. + inputConnection.setSelection(3, 4); + assertEquals(Selection.getSelectionStart(textInputPlugin.getEditable()), 3); + assertEquals(Selection.getSelectionEnd(textInputPlugin.getEditable()), 4); + + verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); + verify(textInputChannel, times(0)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + + verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); + verify(textInputChannel, times(0)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + + inputConnection.endBatchEdit(); + + verify(textInputChannel, times(2)).updateEditingStateWithDeltas(anyInt(), any()); + verify(textInputChannel, times(0)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + } + + @Test + public void textEditingDelta_TestDeltaIsCreatedWhenComposingTextSetIsInserting() + throws NullPointerException { + // Initialize a general TextInputPlugin. + InputMethodSubtype inputMethodSubtype = mock(InputMethodSubtype.class); + TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); + testImm.setCurrentInputMethodSubtype(inputMethodSubtype); + View testView = new View(ctx); + EditorInfo outAttrs = new EditorInfo(); + outAttrs.inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE; + TextInputChannel textInputChannel = spy(new TextInputChannel(mock(DartExecutor.class))); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + CharSequence newText = "I do not fear computers. I fear the lack of them."; + final TextEditingDelta expectedDelta = + new TextEditingDelta("", 0, 0, newText, newText.length(), newText.length(), 0, 49); + + // Change InputTarget to FRAMEWORK_CLIENT. + textInputPlugin.setTextInputClient( + 0, + new TextInputChannel.Configuration( + false, + false, + true, + true, + true, // Enable delta model. + TextInputChannel.TextCapitalization.NONE, + new TextInputChannel.InputType(TextInputChannel.TextInputType.TEXT, false, false), + null, + null, + null, + null, + null)); + + // There's a pending restart since we initialized the text input client. Flush that now. + textInputPlugin.setTextInputEditingState( + testView, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); + verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); + assertEquals( + 0, + ((ListenableEditingState) textInputPlugin.getEditable()) + .extractBatchTextEditingDeltas() + .size()); + + InputConnection inputConnection = + textInputPlugin.createInputConnection(testView, mock(KeyboardManager.class), outAttrs); + + inputConnection.beginBatchEdit(); + verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); + inputConnection.setComposingText(newText, newText.length()); + final ArrayList actualDeltas = + ((ListenableEditingState) textInputPlugin.getEditable()).extractBatchTextEditingDeltas(); + assertEquals(2, actualDeltas.size()); + final TextEditingDelta delta = actualDeltas.get(1); + verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); + inputConnection.endBatchEdit(); + + assertEquals( + 0, + ((ListenableEditingState) textInputPlugin.getEditable()) + .extractBatchTextEditingDeltas() + .size()); + + // Verify delta is what we expect. + assertEquals(expectedDelta.getOldText(), delta.getOldText()); + assertEquals(expectedDelta.getDeltaText(), delta.getDeltaText()); + assertEquals(expectedDelta.getDeltaStart(), delta.getDeltaStart()); + assertEquals(expectedDelta.getDeltaEnd(), delta.getDeltaEnd()); + assertEquals(expectedDelta.getNewSelectionStart(), delta.getNewSelectionStart()); + assertEquals(expectedDelta.getNewSelectionEnd(), delta.getNewSelectionEnd()); + assertEquals(expectedDelta.getNewComposingStart(), delta.getNewComposingStart()); + assertEquals(expectedDelta.getNewComposingEnd(), delta.getNewComposingEnd()); + + verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); + + inputConnection.beginBatchEdit(); + + verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); + + inputConnection.endBatchEdit(); + + assertEquals( + 0, + ((ListenableEditingState) textInputPlugin.getEditable()) + .extractBatchTextEditingDeltas() + .size()); + + verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); + + inputConnection.beginBatchEdit(); + + verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); + + // Selection changes so this will trigger an update to the framework through + // updateEditingStateWithDeltas after the batch edit has completed and notified all listeners + // of the editing state. + inputConnection.setSelection(3, 4); + assertEquals(Selection.getSelectionStart(textInputPlugin.getEditable()), 3); + assertEquals(Selection.getSelectionEnd(textInputPlugin.getEditable()), 4); + + verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); + + verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); + + inputConnection.endBatchEdit(); + + verify(textInputChannel, times(2)).updateEditingStateWithDeltas(anyInt(), any()); + } + + @Test + public void textEditingDelta_TestDeltaIsCreatedWhenComposingTextSetIsDeleting() + throws NullPointerException { + // Initialize a general TextInputPlugin. + InputMethodSubtype inputMethodSubtype = mock(InputMethodSubtype.class); + TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); + testImm.setCurrentInputMethodSubtype(inputMethodSubtype); + View testView = new View(ctx); + EditorInfo outAttrs = new EditorInfo(); + outAttrs.inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE; + TextInputChannel textInputChannel = spy(new TextInputChannel(mock(DartExecutor.class))); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + CharSequence newText = "I do not fear computers. I fear the lack of them."; + final TextEditingDelta expectedDelta = + new TextEditingDelta( + newText, 0, 49, "I do not fear computers. I fear the lack of them", 48, 48, 0, 48); + + // Change InputTarget to FRAMEWORK_CLIENT. + textInputPlugin.setTextInputClient( + 0, + new TextInputChannel.Configuration( + false, + false, + true, + true, + true, // Enable delta model. + TextInputChannel.TextCapitalization.NONE, + new TextInputChannel.InputType(TextInputChannel.TextInputType.TEXT, false, false), + null, + null, + null, + null, + null)); + + // There's a pending restart since we initialized the text input client. Flush that now. + textInputPlugin.setTextInputEditingState( + testView, new TextInputChannel.TextEditState(newText.toString(), 49, 49, 0, 49)); + verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); + assertEquals( + 0, + ((ListenableEditingState) textInputPlugin.getEditable()) + .extractBatchTextEditingDeltas() + .size()); + + InputConnection inputConnection = + textInputPlugin.createInputConnection(testView, mock(KeyboardManager.class), outAttrs); + + inputConnection.beginBatchEdit(); + verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); + inputConnection.setComposingText("I do not fear computers. I fear the lack of them", 48); + final ArrayList actualDeltas = + ((ListenableEditingState) textInputPlugin.getEditable()).extractBatchTextEditingDeltas(); + final TextEditingDelta delta = actualDeltas.get(1); + System.out.println(delta.getDeltaText()); + verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); + inputConnection.endBatchEdit(); + + assertEquals( + 0, + ((ListenableEditingState) textInputPlugin.getEditable()) + .extractBatchTextEditingDeltas() + .size()); + + // Verify delta is what we expect. + assertEquals(expectedDelta.getOldText(), delta.getOldText()); + assertEquals(expectedDelta.getDeltaText(), delta.getDeltaText()); + assertEquals(expectedDelta.getDeltaStart(), delta.getDeltaStart()); + assertEquals(expectedDelta.getDeltaEnd(), delta.getDeltaEnd()); + assertEquals(expectedDelta.getNewSelectionStart(), delta.getNewSelectionStart()); + assertEquals(expectedDelta.getNewSelectionEnd(), delta.getNewSelectionEnd()); + assertEquals(expectedDelta.getNewComposingStart(), delta.getNewComposingStart()); + assertEquals(expectedDelta.getNewComposingEnd(), delta.getNewComposingEnd()); + + verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); + + inputConnection.beginBatchEdit(); + + verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); + + inputConnection.endBatchEdit(); + + assertEquals( + 0, + ((ListenableEditingState) textInputPlugin.getEditable()) + .extractBatchTextEditingDeltas() + .size()); + + verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); + + inputConnection.beginBatchEdit(); + + verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); + + // Selection changes so this will trigger an update to the framework through + // updateEditingStateWithDeltas after the batch edit has completed and notified all listeners + // of the editing state. + inputConnection.setSelection(3, 4); + assertEquals(Selection.getSelectionStart(textInputPlugin.getEditable()), 3); + assertEquals(Selection.getSelectionEnd(textInputPlugin.getEditable()), 4); + + verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); + + verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); + + inputConnection.endBatchEdit(); + + verify(textInputChannel, times(2)).updateEditingStateWithDeltas(anyInt(), any()); + } + + @Test + public void textEditingDelta_TestDeltaIsCreatedWhenComposingTextSetIsReplacing() + throws NullPointerException { + // Initialize a general TextInputPlugin. + InputMethodSubtype inputMethodSubtype = mock(InputMethodSubtype.class); + TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); + testImm.setCurrentInputMethodSubtype(inputMethodSubtype); + View testView = new View(ctx); + EditorInfo outAttrs = new EditorInfo(); + outAttrs.inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE; + TextInputChannel textInputChannel = spy(new TextInputChannel(mock(DartExecutor.class))); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + CharSequence newText = "helfo"; + final TextEditingDelta expectedDelta = new TextEditingDelta(newText, 0, 5, "hello", 5, 5, 0, 5); + + // Change InputTarget to FRAMEWORK_CLIENT. + textInputPlugin.setTextInputClient( + 0, + new TextInputChannel.Configuration( + false, + false, + true, + true, + true, // Enable delta model. + TextInputChannel.TextCapitalization.NONE, + new TextInputChannel.InputType(TextInputChannel.TextInputType.TEXT, false, false), + null, + null, + null, + null, + null)); + + // There's a pending restart since we initialized the text input client. Flush that now. + textInputPlugin.setTextInputEditingState( + testView, new TextInputChannel.TextEditState(newText.toString(), 5, 5, 0, 5)); + verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); + assertEquals( + 0, + ((ListenableEditingState) textInputPlugin.getEditable()) + .extractBatchTextEditingDeltas() + .size()); + + InputConnection inputConnection = + textInputPlugin.createInputConnection(testView, mock(KeyboardManager.class), outAttrs); + + inputConnection.beginBatchEdit(); + verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); + inputConnection.setComposingText("hello", 5); + final ArrayList actualDeltas = + ((ListenableEditingState) textInputPlugin.getEditable()).extractBatchTextEditingDeltas(); + final TextEditingDelta delta = actualDeltas.get(1); + System.out.println(delta.getDeltaText()); + verify(textInputChannel, times(0)).updateEditingStateWithDeltas(anyInt(), any()); + inputConnection.endBatchEdit(); + + assertEquals( + 0, + ((ListenableEditingState) textInputPlugin.getEditable()) + .extractBatchTextEditingDeltas() + .size()); + + // Verify delta is what we expect. + assertEquals(expectedDelta.getOldText(), delta.getOldText()); + assertEquals(expectedDelta.getDeltaText(), delta.getDeltaText()); + assertEquals(expectedDelta.getDeltaStart(), delta.getDeltaStart()); + assertEquals(expectedDelta.getDeltaEnd(), delta.getDeltaEnd()); + assertEquals(expectedDelta.getNewSelectionStart(), delta.getNewSelectionStart()); + assertEquals(expectedDelta.getNewSelectionEnd(), delta.getNewSelectionEnd()); + assertEquals(expectedDelta.getNewComposingStart(), delta.getNewComposingStart()); + assertEquals(expectedDelta.getNewComposingEnd(), delta.getNewComposingEnd()); + + verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); + + inputConnection.beginBatchEdit(); + + verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); + + inputConnection.endBatchEdit(); + + assertEquals( + 0, + ((ListenableEditingState) textInputPlugin.getEditable()) + .extractBatchTextEditingDeltas() + .size()); + + verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); + + inputConnection.beginBatchEdit(); + + verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); + + // Selection changes so this will trigger an update to the framework through + // updateEditingStateWithDeltas after the batch edit has completed and notified all listeners + // of the editing state. + inputConnection.setSelection(3, 4); + assertEquals(Selection.getSelectionStart(textInputPlugin.getEditable()), 3); + assertEquals(Selection.getSelectionEnd(textInputPlugin.getEditable()), 4); + + verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); + + verify(textInputChannel, times(1)).updateEditingStateWithDeltas(anyInt(), any()); + + inputConnection.endBatchEdit(); + + verify(textInputChannel, times(2)).updateEditingStateWithDeltas(anyInt(), any()); + } + + @Test + public void inputConnectionAdaptor_RepeatFilter() throws NullPointerException { + // Initialize a general TextInputPlugin. + InputMethodSubtype inputMethodSubtype = mock(InputMethodSubtype.class); + TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); + testImm.setCurrentInputMethodSubtype(inputMethodSubtype); + View testView = new View(ctx); + EditorInfo outAttrs = new EditorInfo(); + outAttrs.inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE; + TextInputChannel textInputChannel = spy(new TextInputChannel(mock(DartExecutor.class))); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + + // Change InputTarget to FRAMEWORK_CLIENT. + textInputPlugin.setTextInputClient( + 0, + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + new TextInputChannel.InputType(TextInputChannel.TextInputType.TEXT, false, false), + null, + null, + null, + null, + null)); + + // There's a pending restart since we initialized the text input client. Flush that now. + textInputPlugin.setTextInputEditingState( + testView, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); + verify(textInputChannel, times(0)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + + InputConnectionAdaptor inputConnectionAdaptor = + (InputConnectionAdaptor) + textInputPlugin.createInputConnection(testView, mock(KeyboardManager.class), outAttrs); + + inputConnectionAdaptor.beginBatchEdit(); + verify(textInputChannel, times(0)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + inputConnectionAdaptor.setComposingText("I do not fear computers. I fear the lack of them.", 1); + verify(textInputChannel, times(0)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + inputConnectionAdaptor.endBatchEdit(); + verify(textInputChannel, times(1)) + .updateEditingState( + anyInt(), + eq("I do not fear computers. I fear the lack of them."), + eq(49), + eq(49), + eq(0), + eq(49)); + + inputConnectionAdaptor.beginBatchEdit(); + + verify(textInputChannel, times(1)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + + inputConnectionAdaptor.endBatchEdit(); + + verify(textInputChannel, times(1)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + + inputConnectionAdaptor.beginBatchEdit(); + + verify(textInputChannel, times(1)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + + inputConnectionAdaptor.setSelection(3, 4); + assertEquals(Selection.getSelectionStart(textInputPlugin.getEditable()), 3); + assertEquals(Selection.getSelectionEnd(textInputPlugin.getEditable()), 4); + + verify(textInputChannel, times(1)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + + verify(textInputChannel, times(1)) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + + inputConnectionAdaptor.endBatchEdit(); + + verify(textInputChannel, times(1)) + .updateEditingState( + anyInt(), + eq("I do not fear computers. I fear the lack of them."), + eq(3), + eq(4), + eq(0), + eq(49)); + } + + @Test + public void setTextInputEditingState_doesNotRestartWhenTextIsIdentical() { + // Initialize a general TextInputPlugin. + InputMethodSubtype inputMethodSubtype = mock(InputMethodSubtype.class); + TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); + testImm.setCurrentInputMethodSubtype(inputMethodSubtype); + View testView = new View(ctx); + TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + textInputPlugin.setTextInputClient( + 0, + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + null, + null, + null, + null, + null, + null)); + // There's a pending restart since we initialized the text input client. Flush that now. + textInputPlugin.setTextInputEditingState( + testView, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); + + // Move the cursor. + assertEquals(1, testImm.getRestartCount(testView)); + textInputPlugin.setTextInputEditingState( + testView, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); + + // Verify that we haven't restarted the input. + assertEquals(1, testImm.getRestartCount(testView)); + } + + @Test + public void setTextInputEditingState_alwaysSetEditableWhenDifferent() { + // Initialize a general TextInputPlugin. + InputMethodSubtype inputMethodSubtype = mock(InputMethodSubtype.class); + TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); + testImm.setCurrentInputMethodSubtype(inputMethodSubtype); + View testView = new View(ctx); + TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + textInputPlugin.setTextInputClient( + 0, + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + null, + null, + null, + null, + null, + null)); + // There's a pending restart since we initialized the text input client. Flush that now. With + // changed text, we should + // always set the Editable contents. + textInputPlugin.setTextInputEditingState( + testView, new TextInputChannel.TextEditState("hello", 0, 0, -1, -1)); + assertEquals(1, testImm.getRestartCount(testView)); + assertTrue(textInputPlugin.getEditable().toString().equals("hello")); + + // No pending restart, set Editable contents anyways. + textInputPlugin.setTextInputEditingState( + testView, new TextInputChannel.TextEditState("Shibuyawoo", 0, 0, -1, -1)); + assertEquals(1, testImm.getRestartCount(testView)); + assertTrue(textInputPlugin.getEditable().toString().equals("Shibuyawoo")); + } + + // See https://github.com/flutter/flutter/issues/29341 and + // https://github.com/flutter/flutter/issues/31512 + // All modern Samsung keybords are affected including non-korean languages and thus + // need the restart. + // Update: many other keyboards need this too: + // https://github.com/flutter/flutter/issues/78827 + @SuppressWarnings("deprecation") // InputMethodSubtype + @Test + public void setTextInputEditingState_restartsIMEOnlyWhenFrameworkChangesComposingRegion() { + // Initialize a TextInputPlugin that needs to be always restarted. + InputMethodSubtype inputMethodSubtype = + new InputMethodSubtype(0, 0, /*locale=*/ "en", "", "", false, false); + TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); + testImm.setCurrentInputMethodSubtype(inputMethodSubtype); + View testView = new View(ctx); + TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + textInputPlugin.setTextInputClient( + 0, + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + new TextInputChannel.InputType(TextInputChannel.TextInputType.TEXT, false, false), + null, + null, + null, + null, + null)); + // There's a pending restart since we initialized the text input client. Flush that now. + textInputPlugin.setTextInputEditingState( + testView, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); + assertEquals(1, testImm.getRestartCount(testView)); + InputConnection connection = + textInputPlugin.createInputConnection( + testView, mock(KeyboardManager.class), new EditorInfo()); + connection.setComposingText("POWERRRRR", 1); + + textInputPlugin.setTextInputEditingState( + testView, new TextInputChannel.TextEditState("UNLIMITED POWERRRRR", 0, 0, 10, 19)); + // Does not restart since the composing text is not changed. + assertEquals(1, testImm.getRestartCount(testView)); + + connection.finishComposingText(); + // Does not restart since the composing text is committed by the IME. + assertEquals(1, testImm.getRestartCount(testView)); + + // Does not restart since the composing text is changed by the IME. + connection.setComposingText("POWERRRRR", 1); + assertEquals(1, testImm.getRestartCount(testView)); + + // The framework tries to commit the composing region. + textInputPlugin.setTextInputEditingState( + testView, new TextInputChannel.TextEditState("POWERRRRR", 0, 0, -1, -1)); + + // Verify that we've restarted the input. + assertEquals(2, testImm.getRestartCount(testView)); + } + + @Test + public void TextEditState_throwsOnInvalidStatesReceived() { + // Index OOB: + assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("", 0, -9, -1, -1)); + assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("", -9, 0, -1, -1)); + assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("", 0, 1, -1, -1)); + assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("", 1, 0, -1, -1)); + assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("Text", 0, 0, 1, 5)); + assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("Text", 0, 0, 5, 1)); + assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("Text", 0, 0, 5, 5)); + + // Invalid Selections: + assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("", -1, -2, -1, -1)); + assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("", -2, -1, -1, -1)); + assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("", -9, -9, -1, -1)); + + // Invalid Composing Ranges: + assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("Text", 0, 0, -9, -1)); + assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("Text", 0, 0, -1, -9)); + assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("Text", 0, 0, -9, -9)); + assertThrows(IndexOutOfBoundsException.class, () -> new TextEditState("Text", 0, 0, 2, 1)); + + // Valid values (does not throw): + // Nothing selected/composing: + TextEditState state = new TextEditState("", -1, -1, -1, -1); + assertEquals("", state.text); + assertEquals(-1, state.selectionStart); + assertEquals(-1, state.selectionEnd); + assertEquals(-1, state.composingStart); + assertEquals(-1, state.composingEnd); + // Collapsed selection. + state = new TextEditState("x", 0, 0, 0, 1); + assertEquals(0, state.selectionStart); + assertEquals(0, state.selectionEnd); + // Reversed Selection. + state = new TextEditState("REEEE", 4, 2, -1, -1); + assertEquals(4, state.selectionStart); + assertEquals(2, state.selectionEnd); + // A collapsed selection and composing range. + state = new TextEditState("text", 0, 0, 0, 0); + assertEquals("text", state.text); + assertEquals(0, state.selectionStart); + assertEquals(0, state.selectionEnd); + assertEquals(0, state.composingStart); + assertEquals(0, state.composingEnd); + } + + @Test + public void setTextInputEditingState_nullInputMethodSubtype() { + TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); + testImm.setCurrentInputMethodSubtype(null); + + View testView = new View(ctx); + TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + textInputPlugin.setTextInputClient( + 0, + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + null, + null, + null, + null, + null, + null)); + // There's a pending restart since we initialized the text input client. Flush that now. + textInputPlugin.setTextInputEditingState( + testView, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); + assertEquals(1, testImm.getRestartCount(testView)); + } + + @Test + public void destroy_clearTextInputMethodHandler() { + View testView = new View(ctx); + TextInputChannel textInputChannel = spy(new TextInputChannel(mock(DartExecutor.class))); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + verify(textInputChannel, times(1)).setTextInputMethodHandler(isNotNull()); + textInputPlugin.destroy(); + verify(textInputChannel, times(1)).setTextInputMethodHandler(isNull()); + } + + @SuppressWarnings("deprecation") + // DartExecutor.send is deprecated. + private void verifyInputConnection(TextInputChannel.TextInputType textInputType) + throws JSONException { + TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); + FlutterJNI mockFlutterJni = mock(FlutterJNI.class); + View testView = new View(ctx); + DartExecutor dartExecutor = spy(new DartExecutor(mockFlutterJni, mock(AssetManager.class))); + TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + textInputPlugin.setTextInputClient( + 0, + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + new TextInputChannel.InputType(textInputType, false, false), + null, + null, + null, + null, + null)); + // There's a pending restart since we initialized the text input client. Flush that now. + textInputPlugin.setTextInputEditingState( + testView, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); + + ArgumentCaptor channelCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor bufferCaptor = ArgumentCaptor.forClass(ByteBuffer.class); + verify(dartExecutor, times(1)).send(channelCaptor.capture(), bufferCaptor.capture(), isNull()); + assertEquals("flutter/textinput", channelCaptor.getValue()); + verifyMethodCall(bufferCaptor.getValue(), "TextInputClient.requestExistingInputState", null); + InputConnectionAdaptor connection = + (InputConnectionAdaptor) + textInputPlugin.createInputConnection( + testView, mock(KeyboardManager.class), new EditorInfo()); + + connection.handleKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER)); + verify(dartExecutor, times(2)).send(channelCaptor.capture(), bufferCaptor.capture(), isNull()); + assertEquals("flutter/textinput", channelCaptor.getValue()); + verifyMethodCall( + bufferCaptor.getValue(), + "TextInputClient.performAction", + new String[] {"0", "TextInputAction.done"}); + connection.handleKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER)); + + connection.handleKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_NUMPAD_ENTER)); + verify(dartExecutor, times(3)).send(channelCaptor.capture(), bufferCaptor.capture(), isNull()); + assertEquals("flutter/textinput", channelCaptor.getValue()); + verifyMethodCall( + bufferCaptor.getValue(), + "TextInputClient.performAction", + new String[] {"0", "TextInputAction.done"}); + } + + @Test + public void inputConnection_createsActionFromEnter() throws JSONException { + verifyInputConnection(TextInputChannel.TextInputType.TEXT); + } + + @Test + public void inputConnection_respondsToKeyEvents_textInputTypeNone() throws JSONException { + verifyInputConnection(TextInputChannel.TextInputType.NONE); + } + + @SuppressWarnings("deprecation") // InputMethodSubtype + @Test + public void inputConnection_finishComposingTextUpdatesIMM() throws JSONException { + ShadowBuild.setManufacturer("samsung"); + InputMethodSubtype inputMethodSubtype = + new InputMethodSubtype(0, 0, /*locale=*/ "en", "", "", false, false); + Settings.Secure.putString( + ctx.getContentResolver(), + Settings.Secure.DEFAULT_INPUT_METHOD, + "com.sec.android.inputmethod/.SamsungKeypad"); + TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); + testImm.setCurrentInputMethodSubtype(inputMethodSubtype); + FlutterJNI mockFlutterJni = mock(FlutterJNI.class); + View testView = new View(ctx); + DartExecutor dartExecutor = spy(new DartExecutor(mockFlutterJni, mock(AssetManager.class))); + TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + textInputPlugin.setTextInputClient( + 0, + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + new TextInputChannel.InputType(TextInputChannel.TextInputType.TEXT, false, false), + null, + null, + null, + null, + null)); + // There's a pending restart since we initialized the text input client. Flush that now. + textInputPlugin.setTextInputEditingState( + testView, new TextInputChannel.TextEditState("text", 0, 0, -1, -1)); + InputConnection connection = + textInputPlugin.createInputConnection( + testView, mock(KeyboardManager.class), new EditorInfo()); + + connection.requestCursorUpdates( + InputConnection.CURSOR_UPDATE_MONITOR | InputConnection.CURSOR_UPDATE_IMMEDIATE); + + connection.finishComposingText(); + + assertEquals(-1, testImm.getLastCursorAnchorInfo().getComposingTextStart()); + assertEquals(0, testImm.getLastCursorAnchorInfo().getComposingText().length()); + } + + @Test + public void inputConnection_textInputTypeNone() { + View testView = new View(ctx); + DartExecutor dartExecutor = mock(DartExecutor.class); + TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + textInputPlugin.setTextInputClient( + 0, + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + new TextInputChannel.InputType(TextInputChannel.TextInputType.NONE, false, false), + null, + null, + null, + null, + null)); + + InputConnection connection = + textInputPlugin.createInputConnection( + testView, mock(KeyboardManager.class), new EditorInfo()); + assertNotNull(connection); + } + + @Test + public void showTextInput_textInputTypeNone() { + TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); + View testView = new View(ctx); + DartExecutor dartExecutor = mock(DartExecutor.class); + TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + textInputPlugin.setTextInputClient( + 0, + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + new TextInputChannel.InputType(TextInputChannel.TextInputType.NONE, false, false), + null, + null, + null, + null, + null)); + + textInputPlugin.showTextInput(testView); + assertEquals(testImm.isSoftInputVisible(), false); + } + + @Test + public void showTextInput_textInputTypeWebSearch() { + TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); + View testView = new View(ctx); + DartExecutor dartExecutor = mock(DartExecutor.class); + TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + textInputPlugin.setTextInputClient( + 0, + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + new TextInputChannel.InputType(TextInputChannel.TextInputType.WEB_SEARCH, false, false), + null, + null, + null, + null, + null)); + + EditorInfo editorInfo = new EditorInfo(); + InputConnection connection = + textInputPlugin.createInputConnection(testView, mock(KeyboardManager.class), editorInfo); + + assertEquals( + editorInfo.inputType, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI); + } + + @Test + public void showTextInput_textInputTypeTwitter() { + TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); + View testView = new View(ctx); + DartExecutor dartExecutor = mock(DartExecutor.class); + TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + textInputPlugin.setTextInputClient( + 0, + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + new TextInputChannel.InputType(TextInputChannel.TextInputType.TWITTER, false, false), + null, + null, + null, + null, + null)); + + EditorInfo editorInfo = new EditorInfo(); + InputConnection connection = + textInputPlugin.createInputConnection(testView, mock(KeyboardManager.class), editorInfo); + + assertEquals( + editorInfo.inputType, + InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS); + } + + @Test + public void inputConnection_textInputTypeMultilineAndSuggestionsDisabled() { + // Regression test for https://github.com/flutter/flutter/issues/71679. + View testView = new View(ctx); + DartExecutor dartExecutor = mock(DartExecutor.class); + TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + textInputPlugin.setTextInputClient( + 0, + new TextInputChannel.Configuration( + false, + false, + false, // Disable suggestions. + true, + false, + TextInputChannel.TextCapitalization.NONE, + new TextInputChannel.InputType(TextInputChannel.TextInputType.MULTILINE, false, false), + null, + null, + null, + null, + null)); + + EditorInfo editorInfo = new EditorInfo(); + InputConnection connection = + textInputPlugin.createInputConnection(testView, mock(KeyboardManager.class), editorInfo); + + assertEquals( + editorInfo.inputType, + InputType.TYPE_CLASS_TEXT + | InputType.TYPE_TEXT_FLAG_MULTI_LINE + | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS + | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); + } + + @Config(minSdk = API_LEVELS.API_34) + @TargetApi(API_LEVELS.API_34) + @Test + public void inputConnection_setsStylusHandwritingAvailable() { + View testView = new View(ctx); + DartExecutor dartExecutor = mock(DartExecutor.class); + TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + textInputPlugin.setTextInputClient( + 0, + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + new TextInputChannel.InputType(TextInputChannel.TextInputType.MULTILINE, false, false), + null, + null, + null, + null, + null)); + + EditorInfo editorInfo = new EditorInfo(); + InputConnection connection = + textInputPlugin.createInputConnection(testView, mock(KeyboardManager.class), editorInfo); + + assertTrue(EditorInfoCompat.isStylusHandwritingEnabled(editorInfo)); + } + + @Config(sdk = API_LEVELS.API_32) + @TargetApi(API_LEVELS.API_32) + @Test + public void inputConnection_doesNotcallSetsStylusHandwritingAvailableWhenAPILevelUnsupported() { + View testView = new View(ctx); + DartExecutor dartExecutor = mock(DartExecutor.class); + TextInputChannel textInputChannel = new TextInputChannel(dartExecutor); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + textInputPlugin.setTextInputClient( + 0, + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + new TextInputChannel.InputType(TextInputChannel.TextInputType.MULTILINE, false, false), + null, + null, + null, + null, + null)); + + EditorInfo editorInfo = new EditorInfo(); + InputConnection connection = + textInputPlugin.createInputConnection(testView, mock(KeyboardManager.class), editorInfo); + + assertFalse(EditorInfoCompat.isStylusHandwritingEnabled(editorInfo)); + } + + // -------- Start: Autofill Tests ------- + @Test + public void autofill_enabledByDefault() { + if (Build.VERSION.SDK_INT < API_LEVELS.API_26) { + return; + } + FlutterView testView = new FlutterView(ctx); + TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + final TextInputChannel.Configuration.Autofill autofill = + new TextInputChannel.Configuration.Autofill( + "1", new String[] {}, null, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); + + final TextInputChannel.Configuration config = + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + null, + null, + null, + autofill, + null, + null); + + textInputPlugin.setTextInputClient( + 0, + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + null, + null, + null, + autofill, + null, + new TextInputChannel.Configuration[] {config})); + + final ViewStructure viewStructure = mock(ViewStructure.class); + final ViewStructure[] children = {mock(ViewStructure.class), mock(ViewStructure.class)}; + + when(viewStructure.newChild(anyInt())) + .thenAnswer(invocation -> children[(int) invocation.getArgument(0)]); + + textInputPlugin.onProvideAutofillVirtualStructure(viewStructure, 0); + + verify(viewStructure).newChild(0); + + verify(children[0]).setAutofillId(any(), eq("1".hashCode())); + // The flutter application sends an empty hint list, don't set hints. + verify(children[0], never()).setAutofillHints(aryEq(new String[] {})); + verify(children[0]).setDimens(anyInt(), anyInt(), anyInt(), anyInt(), gt(0), gt(0)); + } + + @Test + public void autofill_canBeDisabled() { + if (Build.VERSION.SDK_INT < API_LEVELS.API_26) { + return; + } + FlutterView testView = new FlutterView(ctx); + TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + final TextInputChannel.Configuration.Autofill autofill = + new TextInputChannel.Configuration.Autofill( + "1", new String[] {}, null, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); + + final TextInputChannel.Configuration config = + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + null, + null, + null, + null, + null, + null); + + textInputPlugin.setTextInputClient(0, config); + + final ViewStructure viewStructure = mock(ViewStructure.class); + + textInputPlugin.onProvideAutofillVirtualStructure(viewStructure, 0); + + verify(viewStructure, times(0)).newChild(anyInt()); + } + + @Test + public void autofill_hintText() { + if (Build.VERSION.SDK_INT < API_LEVELS.API_26) { + return; + } + FlutterView testView = new FlutterView(ctx); + TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + final TextInputChannel.Configuration.Autofill autofill = + new TextInputChannel.Configuration.Autofill( + "1", + new String[] {}, + "placeholder", + new TextInputChannel.TextEditState("", 0, 0, -1, -1)); + + final TextInputChannel.Configuration config = + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + null, + null, + null, + autofill, + null, + null); + + textInputPlugin.setTextInputClient(0, config); + + final ViewStructure viewStructure = mock(ViewStructure.class); + final ViewStructure[] children = {mock(ViewStructure.class), mock(ViewStructure.class)}; + + when(viewStructure.newChild(anyInt())) + .thenAnswer(invocation -> children[(int) invocation.getArgument(0)]); + + textInputPlugin.onProvideAutofillVirtualStructure(viewStructure, 0); + verify(children[0]).setHint("placeholder"); + } + + @Config(minSdk = API_LEVELS.API_26) + @SuppressWarnings("deprecation") + @Test + public void autofill_onProvideVirtualViewStructure() { + if (Build.VERSION.SDK_INT < API_LEVELS.API_26) { + return; + } + FlutterView testView = getTestView(); + TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + final TextInputChannel.Configuration.Autofill autofill1 = + new TextInputChannel.Configuration.Autofill( + "1", + new String[] {"HINT1"}, + "placeholder1", + new TextInputChannel.TextEditState("", 0, 0, -1, -1)); + final TextInputChannel.Configuration.Autofill autofill2 = + new TextInputChannel.Configuration.Autofill( + "2", + new String[] {"HINT2", "EXTRA"}, + null, + new TextInputChannel.TextEditState("", 0, 0, -1, -1)); + + final TextInputChannel.Configuration config1 = + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + null, + null, + null, + autofill1, + null, + null); + final TextInputChannel.Configuration config2 = + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + null, + null, + null, + autofill2, + null, + null); + + textInputPlugin.setTextInputClient( + 0, + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + null, + null, + null, + autofill1, + null, + new TextInputChannel.Configuration[] {config1, config2})); + + final ViewStructure viewStructure = mock(ViewStructure.class); + final ViewStructure[] children = {mock(ViewStructure.class), mock(ViewStructure.class)}; + + when(viewStructure.newChild(anyInt())) + .thenAnswer(invocation -> children[(int) invocation.getArgument(0)]); + + textInputPlugin.onProvideAutofillVirtualStructure(viewStructure, 0); + + verify(viewStructure).newChild(0); + verify(viewStructure).newChild(1); + + verify(children[0]).setAutofillId(any(), eq("1".hashCode())); + verify(children[0]).setAutofillHints(aryEq(new String[] {"HINT1"})); + verify(children[0]).setDimens(anyInt(), anyInt(), anyInt(), anyInt(), gt(0), gt(0)); + verify(children[0]).setHint("placeholder1"); + + verify(children[1]).setAutofillId(any(), eq("2".hashCode())); + verify(children[1]).setAutofillHints(aryEq(new String[] {"HINT2", "EXTRA"})); + verify(children[1]).setDimens(anyInt(), anyInt(), anyInt(), anyInt(), gt(0), gt(0)); + verify(children[1], times(0)).setHint(any()); + } + + @SuppressWarnings("deprecation") + @Config(minSdk = API_LEVELS.API_26) + @Test + public void autofill_onProvideVirtualViewStructure_singular_textfield() { + if (Build.VERSION.SDK_INT < API_LEVELS.API_26) { + return; + } + // Migrate to ActivityScenario by following https://github.com/robolectric/robolectric/pull/4736 + FlutterView testView = getTestView(); + TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + final TextInputChannel.Configuration.Autofill autofill = + new TextInputChannel.Configuration.Autofill( + "1", + new String[] {"HINT1"}, + "placeholder", + new TextInputChannel.TextEditState("", 0, 0, -1, -1)); + + // Autofill should still work without AutofillGroup. + textInputPlugin.setTextInputClient( + 0, + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + null, + null, + null, + autofill, + null, + null)); + + final ViewStructure viewStructure = mock(ViewStructure.class); + final ViewStructure[] children = {mock(ViewStructure.class)}; + + when(viewStructure.newChild(anyInt())) + .thenAnswer(invocation -> children[(int) invocation.getArgument(0)]); + + textInputPlugin.onProvideAutofillVirtualStructure(viewStructure, 0); + + verify(viewStructure).newChild(0); + + verify(children[0]).setAutofillId(any(), eq("1".hashCode())); + verify(children[0]).setAutofillHints(aryEq(new String[] {"HINT1"})); + verify(children[0]).setHint("placeholder"); + // Verifies that the child has a non-zero size. + verify(children[0]).setDimens(anyInt(), anyInt(), anyInt(), anyInt(), gt(0), gt(0)); + } + + @Config(minSdk = API_LEVELS.API_26) + @Test + public void autofill_testLifeCycle() { + if (Build.VERSION.SDK_INT < API_LEVELS.API_26) { + return; + } + + TestAfm testAfm = Shadow.extract(ctx.getSystemService(AutofillManager.class)); + FlutterView testView = getTestView(); + TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + + // Set up an autofill scenario with 2 fields. + final TextInputChannel.Configuration.Autofill autofill1 = + new TextInputChannel.Configuration.Autofill( + "1", + new String[] {"HINT1"}, + "placeholder1", + new TextInputChannel.TextEditState("", 0, 0, -1, -1)); + final TextInputChannel.Configuration.Autofill autofill2 = + new TextInputChannel.Configuration.Autofill( + "2", + new String[] {"HINT2", "EXTRA"}, + null, + new TextInputChannel.TextEditState("", 0, 0, -1, -1)); + + final TextInputChannel.Configuration config1 = + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + null, + null, + null, + autofill1, + null, + null); + final TextInputChannel.Configuration config2 = + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + null, + null, + null, + autofill2, + null, + null); + + // Set client. This should call notifyViewExited on the FlutterView if the previous client is + // also eligible for autofill. + final TextInputChannel.Configuration autofillConfiguration = + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + null, + null, + null, + autofill1, + null, + new TextInputChannel.Configuration[] {config1, config2}); + + textInputPlugin.setTextInputClient(0, autofillConfiguration); + + // notifyViewExited should not be called as this is the first client we set. + assertEquals(testAfm.empty, testAfm.exitId); + + // The framework updates the text, call notifyValueChanged. + textInputPlugin.setTextInputEditingState( + testView, new TextInputChannel.TextEditState("new text", -1, -1, -1, -1)); + assertEquals("new text", testAfm.changeString); + assertEquals("1".hashCode(), testAfm.changeVirtualId); + + // The input method updates the text, call notifyValueChanged. + testAfm.resetStates(); + final KeyboardManager mockKeyboardManager = mock(KeyboardManager.class); + InputConnectionAdaptor adaptor = + new InputConnectionAdaptor( + testView, + 0, + mock(TextInputChannel.class), + mock(ScribeChannel.class), + mockKeyboardManager, + (ListenableEditingState) textInputPlugin.getEditable(), + new EditorInfo()); + adaptor.commitText("input from IME ", 1); + + assertEquals("input from IME new text", testAfm.changeString); + assertEquals("1".hashCode(), testAfm.changeVirtualId); + + // notifyViewExited should be called on the previous client. + testAfm.resetStates(); + textInputPlugin.setTextInputClient( + 1, + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + null, + null, + null, + null, + null, + null)); + + assertEquals("1".hashCode(), testAfm.exitId); + + // TextInputPlugin#clearTextInputClient calls notifyViewExited. + testAfm.resetStates(); + textInputPlugin.setTextInputClient(3, autofillConfiguration); + assertEquals(testAfm.empty, testAfm.exitId); + textInputPlugin.clearTextInputClient(); + assertEquals("1".hashCode(), testAfm.exitId); + + // TextInputPlugin#destroy calls notifyViewExited. + testAfm.resetStates(); + textInputPlugin.setTextInputClient(4, autofillConfiguration); + assertEquals(testAfm.empty, testAfm.exitId); + textInputPlugin.destroy(); + assertEquals("1".hashCode(), testAfm.exitId); + } + + @Config(minSdk = API_LEVELS.API_26) + @SuppressWarnings("deprecation") + @Test + public void autofill_testAutofillUpdatesTheFramework() { + if (Build.VERSION.SDK_INT < API_LEVELS.API_26) { + return; + } + + TestAfm testAfm = Shadow.extract(ctx.getSystemService(AutofillManager.class)); + FlutterView testView = getTestView(); + TextInputChannel textInputChannel = spy(new TextInputChannel(mock(DartExecutor.class))); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + + // Set up an autofill scenario with 2 fields. + final TextInputChannel.Configuration.Autofill autofill1 = + new TextInputChannel.Configuration.Autofill( + "1", + new String[] {"HINT1"}, + null, + new TextInputChannel.TextEditState("field 1", 0, 0, -1, -1)); + final TextInputChannel.Configuration.Autofill autofill2 = + new TextInputChannel.Configuration.Autofill( + "2", + new String[] {"HINT2", "EXTRA"}, + null, + new TextInputChannel.TextEditState("field 2", 0, 0, -1, -1)); + + final TextInputChannel.Configuration config1 = + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + null, + null, + null, + autofill1, + null, + null); + final TextInputChannel.Configuration config2 = + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + null, + null, + null, + autofill2, + null, + null); + + final TextInputChannel.Configuration autofillConfiguration = + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + null, + null, + null, + autofill1, + null, + new TextInputChannel.Configuration[] {config1, config2}); + + textInputPlugin.setTextInputClient(0, autofillConfiguration); + textInputPlugin.setTextInputEditingState( + testView, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); + + final SparseArray autofillValues = new SparseArray(); + autofillValues.append("1".hashCode(), AutofillValue.forText("focused field")); + autofillValues.append("2".hashCode(), AutofillValue.forText("unfocused field")); + + // Autofill both fields. + textInputPlugin.autofill(autofillValues); + + // Verify the Editable has been updated. + assertTrue(textInputPlugin.getEditable().toString().equals("focused field")); + + // The autofill value of the focused field is sent via updateEditingState. + verify(textInputChannel, times(1)) + .updateEditingState(anyInt(), eq("focused field"), eq(13), eq(13), eq(-1), eq(-1)); + + final ArgumentCaptor mapCaptor = ArgumentCaptor.forClass(HashMap.class); + + verify(textInputChannel, times(1)).updateEditingStateWithTag(anyInt(), mapCaptor.capture()); + final TextInputChannel.TextEditState editState = + (TextInputChannel.TextEditState) mapCaptor.getValue().get("2"); + assertEquals(editState.text, "unfocused field"); + } + + @Config(minSdk = API_LEVELS.API_26) + @Test + public void autofill_doesNotCrashAfterClearClientCall() { + if (Build.VERSION.SDK_INT < API_LEVELS.API_26) { + return; + } + FlutterView testView = new FlutterView(ctx); + TextInputChannel textInputChannel = spy(new TextInputChannel(mock(DartExecutor.class))); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + // Set up an autofill scenario with 2 fields. + final TextInputChannel.Configuration.Autofill autofillConfig = + new TextInputChannel.Configuration.Autofill( + "1", + new String[] {"HINT1"}, + "placeholder1", + new TextInputChannel.TextEditState("", 0, 0, -1, -1)); + final TextInputChannel.Configuration config = + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + null, + null, + null, + autofillConfig, + null, + null); + + textInputPlugin.setTextInputClient(0, config); + textInputPlugin.setTextInputEditingState( + testView, new TextInputChannel.TextEditState("", 0, 0, -1, -1)); + textInputPlugin.clearTextInputClient(); + + final SparseArray autofillValues = new SparseArray(); + autofillValues.append("1".hashCode(), AutofillValue.forText("focused field")); + autofillValues.append("2".hashCode(), AutofillValue.forText("unfocused field")); + + // Autofill both fields. + textInputPlugin.autofill(autofillValues); + + verify(textInputChannel, never()).updateEditingStateWithTag(anyInt(), any()); + verify(textInputChannel, never()) + .updateEditingState(anyInt(), any(), anyInt(), anyInt(), anyInt(), anyInt()); + } + + @Config(minSdk = API_LEVELS.API_26) + @Test + public void autofill_testSetTextIpnutClientUpdatesSideFields() { + if (Build.VERSION.SDK_INT < API_LEVELS.API_26) { + return; + } + + TestAfm testAfm = Shadow.extract(ctx.getSystemService(AutofillManager.class)); + FlutterView testView = getTestView(); + TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + + // Set up an autofill scenario with 2 fields. + final TextInputChannel.Configuration.Autofill autofill1 = + new TextInputChannel.Configuration.Autofill( + "1", + new String[] {"HINT1"}, + "null", + new TextInputChannel.TextEditState("", 0, 0, -1, -1)); + final TextInputChannel.Configuration.Autofill autofill2 = + new TextInputChannel.Configuration.Autofill( + "2", + new String[] {"HINT2", "EXTRA"}, + "null", + new TextInputChannel.TextEditState( + "Unfocused fields need love like everything does", 0, 0, -1, -1)); + + final TextInputChannel.Configuration config1 = + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + null, + null, + null, + autofill1, + null, + null); + final TextInputChannel.Configuration config2 = + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + null, + null, + null, + autofill2, + null, + null); + + final TextInputChannel.Configuration autofillConfiguration = + new TextInputChannel.Configuration( + false, + false, + true, + true, + false, + TextInputChannel.TextCapitalization.NONE, + null, + null, + null, + autofill1, + null, + new TextInputChannel.Configuration[] {config1, config2}); + + textInputPlugin.setTextInputClient(0, autofillConfiguration); + + // notifyValueChanged should be called for unfocused fields. + assertEquals("2".hashCode(), testAfm.changeVirtualId); + assertEquals("Unfocused fields need love like everything does", testAfm.changeString); + } + // -------- End: Autofill Tests ------- + + @SuppressWarnings("deprecation") + private FlutterView getTestView() { + // TODO(reidbaker): https://github.com/flutter/flutter/issues/133151 + return new FlutterView(Robolectric.setupActivity(Activity.class)); + } + + @SuppressWarnings("deprecation") + // setMessageHandler is deprecated. + @Test + public void respondsToInputChannelMessages() { + ArgumentCaptor binaryMessageHandlerCaptor = + ArgumentCaptor.forClass(BinaryMessenger.BinaryMessageHandler.class); + DartExecutor mockBinaryMessenger = mock(DartExecutor.class); + TextInputChannel.TextInputMethodHandler mockHandler = + mock(TextInputChannel.TextInputMethodHandler.class); + TextInputChannel textInputChannel = new TextInputChannel(mockBinaryMessenger); + + textInputChannel.setTextInputMethodHandler(mockHandler); + + verify(mockBinaryMessenger, times(1)) + .setMessageHandler(any(String.class), binaryMessageHandlerCaptor.capture()); + + BinaryMessenger.BinaryMessageHandler binaryMessageHandler = + binaryMessageHandlerCaptor.getValue(); + + sendToBinaryMessageHandler(binaryMessageHandler, "TextInput.requestAutofill", null); + verify(mockHandler, times(1)).requestAutofill(); + + sendToBinaryMessageHandler(binaryMessageHandler, "TextInput.finishAutofillContext", true); + verify(mockHandler, times(1)).finishAutofillContext(true); + + sendToBinaryMessageHandler(binaryMessageHandler, "TextInput.finishAutofillContext", false); + verify(mockHandler, times(1)).finishAutofillContext(false); + } + + @SuppressWarnings("deprecation") + // setMessageHandler is deprecated. + @Test + public void sendAppPrivateCommand_dataIsEmpty() throws JSONException { + ArgumentCaptor binaryMessageHandlerCaptor = + ArgumentCaptor.forClass(BinaryMessenger.BinaryMessageHandler.class); + DartExecutor mockBinaryMessenger = mock(DartExecutor.class); + TextInputChannel textInputChannel = new TextInputChannel(mockBinaryMessenger); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + + EventHandler mockEventHandler = mock(EventHandler.class); + TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); + testImm.setEventHandler(mockEventHandler); + + View testView = new View(ctx); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + + verify(mockBinaryMessenger, times(1)) + .setMessageHandler(any(String.class), binaryMessageHandlerCaptor.capture()); + + JSONObject arguments = new JSONObject(); + arguments.put("action", "actionCommand"); + arguments.put("data", ""); + + BinaryMessenger.BinaryMessageHandler binaryMessageHandler = + binaryMessageHandlerCaptor.getValue(); + sendToBinaryMessageHandler(binaryMessageHandler, "TextInput.sendAppPrivateCommand", arguments); + verify(mockEventHandler, times(1)) + .sendAppPrivateCommand(any(View.class), eq("actionCommand"), eq(null)); + } + + @SuppressWarnings("deprecation") + // setMessageHandler is deprecated. + @Test + public void sendAppPrivateCommand_hasData() throws JSONException { + ArgumentCaptor binaryMessageHandlerCaptor = + ArgumentCaptor.forClass(BinaryMessenger.BinaryMessageHandler.class); + DartExecutor mockBinaryMessenger = mock(DartExecutor.class); + TextInputChannel textInputChannel = new TextInputChannel(mockBinaryMessenger); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + + EventHandler mockEventHandler = mock(EventHandler.class); + TestImm testImm = Shadow.extract(ctx.getSystemService(Context.INPUT_METHOD_SERVICE)); + testImm.setEventHandler(mockEventHandler); + + View testView = new View(ctx); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + + verify(mockBinaryMessenger, times(1)) + .setMessageHandler(any(String.class), binaryMessageHandlerCaptor.capture()); + + JSONObject arguments = new JSONObject(); + arguments.put("action", "actionCommand"); + arguments.put("data", "actionData"); + + ArgumentCaptor bundleCaptor = ArgumentCaptor.forClass(Bundle.class); + BinaryMessenger.BinaryMessageHandler binaryMessageHandler = + binaryMessageHandlerCaptor.getValue(); + sendToBinaryMessageHandler(binaryMessageHandler, "TextInput.sendAppPrivateCommand", arguments); + verify(mockEventHandler, times(1)) + .sendAppPrivateCommand(any(View.class), eq("actionCommand"), bundleCaptor.capture()); + assertEquals("actionData", bundleCaptor.getValue().getCharSequence("data")); + } + + @Test + @TargetApi(API_LEVELS.API_30) + @Config(sdk = API_LEVELS.API_30) + @SuppressWarnings("deprecation") + // getWindowSystemUiVisibility, SYSTEM_UI_FLAG_LAYOUT_STABLE. + // flutter#133074 tracks migration work. + public void ime_windowInsetsSync_notLaidOutBehindNavigation_excludesNavigationBars() { + FlutterView testView = spy(getTestView()); + when(testView.getWindowSystemUiVisibility()).thenReturn(View.SYSTEM_UI_FLAG_LAYOUT_STABLE); + + TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + ImeSyncDeferringInsetsCallback imeSyncCallback = textInputPlugin.getImeSyncCallback(); + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + FlutterRenderer flutterRenderer = spy(new FlutterRenderer(mockFlutterJni)); + when(flutterEngine.getRenderer()).thenReturn(flutterRenderer); + testView.attachToFlutterEngine(flutterEngine); + + WindowInsetsAnimation animation = mock(WindowInsetsAnimation.class); + when(animation.getTypeMask()).thenReturn(WindowInsets.Type.ime()); + + List animationList = new ArrayList(); + animationList.add(animation); + + ArgumentCaptor viewportMetricsCaptor = + ArgumentCaptor.forClass(FlutterRenderer.ViewportMetrics.class); + + WindowInsets.Builder builder = new WindowInsets.Builder(); + + // Set the initial insets and verify that they were set and the bottom view inset is correct + imeSyncCallback.getInsetsListener().onApplyWindowInsets(testView, builder.build()); + + verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(0, viewportMetricsCaptor.getValue().viewInsetBottom); + + // Call onPrepare and set the lastWindowInsets - these should be stored for the end of the + // animation instead of being applied immediately + imeSyncCallback.getAnimationCallback().onPrepare(animation); + builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 100)); + builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 0)); + imeSyncCallback.getInsetsListener().onApplyWindowInsets(testView, builder.build()); + + verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(0, viewportMetricsCaptor.getValue().viewInsetBottom); + + // Call onStart and apply new insets - these should be ignored completely + imeSyncCallback.getAnimationCallback().onStart(animation, null); + builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 50)); + builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 40)); + imeSyncCallback.getInsetsListener().onApplyWindowInsets(testView, builder.build()); + + verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(0, viewportMetricsCaptor.getValue().viewInsetBottom); + + // Progress the animation and ensure that the navigation bar insets have been subtracted + // from the IME insets + builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 25)); + builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 40)); + imeSyncCallback.getAnimationCallback().onProgress(builder.build(), animationList); + + verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(0, viewportMetricsCaptor.getValue().viewInsetBottom); + + builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 50)); + builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 40)); + imeSyncCallback.getAnimationCallback().onProgress(builder.build(), animationList); + + verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(10, viewportMetricsCaptor.getValue().viewInsetBottom); + + // End the animation and ensure that the bottom insets match the lastWindowInsets that we set + // during onPrepare + imeSyncCallback.getAnimationCallback().onEnd(animation); + + verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(100, viewportMetricsCaptor.getValue().viewInsetBottom); + } + + @Test + @TargetApi(API_LEVELS.API_30) + @Config(sdk = API_LEVELS.API_30) + @SuppressWarnings("deprecation") + // getWindowSystemUiVisibility + // flutter#133074 tracks migration work. + public void ime_windowInsetsSync_laidOutBehindNavigation_includesNavigationBars() { + FlutterView testView = spy(getTestView()); + when(testView.getWindowSystemUiVisibility()) + .thenReturn( + View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); + + TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + ImeSyncDeferringInsetsCallback imeSyncCallback = textInputPlugin.getImeSyncCallback(); + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + FlutterRenderer flutterRenderer = spy(new FlutterRenderer(mockFlutterJni)); + when(flutterEngine.getRenderer()).thenReturn(flutterRenderer); + testView.attachToFlutterEngine(flutterEngine); + + WindowInsetsAnimation animation = mock(WindowInsetsAnimation.class); + when(animation.getTypeMask()).thenReturn(WindowInsets.Type.ime()); + + List animationList = new ArrayList(); + animationList.add(animation); + + ArgumentCaptor viewportMetricsCaptor = + ArgumentCaptor.forClass(FlutterRenderer.ViewportMetrics.class); + + WindowInsets.Builder builder = new WindowInsets.Builder(); + + // Set the initial insets and verify that they were set and the bottom view inset is correct + imeSyncCallback.getInsetsListener().onApplyWindowInsets(testView, builder.build()); + + verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(0, viewportMetricsCaptor.getValue().viewInsetBottom); + + // Call onPrepare and set the lastWindowInsets - these should be stored for the end of the + // animation instead of being applied immediately + imeSyncCallback.getAnimationCallback().onPrepare(animation); + builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 100)); + builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 0)); + imeSyncCallback.getInsetsListener().onApplyWindowInsets(testView, builder.build()); + + verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(0, viewportMetricsCaptor.getValue().viewInsetBottom); + + // Call onStart and apply new insets - these should be ignored completely + imeSyncCallback.getAnimationCallback().onStart(animation, null); + builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 50)); + builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 40)); + imeSyncCallback.getInsetsListener().onApplyWindowInsets(testView, builder.build()); + + verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(0, viewportMetricsCaptor.getValue().viewInsetBottom); + + // Progress the animation and ensure that the navigation bar insets have not been + // subtracted from the IME insets + builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 25)); + builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 40)); + imeSyncCallback.getAnimationCallback().onProgress(builder.build(), animationList); + + verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(25, viewportMetricsCaptor.getValue().viewInsetBottom); + + builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 50)); + builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 40)); + imeSyncCallback.getAnimationCallback().onProgress(builder.build(), animationList); + + verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(50, viewportMetricsCaptor.getValue().viewInsetBottom); + + // End the animation and ensure that the bottom insets match the lastWindowInsets that we set + // during onPrepare + imeSyncCallback.getAnimationCallback().onEnd(animation); + + verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(100, viewportMetricsCaptor.getValue().viewInsetBottom); + } + + @Test + @TargetApi(API_LEVELS.API_30) + @Config(sdk = API_LEVELS.API_30) + @SuppressWarnings("deprecation") + // getWindowSystemUiVisibility, SYSTEM_UI_FLAG_LAYOUT_STABLE + // flutter#133074 tracks migration work. + public void lastWindowInsets_updatedOnSecondOnProgressCall() { + FlutterView testView = spy(getTestView()); + when(testView.getWindowSystemUiVisibility()).thenReturn(View.SYSTEM_UI_FLAG_LAYOUT_STABLE); + + TextInputChannel textInputChannel = new TextInputChannel(mock(DartExecutor.class)); + ScribeChannel scribeChannel = new ScribeChannel(mock(DartExecutor.class)); + TextInputPlugin textInputPlugin = + new TextInputPlugin( + testView, + textInputChannel, + scribeChannel, + mock(PlatformViewsController.class), + mock(PlatformViewsController2.class)); + ImeSyncDeferringInsetsCallback imeSyncCallback = textInputPlugin.getImeSyncCallback(); + FlutterEngine flutterEngine = spy(new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni)); + FlutterRenderer flutterRenderer = spy(new FlutterRenderer(mockFlutterJni)); + when(flutterEngine.getRenderer()).thenReturn(flutterRenderer); + testView.attachToFlutterEngine(flutterEngine); + + WindowInsetsAnimation imeAnimation = mock(WindowInsetsAnimation.class); + when(imeAnimation.getTypeMask()).thenReturn(WindowInsets.Type.ime()); + WindowInsetsAnimation navigationBarAnimation = mock(WindowInsetsAnimation.class); + when(navigationBarAnimation.getTypeMask()).thenReturn(WindowInsets.Type.navigationBars()); + + List animationList = new ArrayList(); + animationList.add(imeAnimation); + animationList.add(navigationBarAnimation); + + ArgumentCaptor viewportMetricsCaptor = + ArgumentCaptor.forClass(FlutterRenderer.ViewportMetrics.class); + + WindowInsets.Builder builder = new WindowInsets.Builder(); + + // Set the initial insets and verify that they were set and the bottom view padding is correct + builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 1000)); + builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 100)); + imeSyncCallback.getInsetsListener().onApplyWindowInsets(testView, builder.build()); + + verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(100, viewportMetricsCaptor.getValue().viewPaddingBottom); + + // Call onPrepare and set the lastWindowInsets - these should be stored for the end of the + // animation instead of being applied immediately + imeSyncCallback.getAnimationCallback().onPrepare(imeAnimation); + builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 0)); + builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 100)); + imeSyncCallback.getInsetsListener().onApplyWindowInsets(testView, builder.build()); + + verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(100, viewportMetricsCaptor.getValue().viewPaddingBottom); + + // Call onPrepare again and apply new insets - these should overrite lastWindowInsets + imeSyncCallback.getAnimationCallback().onPrepare(navigationBarAnimation); + builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 0)); + builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 0)); + imeSyncCallback.getInsetsListener().onApplyWindowInsets(testView, builder.build()); + + verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(100, viewportMetricsCaptor.getValue().viewPaddingBottom); + + // Progress the animation and ensure that the navigation bar insets have not been + // subtracted from the IME insets + builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 500)); + builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 0)); + imeSyncCallback.getAnimationCallback().onProgress(builder.build(), animationList); + + verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(0, viewportMetricsCaptor.getValue().viewPaddingBottom); + + builder.setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, 250)); + builder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(0, 0, 0, 0)); + imeSyncCallback.getAnimationCallback().onProgress(builder.build(), animationList); + + verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(0, viewportMetricsCaptor.getValue().viewPaddingBottom); + + // End the animation and ensure that the bottom insets match the lastWindowInsets that we set + // during onPrepare + imeSyncCallback.getAnimationCallback().onEnd(imeAnimation); + + verify(flutterRenderer, atLeast(1)).setViewportMetrics(viewportMetricsCaptor.capture()); + assertEquals(0, viewportMetricsCaptor.getValue().viewPaddingBottom); + } + + interface EventHandler { + void sendAppPrivateCommand(View view, String action, Bundle data); + } + + @Implements(InputMethodManager.class) + public static class TestImm extends ShadowInputMethodManager { + private InputMethodSubtype currentInputMethodSubtype; + private SparseIntArray restartCounter = new SparseIntArray(); + private CursorAnchorInfo cursorAnchorInfo; + private ArrayList selectionUpdateValues; + private boolean trackSelection = false; + private EventHandler handler; + + public TestImm() { + selectionUpdateValues = new ArrayList(); + } + + @Implementation + public InputMethodSubtype getCurrentInputMethodSubtype() { + return currentInputMethodSubtype; + } + + @Implementation + public void restartInput(View view) { + int count = restartCounter.get(view.hashCode(), /*defaultValue=*/ 0) + 1; + restartCounter.put(view.hashCode(), count); + } + + public void setCurrentInputMethodSubtype(InputMethodSubtype inputMethodSubtype) { + this.currentInputMethodSubtype = inputMethodSubtype; + } + + public int getRestartCount(View view) { + return restartCounter.get(view.hashCode(), /*defaultValue=*/ 0); + } + + public void setEventHandler(EventHandler eventHandler) { + handler = eventHandler; + } + + @Implementation + public void sendAppPrivateCommand(View view, String action, Bundle data) { + handler.sendAppPrivateCommand(view, action, data); + } + + @Implementation + public void updateCursorAnchorInfo(View view, CursorAnchorInfo cursorAnchorInfo) { + this.cursorAnchorInfo = cursorAnchorInfo; + } + + // We simply store the values to verify later. + @Implementation + public void updateSelection( + View view, int selStart, int selEnd, int candidatesStart, int candidatesEnd) { + if (trackSelection) { + this.selectionUpdateValues.add(selStart); + this.selectionUpdateValues.add(selEnd); + this.selectionUpdateValues.add(candidatesStart); + this.selectionUpdateValues.add(candidatesEnd); + } + } + + // only track values when enabled via this. + public void setTrackSelection(boolean val) { + trackSelection = val; + } + + // Returns true if the last updateSelection call passed the following values. + public ArrayList getSelectionUpdateValues() { + return selectionUpdateValues; + } + + public CursorAnchorInfo getLastCursorAnchorInfo() { + return cursorAnchorInfo; + } + } + + @Implements(AutofillManager.class) + public static class TestAfm extends ShadowAutofillManager { + public static int empty = -999; + + String finishState; + int changeVirtualId = empty; + String changeString; + + int enterId = empty; + int exitId = empty; + + @Implementation + public void cancel() { + finishState = "cancel"; + } + + public void commit() { + finishState = "commit"; + } + + public void notifyViewEntered(View view, int virtualId, Rect absBounds) { + enterId = virtualId; + } + + public void notifyViewExited(View view, int virtualId) { + exitId = virtualId; + } + + public void notifyValueChanged(View view, int virtualId, AutofillValue value) { + if (Build.VERSION.SDK_INT < API_LEVELS.API_26) { + return; + } + changeVirtualId = virtualId; + changeString = value.getTextValue().toString(); + } + + public void resetStates() { + finishState = null; + changeVirtualId = empty; + changeString = null; + enterId = empty; + exitId = empty; + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/localization/LocalizationPluginTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/localization/LocalizationPluginTest.java new file mode 100644 index 0000000000000000000000000000000000000000..ca81eddd66b1a350e17dc63f0efbfa6be6f9f683 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/localization/LocalizationPluginTest.java @@ -0,0 +1,460 @@ +package io.flutter.plugin.localization; + +import static io.flutter.Build.API_LEVELS; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.annotation.TargetApi; +import android.content.Context; +import android.content.res.Configuration; +import android.content.res.Resources; +import android.os.LocaleList; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.dart.DartExecutor; +import io.flutter.embedding.engine.systemchannels.LocalizationChannel; +import io.flutter.plugin.common.MethodCall; +import io.flutter.plugin.common.MethodChannel; +import java.util.Locale; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +@TargetApi(API_LEVELS.API_24) // LocaleList and scriptCode are API 24+. +public class LocalizationPluginTest { + private final Context ctx = ApplicationProvider.getApplicationContext(); + + // This test should be synced with the version for API 24. + @Test + @Config(sdk = API_LEVELS.API_26) + public void computePlatformResolvedLocaleAPI26() { + // --- Test Setup --- + FlutterJNI flutterJNI = new FlutterJNI(); + + Context context = mock(Context.class); + Resources resources = mock(Resources.class); + Configuration config = mock(Configuration.class); + DartExecutor dartExecutor = mock(DartExecutor.class); + LocaleList localeList = + new LocaleList(new Locale("es", "MX"), new Locale("zh", "CN"), new Locale("en", "US")); + when(context.getResources()).thenReturn(resources); + when(resources.getConfiguration()).thenReturn(config); + when(config.getLocales()).thenReturn(localeList); + + flutterJNI.setLocalizationPlugin( + new LocalizationPlugin(context, new LocalizationChannel(dartExecutor))); + + // Empty supportedLocales. + String[] supportedLocales = new String[] {}; + String[] result = flutterJNI.computePlatformResolvedLocale(supportedLocales); + assertEquals(result.length, 0); + + // Empty preferredLocales. + supportedLocales = + new String[] { + "fr", "FR", "", + "zh", "", "", + "en", "CA", "" + }; + localeList = new LocaleList(); + when(config.getLocales()).thenReturn(localeList); + result = flutterJNI.computePlatformResolvedLocale(supportedLocales); + // The first locale is default. + assertEquals(result.length, 3); + assertEquals(result[0], "fr"); + assertEquals(result[1], "FR"); + assertEquals(result[2], ""); + + // Example from https://developer.android.com/guide/topics/resources/multilingual-support#postN + supportedLocales = + new String[] { + "en", "", "", + "de", "DE", "", + "es", "ES", "", + "fr", "FR", "", + "it", "IT", "" + }; + localeList = new LocaleList(new Locale("fr", "CH")); + when(config.getLocales()).thenReturn(localeList); + result = flutterJNI.computePlatformResolvedLocale(supportedLocales); + // The call will use the new (> API 24) algorithm. + assertEquals(result.length, 3); + assertEquals(result[0], "fr"); + assertEquals(result[1], "FR"); + assertEquals(result[2], ""); + + supportedLocales = + new String[] { + "en", "", "", + "de", "DE", "", + "es", "ES", "", + "fr", "FR", "", + "fr", "", "", + "it", "IT", "" + }; + localeList = new LocaleList(new Locale("fr", "CH")); + when(config.getLocales()).thenReturn(localeList); + result = flutterJNI.computePlatformResolvedLocale(supportedLocales); + // The call will use the new (> API 24) algorithm. + assertEquals(result.length, 3); + assertEquals(result[0], "fr"); + assertEquals(result[1], ""); + assertEquals(result[2], ""); + + // Example from https://developer.android.com/guide/topics/resources/multilingual-support#postN + supportedLocales = + new String[] { + "en", "", "", + "de", "DE", "", + "es", "ES", "", + "it", "IT", "" + }; + localeList = new LocaleList(new Locale("fr", "CH"), new Locale("it", "CH")); + when(config.getLocales()).thenReturn(localeList); + result = flutterJNI.computePlatformResolvedLocale(supportedLocales); + // The call will use the new (> API 24) algorithm. + assertEquals(result.length, 3); + assertEquals(result[0], "it"); + assertEquals(result[1], "IT"); + assertEquals(result[2], ""); + + supportedLocales = + new String[] { + "zh", "CN", "Hans", + "zh", "HK", "Hant", + }; + localeList = new LocaleList(new Locale("zh", "CN")); + when(config.getLocales()).thenReturn(localeList); + result = flutterJNI.computePlatformResolvedLocale(supportedLocales); + assertEquals(result.length, 3); + assertEquals(result[0], "zh"); + assertEquals(result[1], "CN"); + assertEquals(result[2], "Hans"); + } + + // This test should be synced with the version for API 26. + @Test + @Config(minSdk = API_LEVELS.API_24) + public void computePlatformResolvedLocale_fromAndroidN() { + // --- Test Setup --- + FlutterJNI flutterJNI = new FlutterJNI(); + + Context context = mock(Context.class); + Resources resources = mock(Resources.class); + Configuration config = mock(Configuration.class); + DartExecutor dartExecutor = mock(DartExecutor.class); + LocaleList localeList = + new LocaleList(new Locale("es", "MX"), new Locale("zh", "CN"), new Locale("en", "US")); + when(context.getResources()).thenReturn(resources); + when(resources.getConfiguration()).thenReturn(config); + when(config.getLocales()).thenReturn(localeList); + + flutterJNI.setLocalizationPlugin( + new LocalizationPlugin(context, new LocalizationChannel(dartExecutor))); + + // Empty supportedLocales. + String[] supportedLocales = new String[] {}; + String[] result = flutterJNI.computePlatformResolvedLocale(supportedLocales); + assertEquals(result.length, 0); + + // Empty preferredLocales. + supportedLocales = + new String[] { + "fr", "FR", "", + "zh", "", "", + "en", "CA", "" + }; + localeList = new LocaleList(); + when(config.getLocales()).thenReturn(localeList); + result = flutterJNI.computePlatformResolvedLocale(supportedLocales); + // The first locale is default. + assertEquals(result.length, 3); + assertEquals(result[0], "fr"); + assertEquals(result[1], "FR"); + assertEquals(result[2], ""); + + // Example from https://developer.android.com/guide/topics/resources/multilingual-support#postN + supportedLocales = + new String[] { + "en", "", "", + "de", "DE", "", + "es", "ES", "", + "fr", "FR", "", + "it", "IT", "" + }; + localeList = new LocaleList(new Locale("fr", "CH")); + when(config.getLocales()).thenReturn(localeList); + result = flutterJNI.computePlatformResolvedLocale(supportedLocales); + // The call will use the new (> API 24) algorithm. + assertEquals(result.length, 3); + assertEquals(result[0], "fr"); + assertEquals(result[1], "FR"); + assertEquals(result[2], ""); + + supportedLocales = + new String[] { + "en", "", "", + "de", "DE", "", + "es", "ES", "", + "fr", "FR", "", + "fr", "", "", + "it", "IT", "" + }; + localeList = new LocaleList(new Locale("fr", "CH")); + when(config.getLocales()).thenReturn(localeList); + result = flutterJNI.computePlatformResolvedLocale(supportedLocales); + // The call will use the new (> API 24) algorithm. + assertEquals(result.length, 3); + assertEquals(result[0], "fr"); + assertEquals(result[1], ""); + assertEquals(result[2], ""); + + // Example from https://developer.android.com/guide/topics/resources/multilingual-support#postN + supportedLocales = + new String[] { + "en", "", "", + "de", "DE", "", + "es", "ES", "", + "it", "IT", "" + }; + localeList = new LocaleList(new Locale("fr", "CH"), new Locale("it", "CH")); + when(config.getLocales()).thenReturn(localeList); + result = flutterJNI.computePlatformResolvedLocale(supportedLocales); + // The call will use the new (> API 24) algorithm. + assertEquals(result.length, 3); + assertEquals(result[0], "it"); + assertEquals(result[1], "IT"); + assertEquals(result[2], ""); + } + + // Tests the legacy pre API 24 algorithm. + @Test + @Config(minSdk = API_LEVELS.API_21, maxSdk = API_LEVELS.API_23, qualifiers = "es-rMX") + public void computePlatformResolvedLocale_emptySupportedLocales_beforeAndroidN() { + FlutterJNI flutterJNI = new FlutterJNI(); + DartExecutor dartExecutor = mock(DartExecutor.class); + flutterJNI.setLocalizationPlugin( + new LocalizationPlugin(ctx, new LocalizationChannel(dartExecutor))); + String[] supportedLocales = new String[] {}; + String[] result = flutterJNI.computePlatformResolvedLocale(supportedLocales); + assertEquals(result.length, 0); + } + + @Test + @Config(minSdk = API_LEVELS.API_21, maxSdk = API_LEVELS.API_23, qualifiers = "") + public void computePlatformResolvedLocale_selectFirstLocaleWhenNoUserSetting_beforeAndroidN() { + FlutterJNI flutterJNI = new FlutterJNI(); + DartExecutor dartExecutor = mock(DartExecutor.class); + flutterJNI.setLocalizationPlugin( + new LocalizationPlugin(ctx, new LocalizationChannel(dartExecutor))); + String[] supportedLocales = + new String[] { + "fr", "FR", "", + "zh", "", "", + "en", "CA", "" + }; + String[] result = flutterJNI.computePlatformResolvedLocale(supportedLocales); + assertEquals(result.length, 3); + assertEquals(result[0], "fr"); + assertEquals(result[1], "FR"); + assertEquals(result[2], ""); + } + + @Test + @Config(minSdk = API_LEVELS.API_21, maxSdk = API_LEVELS.API_23, qualifiers = "fr-rCH") + public void computePlatformResolvedLocale_selectFirstLocaleWhenNoExactMatch_beforeAndroidN() { + FlutterJNI flutterJNI = new FlutterJNI(); + DartExecutor dartExecutor = mock(DartExecutor.class); + flutterJNI.setLocalizationPlugin( + new LocalizationPlugin(ctx, new LocalizationChannel(dartExecutor))); + // Example from https://developer.android.com/guide/topics/resources/multilingual-support#postN + String[] supportedLocales = + new String[] { + "en", "", "", + "de", "DE", "", + "es", "ES", "", + "fr", "FR", "", + "it", "IT", "" + }; + String[] result = flutterJNI.computePlatformResolvedLocale(supportedLocales); + assertEquals(result.length, 3); + assertEquals(result[0], "en"); + assertEquals(result[1], ""); + assertEquals(result[2], ""); + } + + @Test + @Config(minSdk = API_LEVELS.API_21, maxSdk = API_LEVELS.API_23, qualifiers = "it-rIT") + public void computePlatformResolvedLocale_selectExactMatchLocale_beforeAndroidN() { + FlutterJNI flutterJNI = new FlutterJNI(); + DartExecutor dartExecutor = mock(DartExecutor.class); + flutterJNI.setLocalizationPlugin( + new LocalizationPlugin(ctx, new LocalizationChannel(dartExecutor))); + + String[] supportedLocales = + new String[] { + "en", "", "", + "de", "DE", "", + "es", "ES", "", + "fr", "FR", "", + "it", "IT", "" + }; + String[] result = flutterJNI.computePlatformResolvedLocale(supportedLocales); + assertEquals(result.length, 3); + assertEquals(result[0], "it"); + assertEquals(result[1], "IT"); + assertEquals(result[2], ""); + } + + @Test + @Config(minSdk = API_LEVELS.API_21, maxSdk = API_LEVELS.API_23, qualifiers = "fr-rCH") + public void computePlatformResolvedLocale_selectOnlyLanguageLocale_beforeAndroidN() { + FlutterJNI flutterJNI = new FlutterJNI(); + DartExecutor dartExecutor = mock(DartExecutor.class); + flutterJNI.setLocalizationPlugin( + new LocalizationPlugin(ctx, new LocalizationChannel(dartExecutor))); + + String[] supportedLocales = + new String[] { + "en", "", "", + "de", "DE", "", + "es", "ES", "", + "fr", "FR", "", + "fr", "", "", + "it", "IT", "" + }; + String[] result = flutterJNI.computePlatformResolvedLocale(supportedLocales); + assertEquals(result.length, 3); + assertEquals(result[0], "fr"); + assertEquals(result[1], ""); + assertEquals(result[2], ""); + } + + @Test + public void localeFromString_languageOnly() { + Locale locale = LocalizationPlugin.localeFromString("en"); + assertEquals(locale, new Locale("en")); + } + + @Test + public void localeFromString_languageAndCountry() { + Locale locale = LocalizationPlugin.localeFromString("en-US"); + assertEquals(locale, new Locale("en", "US")); + } + + @Test + public void localeFromString_languageCountryAndVariant() { + Locale locale = LocalizationPlugin.localeFromString("zh-Hans-CN"); + assertEquals(locale, new Locale("zh", "CN", "Hans")); + } + + @Test + public void localeFromString_underscore() { + Locale locale = LocalizationPlugin.localeFromString("zh_Hans_CN"); + assertEquals(locale, new Locale("zh", "CN", "Hans")); + } + + @Test + public void localeFromString_additionalVariantsAreIgnored() { + Locale locale = LocalizationPlugin.localeFromString("de-DE-u-co-phonebk"); + assertEquals(locale, new Locale("de", "DE")); + } + + @Test + public void getStringResource_withoutLocale() throws JSONException { + Context context = mock(Context.class); + Resources resources = mock(Resources.class); + DartExecutor dartExecutor = mock(DartExecutor.class); + LocalizationChannel localizationChannel = new LocalizationChannel(dartExecutor); + LocalizationPlugin plugin = new LocalizationPlugin(context, localizationChannel); + + MethodChannel.Result mockResult = mock(MethodChannel.Result.class); + + String fakePackageName = "package_name"; + String fakeKey = "test_key"; + int fakeId = 123; + + when(context.getPackageName()).thenReturn(fakePackageName); + when(context.getResources()).thenReturn(resources); + when(resources.getIdentifier(fakeKey, "string", fakePackageName)).thenReturn(fakeId); + when(resources.getString(fakeId)).thenReturn("test_value"); + + JSONObject param = new JSONObject(); + param.put("key", fakeKey); + + localizationChannel.handler.onMethodCall( + new MethodCall("Localization.getStringResource", param), mockResult); + + verify(mockResult).success("test_value"); + } + + @Test + public void getStringResource_withLocale() throws JSONException { + Context context = mock(Context.class); + Context localContext = mock(Context.class); + Resources resources = mock(Resources.class); + Resources localResources = mock(Resources.class); + Configuration configuration = new Configuration(); + DartExecutor dartExecutor = mock(DartExecutor.class); + LocalizationChannel localizationChannel = new LocalizationChannel(dartExecutor); + LocalizationPlugin plugin = new LocalizationPlugin(context, localizationChannel); + + MethodChannel.Result mockResult = mock(MethodChannel.Result.class); + + String fakePackageName = "package_name"; + String fakeKey = "test_key"; + int fakeId = 123; + + when(context.getPackageName()).thenReturn(fakePackageName); + when(context.createConfigurationContext(any())).thenReturn(localContext); + when(context.getResources()).thenReturn(resources); + when(localContext.getResources()).thenReturn(localResources); + when(resources.getConfiguration()).thenReturn(configuration); + when(localResources.getIdentifier(fakeKey, "string", fakePackageName)).thenReturn(fakeId); + when(localResources.getString(fakeId)).thenReturn("test_value"); + + JSONObject param = new JSONObject(); + param.put("key", fakeKey); + param.put("locale", "en-US"); + + localizationChannel.handler.onMethodCall( + new MethodCall("Localization.getStringResource", param), mockResult); + + verify(mockResult).success("test_value"); + } + + @Test + public void getStringResource_nonExistentKey() throws JSONException { + Context context = mock(Context.class); + Resources resources = mock(Resources.class); + DartExecutor dartExecutor = mock(DartExecutor.class); + LocalizationChannel localizationChannel = new LocalizationChannel(dartExecutor); + LocalizationPlugin plugin = new LocalizationPlugin(context, localizationChannel); + + MethodChannel.Result mockResult = mock(MethodChannel.Result.class); + + String fakePackageName = "package_name"; + String fakeKey = "test_key"; + + when(context.getPackageName()).thenReturn(fakePackageName); + when(context.getResources()).thenReturn(resources); + when(resources.getIdentifier(fakeKey, "string", fakePackageName)) + .thenReturn(0); // 0 means not exist + + JSONObject param = new JSONObject(); + param.put("key", fakeKey); + + localizationChannel.handler.onMethodCall( + new MethodCall("Localization.getStringResource", param), mockResult); + + verify(mockResult).success(null); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/mouse/MouseCursorPluginTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/mouse/MouseCursorPluginTest.java new file mode 100644 index 0000000000000000000000000000000000000000..11feb418538c42dd7d7681145bab35affcaea734 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/mouse/MouseCursorPluginTest.java @@ -0,0 +1,79 @@ +package io.flutter.plugin.mouse; + +import static io.flutter.Build.API_LEVELS; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import android.annotation.TargetApi; +import android.app.Activity; +import android.view.PointerIcon; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.android.FlutterView; +import io.flutter.embedding.engine.dart.DartExecutor; +import io.flutter.embedding.engine.systemchannels.MouseCursorChannel; +import io.flutter.plugin.common.MethodCall; +import io.flutter.plugin.common.MethodChannel; +import java.util.HashMap; +import org.json.JSONException; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.Robolectric; +import org.robolectric.annotation.Config; + +@Config( + manifest = Config.NONE, + minSdk = API_LEVELS.API_24, + shadows = {}) +@RunWith(AndroidJUnit4.class) +@TargetApi(API_LEVELS.API_24) +public class MouseCursorPluginTest { + + @SuppressWarnings("deprecation") + // Robolectric.setupActivity. + // TODO(reidbaker): https://github.com/flutter/flutter/issues/133151 + @Test + public void mouseCursorPlugin_SetsSystemCursorOnRequest() throws JSONException { + // Migrate to ActivityScenario by following https://github.com/robolectric/robolectric/pull/4736 + // Initialize a general MouseCursorPlugin. + FlutterView testView = spy(new FlutterView(Robolectric.setupActivity(Activity.class))); + MouseCursorChannel mouseCursorChannel = new MouseCursorChannel(mock(DartExecutor.class)); + + MouseCursorPlugin mouseCursorPlugin = new MouseCursorPlugin(testView, mouseCursorChannel); + + final StoredResult methodResult = new StoredResult(); + mouseCursorChannel.synthesizeMethodCall( + new MethodCall( + "activateSystemCursor", + new HashMap() { + private static final long serialVersionUID = 1L; + + { + put("device", 1); + put("kind", "text"); + } + }), + methodResult); + verify(testView, times(1)).getSystemPointerIcon(PointerIcon.TYPE_TEXT); + verify(testView, times(1)).setPointerIcon(any(PointerIcon.class)); + assertEquals(methodResult.result, Boolean.TRUE); + } +} + +class StoredResult implements MethodChannel.Result { + Object result; + + @Override + public void success(Object result) { + this.result = result; + } + + @Override + public void error(String errorCode, String errorMessage, Object errorDetails) {} + + @Override + public void notImplemented() {} +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/AccessibilityEventsDelegateTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/AccessibilityEventsDelegateTest.java new file mode 100644 index 0000000000000000000000000000000000000000..a6881d2fe1c71db39aabe1f334ed166a6fda2b3a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/AccessibilityEventsDelegateTest.java @@ -0,0 +1,83 @@ +// 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. + +package io.flutter.plugin.platform; + +import static junit.framework.TestCase.assertFalse; +import static junit.framework.TestCase.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.view.MotionEvent; +import android.view.View; +import android.view.accessibility.AccessibilityEvent; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.view.AccessibilityBridge; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(AndroidJUnit4.class) +public class AccessibilityEventsDelegateTest { + @Test + public void acessibilityEventsDelegate_forwardsAccessibilityEvents() { + final AccessibilityBridge mockAccessibilityBridge = mock(AccessibilityBridge.class); + final View embeddedView = mock(View.class); + final View originView = mock(View.class); + final AccessibilityEvent event = mock(AccessibilityEvent.class); + + AccessibilityEventsDelegate delegate = new AccessibilityEventsDelegate(); + delegate.setAccessibilityBridge(mockAccessibilityBridge); + when(mockAccessibilityBridge.externalViewRequestSendAccessibilityEvent(any(), any(), any())) + .thenReturn(true); + + final boolean handled = delegate.requestSendAccessibilityEvent(embeddedView, originView, event); + + assertTrue(handled); + verify(mockAccessibilityBridge, times(1)) + .externalViewRequestSendAccessibilityEvent(embeddedView, originView, event); + } + + @Test + public void acessibilityEventsDelegate_withoutBridge_noopsAccessibilityEvents() { + final View embeddedView = mock(View.class); + final View originView = mock(View.class); + final AccessibilityEvent event = mock(AccessibilityEvent.class); + + AccessibilityEventsDelegate delegate = new AccessibilityEventsDelegate(); + + final boolean handled = delegate.requestSendAccessibilityEvent(embeddedView, originView, event); + + assertFalse(handled); + } + + @Test + public void acessibilityEventsDelegate_forwardsHoverEvents() { + final AccessibilityBridge mockAccessibilityBridge = mock(AccessibilityBridge.class); + final MotionEvent event = mock(MotionEvent.class); + + AccessibilityEventsDelegate delegate = new AccessibilityEventsDelegate(); + delegate.setAccessibilityBridge(mockAccessibilityBridge); + when(mockAccessibilityBridge.onAccessibilityHoverEvent(any(), anyBoolean())).thenReturn(true); + + final boolean handled = delegate.onAccessibilityHoverEvent(event, true); + + assertTrue(handled); + verify(mockAccessibilityBridge, times(1)).onAccessibilityHoverEvent(event, true); + } + + @Test + public void acessibilityEventsDelegate_withoutBridge_noopsHoverEvents() { + final MotionEvent event = mock(MotionEvent.class); + + AccessibilityEventsDelegate delegate = new AccessibilityEventsDelegate(); + + final boolean handled = delegate.onAccessibilityHoverEvent(event, true); + + assertFalse(handled); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/ImageReaderPlatformViewRenderTargetTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/ImageReaderPlatformViewRenderTargetTest.java new file mode 100644 index 0000000000000000000000000000000000000000..11df94d395ef92638b896a77f4b2d1e0e644154c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/ImageReaderPlatformViewRenderTargetTest.java @@ -0,0 +1,109 @@ +// 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. + +package io.flutter.plugin.platform; + +import static android.os.Looper.getMainLooper; +import static io.flutter.Build.API_LEVELS; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; +import static org.robolectric.Shadows.shadowOf; + +import android.annotation.TargetApi; +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.PorterDuff; +import android.media.Image; +import android.view.Surface; +import android.view.View; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.view.TextureRegistry.ImageTextureEntry; +import org.junit.Test; +import org.junit.runner.RunWith; + +@TargetApi(API_LEVELS.API_29) +@RunWith(AndroidJUnit4.class) +public class ImageReaderPlatformViewRenderTargetTest { + private final Context ctx = ApplicationProvider.getApplicationContext(); + + class TestImageTextureEntry implements ImageTextureEntry { + private Image lastPushedImage; + + public long id() { + return 1; + } + + public void release() { + if (this.lastPushedImage != null) { + this.lastPushedImage.close(); + } + } + + public void pushImage(Image image) { + if (this.lastPushedImage != null) { + this.lastPushedImage.close(); + } + this.lastPushedImage = image; + } + + public Image acquireLatestImage() { + Image r = this.lastPushedImage; + this.lastPushedImage = null; + return r; + } + } + + @Test + public void viewDraw_writesToBuffer() { + final TestImageTextureEntry textureEntry = new TestImageTextureEntry(); + final ImageReaderPlatformViewRenderTarget renderTarget = + new ImageReaderPlatformViewRenderTarget(textureEntry); + // Custom view. + final View platformView = + new View(ctx) { + @Override + public void draw(Canvas canvas) { + super.draw(canvas); + canvas.drawColor(Color.RED); + } + }; + final int size = 100; + platformView.measure(size, size); + platformView.layout(0, 0, size, size); + renderTarget.resize(size, size); + + // We don't have an image in the texture entry. + assertNull(textureEntry.acquireLatestImage()); + + // Start rendering a frame. + final Surface s = renderTarget.getSurface(); + assertNotNull(s); + final Canvas targetCanvas = s.lockHardwareCanvas(); + assertNotNull(targetCanvas); + + try { + // Fill the render target with transparent pixels. This is needed for platform views that + // expect a transparent background. + targetCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); + // Override the canvas that this subtree of views will use to draw. + platformView.draw(targetCanvas); + } finally { + // Finish rendering a frame. + s.unlockCanvasAndPost(targetCanvas); + } + + // Pump the UI thread task loop. This is needed so that the OnImageAvailable callback + // gets invoked (resulting in textureEntry.pushImage being invoked). + shadowOf(getMainLooper()).idle(); + + // An image was pushed into the texture entry and it has the correct dimensions. + Image pushedImage = textureEntry.acquireLatestImage(); + assertNotNull(pushedImage); + assertEquals(pushedImage.getWidth(), size); + assertEquals(pushedImage.getHeight(), size); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/PlatformOverlayViewTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/PlatformOverlayViewTest.java new file mode 100644 index 0000000000000000000000000000000000000000..fc4d36e7f0fe3dc1553cb70d0192a9c1bd3cd7ca --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/PlatformOverlayViewTest.java @@ -0,0 +1,47 @@ +// 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. + +package io.flutter.plugin.platform; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.content.Context; +import android.os.SystemClock; +import android.view.MotionEvent; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(AndroidJUnit4.class) +public class PlatformOverlayViewTest { + private final Context ctx = ApplicationProvider.getApplicationContext(); + + @Test + public void platformOverlayView_forwardsHover() { + final AccessibilityEventsDelegate mockAccessibilityDelegate = + mock(AccessibilityEventsDelegate.class); + when(mockAccessibilityDelegate.onAccessibilityHoverEvent(any(), eq(true))).thenReturn(true); + + final int size = 10; + final PlatformOverlayView imageView = + new PlatformOverlayView(ctx, size, size, mockAccessibilityDelegate); + MotionEvent event = + MotionEvent.obtain( + SystemClock.uptimeMillis(), + SystemClock.uptimeMillis(), + MotionEvent.ACTION_HOVER_MOVE, + size / 2, + size / 2, + 0); + imageView.onHoverEvent(event); + + verify(mockAccessibilityDelegate, times(1)).onAccessibilityHoverEvent(event, true); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/PlatformPluginTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/PlatformPluginTest.java new file mode 100644 index 0000000000000000000000000000000000000000..9b48dbcae1a73a3b0f724fb1cf3e6288cae13f92 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/PlatformPluginTest.java @@ -0,0 +1,750 @@ +// 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. + +package io.flutter.plugin.platform; + +import static android.view.WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS; +import static android.view.WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS; +import static io.flutter.Build.API_LEVELS; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyBoolean; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.app.Activity; +import android.content.ClipData; +import android.content.ClipboardManager; +import android.content.ContentResolver; +import android.content.Context; +import android.content.Intent; +import android.content.res.AssetFileDescriptor; +import android.net.Uri; +import android.os.Build; +import android.view.View; +import android.view.Window; +import android.view.WindowInsetsController; +import android.view.WindowManager; +import androidx.activity.OnBackPressedCallback; +import androidx.fragment.app.FragmentActivity; +import androidx.test.core.app.ApplicationProvider; +import io.flutter.embedding.engine.systemchannels.PlatformChannel; +import io.flutter.embedding.engine.systemchannels.PlatformChannel.Brightness; +import io.flutter.embedding.engine.systemchannels.PlatformChannel.ClipboardContentFormat; +import io.flutter.embedding.engine.systemchannels.PlatformChannel.SystemChromeStyle; +import io.flutter.plugin.platform.PlatformPlugin.PlatformPluginDelegate; +import java.io.IOException; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.robolectric.Robolectric; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.android.controller.ActivityController; +import org.robolectric.annotation.Config; +import org.robolectric.shadows.ShadowLooper; + +@Config(manifest = Config.NONE) +@RunWith(RobolectricTestRunner.class) +public class PlatformPluginTest { + private final Context ctx = ApplicationProvider.getApplicationContext(); + private final PlatformChannel mockPlatformChannel = mock(PlatformChannel.class); + + private ClipboardManager clipboardManager; + private ClipboardContentFormat clipboardFormat; + + public void setUpForTextClipboardTests(Activity mockActivity) { + clipboardManager = spy(ctx.getSystemService(ClipboardManager.class)); + when(mockActivity.getSystemService(Context.CLIPBOARD_SERVICE)).thenReturn(clipboardManager); + clipboardFormat = ClipboardContentFormat.PLAIN_TEXT; + } + + @Test + public void platformPlugin_getClipboardDataIsNonNullWhenPlainTextCopied() throws IOException { + View fakeDecorView = mock(View.class); + Window fakeWindow = mock(Window.class); + Activity mockActivity = mock(Activity.class); + when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); + when(mockActivity.getWindow()).thenReturn(fakeWindow); + PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); + setUpForTextClipboardTests(mockActivity); + + // Primary clip contains non-text media. + ClipData clip = ClipData.newPlainText("label", "Text"); + assertNull(platformPlugin.mPlatformMessageHandler.getClipboardData(clipboardFormat)); + clipboardManager.setPrimaryClip(clip); + assertNotNull(platformPlugin.mPlatformMessageHandler.getClipboardData(clipboardFormat)); + } + + @Test + public void platformPlugin_getClipboardDataIsNonNullWhenIOExceptionThrown() throws IOException { + View fakeDecorView = mock(View.class); + Window fakeWindow = mock(Window.class); + Activity mockActivity = mock(Activity.class); + when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); + when(mockActivity.getWindow()).thenReturn(fakeWindow); + PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); + setUpForTextClipboardTests(mockActivity); + ContentResolver contentResolver = mock(ContentResolver.class); + ClipData.Item mockItem = mock(ClipData.Item.class); + Uri mockUri = mock(Uri.class); + AssetFileDescriptor mockAssetFileDescriptor = mock(AssetFileDescriptor.class); + + when(mockActivity.getContentResolver()).thenReturn(contentResolver); + when(mockUri.getScheme()).thenReturn("content"); + when(mockItem.getText()).thenReturn(null); + when(mockItem.getUri()).thenReturn(mockUri); + when(contentResolver.openTypedAssetFileDescriptor(any(Uri.class), any(), any())) + .thenReturn(mockAssetFileDescriptor); + when(mockItem.coerceToText(mockActivity)).thenReturn("something non-null"); + doThrow(new IOException()).when(mockAssetFileDescriptor).close(); + + ClipData clip = new ClipData("label", new String[0], mockItem); + + assertNull(platformPlugin.mPlatformMessageHandler.getClipboardData(clipboardFormat)); + clipboardManager.setPrimaryClip(clip); + assertNotNull(platformPlugin.mPlatformMessageHandler.getClipboardData(clipboardFormat)); + } + + @Test + public void platformPlugin_getClipboardDataIsNonNullWhenContentUriWithTextProvided() + throws IOException { + View fakeDecorView = mock(View.class); + Window fakeWindow = mock(Window.class); + Activity mockActivity = mock(Activity.class); + when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); + when(mockActivity.getWindow()).thenReturn(fakeWindow); + PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); + setUpForTextClipboardTests(mockActivity); + ContentResolver contentResolver = mock(ContentResolver.class); + ClipData.Item mockItem = mock(ClipData.Item.class); + Uri mockUri = mock(Uri.class); + + when(mockActivity.getContentResolver()).thenReturn(contentResolver); + when(mockUri.getScheme()).thenReturn("content"); + when(mockItem.getText()).thenReturn(null); + when(mockItem.getUri()).thenReturn(mockUri); + when(contentResolver.openTypedAssetFileDescriptor(any(Uri.class), any(), any())) + .thenReturn(mock(AssetFileDescriptor.class)); + when(mockItem.coerceToText(mockActivity)).thenReturn("something non-null"); + + ClipData clip = new ClipData("label", new String[0], mockItem); + + assertNull(platformPlugin.mPlatformMessageHandler.getClipboardData(clipboardFormat)); + clipboardManager.setPrimaryClip(clip); + assertNotNull(platformPlugin.mPlatformMessageHandler.getClipboardData(clipboardFormat)); + } + + @Test + public void platformPlugin_getClipboardDataIsNullWhenContentUriProvidedContainsNoText() + throws IOException { + View fakeDecorView = mock(View.class); + Window fakeWindow = mock(Window.class); + Activity mockActivity = mock(Activity.class); + when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); + when(mockActivity.getWindow()).thenReturn(fakeWindow); + PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); + setUpForTextClipboardTests(mockActivity); + ContentResolver contentResolver = ctx.getContentResolver(); + + when(mockActivity.getContentResolver()).thenReturn(contentResolver); + + Uri uri = Uri.parse("content://media/external_primary/images/media/"); + ClipData clip = ClipData.newUri(contentResolver, "URI", uri); + + clipboardManager.setPrimaryClip(clip); + assertNull(platformPlugin.mPlatformMessageHandler.getClipboardData(clipboardFormat)); + } + + @Test + public void platformPlugin_getClipboardDataIsNullWhenNonContentUriProvided() throws IOException { + View fakeDecorView = mock(View.class); + Window fakeWindow = mock(Window.class); + Activity mockActivity = mock(Activity.class); + when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); + when(mockActivity.getWindow()).thenReturn(fakeWindow); + PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); + setUpForTextClipboardTests(mockActivity); + ContentResolver contentResolver = ctx.getContentResolver(); + + when(mockActivity.getContentResolver()).thenReturn(contentResolver); + + Uri uri = Uri.parse("file:///"); + ClipData clip = ClipData.newUri(contentResolver, "URI", uri); + + clipboardManager.setPrimaryClip(clip); + assertNull(platformPlugin.mPlatformMessageHandler.getClipboardData(clipboardFormat)); + } + + @Test + public void platformPlugin_getClipboardDataIsNullWhenItemHasNoTextNorUri() throws IOException { + View fakeDecorView = mock(View.class); + Window fakeWindow = mock(Window.class); + Activity mockActivity = mock(Activity.class); + when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); + when(mockActivity.getWindow()).thenReturn(fakeWindow); + PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); + setUpForTextClipboardTests(mockActivity); + ClipData.Item mockItem = mock(ClipData.Item.class); + + when(mockItem.getText()).thenReturn(null); + when(mockItem.getUri()).thenReturn(null); + + ClipData clip = new ClipData("label", new String[0], mockItem); + + clipboardManager.setPrimaryClip(clip); + assertNull(platformPlugin.mPlatformMessageHandler.getClipboardData(clipboardFormat)); + } + + @SuppressWarnings("deprecation") + // ClipboardManager.getText + @Config(sdk = API_LEVELS.API_28) + @Test + public void platformPlugin_hasStrings() { + View fakeDecorView = mock(View.class); + Window fakeWindow = mock(Window.class); + Activity mockActivity = mock(Activity.class); + when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); + when(mockActivity.getWindow()).thenReturn(fakeWindow); + PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); + setUpForTextClipboardTests(mockActivity); + + // Plain text + ClipData clip = ClipData.newPlainText("label", "Text"); + clipboardManager.setPrimaryClip(clip); + assertTrue(platformPlugin.mPlatformMessageHandler.clipboardHasStrings()); + + // Empty plain text + clip = ClipData.newPlainText("", ""); + clipboardManager.setPrimaryClip(clip); + // Without actually accessing clipboard data (preferred behavior), it is not possible to + // distinguish between empty and non-empty string contents. + assertTrue(platformPlugin.mPlatformMessageHandler.clipboardHasStrings()); + + // HTML text + clip = ClipData.newHtmlText("motto", "Don't be evil", "Don't be evil"); + clipboardManager.setPrimaryClip(clip); + assertTrue(platformPlugin.mPlatformMessageHandler.clipboardHasStrings()); + + // Text MIME type + clip = new ClipData("label", new String[] {"text/something"}, new ClipData.Item("content")); + clipboardManager.setPrimaryClip(clip); + assertTrue(platformPlugin.mPlatformMessageHandler.clipboardHasStrings()); + + // Other MIME type + clip = + new ClipData( + "label", new String[] {"application/octet-stream"}, new ClipData.Item("content")); + clipboardManager.setPrimaryClip(clip); + assertFalse(platformPlugin.mPlatformMessageHandler.clipboardHasStrings()); + + if (Build.VERSION.SDK_INT >= API_LEVELS.API_28) { + // Empty clipboard + clipboardManager.clearPrimaryClip(); + assertFalse(platformPlugin.mPlatformMessageHandler.clipboardHasStrings()); + } + + // Verify that the clipboard contents are never accessed. + verify(clipboardManager, never()).getPrimaryClip(); + verify(clipboardManager, never()).getText(); + } + + @Config(sdk = API_LEVELS.API_29) + @SuppressWarnings("deprecation") + // setStatusBarColor, setNavigationBarColor, setNavigationBarDividerColor, + // setStatusBarContrastEnforced, setNavigationBarContrastEnforced + @Test + public void setNavigationBarDividerColor() { + View fakeDecorView = mock(View.class); + Window fakeWindow = mock(Window.class); + Activity mockActivity = mock(Activity.class); + when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); + when(mockActivity.getWindow()).thenReturn(fakeWindow); + PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); + + if (Build.VERSION.SDK_INT >= API_LEVELS.API_28) { + // Default style test + SystemChromeStyle style = + new SystemChromeStyle( + 0XFF000000, // statusBarColor + Brightness.LIGHT, // statusBarIconBrightness + true, // systemStatusBarContrastEnforced + 0XFFC70039, // systemNavigationBarColor + Brightness.LIGHT, // systemNavigationBarIconBrightness + 0XFF006DB3, // systemNavigationBarDividerColor + true); // systemNavigationBarContrastEnforced + + platformPlugin.mPlatformMessageHandler.setSystemUiOverlayStyle(style); + + verify(fakeWindow).setStatusBarColor(0xFF000000); + verify(fakeWindow).setNavigationBarColor(0XFFC70039); + verify(fakeWindow).setNavigationBarDividerColor(0XFF006DB3); + verify(fakeWindow).setStatusBarContrastEnforced(true); + verify(fakeWindow).setNavigationBarContrastEnforced(true); + + // Regression test for https://github.com/flutter/flutter/issues/88431 + // A null brightness should not affect changing color settings. + style = + new SystemChromeStyle( + 0XFF006DB3, // statusBarColor + null, // statusBarIconBrightness + false, // systemStatusBarContrastEnforced + 0XFF000000, // systemNavigationBarColor + null, // systemNavigationBarIconBrightness + 0XFF006DB3, // systemNavigationBarDividerColor + false); // systemNavigationBarContrastEnforced + + platformPlugin.mPlatformMessageHandler.setSystemUiOverlayStyle(style); + + verify(fakeWindow).setStatusBarColor(0XFF006DB3); + verify(fakeWindow).setNavigationBarColor(0XFF000000); + verify(fakeWindow, times(2)).setNavigationBarDividerColor(0XFF006DB3); + verify(fakeWindow).setStatusBarContrastEnforced(false); + verify(fakeWindow).setNavigationBarContrastEnforced(false); + + // Null contrasts values should be allowed. + style = + new SystemChromeStyle( + 0XFF006DB3, // statusBarColor + null, // statusBarIconBrightness + null, // systemStatusBarContrastEnforced + 0XFF000000, // systemNavigationBarColor + null, // systemNavigationBarIconBrightness + 0XFF006DB3, // systemNavigationBarDividerColor + null); // systemNavigationBarContrastEnforced + + platformPlugin.mPlatformMessageHandler.setSystemUiOverlayStyle(style); + + verify(fakeWindow, times(2)).setStatusBarColor(0XFF006DB3); + verify(fakeWindow, times(2)).setNavigationBarColor(0XFF000000); + verify(fakeWindow, times(3)).setNavigationBarDividerColor(0XFF006DB3); + // Count is 1 each from earlier calls + verify(fakeWindow, times(1)).setStatusBarContrastEnforced(true); + verify(fakeWindow, times(1)).setNavigationBarContrastEnforced(true); + verify(fakeWindow, times(1)).setStatusBarContrastEnforced(false); + verify(fakeWindow, times(1)).setNavigationBarContrastEnforced(false); + } + } + + @Config(sdk = API_LEVELS.API_30) + @Test + public void setNavigationBarIconBrightness() { + View fakeDecorView = mock(View.class); + Window fakeWindow = mock(Window.class); + Activity mockActivity = mock(Activity.class); + when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); + when(mockActivity.getWindow()).thenReturn(fakeWindow); + PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); + + if (Build.VERSION.SDK_INT >= API_LEVELS.API_30) { + WindowInsetsController fakeWindowInsetsController = mock(WindowInsetsController.class); + when(fakeWindow.getInsetsController()).thenReturn(fakeWindowInsetsController); + + SystemChromeStyle style = + new SystemChromeStyle( + null, // statusBarColor + null, // statusBarIconBrightness + null, // systemStatusBarContrastEnforced + null, // systemNavigationBarColor + Brightness.LIGHT, // systemNavigationBarIconBrightness + null, // systemNavigationBarDividerColor + null); // systemNavigationBarContrastEnforced + + platformPlugin.mPlatformMessageHandler.setSystemUiOverlayStyle(style); + + verify(fakeWindowInsetsController) + .setSystemBarsAppearance(0, APPEARANCE_LIGHT_NAVIGATION_BARS); + + style = + new SystemChromeStyle( + null, // statusBarColor + null, // statusBarIconBrightness + null, // systemStatusBarContrastEnforced + null, // systemNavigationBarColor + Brightness.DARK, // systemNavigationBarIconBrightness + null, // systemNavigationBarDividerColor + null); // systemNavigationBarContrastEnforced + + platformPlugin.mPlatformMessageHandler.setSystemUiOverlayStyle(style); + + verify(fakeWindowInsetsController) + .setSystemBarsAppearance( + APPEARANCE_LIGHT_NAVIGATION_BARS, APPEARANCE_LIGHT_NAVIGATION_BARS); + } + } + + @Config(sdk = API_LEVELS.API_30) + @Test + public void setStatusBarIconBrightness() { + View fakeDecorView = mock(View.class); + Window fakeWindow = mock(Window.class); + Activity mockActivity = mock(Activity.class); + when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); + when(mockActivity.getWindow()).thenReturn(fakeWindow); + PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); + + if (Build.VERSION.SDK_INT >= API_LEVELS.API_30) { + WindowInsetsController fakeWindowInsetsController = mock(WindowInsetsController.class); + when(fakeWindow.getInsetsController()).thenReturn(fakeWindowInsetsController); + + SystemChromeStyle style = + new SystemChromeStyle( + null, // statusBarColor + Brightness.LIGHT, // statusBarIconBrightness + null, // systemStatusBarContrastEnforced + null, // systemNavigationBarColor + null, // systemNavigationBarIconBrightness + null, // systemNavigationBarDividerColor + null); // systemNavigationBarContrastEnforced + + platformPlugin.mPlatformMessageHandler.setSystemUiOverlayStyle(style); + + verify(fakeWindowInsetsController).setSystemBarsAppearance(0, APPEARANCE_LIGHT_STATUS_BARS); + + style = + new SystemChromeStyle( + null, // statusBarColor + Brightness.DARK, // statusBarIconBrightness + null, // systemStatusBarContrastEnforced + null, // systemNavigationBarColor + null, // systemNavigationBarIconBrightness + null, // systemNavigationBarDividerColor + null); // systemNavigationBarContrastEnforced + + platformPlugin.mPlatformMessageHandler.setSystemUiOverlayStyle(style); + + verify(fakeWindowInsetsController) + .setSystemBarsAppearance(APPEARANCE_LIGHT_STATUS_BARS, APPEARANCE_LIGHT_STATUS_BARS); + } + } + + @SuppressWarnings("deprecation") + // SYSTEM_UI_FLAG_*, setSystemUiVisibility + @Config(sdk = API_LEVELS.API_29) + @Test + public void setSystemUiMode() { + View fakeDecorView = mock(View.class); + Window fakeWindow = mock(Window.class); + Activity mockActivity = mock(Activity.class); + when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); + when(mockActivity.getWindow()).thenReturn(fakeWindow); + PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); + + if (Build.VERSION.SDK_INT >= API_LEVELS.API_28) { + platformPlugin.mPlatformMessageHandler.showSystemUiMode( + PlatformChannel.SystemUiMode.LEAN_BACK); + verify(fakeDecorView) + .setSystemUiVisibility( + View.SYSTEM_UI_FLAG_LAYOUT_STABLE + | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN + | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_FULLSCREEN); + + platformPlugin.mPlatformMessageHandler.showSystemUiMode( + PlatformChannel.SystemUiMode.IMMERSIVE); + verify(fakeDecorView) + .setSystemUiVisibility( + View.SYSTEM_UI_FLAG_IMMERSIVE + | View.SYSTEM_UI_FLAG_LAYOUT_STABLE + | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN + | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_FULLSCREEN); + + platformPlugin.mPlatformMessageHandler.showSystemUiMode( + PlatformChannel.SystemUiMode.IMMERSIVE_STICKY); + verify(fakeDecorView) + .setSystemUiVisibility( + View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY + | View.SYSTEM_UI_FLAG_LAYOUT_STABLE + | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN + | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_FULLSCREEN); + } + + if (Build.VERSION.SDK_INT >= API_LEVELS.API_29) { + platformPlugin.mPlatformMessageHandler.showSystemUiMode( + PlatformChannel.SystemUiMode.EDGE_TO_EDGE); + verify(fakeDecorView) + .setSystemUiVisibility( + View.SYSTEM_UI_FLAG_LAYOUT_STABLE + | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); + } + } + + @SuppressWarnings("deprecation") + // SYSTEM_UI_FLAG_FULLSCREEN + @Test + public void setSystemUiModeListener_overlaysAreHidden() { + ActivityController controller = Robolectric.buildActivity(Activity.class); + controller.setup(); + Activity fakeActivity = controller.get(); + + PlatformPlugin platformPlugin = new PlatformPlugin(fakeActivity, mockPlatformChannel); + + // Subscribe to system UI visibility events. + platformPlugin.mPlatformMessageHandler.setSystemUiChangeListener(); + + // Simulate system UI changed to full screen. + fakeActivity + .getWindow() + .getDecorView() + .dispatchSystemUiVisibilityChanged(View.SYSTEM_UI_FLAG_FULLSCREEN); + + // No events should have been sent to the platform channel yet. They are scheduled for + // the next frame. + verify(mockPlatformChannel, never()).systemChromeChanged(anyBoolean()); + + // Simulate the next frame. + ShadowLooper.runUiThreadTasksIncludingDelayedTasks(); + + // Now the platform channel should receive the event. + verify(mockPlatformChannel).systemChromeChanged(false); + } + + @SuppressWarnings("deprecation") + // dispatchSystemUiVisibilityChanged + @Test + public void setSystemUiModeListener_overlaysAreVisible() { + ActivityController controller = Robolectric.buildActivity(Activity.class); + controller.setup(); + Activity fakeActivity = controller.get(); + PlatformPlugin platformPlugin = new PlatformPlugin(fakeActivity, mockPlatformChannel); + + // Subscribe to system Ui visibility events. + platformPlugin.mPlatformMessageHandler.setSystemUiChangeListener(); + + // Simulate system UI changed to *not* full screen. + fakeActivity.getWindow().getDecorView().dispatchSystemUiVisibilityChanged(0); + + // No events should have been sent to the platform channel yet. They are scheduled for + // the next frame. + verify(mockPlatformChannel, never()).systemChromeChanged(anyBoolean()); + + // Simulate the next frame. + ShadowLooper.runUiThreadTasksIncludingDelayedTasks(); + + // Now the platform channel should receive the event. + verify(mockPlatformChannel).systemChromeChanged(true); + } + + @SuppressWarnings("deprecation") + // SYSTEM_UI_FLAG_*, setSystemUiVisibility + @Config(sdk = API_LEVELS.API_28) + @Test + public void doNotEnableEdgeToEdgeOnOlderSdk() { + View fakeDecorView = mock(View.class); + Window fakeWindow = mock(Window.class); + Activity mockActivity = mock(Activity.class); + when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); + when(mockActivity.getWindow()).thenReturn(fakeWindow); + PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); + + platformPlugin.mPlatformMessageHandler.showSystemUiMode( + PlatformChannel.SystemUiMode.EDGE_TO_EDGE); + verify(fakeDecorView, never()) + .setSystemUiVisibility( + View.SYSTEM_UI_FLAG_LAYOUT_STABLE + | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); + } + + @SuppressWarnings("deprecation") + // FLAG_TRANSLUCENT_STATUS, FLAG_TRANSLUCENT_NAVIGATION + @Config(sdk = API_LEVELS.API_29) + @Test + public void verifyWindowFlagsSetToStyleOverlays() { + View fakeDecorView = mock(View.class); + Window fakeWindow = mock(Window.class); + Activity mockActivity = mock(Activity.class); + when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); + when(mockActivity.getWindow()).thenReturn(fakeWindow); + PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); + + SystemChromeStyle style = + new SystemChromeStyle( + 0XFF000000, Brightness.LIGHT, true, 0XFFC70039, Brightness.LIGHT, 0XFF006DB3, true); + + platformPlugin.mPlatformMessageHandler.setSystemUiOverlayStyle(style); + verify(fakeWindow).addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); + verify(fakeWindow) + .clearFlags( + WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS + | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); + } + + @Test + public void setFrameworkHandlesBackFlutterActivity() { + Activity mockActivity = mock(Activity.class); + PlatformPluginDelegate mockPlatformPluginDelegate = mock(PlatformPluginDelegate.class); + PlatformPlugin platformPlugin = + new PlatformPlugin(mockActivity, mockPlatformChannel, mockPlatformPluginDelegate); + + platformPlugin.mPlatformMessageHandler.setFrameworkHandlesBack(true); + + verify(mockPlatformPluginDelegate, times(1)).setFrameworkHandlesBack(true); + } + + @Test + public void testPlatformPluginDelegateNull() throws Exception { + Activity mockActivity = mock(Activity.class); + PlatformPlugin platformPlugin = + new PlatformPlugin(mockActivity, mockPlatformChannel, null /*platformPluginDelegate*/); + + try { + platformPlugin.mPlatformMessageHandler.setFrameworkHandlesBack(true); + } catch (NullPointerException e) { + // Not expected + fail("NullPointerException was thrown"); + } + } + + @Test + public void popSystemNavigatorFlutterActivity() { + Activity mockActivity = mock(Activity.class); + PlatformPluginDelegate mockPlatformPluginDelegate = mock(PlatformPluginDelegate.class); + PlatformPlugin platformPlugin = + new PlatformPlugin(mockActivity, mockPlatformChannel, mockPlatformPluginDelegate); + + when(mockPlatformPluginDelegate.popSystemNavigator()).thenReturn(false); + + platformPlugin.mPlatformMessageHandler.popSystemNavigator(); + + verify(mockPlatformPluginDelegate, times(1)).popSystemNavigator(); + verify(mockActivity, times(1)).finish(); + } + + @Test + public void doesNotDoAnythingByDefaultIfPopSystemNavigatorOverridden() { + Activity mockActivity = mock(Activity.class); + PlatformPluginDelegate mockPlatformPluginDelegate = mock(PlatformPluginDelegate.class); + PlatformPlugin platformPlugin = + new PlatformPlugin(mockActivity, mockPlatformChannel, mockPlatformPluginDelegate); + + when(mockPlatformPluginDelegate.popSystemNavigator()).thenReturn(true); + + platformPlugin.mPlatformMessageHandler.popSystemNavigator(); + + verify(mockPlatformPluginDelegate, times(1)).popSystemNavigator(); + // No longer perform the default action when overridden. + verify(mockActivity, never()).finish(); + } + + @SuppressWarnings("deprecation") + // Robolectric.setupActivity. + // TODO(reidbaker): https://github.com/flutter/flutter/issues/133151 + @Test + public void popSystemNavigatorFlutterFragment() { + // Migrate to ActivityScenario by following https://github.com/robolectric/robolectric/pull/4736 + FragmentActivity activity = spy(Robolectric.setupActivity(FragmentActivity.class)); + final AtomicBoolean onBackPressedCalled = new AtomicBoolean(false); + OnBackPressedCallback backCallback = + new OnBackPressedCallback(true) { + @Override + public void handleOnBackPressed() { + onBackPressedCalled.set(true); + } + }; + activity.getOnBackPressedDispatcher().addCallback(backCallback); + + PlatformPluginDelegate mockPlatformPluginDelegate = mock(PlatformPluginDelegate.class); + when(mockPlatformPluginDelegate.popSystemNavigator()).thenReturn(false); + PlatformPlugin platformPlugin = + new PlatformPlugin(activity, mockPlatformChannel, mockPlatformPluginDelegate); + + platformPlugin.mPlatformMessageHandler.popSystemNavigator(); + + verify(activity, never()).finish(); + verify(mockPlatformPluginDelegate, times(1)).popSystemNavigator(); + assertTrue(onBackPressedCalled.get()); + } + + @SuppressWarnings("deprecation") + // Robolectric.setupActivity. + // TODO(reidbaker): https://github.com/flutter/flutter/issues/133151 + @Test + public void doesNotDoAnythingByDefaultIfFragmentPopSystemNavigatorOverridden() { + FragmentActivity activity = spy(Robolectric.setupActivity(FragmentActivity.class)); + PlatformPluginDelegate mockPlatformPluginDelegate = mock(PlatformPluginDelegate.class); + when(mockPlatformPluginDelegate.popSystemNavigator()).thenReturn(true); + PlatformPlugin platformPlugin = + new PlatformPlugin(activity, mockPlatformChannel, mockPlatformPluginDelegate); + + platformPlugin.mPlatformMessageHandler.popSystemNavigator(); + + verify(mockPlatformPluginDelegate, times(1)).popSystemNavigator(); + // No longer perform the default action when overridden. + verify(activity, never()).finish(); + } + + @Test + public void setRequestedOrientationFlutterFragment() { + FragmentActivity mockFragmentActivity = mock(FragmentActivity.class); + PlatformPluginDelegate mockPlatformPluginDelegate = mock(PlatformPluginDelegate.class); + when(mockPlatformPluginDelegate.popSystemNavigator()).thenReturn(false); + PlatformPlugin platformPlugin = + new PlatformPlugin(mockFragmentActivity, mockPlatformChannel, mockPlatformPluginDelegate); + + platformPlugin.mPlatformMessageHandler.setPreferredOrientations(0); + + verify(mockFragmentActivity, times(1)).setRequestedOrientation(0); + } + + @Test + public void performsDefaultBehaviorWhenNoDelegateProvided() { + Activity mockActivity = mock(Activity.class); + PlatformChannel mockPlatformChannel = mock(PlatformChannel.class); + PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); + + platformPlugin.mPlatformMessageHandler.popSystemNavigator(); + + verify(mockActivity, times(1)).finish(); + } + + @Test + public void startChoosenActivityWhenSharingText() { + Activity mockActivity = mock(Activity.class); + PlatformChannel mockPlatformChannel = mock(PlatformChannel.class); + PlatformPluginDelegate mockPlatformPluginDelegate = mock(PlatformPluginDelegate.class); + PlatformPlugin platformPlugin = + new PlatformPlugin(mockActivity, mockPlatformChannel, mockPlatformPluginDelegate); + + // Mock Intent.createChooser (in real application it opens a chooser where the user can + // select which application will be used to share the selected text). + Intent choosenIntent = new Intent(); + MockedStatic intentClass = mockStatic(Intent.class); + ArgumentCaptor intentCaptor = ArgumentCaptor.forClass(Intent.class); + intentClass + .when(() -> Intent.createChooser(intentCaptor.capture(), any())) + .thenReturn(choosenIntent); + + final String expectedContent = "Flutter"; + platformPlugin.mPlatformMessageHandler.share(expectedContent); + + // Activity.startActivity should have been called. + verify(mockActivity, times(1)).startActivity(choosenIntent); + + // The intent action created by the plugin and passed to Intent.createChooser should be + // 'Intent.ACTION_SEND'. + Intent sendToIntent = intentCaptor.getValue(); + assertEquals(sendToIntent.getAction(), Intent.ACTION_SEND); + assertEquals(sendToIntent.getType(), "text/plain"); + assertEquals(sendToIntent.getStringExtra(Intent.EXTRA_TEXT), expectedContent); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/PlatformViewWrapperTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/PlatformViewWrapperTest.java new file mode 100644 index 0000000000000000000000000000000000000000..11c3094f982e73415fb4ced9d05dbbb172e81875 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/PlatformViewWrapperTest.java @@ -0,0 +1,281 @@ +// 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. + +package io.flutter.plugin.platform; + +import static android.view.View.OnFocusChangeListener; +import static io.flutter.Build.API_LEVELS; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; +import static org.mockito.Mockito.spy; + +import android.annotation.TargetApi; +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.Color; +import android.view.Surface; +import android.view.View; +import android.view.View.OnFocusChangeListener; +import android.view.ViewGroup; +import android.view.ViewTreeObserver; +import android.view.accessibility.AccessibilityEvent; +import android.widget.FrameLayout; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.renderer.FlutterRenderer; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.robolectric.annotation.Config; +import org.robolectric.annotation.Implementation; +import org.robolectric.annotation.Implements; + +@TargetApi(API_LEVELS.API_31) +@RunWith(AndroidJUnit4.class) +public class PlatformViewWrapperTest { + private final Context ctx = ApplicationProvider.getApplicationContext(); + + @Test + public void invalidateChildInParent_callsInvalidate() { + final PlatformViewWrapper wrapper = spy(new PlatformViewWrapper(ctx)); + + // Mock Android framework calls. + wrapper.invalidateChildInParent(null, null); + + // Verify. + verify(wrapper, times(1)).invalidate(); + } + + @Test + public void draw_withoutSurface() { + final PlatformViewWrapper wrapper = + new PlatformViewWrapper(ctx) { + @Override + public void onDraw(Canvas canvas) { + canvas.drawColor(Color.RED); + } + }; + // Test. + final Canvas canvas = mock(Canvas.class); + wrapper.draw(canvas); + + // Verify. + verify(canvas, times(1)).drawColor(Color.RED); + } + + @Test + public void draw_withoutValidSurface() { + FlutterRenderer.debugDisableSurfaceClear = true; + final Surface surface = mock(Surface.class); + when(surface.isValid()).thenReturn(false); + final PlatformViewRenderTarget renderTarget = mock(PlatformViewRenderTarget.class); + when(renderTarget.getSurface()).thenReturn(surface); + + final PlatformViewWrapper wrapper = new PlatformViewWrapper(ctx, renderTarget); + final Canvas canvas = mock(Canvas.class); + wrapper.draw(canvas); + + verify(canvas, times(0)).drawColor(Color.TRANSPARENT, android.graphics.PorterDuff.Mode.CLEAR); + } + + @Test + public void draw_withValidSurface() { + FlutterRenderer.debugDisableSurfaceClear = true; + final Canvas canvas = mock(Canvas.class); + final Surface surface = mock(Surface.class); + when(surface.isValid()).thenReturn(true); + final PlatformViewRenderTarget renderTarget = mock(PlatformViewRenderTarget.class); + when(renderTarget.getSurface()).thenReturn(surface); + when(surface.lockHardwareCanvas()).thenReturn(canvas); + final PlatformViewWrapper wrapper = new PlatformViewWrapper(ctx, renderTarget); + + wrapper.draw(canvas); + + verify(canvas, times(1)).drawColor(Color.TRANSPARENT, android.graphics.PorterDuff.Mode.CLEAR); + } + + @Test + public void focusChangeListener_hasFocus() { + final ViewTreeObserver viewTreeObserver = mock(ViewTreeObserver.class); + when(viewTreeObserver.isAlive()).thenReturn(true); + + final PlatformViewWrapper view = + new PlatformViewWrapper(ctx) { + @Override + public ViewTreeObserver getViewTreeObserver() { + return viewTreeObserver; + } + + @Override + public boolean hasFocus() { + return true; + } + }; + + final OnFocusChangeListener focusListener = mock(OnFocusChangeListener.class); + view.setOnDescendantFocusChangeListener(focusListener); + + final ArgumentCaptor focusListenerCaptor = + ArgumentCaptor.forClass(ViewTreeObserver.OnGlobalFocusChangeListener.class); + verify(viewTreeObserver).addOnGlobalFocusChangeListener(focusListenerCaptor.capture()); + + focusListenerCaptor.getValue().onGlobalFocusChanged(null, null); + verify(focusListener).onFocusChange(view, true); + } + + @Test + public void focusChangeListener_doesNotHaveFocus() { + final ViewTreeObserver viewTreeObserver = mock(ViewTreeObserver.class); + when(viewTreeObserver.isAlive()).thenReturn(true); + + final PlatformViewWrapper view = + new PlatformViewWrapper(ctx) { + @Override + public ViewTreeObserver getViewTreeObserver() { + return viewTreeObserver; + } + + @Override + public boolean hasFocus() { + return false; + } + }; + + final OnFocusChangeListener focusListener = mock(OnFocusChangeListener.class); + view.setOnDescendantFocusChangeListener(focusListener); + + final ArgumentCaptor focusListenerCaptor = + ArgumentCaptor.forClass(ViewTreeObserver.OnGlobalFocusChangeListener.class); + verify(viewTreeObserver).addOnGlobalFocusChangeListener(focusListenerCaptor.capture()); + + focusListenerCaptor.getValue().onGlobalFocusChanged(null, null); + verify(focusListener).onFocusChange(view, false); + } + + @Test + public void focusChangeListener_viewTreeObserverIsAliveFalseDoesNotThrow() { + final PlatformViewWrapper view = + new PlatformViewWrapper(ctx) { + @Override + public ViewTreeObserver getViewTreeObserver() { + final ViewTreeObserver viewTreeObserver = mock(ViewTreeObserver.class); + when(viewTreeObserver.isAlive()).thenReturn(false); + return viewTreeObserver; + } + }; + view.setOnDescendantFocusChangeListener(mock(OnFocusChangeListener.class)); + } + + @Test + public void setOnDescendantFocusChangeListener_keepsSingleListener() { + final ViewTreeObserver viewTreeObserver = mock(ViewTreeObserver.class); + when(viewTreeObserver.isAlive()).thenReturn(true); + + final PlatformViewWrapper view = + new PlatformViewWrapper(ctx) { + @Override + public ViewTreeObserver getViewTreeObserver() { + return viewTreeObserver; + } + }; + + assertNull(view.getActiveFocusListener()); + + view.setOnDescendantFocusChangeListener(mock(OnFocusChangeListener.class)); + assertNotNull(view.getActiveFocusListener()); + + final ViewTreeObserver.OnGlobalFocusChangeListener activeFocusListener = + view.getActiveFocusListener(); + + view.setOnDescendantFocusChangeListener(mock(OnFocusChangeListener.class)); + assertNotNull(view.getActiveFocusListener()); + + verify(viewTreeObserver, times(1)).removeOnGlobalFocusChangeListener(activeFocusListener); + } + + @Test + public void unsetOnDescendantFocusChangeListener_removesActiveListener() { + final ViewTreeObserver viewTreeObserver = mock(ViewTreeObserver.class); + when(viewTreeObserver.isAlive()).thenReturn(true); + + final PlatformViewWrapper view = + new PlatformViewWrapper(ctx) { + @Override + public ViewTreeObserver getViewTreeObserver() { + return viewTreeObserver; + } + }; + + assertNull(view.getActiveFocusListener()); + + view.setOnDescendantFocusChangeListener(mock(OnFocusChangeListener.class)); + assertNotNull(view.getActiveFocusListener()); + + final ViewTreeObserver.OnGlobalFocusChangeListener activeFocusListener = + view.getActiveFocusListener(); + + view.unsetOnDescendantFocusChangeListener(); + assertNull(view.getActiveFocusListener()); + + view.unsetOnDescendantFocusChangeListener(); + verify(viewTreeObserver, times(1)).removeOnGlobalFocusChangeListener(activeFocusListener); + } + + @Test + @Config( + shadows = { + ShadowFrameLayout.class, + ShadowViewGroup.class, + }) + public void ignoreAccessibilityEvents() { + final PlatformViewWrapper wrapperView = new PlatformViewWrapper(ctx); + + final View embeddedView = mock(View.class); + wrapperView.addView(embeddedView); + + when(embeddedView.getImportantForAccessibility()) + .thenReturn(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); + final boolean eventSent = + wrapperView.requestSendAccessibilityEvent(embeddedView, mock(AccessibilityEvent.class)); + assertFalse(eventSent); + } + + @Test + @Config( + shadows = { + ShadowFrameLayout.class, + ShadowViewGroup.class, + }) + public void sendAccessibilityEvents() { + final PlatformViewWrapper wrapperView = new PlatformViewWrapper(ctx); + + final View embeddedView = mock(View.class); + wrapperView.addView(embeddedView); + + when(embeddedView.getImportantForAccessibility()) + .thenReturn(View.IMPORTANT_FOR_ACCESSIBILITY_YES); + boolean eventSent = + wrapperView.requestSendAccessibilityEvent(embeddedView, mock(AccessibilityEvent.class)); + assertTrue(eventSent); + + when(embeddedView.getImportantForAccessibility()) + .thenReturn(View.IMPORTANT_FOR_ACCESSIBILITY_AUTO); + eventSent = + wrapperView.requestSendAccessibilityEvent(embeddedView, mock(AccessibilityEvent.class)); + assertTrue(eventSent); + } + + @Implements(ViewGroup.class) + public static class ShadowViewGroup extends org.robolectric.shadows.ShadowViewGroup { + @Implementation + protected boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { + return true; + } + } + + @Implements(FrameLayout.class) + public static class ShadowFrameLayout + extends io.flutter.plugin.platform.PlatformViewWrapperTest.ShadowViewGroup {} +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/PlatformViewsController2Test.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/PlatformViewsController2Test.java new file mode 100644 index 0000000000000000000000000000000000000000..9efe663813fe2dc90c091352b1ba3316624f5713 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/PlatformViewsController2Test.java @@ -0,0 +1,748 @@ +// 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. + +package io.flutter.plugin.platform; + +import static io.flutter.embedding.engine.systemchannels.PlatformViewsChannel2.PlatformViewTouch; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +import android.app.Presentation; +import android.content.Context; +import android.content.res.AssetManager; +import android.util.SparseArray; +import android.view.MotionEvent; +import android.view.Surface; +import android.view.SurfaceHolder; +import android.view.SurfaceView; +import android.view.View; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.android.FlutterImageView; +import io.flutter.embedding.android.FlutterSurfaceView; +import io.flutter.embedding.android.FlutterView; +import io.flutter.embedding.android.MotionEventTracker; +import io.flutter.embedding.engine.FlutterEngine; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.dart.DartExecutor; +import io.flutter.embedding.engine.mutatorsstack.FlutterMutatorView; +import io.flutter.embedding.engine.renderer.FlutterRenderer; +import io.flutter.embedding.engine.systemchannels.AccessibilityChannel; +import io.flutter.embedding.engine.systemchannels.MouseCursorChannel; +import io.flutter.embedding.engine.systemchannels.PlatformViewsChannel2; +import io.flutter.embedding.engine.systemchannels.PlatformViewsChannel2.PlatformViewTouch; +import io.flutter.embedding.engine.systemchannels.ScribeChannel; +import io.flutter.embedding.engine.systemchannels.SettingsChannel; +import io.flutter.embedding.engine.systemchannels.TextInputChannel; +import io.flutter.plugin.common.MethodCall; +import io.flutter.plugin.common.StandardMessageCodec; +import io.flutter.plugin.common.StandardMethodCodec; +import io.flutter.plugin.localization.LocalizationPlugin; +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; +import org.robolectric.annotation.Implementation; +import org.robolectric.annotation.Implements; +import org.robolectric.shadows.ShadowDialog; +import org.robolectric.shadows.ShadowSurfaceView; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class PlatformViewsController2Test { + // An implementation of PlatformView that counts invocations of its lifecycle callbacks. + class CountingPlatformView implements PlatformView { + static final String VIEW_TYPE_ID = "CountingPlatformView"; + private View view; + + public CountingPlatformView(Context context) { + view = new SurfaceView(context); + } + + public int disposeCalls = 0; + public int attachCalls = 0; + public int detachCalls = 0; + + @Override + public void dispose() { + // We have been removed from the view hierarhy before the call to dispose. + assertNull(view.getParent()); + disposeCalls++; + } + + @Override + public View getView() { + return view; + } + + @Override + public void onFlutterViewAttached(View flutterView) { + attachCalls++; + } + + @Override + public void onFlutterViewDetached() { + detachCalls++; + } + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void itRemovesPlatformViewBeforeDiposeIsCalled() { + PlatformViewRegistryImpl registryImpl = new PlatformViewRegistryImpl(); + PlatformViewsController2 PlatformViewsController2 = new PlatformViewsController2(); + PlatformViewsController2.setRegistry(registryImpl); + FlutterJNI jni = new FlutterJNI(); + attach(jni, PlatformViewsController2); + // Get the platform view registry. + PlatformViewRegistry registry = PlatformViewsController2.getRegistry(); + + // Register a factory for our platform view. + registry.registerViewFactory( + CountingPlatformView.VIEW_TYPE_ID, + new PlatformViewFactory(StandardMessageCodec.INSTANCE) { + @Override + public PlatformView create(Context context, int viewId, Object args) { + return new CountingPlatformView(context); + } + }); + + // Create the platform view. + int viewId = 0; + final PlatformViewsChannel2.PlatformViewCreationRequest request = + new PlatformViewsChannel2.PlatformViewCreationRequest( + viewId, CountingPlatformView.VIEW_TYPE_ID, 128, 128, View.LAYOUT_DIRECTION_LTR, null); + PlatformView pView = PlatformViewsController2.createFlutterPlatformView(request); + assertTrue(pView instanceof CountingPlatformView); + CountingPlatformView cpv = (CountingPlatformView) pView; + + PlatformViewsController2.disposePlatformView(viewId); + assertEquals(1, cpv.disposeCalls); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void itNotifiesPlatformViewsOfEngineAttachmentAndDetachment() { + PlatformViewRegistryImpl registryImpl = new PlatformViewRegistryImpl(); + PlatformViewsController2 PlatformViewsController2 = new PlatformViewsController2(); + PlatformViewsController2.setRegistry(registryImpl); + FlutterJNI jni = new FlutterJNI(); + attach(jni, PlatformViewsController2); + // Get the platform view registry. + PlatformViewRegistry registry = PlatformViewsController2.getRegistry(); + + // Register a factory for our platform view. + registry.registerViewFactory( + CountingPlatformView.VIEW_TYPE_ID, + new PlatformViewFactory(StandardMessageCodec.INSTANCE) { + @Override + public PlatformView create(Context context, int viewId, Object args) { + return new CountingPlatformView(context); + } + }); + + // Create the platform view. + int viewId = 0; + final PlatformViewsChannel2.PlatformViewCreationRequest request = + new PlatformViewsChannel2.PlatformViewCreationRequest( + viewId, CountingPlatformView.VIEW_TYPE_ID, 128, 128, View.LAYOUT_DIRECTION_LTR, null); + + PlatformView pView = PlatformViewsController2.createFlutterPlatformView(request); + assertTrue(pView instanceof CountingPlatformView); + CountingPlatformView cpv = (CountingPlatformView) pView; + assertEquals(1, cpv.attachCalls); + assertEquals(0, cpv.detachCalls); + assertEquals(0, cpv.disposeCalls); + PlatformViewsController2.detachFromView(); + assertEquals(1, cpv.attachCalls); + assertEquals(1, cpv.detachCalls); + assertEquals(0, cpv.disposeCalls); + PlatformViewsController2.disposePlatformView(viewId); + } + + @Test + public void itUsesActionEventTypeFromFrameworkEventAsActionChanged() { + MotionEventTracker motionEventTracker = MotionEventTracker.getInstance(); + PlatformViewRegistryImpl registryImpl = new PlatformViewRegistryImpl(); + PlatformViewsController2 PlatformViewsController2 = new PlatformViewsController2(); + PlatformViewsController2.setRegistry(registryImpl); + + MotionEvent original = + MotionEvent.obtain( + 10, // downTime + 10, // eventTime + 261, // action + 0, // x + 0, // y + 0 // metaState + ); + + MotionEventTracker.MotionEventId motionEventId = motionEventTracker.track(original); + + PlatformViewTouch frameWorkTouch = + new PlatformViewTouch( + 0, // viewId + original.getDownTime(), + original.getEventTime(), + 0, // action + 1, // pointerCount + Arrays.asList(Arrays.asList(0, 0)), // pointer properties + Arrays.asList(Arrays.asList(0., 1., 2., 3., 4., 5., 6., 7., 8.)), // pointer coords + original.getMetaState(), + original.getButtonState(), + original.getXPrecision(), + original.getYPrecision(), + original.getDeviceId(), + original.getEdgeFlags(), + original.getSource(), + original.getFlags(), + motionEventId.getId()); + MotionEvent resolvedEvent = + PlatformViewsController2.toMotionEvent( + 1, // density + frameWorkTouch); + assertEquals(resolvedEvent.getAction(), original.getAction()); + assertNotEquals(resolvedEvent.getAction(), frameWorkTouch.action); + } + + private MotionEvent makePlatformViewTouchAndInvokeToMotionEvent( + PlatformViewsController2 PlatformViewsController2, + MotionEventTracker motionEventTracker, + MotionEvent original, + boolean usingVirtualDisplays) { + MotionEventTracker.MotionEventId motionEventId = motionEventTracker.track(original); + + // Construct a PlatformViewTouch.rawPointerPropertiesList by doing the inverse of + // PlatformViewsController2.parsePointerPropertiesList. + List> pointerProperties = + Arrays.asList(Arrays.asList(original.getPointerId(0), original.getToolType(0))); + // Construct a PlatformViewTouch.rawPointerCoords by doing the inverse of + // PlatformViewsController2.parsePointerCoordsList. + List> pointerCoordinates = + Arrays.asList( + Arrays.asList( + (double) original.getOrientation(), + (double) original.getPressure(), + (double) original.getSize(), + (double) original.getToolMajor(), + (double) original.getToolMinor(), + (double) original.getTouchMajor(), + (double) original.getTouchMinor(), + (double) original.getX(), + (double) original.getY())); + // Make a platform view touch from the motion event. + PlatformViewTouch frameWorkTouchNonVd = + new PlatformViewTouch( + 0, // viewId + original.getDownTime(), + original.getEventTime(), + original.getAction(), + 1, // pointerCount + pointerProperties, // pointer properties + pointerCoordinates, // pointer coords + original.getMetaState(), + original.getButtonState(), + original.getXPrecision(), + original.getYPrecision(), + original.getDeviceId(), + original.getEdgeFlags(), + original.getSource(), + original.getFlags(), + motionEventId.getId()); + + return PlatformViewsController2.toMotionEvent( + 1, // density + frameWorkTouchNonVd); + } + + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void getPlatformViewById() { + PlatformViewRegistryImpl registryImpl = new PlatformViewRegistryImpl(); + PlatformViewsController2 PlatformViewsController2 = new PlatformViewsController2(); + PlatformViewsController2.setRegistry(registryImpl); + + int platformViewId = 0; + assertNull(PlatformViewsController2.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + View androidView = mock(View.class); + when(platformView.getView()).thenReturn(androidView); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + PlatformViewsController2.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, PlatformViewsController2); + + // Simulate create call from the framework. + createPlatformView(jni, PlatformViewsController2, platformViewId, "testType"); + + assertTrue(PlatformViewsController2.initializePlatformViewIfNeeded(platformViewId)); + + View resultAndroidView = PlatformViewsController2.getPlatformViewById(platformViewId); + assertNotNull(resultAndroidView); + assertEquals(resultAndroidView, androidView); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void createPlatformViewMessage_initializesAndroidView() { + PlatformViewRegistryImpl registryImpl = new PlatformViewRegistryImpl(); + PlatformViewsController2 PlatformViewsController2 = new PlatformViewsController2(); + PlatformViewsController2.setRegistry(registryImpl); + + int platformViewId = 0; + assertNull(PlatformViewsController2.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + when(platformView.getView()).thenReturn(mock(View.class)); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + PlatformViewsController2.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, PlatformViewsController2); + + // Simulate create call from the framework. + createPlatformView(jni, PlatformViewsController2, platformViewId, "testType"); + verify(viewFactory, times(1)).create(any(), eq(platformViewId), any()); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void createPlatformViewMessage_setsAndroidViewLayoutDirection() { + PlatformViewRegistryImpl registryImpl = new PlatformViewRegistryImpl(); + PlatformViewsController2 PlatformViewsController2 = new PlatformViewsController2(); + PlatformViewsController2.setRegistry(registryImpl); + + int platformViewId = 0; + assertNull(PlatformViewsController2.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + + View androidView = mock(View.class); + when(platformView.getView()).thenReturn(androidView); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + PlatformViewsController2.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, PlatformViewsController2); + + // Simulate create call from the framework. + createPlatformView(jni, PlatformViewsController2, platformViewId, "testType"); + verify(androidView, times(1)).setLayoutDirection(0); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void createPlatformViewMessage_throwsIfViewIsNull() { + PlatformViewRegistryImpl registryImpl = new PlatformViewRegistryImpl(); + PlatformViewsController2 PlatformViewsController2 = new PlatformViewsController2(); + PlatformViewsController2.setRegistry(registryImpl); + + int platformViewId = 0; + assertNull(PlatformViewsController2.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + when(platformView.getView()).thenReturn(null); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + PlatformViewsController2.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, PlatformViewsController2); + + // Simulate create call from the framework. + createPlatformView(jni, PlatformViewsController2, platformViewId, "testType"); + assertEquals(ShadowFlutterJNI.getResponses().size(), 1); + + assertFalse(PlatformViewsController2.initializePlatformViewIfNeeded(platformViewId)); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void createHybridPlatformViewMessage_throwsIfViewIsNull() { + PlatformViewRegistryImpl registryImpl = new PlatformViewRegistryImpl(); + PlatformViewsController2 PlatformViewsController2 = new PlatformViewsController2(); + PlatformViewsController2.setRegistry(registryImpl); + + int platformViewId = 0; + assertNull(PlatformViewsController2.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + when(platformView.getView()).thenReturn(null); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + PlatformViewsController2.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, PlatformViewsController2); + + // Simulate create call from the framework. + createPlatformView(jni, PlatformViewsController2, platformViewId, "testType"); + assertEquals(ShadowFlutterJNI.getResponses().size(), 1); + + assertFalse(PlatformViewsController2.initializePlatformViewIfNeeded(platformViewId)); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void setPlatformViewDirection_throwIfPlatformViewNotFound() { + PlatformViewRegistryImpl registryImpl = new PlatformViewRegistryImpl(); + PlatformViewsController2 PlatformViewsController2 = new PlatformViewsController2(); + PlatformViewsController2.setRegistry(registryImpl); + + int platformViewId = 0; + assertNull(PlatformViewsController2.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + final View androidView = mock(View.class); + when(platformView.getView()).thenReturn(androidView); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + PlatformViewsController2.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, PlatformViewsController2); + + verify(androidView, never()).setLayoutDirection(anyInt()); + + // Simulate create call from the framework. + createPlatformView(jni, PlatformViewsController2, platformViewId, "testType"); + assertEquals(ShadowFlutterJNI.getResponses().size(), 1); + + // Simulate set direction call from the framework. + setLayoutDirection(jni, PlatformViewsController2, platformViewId, 1); + verify(androidView, times(1)).setLayoutDirection(1); + + // The limit value of reply message will be equal to 2 if the layout direction is set + // successfully, otherwise it will be much more than 2 due to the reply message contains + // an error message wrapped with exception detail information. + assertEquals(ShadowFlutterJNI.getResponses().get(0).limit(), 2); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void disposeAndroidView() { + PlatformViewRegistryImpl registryImpl = new PlatformViewRegistryImpl(); + PlatformViewsController2 PlatformViewsController2 = new PlatformViewsController2(); + PlatformViewsController2.setRegistry(registryImpl); + + int platformViewId = 0; + assertNull(PlatformViewsController2.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + + Context context = ApplicationProvider.getApplicationContext(); + View androidView = new View(context); + + when(platformView.getView()).thenReturn(androidView); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + PlatformViewsController2.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, PlatformViewsController2); + + // Simulate create call from the framework. + createPlatformView(jni, PlatformViewsController2, platformViewId, "testType"); + assertTrue(PlatformViewsController2.initializePlatformViewIfNeeded(platformViewId)); + + assertNotNull(androidView.getParent()); + assertTrue(androidView.getParent() instanceof FlutterMutatorView); + + // Simulate dispose call from the framework. + disposePlatformView(jni, PlatformViewsController2, platformViewId); + assertNull(androidView.getParent()); + + // Simulate create call from the framework. + createPlatformView(jni, PlatformViewsController2, platformViewId, "testType"); + assertTrue(PlatformViewsController2.initializePlatformViewIfNeeded(platformViewId)); + + assertNotNull(androidView.getParent()); + assertTrue(androidView.getParent() instanceof FlutterMutatorView); + verify(platformView, times(1)).dispose(); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void disposeNullAndroidView() { + PlatformViewRegistryImpl registryImpl = new PlatformViewRegistryImpl(); + PlatformViewsController2 PlatformViewsController2 = new PlatformViewsController2(); + PlatformViewsController2.setRegistry(registryImpl); + + int platformViewId = 0; + assertNull(PlatformViewsController2.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + + View androidView = mock(View.class); + when(platformView.getView()).thenReturn(androidView); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + PlatformViewsController2.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, PlatformViewsController2); + + // Simulate create call from the framework. + createPlatformView(jni, PlatformViewsController2, platformViewId, "testType"); + assertTrue(PlatformViewsController2.initializePlatformViewIfNeeded(platformViewId)); + + when(platformView.getView()).thenReturn(null); + + // Simulate dispose call from the framework. + disposePlatformView(jni, PlatformViewsController2, platformViewId); + verify(platformView, times(1)).dispose(); + } + + private static ByteBuffer encodeMethodCall(MethodCall call) { + final ByteBuffer buffer = StandardMethodCodec.INSTANCE.encodeMethodCall(call); + buffer.rewind(); + return buffer; + } + + private static void createPlatformView( + FlutterJNI jni, + PlatformViewsController2 PlatformViewsController2, + int platformViewId, + String viewType) { + final Map args = new HashMap<>(); + args.put("id", platformViewId); + args.put("viewType", viewType); + args.put("direction", 0); + args.put("width", 1.0); + args.put("height", 1.0); + + final MethodCall platformCreateMethodCall = new MethodCall("create", args); + + jni.handlePlatformMessage( + "flutter/platform_views_2", + encodeMethodCall(platformCreateMethodCall), + /*replyId=*/ 0, + /*messageData=*/ 0); + } + + private static void setLayoutDirection( + FlutterJNI jni, + PlatformViewsController2 PlatformViewsController2, + int platformViewId, + int direction) { + final Map args = new HashMap<>(); + args.put("id", platformViewId); + args.put("direction", direction); + + final MethodCall platformSetDirectionMethodCall = new MethodCall("setDirection", args); + + jni.handlePlatformMessage( + "flutter/platform_views_2", + encodeMethodCall(platformSetDirectionMethodCall), + /*replyId=*/ 0, + /*messageData=*/ 0); + } + + private static void disposePlatformView( + FlutterJNI jni, PlatformViewsController2 PlatformViewsController2, int platformViewId) { + + final Map args = new HashMap<>(); + args.put("id", platformViewId); + + final MethodCall platformDisposeMethodCall = new MethodCall("dispose", args); + + jni.handlePlatformMessage( + "flutter/platform_views_2", + encodeMethodCall(platformDisposeMethodCall), + /*replyId=*/ 0, + /*messageData=*/ 0); + } + + private static void synchronizeToNativeViewHierarchy( + FlutterJNI jni, PlatformViewsController2 PlatformViewsController2, boolean yes) { + + final MethodCall convertMethodCall = new MethodCall("synchronizeToNativeViewHierarchy", yes); + + jni.handlePlatformMessage( + "flutter/platform_views_2", + encodeMethodCall(convertMethodCall), + /*replyId=*/ 0, + /*messageData=*/ 0); + } + + private static FlutterView attach( + FlutterJNI jni, PlatformViewsController2 PlatformViewsController2) { + final Context context = ApplicationProvider.getApplicationContext(); + final FlutterView flutterView = + new FlutterView(context, new FlutterSurfaceView(context)) { + @Override + public FlutterImageView createImageView() { + final FlutterImageView view = mock(FlutterImageView.class); + when(view.acquireLatestImage()).thenReturn(true); + return mock(FlutterImageView.class); + } + }; + attachToFlutterView(jni, PlatformViewsController2, flutterView); + return flutterView; + } + + private static void attachToFlutterView( + FlutterJNI jni, PlatformViewsController2 PlatformViewsController2, FlutterView flutterView) { + final DartExecutor executor = new DartExecutor(jni, mock(AssetManager.class)); + executor.onAttachedToJNI(); + + final Context context = ApplicationProvider.getApplicationContext(); + PlatformViewsController2.attach(context, executor); + + PlatformViewsController oldController = new PlatformViewsController(); + + final FlutterEngine engine = mock(FlutterEngine.class); + when(engine.getRenderer()).thenReturn(new FlutterRenderer(jni)); + when(engine.getMouseCursorChannel()).thenReturn(mock(MouseCursorChannel.class)); + when(engine.getTextInputChannel()).thenReturn(mock(TextInputChannel.class)); + when(engine.getSettingsChannel()).thenReturn(new SettingsChannel(executor)); + when(engine.getScribeChannel()).thenReturn(mock(ScribeChannel.class)); + when(engine.getPlatformViewsController2()).thenReturn(PlatformViewsController2); + when(engine.getPlatformViewsController()).thenReturn(oldController); + when(engine.getLocalizationPlugin()).thenReturn(mock(LocalizationPlugin.class)); + when(engine.getAccessibilityChannel()).thenReturn(mock(AccessibilityChannel.class)); + when(engine.getDartExecutor()).thenReturn(executor); + + flutterView.attachToFlutterEngine(engine); + PlatformViewsController2.attachToView(flutterView); + } + + /** + * For convenience when writing tests, this allows us to make fake messages from Flutter via + * Platform Channels. Typically those calls happen on the ui thread which dispatches to the + * platform thread. Since tests run on the platform thread it makes it difficult to test without + * this, but isn't technically required. + */ + @Implements(io.flutter.embedding.engine.dart.PlatformTaskQueue.class) + public static class ShadowPlatformTaskQueue { + @Implementation + public void dispatch(Runnable runnable) { + runnable.run(); + } + } + + /** + * The shadow class of {@link Presentation} to simulate Presentation showing logic. + * + *

Robolectric doesn't support VirtualDisplay creating correctly now, so this shadow class is + * used to simulate custom logic for Presentation. + */ + @Implements(Presentation.class) + public static class ShadowPresentation extends ShadowDialog { + private boolean isShowing = false; + + public ShadowPresentation() {} + + @Implementation + protected void show() { + isShowing = true; + } + + @Implementation + protected void dismiss() { + isShowing = false; + } + + @Implementation + protected boolean isShowing() { + return isShowing; + } + } + + @Implements(FlutterJNI.class) + public static class ShadowFlutterJNI { + private static SparseArray replies = new SparseArray<>(); + + public ShadowFlutterJNI() {} + + @Implementation + public boolean getIsSoftwareRenderingEnabled() { + return false; + } + + @Implementation + public long performNativeAttach(FlutterJNI flutterJNI) { + return 1; + } + + @Implementation + public void dispatchPlatformMessage( + String channel, ByteBuffer message, int position, int responseId) {} + + @Implementation + public void onSurfaceCreated(Surface surface) {} + + @Implementation + public void onSurfaceDestroyed() {} + + @Implementation + public void onSurfaceWindowChanged(Surface surface) {} + + @Implementation + public void setViewportMetrics( + float devicePixelRatio, + int physicalWidth, + int physicalHeight, + int physicalPaddingTop, + int physicalPaddingRight, + int physicalPaddingBottom, + int physicalPaddingLeft, + int physicalViewInsetTop, + int physicalViewInsetRight, + int physicalViewInsetBottom, + int physicalViewInsetLeft, + int systemGestureInsetTop, + int systemGestureInsetRight, + int systemGestureInsetBottom, + int systemGestureInsetLeft, + int physicalTouchSlop, + int[] displayFeaturesBounds, + int[] displayFeaturesType, + int[] displayFeaturesState) {} + + @Implementation + public void invokePlatformMessageResponseCallback( + int responseId, ByteBuffer message, int position) { + replies.put(responseId, message); + } + + public static SparseArray getResponses() { + return replies; + } + } + + @Implements(SurfaceView.class) + public static class ShadowFlutterSurfaceView extends ShadowSurfaceView { + private final FakeSurfaceHolder holder = new FakeSurfaceHolder(); + + public static class FakeSurfaceHolder extends ShadowSurfaceView.FakeSurfaceHolder { + private final Surface surface = mock(Surface.class); + + public Surface getSurface() { + return surface; + } + + @Implementation + public void addCallback(SurfaceHolder.Callback callback) { + callback.surfaceCreated(this); + } + } + + public ShadowFlutterSurfaceView() {} + + @Implementation + public SurfaceHolder getHolder() { + return holder; + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/PlatformViewsControllerTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/PlatformViewsControllerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..1b40dc35f6605ead9fad37e19e7c06948269965c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/PlatformViewsControllerTest.java @@ -0,0 +1,1866 @@ +// 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. + +package io.flutter.plugin.platform; + +import static android.os.Looper.getMainLooper; +import static io.flutter.embedding.engine.systemchannels.PlatformViewsChannel.PlatformViewTouch; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; +import static org.robolectric.Shadows.shadowOf; + +import android.app.Presentation; +import android.content.Context; +import android.content.MutableContextWrapper; +import android.content.res.AssetManager; +import android.graphics.SurfaceTexture; +import android.media.Image; +import android.util.SparseArray; +import android.view.MotionEvent; +import android.view.Surface; +import android.view.SurfaceHolder; +import android.view.SurfaceView; +import android.view.View; +import android.view.ViewParent; +import android.widget.FrameLayout; +import android.widget.FrameLayout.LayoutParams; +import androidx.annotation.NonNull; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.android.FlutterImageView; +import io.flutter.embedding.android.FlutterSurfaceView; +import io.flutter.embedding.android.FlutterView; +import io.flutter.embedding.android.MotionEventTracker; +import io.flutter.embedding.engine.FlutterEngine; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.FlutterOverlaySurface; +import io.flutter.embedding.engine.dart.DartExecutor; +import io.flutter.embedding.engine.mutatorsstack.FlutterMutatorView; +import io.flutter.embedding.engine.mutatorsstack.FlutterMutatorsStack; +import io.flutter.embedding.engine.renderer.FlutterRenderer; +import io.flutter.embedding.engine.systemchannels.AccessibilityChannel; +import io.flutter.embedding.engine.systemchannels.MouseCursorChannel; +import io.flutter.embedding.engine.systemchannels.PlatformViewsChannel; +import io.flutter.embedding.engine.systemchannels.PlatformViewsChannel.PlatformViewTouch; +import io.flutter.embedding.engine.systemchannels.ScribeChannel; +import io.flutter.embedding.engine.systemchannels.SettingsChannel; +import io.flutter.embedding.engine.systemchannels.TextInputChannel; +import io.flutter.plugin.common.MethodCall; +import io.flutter.plugin.common.StandardMessageCodec; +import io.flutter.plugin.common.StandardMethodCodec; +import io.flutter.plugin.localization.LocalizationPlugin; +import io.flutter.view.TextureRegistry; +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.robolectric.annotation.Config; +import org.robolectric.annotation.Implementation; +import org.robolectric.annotation.Implements; +import org.robolectric.shadows.ShadowDialog; +import org.robolectric.shadows.ShadowSurfaceView; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class PlatformViewsControllerTest { + // An implementation of PlatformView that counts invocations of its lifecycle callbacks. + class CountingPlatformView implements PlatformView { + static final String VIEW_TYPE_ID = "CountingPlatformView"; + private View view; + + public CountingPlatformView(Context context) { + view = new SurfaceView(context); + } + + public int disposeCalls = 0; + public int attachCalls = 0; + public int detachCalls = 0; + + @Override + public void dispose() { + // We have been removed from the view hierarhy before the call to dispose. + assertNull(view.getParent()); + disposeCalls++; + } + + @Override + public View getView() { + return view; + } + + @Override + public void onFlutterViewAttached(View flutterView) { + attachCalls++; + } + + @Override + public void onFlutterViewDetached() { + detachCalls++; + } + } + + @Test + @Config( + shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}, + minSdk = 35) + public void itRemovesPlatformViewBeforeDiposeIsCalled() { + PlatformViewsController platformViewsController = new PlatformViewsController(); + FlutterJNI jni = new FlutterJNI(); + attach(jni, platformViewsController); + // Get the platform view registry. + PlatformViewRegistry registry = platformViewsController.getRegistry(); + + // Register a factory for our platform view. + registry.registerViewFactory( + CountingPlatformView.VIEW_TYPE_ID, + new PlatformViewFactory(StandardMessageCodec.INSTANCE) { + @Override + public PlatformView create(Context context, int viewId, Object args) { + return new CountingPlatformView(context); + } + }); + + // Create the platform view. + int viewId = 0; + final PlatformViewsChannel.PlatformViewCreationRequest request = + new PlatformViewsChannel.PlatformViewCreationRequest( + viewId, + CountingPlatformView.VIEW_TYPE_ID, + 0, + 0, + 128, + 128, + View.LAYOUT_DIRECTION_LTR, + null); + PlatformView pView = platformViewsController.createPlatformView(request, true); + assertTrue(pView instanceof CountingPlatformView); + CountingPlatformView cpv = (CountingPlatformView) pView; + platformViewsController.configureForTextureLayerComposition(pView, request); + verify(platformViewsController.textureRegistry, times(1)) + .createSurfaceProducer(TextureRegistry.SurfaceLifecycle.manual); + assertEquals(0, cpv.disposeCalls); + platformViewsController.disposePlatformView(viewId); + assertEquals(1, cpv.disposeCalls); + } + + @Test + @Config( + shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}, + minSdk = 29, + maxSdk = 34) + public void itPassesSurfaceLifecyleResetInBackgroundLeqApi34() { + PlatformViewsController platformViewsController = new PlatformViewsController(); + FlutterJNI jni = new FlutterJNI(); + attach(jni, platformViewsController); + // Get the platform view registry. + PlatformViewRegistry registry = platformViewsController.getRegistry(); + + // Register a factory for our platform view. + registry.registerViewFactory( + CountingPlatformView.VIEW_TYPE_ID, + new PlatformViewFactory(StandardMessageCodec.INSTANCE) { + @Override + public PlatformView create(Context context, int viewId, Object args) { + return new CountingPlatformView(context); + } + }); + + // Create the platform view. + int viewId = 0; + final PlatformViewsChannel.PlatformViewCreationRequest request = + new PlatformViewsChannel.PlatformViewCreationRequest( + viewId, + CountingPlatformView.VIEW_TYPE_ID, + 0, + 0, + 128, + 128, + View.LAYOUT_DIRECTION_LTR, + null); + PlatformView pView = platformViewsController.createPlatformView(request, true); + assertTrue(pView instanceof CountingPlatformView); + CountingPlatformView cpv = (CountingPlatformView) pView; + platformViewsController.configureForTextureLayerComposition(pView, request); + verify(platformViewsController.textureRegistry, times(1)) + .createSurfaceProducer(TextureRegistry.SurfaceLifecycle.resetInBackground); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void itNotifiesPlatformViewsOfEngineAttachmentAndDetachment() { + PlatformViewsController platformViewsController = new PlatformViewsController(); + FlutterJNI jni = new FlutterJNI(); + attach(jni, platformViewsController); + // Get the platform view registry. + PlatformViewRegistry registry = platformViewsController.getRegistry(); + + // Register a factory for our platform view. + registry.registerViewFactory( + CountingPlatformView.VIEW_TYPE_ID, + new PlatformViewFactory(StandardMessageCodec.INSTANCE) { + @Override + public PlatformView create(Context context, int viewId, Object args) { + return new CountingPlatformView(context); + } + }); + + // Create the platform view. + int viewId = 0; + final PlatformViewsChannel.PlatformViewCreationRequest request = + new PlatformViewsChannel.PlatformViewCreationRequest( + viewId, + CountingPlatformView.VIEW_TYPE_ID, + 0, + 0, + 128, + 128, + View.LAYOUT_DIRECTION_LTR, + null); + PlatformView pView = platformViewsController.createPlatformView(request, true); + assertTrue(pView instanceof CountingPlatformView); + CountingPlatformView cpv = (CountingPlatformView) pView; + assertEquals(1, cpv.attachCalls); + assertEquals(0, cpv.detachCalls); + assertEquals(0, cpv.disposeCalls); + platformViewsController.detachFromView(); + assertEquals(1, cpv.attachCalls); + assertEquals(1, cpv.detachCalls); + assertEquals(0, cpv.disposeCalls); + platformViewsController.disposePlatformView(viewId); + } + + @Ignore + @Test + public void itCancelsOldPresentationOnResize() { + // Setup test structure. + // Create a fake View that represents the View that renders a Flutter UI. + View fakeFlutterView = new View(ApplicationProvider.getApplicationContext()); + + // Create fake VirtualDisplayControllers. This requires internal knowledge of + // PlatformViewsController. We know that all PlatformViewsController does is + // forward view attachment/detachment calls to it's VirtualDisplayControllers. + // + // TODO(mattcarroll): once PlatformViewsController is refactored into testable + // pieces, remove this test and avoid verifying private behavior. + VirtualDisplayController fakeVdController1 = mock(VirtualDisplayController.class); + + SingleViewPresentation presentation = fakeVdController1.presentation; + + fakeVdController1.resize(10, 10, null); + + assertEquals(fakeVdController1.presentation != presentation, true); + assertEquals(presentation.isShowing(), false); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void virtualDisplay_handlesResizeResponseWithoutContext() { + final int platformViewId = 0; + FlutterView fakeFlutterView = new FlutterView(ApplicationProvider.getApplicationContext()); + VirtualDisplayController fakeVdController = mock(VirtualDisplayController.class); + PlatformViewsController platformViewsController = new PlatformViewsController(); + platformViewsController.vdControllers.put(platformViewId, fakeVdController); + + platformViewsController.attachToView(fakeFlutterView); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, platformViewsController); + + resize(jni, platformViewsController, platformViewId, 10.0, 20.0); + + ArgumentCaptor resizeCallbackCaptor = ArgumentCaptor.forClass(Runnable.class); + verify(fakeVdController, times(1)).resize(anyInt(), anyInt(), resizeCallbackCaptor.capture()); + + // Simulate a detach call before the resize completes. + platformViewsController.detach(); + + // Trigger the callback to ensure that it doesn't crash. + resizeCallbackCaptor.getValue().run(); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void virtualDisplay_ensureDisposeVirtualDisplayController() { + final int platformViewId = 0; + FlutterView fakeFlutterView = new FlutterView(ApplicationProvider.getApplicationContext()); + VirtualDisplayController fakeVdController = mock(VirtualDisplayController.class); + PlatformViewsController platformViewsController = new PlatformViewsController(); + FlutterJNI jni = new FlutterJNI(); + attach(jni, platformViewsController); + platformViewsController.attachToView(fakeFlutterView); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + Context context = ApplicationProvider.getApplicationContext(); + View androidView = new View(context); + when(platformView.getView()).thenReturn(androidView); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + createPlatformView( + jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ false); + + platformViewsController.vdControllers.put(platformViewId, fakeVdController); + + // Simulate dispose call from the framework. + disposePlatformView(jni, platformViewsController, platformViewId); + + // Ensure VirtualDisplayController.dispose() is called + verify(fakeVdController, times(1)).dispose(); + } + + @Test + public void itUsesActionEventTypeFromFrameworkEventForVirtualDisplays() { + MotionEventTracker motionEventTracker = MotionEventTracker.getInstance(); + PlatformViewsController platformViewsController = new PlatformViewsController(); + + MotionEvent original = + MotionEvent.obtain( + 100, // downTime + 100, // eventTime + 1, // action + 0, // x + 0, // y + 0 // metaState + ); + + // track an event that will later get passed to us from framework + MotionEventTracker.MotionEventId motionEventId = motionEventTracker.track(original); + + PlatformViewTouch frameWorkTouch = + new PlatformViewTouch( + 0, // viewId + original.getDownTime(), + original.getEventTime(), + 2, // action + 1, // pointerCount + Arrays.asList(Arrays.asList(0, 0)), // pointer properties + Arrays.asList(Arrays.asList(0., 1., 2., 3., 4., 5., 6., 7., 8.)), // pointer coords + original.getMetaState(), + original.getButtonState(), + original.getXPrecision(), + original.getYPrecision(), + original.getDeviceId(), + original.getEdgeFlags(), + original.getSource(), + original.getFlags(), + motionEventId.getId()); + + MotionEvent resolvedEvent = + platformViewsController.toMotionEvent( + 1, // density + frameWorkTouch, + true // usingVirtualDisplays + ); + + assertEquals(resolvedEvent.getAction(), frameWorkTouch.action); + assertNotEquals(resolvedEvent.getAction(), original.getAction()); + } + + @Test + public void itUsesActionEventTypeFromFrameworkEventAsActionChanged() { + MotionEventTracker motionEventTracker = MotionEventTracker.getInstance(); + PlatformViewsController platformViewsController = new PlatformViewsController(); + + MotionEvent original = + MotionEvent.obtain( + 10, // downTime + 10, // eventTime + 261, // action + 0, // x + 0, // y + 0 // metaState + ); + + MotionEventTracker.MotionEventId motionEventId = motionEventTracker.track(original); + + PlatformViewTouch frameWorkTouch = + new PlatformViewTouch( + 0, // viewId + original.getDownTime(), + original.getEventTime(), + 0, // action + 1, // pointerCount + Arrays.asList(Arrays.asList(0, 0)), // pointer properties + Arrays.asList(Arrays.asList(0., 1., 2., 3., 4., 5., 6., 7., 8.)), // pointer coords + original.getMetaState(), + original.getButtonState(), + original.getXPrecision(), + original.getYPrecision(), + original.getDeviceId(), + original.getEdgeFlags(), + original.getSource(), + original.getFlags(), + motionEventId.getId()); + MotionEvent resolvedEvent = + platformViewsController.toMotionEvent( + 1, // density + frameWorkTouch, + false // usingVirtualDisplays + ); + assertEquals(resolvedEvent.getAction(), original.getAction()); + assertNotEquals(resolvedEvent.getAction(), frameWorkTouch.action); + } + + private MotionEvent makePlatformViewTouchAndInvokeToMotionEvent( + PlatformViewsController platformViewsController, + MotionEventTracker motionEventTracker, + MotionEvent original, + boolean usingVirtualDisplays) { + MotionEventTracker.MotionEventId motionEventId = motionEventTracker.track(original); + + // Construct a PlatformViewTouch.rawPointerPropertiesList by doing the inverse of + // PlatformViewsController.parsePointerPropertiesList. + List> pointerProperties = + Arrays.asList(Arrays.asList(original.getPointerId(0), original.getToolType(0))); + // Construct a PlatformViewTouch.rawPointerCoords by doing the inverse of + // PlatformViewsController.parsePointerCoordsList. + List> pointerCoordinates = + Arrays.asList( + Arrays.asList( + (double) original.getOrientation(), + (double) original.getPressure(), + (double) original.getSize(), + (double) original.getToolMajor(), + (double) original.getToolMinor(), + (double) original.getTouchMajor(), + (double) original.getTouchMinor(), + (double) original.getX(), + (double) original.getY())); + // Make a platform view touch from the motion event. + PlatformViewTouch frameWorkTouchNonVd = + new PlatformViewTouch( + 0, // viewId + original.getDownTime(), + original.getEventTime(), + original.getAction(), + 1, // pointerCount + pointerProperties, // pointer properties + pointerCoordinates, // pointer coords + original.getMetaState(), + original.getButtonState(), + original.getXPrecision(), + original.getYPrecision(), + original.getDeviceId(), + original.getEdgeFlags(), + original.getSource(), + original.getFlags(), + motionEventId.getId()); + + return platformViewsController.toMotionEvent( + 1, // density + frameWorkTouchNonVd, + usingVirtualDisplays); + } + + @Test + public void toMotionEvent_returnsSameCoordsForVdAndNonVd() { + MotionEventTracker motionEventTracker = MotionEventTracker.getInstance(); + PlatformViewsController platformViewsController = new PlatformViewsController(); + + MotionEvent original = + MotionEvent.obtain( + 10, // downTime + 10, // eventTime + 261, // action + 1, // x + 1, // y + 0 // metaState + ); + + MotionEvent resolvedNonVdEvent = + makePlatformViewTouchAndInvokeToMotionEvent( + platformViewsController, motionEventTracker, original, false); + + MotionEvent resolvedVdEvent = + makePlatformViewTouchAndInvokeToMotionEvent( + platformViewsController, motionEventTracker, original, true); + + assertEquals(resolvedVdEvent.getEventTime(), resolvedNonVdEvent.getEventTime()); + assertEquals(resolvedVdEvent.getX(), resolvedNonVdEvent.getX(), 0.001f); + assertEquals(resolvedVdEvent.getY(), resolvedNonVdEvent.getY(), 0.001f); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void getPlatformViewById_hybridComposition() { + PlatformViewsController platformViewsController = new PlatformViewsController(); + + int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + View androidView = mock(View.class); + when(platformView.getView()).thenReturn(androidView); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, platformViewsController); + + // Simulate create call from the framework. + createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); + + assertTrue(platformViewsController.initializePlatformViewIfNeeded(platformViewId)); + + View resultAndroidView = platformViewsController.getPlatformViewById(platformViewId); + assertNotNull(resultAndroidView); + assertEquals(resultAndroidView, androidView); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void createPlatformViewMessage_initializesAndroidView() { + PlatformViewsController platformViewsController = new PlatformViewsController(); + + int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + when(platformView.getView()).thenReturn(mock(View.class)); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, platformViewsController); + + // Simulate create call from the framework. + createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); + verify(viewFactory, times(1)).create(any(), eq(platformViewId), any()); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void createPlatformViewMessage_wrapsContextForVirtualDisplay() { + PlatformViewsController platformViewsController = new PlatformViewsController(); + + int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + when(platformView.getView()).thenReturn(mock(View.class)); + ArgumentCaptor passedContext = ArgumentCaptor.forClass(Context.class); + when(viewFactory.create(passedContext.capture(), eq(platformViewId), any())) + .thenReturn(platformView); + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, platformViewsController); + + // Simulate create call from the framework. + createPlatformView( + jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ false); + assertTrue(passedContext.getValue() instanceof MutableContextWrapper); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void createPlatformViewMessage_doesNotWrapContextForHybrid() { + PlatformViewsController platformViewsController = new PlatformViewsController(); + + int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + when(platformView.getView()).thenReturn(mock(View.class)); + ArgumentCaptor passedContext = ArgumentCaptor.forClass(Context.class); + when(viewFactory.create(passedContext.capture(), eq(platformViewId), any())) + .thenReturn(platformView); + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, platformViewsController); + + // Simulate create call from the framework. + createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); + assertFalse(passedContext.getValue() instanceof MutableContextWrapper); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void createPlatformViewMessage_setsAndroidViewLayoutDirection() { + PlatformViewsController platformViewsController = new PlatformViewsController(); + platformViewsController.setSoftwareRendering(true); + + int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + + View androidView = mock(View.class); + when(platformView.getView()).thenReturn(androidView); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, platformViewsController); + + // Simulate create call from the framework. + createPlatformView( + jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ false); + verify(androidView, times(1)).setLayoutDirection(0); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void createPlatformViewMessage_setsAndroidViewSize() { + PlatformViewsController platformViewsController = new PlatformViewsController(); + platformViewsController.setSoftwareRendering(true); + + int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + + View androidView = mock(View.class); + when(platformView.getView()).thenReturn(androidView); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, platformViewsController); + + // Simulate create call from the framework. + createPlatformView( + jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ false); + + ArgumentCaptor layoutParamsCaptor = + ArgumentCaptor.forClass(FrameLayout.LayoutParams.class); + verify(androidView, times(2)).setLayoutParams(layoutParamsCaptor.capture()); + + List capturedLayoutParams = layoutParamsCaptor.getAllValues(); + assertEquals(capturedLayoutParams.get(0).width, 1); + assertEquals(capturedLayoutParams.get(0).height, 1); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void createPlatformViewMessage_disablesAccessibility() { + PlatformViewsController platformViewsController = new PlatformViewsController(); + platformViewsController.setSoftwareRendering(true); + + int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + + View androidView = mock(View.class); + when(platformView.getView()).thenReturn(androidView); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, platformViewsController); + + // Simulate create call from the framework. + createPlatformView( + jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ false); + verify(androidView, times(1)) + .setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void createPlatformViewMessage_throwsIfViewIsNull() { + PlatformViewsController platformViewsController = new PlatformViewsController(); + + int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + when(platformView.getView()).thenReturn(null); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, platformViewsController); + + // Simulate create call from the framework. + createPlatformView( + jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ false); + assertEquals(ShadowFlutterJNI.getResponses().size(), 1); + + assertFalse(platformViewsController.initializePlatformViewIfNeeded(platformViewId)); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void createHybridPlatformViewMessage_throwsIfViewIsNull() { + PlatformViewsController platformViewsController = new PlatformViewsController(); + + int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + when(platformView.getView()).thenReturn(null); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, platformViewsController); + + // Simulate create call from the framework. + createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); + assertEquals(ShadowFlutterJNI.getResponses().size(), 1); + + assertFalse(platformViewsController.initializePlatformViewIfNeeded(platformViewId)); + } + + @Test + @Config( + shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class, ShadowPresentation.class}) + public void onDetachedFromJNI_clearsPlatformViewContext() { + PlatformViewsController platformViewsController = new PlatformViewsController(); + + int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + + SurfaceView pv = mock(SurfaceView.class); + when(pv.getContext()).thenReturn(mock(MutableContextWrapper.class)); + when(pv.getLayoutParams()).thenReturn(new LayoutParams(1, 1)); + + when(platformView.getView()).thenReturn(pv); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, platformViewsController); + + // Simulate create call from the framework. + createPlatformView( + jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ false); + + assertFalse(platformViewsController.contextToEmbeddedView.isEmpty()); + platformViewsController.onDetachedFromJNI(); + assertTrue(platformViewsController.contextToEmbeddedView.isEmpty()); + } + + @Test + @Config( + shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class, ShadowPresentation.class}) + public void onPreEngineRestart_clearsPlatformViewContext() { + PlatformViewsController platformViewsController = new PlatformViewsController(); + + int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + + SurfaceView pv = mock(SurfaceView.class); + when(pv.getContext()).thenReturn(mock(MutableContextWrapper.class)); + when(pv.getLayoutParams()).thenReturn(new LayoutParams(1, 1)); + + when(platformView.getView()).thenReturn(pv); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, platformViewsController); + + // Simulate create call from the framework. + createPlatformView( + jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ false); + + assertFalse(platformViewsController.contextToEmbeddedView.isEmpty()); + platformViewsController.onDetachedFromJNI(); + assertTrue(platformViewsController.contextToEmbeddedView.isEmpty()); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void createPlatformViewMessage_throwsIfViewHasParent() { + PlatformViewsController platformViewsController = new PlatformViewsController(); + + int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + View androidView = mock(View.class); + when(androidView.getParent()).thenReturn(mock(ViewParent.class)); + when(platformView.getView()).thenReturn(androidView); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, platformViewsController); + + // Simulate create call from the framework. + createPlatformView( + jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ false); + assertEquals(ShadowFlutterJNI.getResponses().size(), 1); + + assertThrows( + IllegalStateException.class, + () -> { + platformViewsController.initializePlatformViewIfNeeded(platformViewId); + }); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void createHybridPlatformViewMessage_throwsIfViewHasParent() { + PlatformViewsController platformViewsController = new PlatformViewsController(); + + int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + View androidView = mock(View.class); + when(androidView.getParent()).thenReturn(mock(ViewParent.class)); + when(platformView.getView()).thenReturn(androidView); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, platformViewsController); + + // Simulate create call from the framework. + createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); + assertEquals(ShadowFlutterJNI.getResponses().size(), 1); + + assertThrows( + IllegalStateException.class, + () -> { + platformViewsController.initializePlatformViewIfNeeded(platformViewId); + }); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void setPlatformViewDirection_throwIfPlatformViewNotFound() { + PlatformViewsController platformViewsController = new PlatformViewsController(); + + int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + final View androidView = mock(View.class); + when(platformView.getView()).thenReturn(androidView); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, platformViewsController); + + verify(androidView, never()).setLayoutDirection(anyInt()); + + // Simulate create call from the framework. + createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); + assertEquals(ShadowFlutterJNI.getResponses().size(), 1); + + // Simulate set direction call from the framework. + setLayoutDirection(jni, platformViewsController, platformViewId, 1); + verify(androidView, times(1)).setLayoutDirection(1); + + // The limit value of reply message will be equal to 2 if the layout direction is set + // successfully, otherwise it will be much more than 2 due to the reply message contains + // an error message wrapped with exception detail information. + assertEquals(ShadowFlutterJNI.getResponses().get(0).limit(), 2); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void resizeAndroidView() { + PlatformViewsController platformViewsController = new PlatformViewsController(); + platformViewsController.setSoftwareRendering(true); + + int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + final View androidView = mock(View.class); + when(platformView.getView()).thenReturn(androidView); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, platformViewsController); + + // Simulate create call from the framework. + createPlatformView( + jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ false); + + reset(androidView); + when(androidView.getLayoutParams()).thenReturn(new FrameLayout.LayoutParams(0, 0)); + + // Simulate a resize call from the framework. + resize(jni, platformViewsController, platformViewId, 10.0, 20.0); + + ArgumentCaptor layoutParamsCaptor = + ArgumentCaptor.forClass(FrameLayout.LayoutParams.class); + verify(androidView, times(1)).setLayoutParams(layoutParamsCaptor.capture()); + + assertEquals(layoutParamsCaptor.getValue().width, 10); + assertEquals(layoutParamsCaptor.getValue().height, 20); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void disposeAndroidView_hybridComposition() { + PlatformViewsController platformViewsController = new PlatformViewsController(); + + int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + + Context context = ApplicationProvider.getApplicationContext(); + View androidView = new View(context); + + when(platformView.getView()).thenReturn(androidView); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, platformViewsController); + + // Simulate create call from the framework. + createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); + assertTrue(platformViewsController.initializePlatformViewIfNeeded(platformViewId)); + + assertNotNull(androidView.getParent()); + assertTrue(androidView.getParent() instanceof FlutterMutatorView); + + // Simulate dispose call from the framework. + disposePlatformView(jni, platformViewsController, platformViewId); + assertNull(androidView.getParent()); + + // Simulate create call from the framework. + createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); + assertTrue(platformViewsController.initializePlatformViewIfNeeded(platformViewId)); + + assertNotNull(androidView.getParent()); + assertTrue(androidView.getParent() instanceof FlutterMutatorView); + verify(platformView, times(1)).dispose(); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void disposeNullAndroidView() { + PlatformViewsController platformViewsController = new PlatformViewsController(); + + int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + + View androidView = mock(View.class); + when(platformView.getView()).thenReturn(androidView); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + attach(jni, platformViewsController); + + // Simulate create call from the framework. + createPlatformView( + jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ false); + assertTrue(platformViewsController.initializePlatformViewIfNeeded(platformViewId)); + + when(platformView.getView()).thenReturn(null); + + // Simulate dispose call from the framework. + disposePlatformView(jni, platformViewsController, platformViewId); + verify(platformView, times(1)).dispose(); + } + + @Test + @Config( + shadows = { + ShadowFlutterSurfaceView.class, + ShadowFlutterJNI.class, + ShadowPlatformTaskQueue.class + }) + public void onEndFrame_destroysOverlaySurfaceAfterFrameOnFlutterSurfaceView() { + final PlatformViewsController platformViewsController = new PlatformViewsController(); + + final int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + final PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + final PlatformView platformView = mock(PlatformView.class); + when(platformView.getView()).thenReturn(mock(View.class)); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + final FlutterJNI jni = new FlutterJNI(); + jni.attachToNative(); + attach(jni, platformViewsController); + + jni.onFirstFrame(); + + // Simulate create call from the framework. + createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); + + // Produce a frame that displays a platform view and an overlay surface. + platformViewsController.onBeginFrame(); + platformViewsController.onDisplayPlatformView( + platformViewId, + /* x=*/ 0, + /* y=*/ 0, + /* width=*/ 10, + /* height=*/ 10, + /* viewWidth=*/ 10, + /* viewHeight=*/ 10, + /* mutatorsStack=*/ new FlutterMutatorsStack()); + + final PlatformOverlayView overlayImageView = mock(PlatformOverlayView.class); + when(overlayImageView.acquireLatestImage()).thenReturn(true); + + final FlutterOverlaySurface overlaySurface = + platformViewsController.createOverlaySurface(overlayImageView); + platformViewsController.onDisplayOverlaySurface( + overlaySurface.getId(), /* x=*/ 0, /* y=*/ 0, /* width=*/ 10, /* height=*/ 10); + + platformViewsController.onEndFrame(); + + // Simulate first frame from the framework. + jni.onFirstFrame(); + + verify(overlayImageView, never()).detachFromRenderer(); + + // Produce a frame that doesn't display platform views. + platformViewsController.onBeginFrame(); + platformViewsController.onEndFrame(); + + shadowOf(getMainLooper()).idle(); + verify(overlayImageView, times(1)).detachFromRenderer(); + } + + @Test + @Config(shadows = {ShadowFlutterSurfaceView.class, ShadowFlutterJNI.class}) + public void onEndFrame_removesPlatformView() { + final PlatformViewsController platformViewsController = new PlatformViewsController(); + + final int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + final PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + final PlatformView platformView = mock(PlatformView.class); + final View androidView = mock(View.class); + when(platformView.getView()).thenReturn(androidView); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + final FlutterJNI jni = new FlutterJNI(); + jni.attachToNative(); + attach(jni, platformViewsController); + + jni.onFirstFrame(); + + // Simulate create call from the framework. + createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); + + // Simulate first frame from the framework. + jni.onFirstFrame(); + platformViewsController.onBeginFrame(); + + platformViewsController.onEndFrame(); + verify(androidView, never()).setVisibility(View.GONE); + + final ViewParent parentView = mock(ViewParent.class); + when(androidView.getParent()).thenReturn(parentView); + } + + @Test + @Config( + shadows = { + ShadowFlutterSurfaceView.class, + ShadowFlutterJNI.class, + ShadowPlatformTaskQueue.class + }) + public void onEndFrame_removesPlatformViewParent() { + final PlatformViewsController platformViewsController = new PlatformViewsController(); + + final int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + final PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + final PlatformView platformView = mock(PlatformView.class); + final View androidView = mock(View.class); + when(platformView.getView()).thenReturn(androidView); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + final FlutterJNI jni = new FlutterJNI(); + jni.attachToNative(); + + final FlutterView flutterView = attach(jni, platformViewsController); + + jni.onFirstFrame(); + + // Simulate create call from the framework. + createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); + assertTrue(platformViewsController.initializePlatformViewIfNeeded(platformViewId)); + assertEquals(flutterView.getChildCount(), 2); + + // Simulate first frame from the framework. + jni.onFirstFrame(); + platformViewsController.onBeginFrame(); + platformViewsController.onEndFrame(); + + // Simulate dispose call from the framework. + disposePlatformView(jni, platformViewsController, platformViewId); + assertEquals(flutterView.getChildCount(), 1); + } + + @Test + @Config( + shadows = { + ShadowFlutterSurfaceView.class, + ShadowFlutterJNI.class, + ShadowPlatformTaskQueue.class + }) + public void detach_destroysOverlaySurfaces() { + final PlatformViewsController platformViewsController = new PlatformViewsController(); + + final int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + final PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + final PlatformView platformView = mock(PlatformView.class); + when(platformView.getView()).thenReturn(mock(View.class)); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + final FlutterJNI jni = new FlutterJNI(); + jni.attachToNative(); + attach(jni, platformViewsController); + + jni.onFirstFrame(); + + // Simulate create call from the framework. + createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); + + // Produce a frame that displays a platform view and an overlay surface. + platformViewsController.onBeginFrame(); + platformViewsController.onDisplayPlatformView( + platformViewId, + /* x=*/ 0, + /* y=*/ 0, + /* width=*/ 10, + /* height=*/ 10, + /* viewWidth=*/ 10, + /* viewHeight=*/ 10, + /* mutatorsStack=*/ new FlutterMutatorsStack()); + + final PlatformOverlayView overlayImageView = mock(PlatformOverlayView.class); + when(overlayImageView.acquireLatestImage()).thenReturn(true); + + final FlutterOverlaySurface overlaySurface = + platformViewsController.createOverlaySurface(overlayImageView); + // This is OK. + platformViewsController.onDisplayOverlaySurface( + overlaySurface.getId(), /* x=*/ 0, /* y=*/ 0, /* width=*/ 10, /* height=*/ 10); + + platformViewsController.detach(); + + verify(overlayImageView, times(1)).closeImageReader(); + verify(overlayImageView, times(1)).detachFromRenderer(); + } + + @Test + @Config(shadows = {ShadowFlutterSurfaceView.class, ShadowFlutterJNI.class}) + public void detachFromView_removesAndDestroysOverlayViews() { + final PlatformViewsController platformViewsController = new PlatformViewsController(); + + final int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + final PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + final PlatformView platformView = mock(PlatformView.class); + when(platformView.getView()).thenReturn(mock(View.class)); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + final FlutterJNI jni = new FlutterJNI(); + jni.attachToNative(); + attach(jni, platformViewsController); + + final FlutterView flutterView = mock(FlutterView.class); + platformViewsController.attachToView(flutterView); + + final PlatformOverlayView overlayImageView = mock(PlatformOverlayView.class); + when(overlayImageView.acquireLatestImage()).thenReturn(true); + + final FlutterOverlaySurface overlaySurface = + platformViewsController.createOverlaySurface(overlayImageView); + + platformViewsController.onDisplayOverlaySurface( + overlaySurface.getId(), /* x=*/ 0, /* y=*/ 0, /* width=*/ 10, /* height=*/ 10); + + platformViewsController.detachFromView(); + + verify(overlayImageView, times(1)).closeImageReader(); + verify(overlayImageView, times(1)).detachFromRenderer(); + verify(flutterView, times(1)).removeView(overlayImageView); + } + + @Test + @Config(shadows = {ShadowFlutterSurfaceView.class, ShadowFlutterJNI.class}) + public void destroyOverlaySurfaces_doesNotThrowIfFlutterViewIsDetached() { + final PlatformViewsController platformViewsController = new PlatformViewsController(); + + final int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + final PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + final PlatformView platformView = mock(PlatformView.class); + when(platformView.getView()).thenReturn(mock(View.class)); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + final FlutterJNI jni = new FlutterJNI(); + jni.attachToNative(); + attach(jni, platformViewsController); + + final FlutterView flutterView = mock(FlutterView.class); + platformViewsController.attachToView(flutterView); + + final PlatformOverlayView overlayImageView = mock(PlatformOverlayView.class); + when(overlayImageView.acquireLatestImage()).thenReturn(true); + + final FlutterOverlaySurface overlaySurface = + platformViewsController.createOverlaySurface(overlayImageView); + + platformViewsController.onDisplayOverlaySurface( + overlaySurface.getId(), /* x=*/ 0, /* y=*/ 0, /* width=*/ 10, /* height=*/ 10); + + platformViewsController.detachFromView(); + + platformViewsController.destroyOverlaySurfaces(); + verify(overlayImageView, times(1)).closeImageReader(); + verify(overlayImageView, times(1)).detachFromRenderer(); + } + + @Test + @Config(shadows = {ShadowFlutterSurfaceView.class, ShadowFlutterJNI.class}) + public void destroyOverlaySurfaces_doesNotRemoveOverlayView() { + final PlatformViewsController platformViewsController = new PlatformViewsController(); + + final int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + final PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + final PlatformView platformView = mock(PlatformView.class); + when(platformView.getView()).thenReturn(mock(View.class)); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + final FlutterJNI jni = new FlutterJNI(); + jni.attachToNative(); + attach(jni, platformViewsController); + + final FlutterView flutterView = mock(FlutterView.class); + platformViewsController.attachToView(flutterView); + + final PlatformOverlayView overlayImageView = mock(PlatformOverlayView.class); + when(overlayImageView.acquireLatestImage()).thenReturn(true); + + final FlutterOverlaySurface overlaySurface = + platformViewsController.createOverlaySurface(overlayImageView); + + platformViewsController.onDisplayOverlaySurface( + overlaySurface.getId(), /* x=*/ 0, /* y=*/ 0, /* width=*/ 10, /* height=*/ 10); + + platformViewsController.destroyOverlaySurfaces(); + verify(flutterView, never()).removeView(overlayImageView); + } + + @Test + public void checkInputConnectionProxy_falseIfViewIsNull() { + final PlatformViewsController platformViewsController = new PlatformViewsController(); + boolean shouldProxying = platformViewsController.checkInputConnectionProxy(null); + assertFalse(shouldProxying); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void convertPlatformViewRenderSurfaceAsDefault() { + final PlatformViewsController platformViewsController = new PlatformViewsController(); + + final int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + final PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + final PlatformView platformView = mock(PlatformView.class); + final View androidView = mock(View.class); + when(platformView.getView()).thenReturn(androidView); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + final FlutterJNI jni = new FlutterJNI(); + jni.attachToNative(); + final FlutterView flutterView = attach(jni, platformViewsController); + + jni.onFirstFrame(); + + // Simulate create call from the framework. + createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); + + // Produce a frame that displays a platform view and an overlay surface. + platformViewsController.onBeginFrame(); + platformViewsController.onDisplayPlatformView( + platformViewId, + /* x=*/ 0, + /* y=*/ 0, + /* width=*/ 10, + /* height=*/ 10, + /* viewWidth=*/ 10, + /* viewHeight=*/ 10, + /* mutatorsStack=*/ new FlutterMutatorsStack()); + + assertEquals(flutterView.getChildCount(), 3); + + final View view = flutterView.getChildAt(1); + assertTrue(view instanceof FlutterImageView); + + // Simulate dispose call from the framework. + disposePlatformView(jni, platformViewsController, platformViewId); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void dontConverRenderSurfaceWhenFlagIsTrue() { + final PlatformViewsController platformViewsController = new PlatformViewsController(); + + final int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + final PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + final PlatformView platformView = mock(PlatformView.class); + final View androidView = mock(View.class); + when(platformView.getView()).thenReturn(androidView); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + final FlutterJNI jni = new FlutterJNI(); + jni.attachToNative(); + final FlutterView flutterView = attach(jni, platformViewsController); + + jni.onFirstFrame(); + + // Simulate setting render surface conversion flag. + synchronizeToNativeViewHierarchy(jni, platformViewsController, false); + + // Simulate create call from the framework. + createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); + + // Produce a frame that displays a platform view and an overlay surface. + platformViewsController.onBeginFrame(); + platformViewsController.onDisplayPlatformView( + platformViewId, + /* x=*/ 0, + /* y=*/ 0, + /* width=*/ 10, + /* height=*/ 10, + /* viewWidth=*/ 10, + /* viewHeight=*/ 10, + /* mutatorsStack=*/ new FlutterMutatorsStack()); + + assertEquals(flutterView.getChildCount(), 2); + assertTrue(!(flutterView.getChildAt(0) instanceof PlatformOverlayView)); + assertTrue(flutterView.getChildAt(1) instanceof FlutterMutatorView); + + // Simulate dispose call from the framework. + disposePlatformView(jni, platformViewsController, platformViewId); + } + + @Test + @Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class}) + public void reattachToFlutterView() { + PlatformViewsController platformViewsController = new PlatformViewsController(); + platformViewsController.setSoftwareRendering(true); + + int platformViewId = 100; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + PlatformView platformView = mock(PlatformView.class); + View androidView = mock(View.class); + when(platformView.getView()).thenReturn(androidView); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + FlutterJNI jni = new FlutterJNI(); + FlutterView initFlutterView = mock(FlutterView.class); + attachToFlutterView(jni, platformViewsController, initFlutterView); + + createPlatformView( + jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ false); + verify(initFlutterView, times(1)).addView(any(PlatformViewWrapper.class)); + + platformViewsController.detachFromView(); + verify(initFlutterView, times(1)).removeView(any(PlatformViewWrapper.class)); + + FlutterView newFlutterView = mock(FlutterView.class); + platformViewsController.attachToView(newFlutterView); + verify(newFlutterView, times(1)).addView(any(PlatformViewWrapper.class)); + } + + @Config( + shadows = { + ShadowFlutterSurfaceView.class, + ShadowFlutterJNI.class, + ShadowPlatformTaskQueue.class + }) + public void revertImageViewAndRemoveImageView() { + final PlatformViewsController platformViewsController = new PlatformViewsController(); + + final int platformViewId = 0; + assertNull(platformViewsController.getPlatformViewById(platformViewId)); + + final PlatformViewFactory viewFactory = mock(PlatformViewFactory.class); + final PlatformView platformView = mock(PlatformView.class); + final View androidView = mock(View.class); + when(platformView.getView()).thenReturn(androidView); + when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView); + + platformViewsController.getRegistry().registerViewFactory("testType", viewFactory); + + final FlutterJNI jni = new FlutterJNI(); + jni.attachToNative(); + + final FlutterView flutterView = attach(jni, platformViewsController); + + jni.onFirstFrame(); + + // Simulate create call from the framework. + createPlatformView(jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ true); + + // The simulation creates an Overlay on top of the PlatformView + // This is going to be called `flutterView.convertToImageView` + platformViewsController.createOverlaySurface(); + platformViewsController.onDisplayOverlaySurface(platformViewId, 0, 0, 10, 10); + + // This will contain three views: Background ImageView、PlatformView、Overlay ImageView + assertEquals(flutterView.getChildCount(), 3); + + FlutterImageView imageView = flutterView.getCurrentImageSurface(); + + // Make sure the ImageView is inside the current FlutterView. + assertTrue(imageView != null); + assertTrue(flutterView.indexOfChild(imageView) != -1); + + // Make sure the overlayView is inside the current FlutterView + assertTrue(platformViewsController.getOverlayLayerViews().size() != 0); + PlatformOverlayView overlayView = platformViewsController.getOverlayLayerViews().get(0); + assertTrue(overlayView != null); + assertTrue(flutterView.indexOfChild(overlayView) != -1); + + // Simulate in a new frame, there's no PlatformView, which is called + // `flutterView.revertImageView`. And register a `FlutterUiDisplayListener` callback. + // During callback execution it will invoke `flutterImageView.detachFromRenderer()`. + platformViewsController.onBeginFrame(); + platformViewsController.onEndFrame(); + + // Invoke all registered `FlutterUiDisplayListener` callback + jni.onFirstFrame(); + + assertEquals(null, flutterView.getCurrentImageSurface()); + + // Make sure the background ImageVIew is not in the FlutterView + assertTrue(flutterView.indexOfChild(imageView) == -1); + + // Make sure the overlay ImageVIew is not in the FlutterView + assertTrue(flutterView.indexOfChild(overlayView) == -1); + } + + private static ByteBuffer encodeMethodCall(MethodCall call) { + final ByteBuffer buffer = StandardMethodCodec.INSTANCE.encodeMethodCall(call); + buffer.rewind(); + return buffer; + } + + private static void createPlatformView( + FlutterJNI jni, + PlatformViewsController platformViewsController, + int platformViewId, + String viewType, + boolean hybrid) { + final Map args = new HashMap<>(); + args.put("hybrid", hybrid); + args.put("id", platformViewId); + args.put("viewType", viewType); + args.put("direction", 0); + args.put("width", 1.0); + args.put("height", 1.0); + + final MethodCall platformCreateMethodCall = new MethodCall("create", args); + + jni.handlePlatformMessage( + "flutter/platform_views", + encodeMethodCall(platformCreateMethodCall), + /*replyId=*/ 0, + /*messageData=*/ 0); + } + + private static void setLayoutDirection( + FlutterJNI jni, + PlatformViewsController platformViewsController, + int platformViewId, + int direction) { + final Map args = new HashMap<>(); + args.put("id", platformViewId); + args.put("direction", direction); + + final MethodCall platformSetDirectionMethodCall = new MethodCall("setDirection", args); + + jni.handlePlatformMessage( + "flutter/platform_views", + encodeMethodCall(platformSetDirectionMethodCall), + /*replyId=*/ 0, + /*messageData=*/ 0); + } + + private static void resize( + FlutterJNI jni, + PlatformViewsController platformViewsController, + int platformViewId, + double width, + double height) { + final Map args = new HashMap<>(); + args.put("id", platformViewId); + args.put("width", width); + args.put("height", height); + + final MethodCall platformResizeMethodCall = new MethodCall("resize", args); + + jni.handlePlatformMessage( + "flutter/platform_views", + encodeMethodCall(platformResizeMethodCall), + /*replyId=*/ 0, + /*messageData=*/ 0); + } + + private static void disposePlatformView( + FlutterJNI jni, PlatformViewsController platformViewsController, int platformViewId) { + + final Map args = new HashMap<>(); + args.put("hybrid", true); + args.put("id", platformViewId); + + final MethodCall platformDisposeMethodCall = new MethodCall("dispose", args); + + jni.handlePlatformMessage( + "flutter/platform_views", + encodeMethodCall(platformDisposeMethodCall), + /*replyId=*/ 0, + /*messageData=*/ 0); + } + + private static void synchronizeToNativeViewHierarchy( + FlutterJNI jni, PlatformViewsController platformViewsController, boolean yes) { + + final MethodCall convertMethodCall = new MethodCall("synchronizeToNativeViewHierarchy", yes); + + jni.handlePlatformMessage( + "flutter/platform_views", + encodeMethodCall(convertMethodCall), + /*replyId=*/ 0, + /*messageData=*/ 0); + } + + private static FlutterView attach( + FlutterJNI jni, PlatformViewsController platformViewsController) { + final Context context = ApplicationProvider.getApplicationContext(); + final FlutterView flutterView = + new FlutterView(context, new FlutterSurfaceView(context)) { + @Override + public FlutterImageView createImageView() { + final FlutterImageView view = mock(FlutterImageView.class); + when(view.acquireLatestImage()).thenReturn(true); + return mock(FlutterImageView.class); + } + }; + attachToFlutterView(jni, platformViewsController, flutterView); + return flutterView; + } + + private static void attachToFlutterView( + FlutterJNI jni, PlatformViewsController platformViewsController, FlutterView flutterView) { + final DartExecutor executor = new DartExecutor(jni, mock(AssetManager.class)); + executor.onAttachedToJNI(); + + final Context context = ApplicationProvider.getApplicationContext(); + final TextureRegistry registry = + spy( + new TextureRegistry() { + public void TextureRegistry() {} + + @NonNull + @Override + public SurfaceTextureEntry createSurfaceTexture() { + return registerSurfaceTexture(mock(SurfaceTexture.class)); + } + + @NonNull + @Override + public SurfaceTextureEntry registerSurfaceTexture( + @NonNull SurfaceTexture surfaceTexture) { + return new SurfaceTextureEntry() { + @NonNull + @Override + public SurfaceTexture surfaceTexture() { + return mock(SurfaceTexture.class); + } + + @Override + public long id() { + return 0; + } + + @Override + public void release() {} + }; + } + + @NonNull + @Override + public ImageTextureEntry createImageTexture() { + return new ImageTextureEntry() { + @Override + public long id() { + return 0; + } + + @Override + public void release() {} + + @Override + public void pushImage(Image image) {} + }; + } + + @NonNull + @Override + public SurfaceProducer createSurfaceProducer(SurfaceLifecycle lifecycle) { + return new SurfaceProducer() { + @Override + public void setCallback(SurfaceProducer.Callback cb) {} + + @Override + public long id() { + return 0; + } + + @Override + public void release() {} + + @Override + public int getWidth() { + return 0; + } + + @Override + public int getHeight() { + return 0; + } + + @Override + public void setSize(int width, int height) {} + + @Override + public Surface getSurface() { + return null; + } + + @Override + public Surface getForcedNewSurface() { + return null; + } + + @Override + public boolean handlesCropAndRotation() { + return false; + } + + public void scheduleFrame() {} + }; + } + }); + + platformViewsController.attach(context, registry, executor); + + PlatformViewsController2 secondController = new PlatformViewsController2(); + secondController.setRegistry(new PlatformViewRegistryImpl()); + + final FlutterEngine engine = mock(FlutterEngine.class); + when(engine.getRenderer()).thenReturn(new FlutterRenderer(jni)); + when(engine.getMouseCursorChannel()).thenReturn(mock(MouseCursorChannel.class)); + when(engine.getTextInputChannel()).thenReturn(mock(TextInputChannel.class)); + when(engine.getSettingsChannel()).thenReturn(new SettingsChannel(executor)); + when(engine.getScribeChannel()).thenReturn(mock(ScribeChannel.class)); + when(engine.getPlatformViewsController()).thenReturn(platformViewsController); + when(engine.getPlatformViewsController2()).thenReturn(secondController); + when(engine.getLocalizationPlugin()).thenReturn(mock(LocalizationPlugin.class)); + when(engine.getAccessibilityChannel()).thenReturn(mock(AccessibilityChannel.class)); + when(engine.getDartExecutor()).thenReturn(executor); + + flutterView.attachToFlutterEngine(engine); + platformViewsController.attachToView(flutterView); + } + + /** + * For convenience when writing tests, this allows us to make fake messages from Flutter via + * Platform Channels. Typically those calls happen on the ui thread which dispatches to the + * platform thread. Since tests run on the platform thread it makes it difficult to test without + * this, but isn't technically required. + */ + @Implements(io.flutter.embedding.engine.dart.PlatformTaskQueue.class) + public static class ShadowPlatformTaskQueue { + @Implementation + public void dispatch(Runnable runnable) { + runnable.run(); + } + } + + /** + * The shadow class of {@link Presentation} to simulate Presentation showing logic. + * + *

Robolectric doesn't support VirtualDisplay creating correctly now, so this shadow class is + * used to simulate custom logic for Presentation. + */ + @Implements(Presentation.class) + public static class ShadowPresentation extends ShadowDialog { + private boolean isShowing = false; + + public ShadowPresentation() {} + + @Implementation + protected void show() { + isShowing = true; + } + + @Implementation + protected void dismiss() { + isShowing = false; + } + + @Implementation + protected boolean isShowing() { + return isShowing; + } + } + + @Implements(FlutterJNI.class) + public static class ShadowFlutterJNI { + private static SparseArray replies = new SparseArray<>(); + + public ShadowFlutterJNI() {} + + @Implementation + public boolean getIsSoftwareRenderingEnabled() { + return false; + } + + @Implementation + public long performNativeAttach(FlutterJNI flutterJNI) { + return 1; + } + + @Implementation + public void dispatchPlatformMessage( + String channel, ByteBuffer message, int position, int responseId) {} + + @Implementation + public void onSurfaceCreated(Surface surface) {} + + @Implementation + public void onSurfaceDestroyed() {} + + @Implementation + public void onSurfaceWindowChanged(Surface surface) {} + + @Implementation + public void setViewportMetrics( + float devicePixelRatio, + int physicalWidth, + int physicalHeight, + int physicalPaddingTop, + int physicalPaddingRight, + int physicalPaddingBottom, + int physicalPaddingLeft, + int physicalViewInsetTop, + int physicalViewInsetRight, + int physicalViewInsetBottom, + int physicalViewInsetLeft, + int systemGestureInsetTop, + int systemGestureInsetRight, + int systemGestureInsetBottom, + int systemGestureInsetLeft, + int physicalTouchSlop, + int[] displayFeaturesBounds, + int[] displayFeaturesType, + int[] displayFeaturesState) {} + + @Implementation + public void invokePlatformMessageResponseCallback( + int responseId, ByteBuffer message, int position) { + replies.put(responseId, message); + } + + public static SparseArray getResponses() { + return replies; + } + } + + @Implements(SurfaceView.class) + public static class ShadowFlutterSurfaceView extends ShadowSurfaceView { + private final FakeSurfaceHolder holder = new FakeSurfaceHolder(); + + public static class FakeSurfaceHolder extends ShadowSurfaceView.FakeSurfaceHolder { + private final Surface surface = mock(Surface.class); + + public Surface getSurface() { + return surface; + } + + @Implementation + public void addCallback(SurfaceHolder.Callback callback) { + callback.surfaceCreated(this); + } + } + + public ShadowFlutterSurfaceView() {} + + @Implementation + public SurfaceHolder getHolder() { + return holder; + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/SingleViewPresentationTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/SingleViewPresentationTest.java new file mode 100644 index 0000000000000000000000000000000000000000..592a9f22bbeec4093e4a7df365921d978115690b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/SingleViewPresentationTest.java @@ -0,0 +1,84 @@ +// 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. + +package io.flutter.plugin.platform; + +import static io.flutter.Build.API_LEVELS; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import android.annotation.TargetApi; +import android.content.Context; +import android.hardware.display.DisplayManager; +import android.view.Display; +import android.view.inputmethod.InputMethodManager; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +@TargetApi(API_LEVELS.API_28) +public class SingleViewPresentationTest { + @Test + @Config(minSdk = API_LEVELS.API_21, maxSdk = API_LEVELS.API_30) + public void returnsOuterContextInputMethodManager() { + // There's a bug in Android Q caused by the IMM being instanced per display. + // https://github.com/flutter/flutter/issues/38375. We need the context returned by + // SingleViewPresentation to be consistent from its instantiation instead of defaulting to + // what the system would have returned at call time. + + // It's not possible to set up the exact same conditions as the unit test in the bug here, + // but we can make sure that we're wrapping the Context passed in at instantiation time and + // returning the same InputMethodManager from it. This test passes in a Spy context instance + // that initially returns a mock. Without the bugfix this test falls back to Robolectric's + // system service instead of the spy's and fails. + + // Create an SVP under test with a Context that returns a local IMM mock. + Context context = spy(ApplicationProvider.getApplicationContext()); + InputMethodManager expected = mock(InputMethodManager.class); + when(context.getSystemService(Context.INPUT_METHOD_SERVICE)).thenReturn(expected); + DisplayManager dm = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE); + SingleViewPresentation svp = + new SingleViewPresentation(context, dm.getDisplay(0), null, null, null, false); + + // Get the IMM from the SVP's context. + InputMethodManager actual = + (InputMethodManager) svp.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + + // This should be the mocked instance from construction, not the IMM from the greater + // Android OS (or Robolectric's shadow, in this case). + assertEquals(expected, actual); + } + + @Test + @Config(minSdk = API_LEVELS.API_21, maxSdk = API_LEVELS.API_30) + public void returnsOuterContextInputMethodManager_createDisplayContext() { + // The IMM should also persist across display contexts created from the base context. + + // Create an SVP under test with a Context that returns a local IMM mock. + Context context = spy(ApplicationProvider.getApplicationContext()); + InputMethodManager expected = mock(InputMethodManager.class); + when(context.getSystemService(Context.INPUT_METHOD_SERVICE)).thenReturn(expected); + Display display = + ((DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE)).getDisplay(0); + SingleViewPresentation svp = + new SingleViewPresentation(context, display, null, null, null, false); + + // Get the IMM from the SVP's context. + InputMethodManager actual = + (InputMethodManager) + svp.getContext() + .createDisplayContext(display) + .getSystemService(Context.INPUT_METHOD_SERVICE); + + // This should be the mocked instance from construction, not the IMM from the greater + // Android OS (or Robolectric's shadow, in this case). + assertEquals(expected, actual); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/SurfaceTexturePlatformViewRenderTargetTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/SurfaceTexturePlatformViewRenderTargetTest.java new file mode 100644 index 0000000000000000000000000000000000000000..1921c935b7a8ce1b1a6be13526d723ff0f8dfb98 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/SurfaceTexturePlatformViewRenderTargetTest.java @@ -0,0 +1,108 @@ +// 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. + +package io.flutter.plugin.platform; + +import static io.flutter.Build.API_LEVELS; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +import android.annotation.TargetApi; +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.SurfaceTexture; +import android.view.Surface; +import android.view.View; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.view.TextureRegistry.SurfaceTextureEntry; +import org.junit.Test; +import org.junit.runner.RunWith; + +@TargetApi(API_LEVELS.API_31) +@RunWith(AndroidJUnit4.class) +public class SurfaceTexturePlatformViewRenderTargetTest { + private final Context ctx = ApplicationProvider.getApplicationContext(); + + @Test + public void viewDraw_writesToBuffer() { + final Canvas canvas = mock(Canvas.class); + final Surface surface = mock(Surface.class); + when(surface.lockHardwareCanvas()).thenReturn(canvas); + when(surface.isValid()).thenReturn(true); + final SurfaceTexture surfaceTexture = mock(SurfaceTexture.class); + final SurfaceTextureEntry surfaceTextureEntry = mock(SurfaceTextureEntry.class); + when(surfaceTextureEntry.surfaceTexture()).thenReturn(surfaceTexture); + when(surfaceTexture.isReleased()).thenReturn(false); + + final SurfaceTexturePlatformViewRenderTarget renderTarget = + new SurfaceTexturePlatformViewRenderTarget(surfaceTextureEntry) { + @Override + protected Surface createSurface() { + return surface; + } + }; + + // Custom view. + final View platformView = + new View(ctx) { + @Override + public void draw(Canvas canvas) { + super.draw(canvas); + canvas.drawColor(Color.RED); + } + }; + final int size = 100; + platformView.measure(size, size); + platformView.layout(0, 0, size, size); + + // Test. + final Surface s = renderTarget.getSurface(); + final Canvas c = s.lockHardwareCanvas(); + platformView.draw(c); + s.unlockCanvasAndPost(c); + + // Verify. + verify(canvas, times(1)).drawColor(Color.RED); + verify(surface, times(1)).lockHardwareCanvas(); + verify(surface, times(1)).unlockCanvasAndPost(canvas); + verifyNoMoreInteractions(surface); + } + + @Test + public void release() { + final Canvas canvas = mock(Canvas.class); + final Surface surface = mock(Surface.class); + when(surface.lockHardwareCanvas()).thenReturn(canvas); + when(surface.isValid()).thenReturn(true); + final SurfaceTexture surfaceTexture = mock(SurfaceTexture.class); + final SurfaceTextureEntry surfaceTextureEntry = mock(SurfaceTextureEntry.class); + when(surfaceTextureEntry.surfaceTexture()).thenReturn(surfaceTexture); + when(surfaceTexture.isReleased()).thenReturn(false); + final SurfaceTexturePlatformViewRenderTarget renderTarget = + new SurfaceTexturePlatformViewRenderTarget(surfaceTextureEntry) { + @Override + protected Surface createSurface() { + return surface; + } + }; + + final Surface s = renderTarget.getSurface(); + final Canvas c = s.lockHardwareCanvas(); + s.unlockCanvasAndPost(c); + + reset(surface); + reset(surfaceTexture); + + // Test. + renderTarget.release(); + + // Verify. + verify(surface, times(1)).release(); + verifyNoMoreInteractions(surface); + verifyNoMoreInteractions(surfaceTexture); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/WindowManagerHandlerTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/WindowManagerHandlerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..230172d9e6cf82373c641a7ef5e8c9db6e987209 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/WindowManagerHandlerTest.java @@ -0,0 +1,138 @@ +// 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. + +package io.flutter.plugin.platform; + +import static io.flutter.Build.API_LEVELS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; + +import android.annotation.TargetApi; +import android.view.View; +import android.view.ViewGroup; +import android.view.WindowManager; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import java.util.concurrent.Executor; +import java.util.function.Consumer; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +@TargetApi(API_LEVELS.API_28) +public class WindowManagerHandlerTest { + @Test + @Config(minSdk = API_LEVELS.API_30) + public void windowManagerHandler_passesCorrectlyToFakeWindowViewGroup() { + // Mock the WindowManager and FakeWindowViewGroup that get used by the WindowManagerHandler. + WindowManager mockWindowManager = mock(WindowManager.class); + SingleViewFakeWindowViewGroup mockSingleViewFakeWindowViewGroup = + mock(SingleViewFakeWindowViewGroup.class); + + View mockView = mock(View.class); + ViewGroup.LayoutParams mockLayoutParams = mock(ViewGroup.LayoutParams.class); + + WindowManagerHandler windowManagerHandler = + new WindowManagerHandler(mockWindowManager, mockSingleViewFakeWindowViewGroup); + + // removeViewImmediate + windowManagerHandler.removeViewImmediate(mockView); + verify(mockView).clearAnimation(); + verify(mockSingleViewFakeWindowViewGroup).removeView(mockView); + verifyNoInteractions(mockWindowManager); + + // addView + windowManagerHandler.addView(mockView, mockLayoutParams); + verify(mockSingleViewFakeWindowViewGroup).addView(mockView, mockLayoutParams); + verifyNoInteractions(mockWindowManager); + + // updateViewLayout + windowManagerHandler.updateViewLayout(mockView, mockLayoutParams); + verify(mockSingleViewFakeWindowViewGroup).updateViewLayout(mockView, mockLayoutParams); + verifyNoInteractions(mockWindowManager); + + // removeView + windowManagerHandler.updateViewLayout(mockView, mockLayoutParams); + verify(mockSingleViewFakeWindowViewGroup).removeView(mockView); + verifyNoInteractions(mockWindowManager); + } + + @Test + @Config(minSdk = API_LEVELS.API_30) + public void windowManagerHandler_logAndReturnEarly_whenFakeWindowViewGroupIsNull() { + // Mock the WindowManager and FakeWindowViewGroup that get used by the WindowManagerHandler. + WindowManager mockWindowManager = mock(WindowManager.class); + + View mockView = mock(View.class); + ViewGroup.LayoutParams mockLayoutParams = mock(ViewGroup.LayoutParams.class); + + WindowManagerHandler windowManagerHandler = new WindowManagerHandler(mockWindowManager, null); + + // removeViewImmediate + windowManagerHandler.removeViewImmediate(mockView); + verifyNoInteractions(mockView); + verifyNoInteractions(mockWindowManager); + + // addView + windowManagerHandler.addView(mockView, mockLayoutParams); + verifyNoInteractions(mockWindowManager); + + // updateViewLayout + windowManagerHandler.updateViewLayout(mockView, mockLayoutParams); + verifyNoInteractions(mockWindowManager); + + // removeView + windowManagerHandler.updateViewLayout(mockView, mockLayoutParams); + verifyNoInteractions(mockWindowManager); + } + + // This section tests that WindowManagerHandler forwards all of the non-special case calls to the + // delegate WindowManager. Because this must include some deprecated WindowManager method calls + // (because the proxy overrides every method), we suppress deprecation warnings here. + @Test + @Config(minSdk = API_LEVELS.API_31) + @SuppressWarnings("deprecation") + public void windowManagerHandler_forwardsAllOtherCallsToDelegate() { + // Mock the WindowManager and FakeWindowViewGroup that get used by the WindowManagerHandler. + WindowManager mockWindowManager = mock(WindowManager.class); + SingleViewFakeWindowViewGroup mockSingleViewFakeWindowViewGroup = + mock(SingleViewFakeWindowViewGroup.class); + + WindowManagerHandler windowManagerHandler = + new WindowManagerHandler(mockWindowManager, mockSingleViewFakeWindowViewGroup); + + // Verify that all other calls get forwarded to the delegate. + Executor mockExecutor = mock(Executor.class); + @SuppressWarnings("Unchecked cast") + Consumer mockListener = (Consumer) mock(Consumer.class); + + // Windowmanager's getDefaultDisplay() function is deprecated in API 30 level 30. + // See Android docs here: + // https://developer.android.com/reference/android/view/WindowManager#getDefaultDisplay() + // We expect this behavior because this unit test expects a blind forward that includes + // deprecated function calls. See comment above for more details. + windowManagerHandler.getDefaultDisplay(); + verify(mockWindowManager).getDefaultDisplay(); + + windowManagerHandler.getCurrentWindowMetrics(); + verify(mockWindowManager).getCurrentWindowMetrics(); + + windowManagerHandler.getMaximumWindowMetrics(); + verify(mockWindowManager).getMaximumWindowMetrics(); + + windowManagerHandler.isCrossWindowBlurEnabled(); + verify(mockWindowManager).isCrossWindowBlurEnabled(); + + windowManagerHandler.addCrossWindowBlurEnabledListener(mockListener); + verify(mockWindowManager).addCrossWindowBlurEnabledListener(mockListener); + + windowManagerHandler.addCrossWindowBlurEnabledListener(mockExecutor, mockListener); + verify(mockWindowManager).addCrossWindowBlurEnabledListener(mockExecutor, mockListener); + + windowManagerHandler.removeCrossWindowBlurEnabledListener(mockListener); + verify(mockWindowManager).removeCrossWindowBlurEnabledListener(mockListener); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/text/ProcessTextPluginTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/text/ProcessTextPluginTest.java new file mode 100644 index 0000000000000000000000000000000000000000..8891e72cdbfcfc2d91fb8aff25de6ad9fbfe832c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugin/text/ProcessTextPluginTest.java @@ -0,0 +1,280 @@ +package io.flutter.plugin.text; + +import static io.flutter.Build.API_LEVELS; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyInt; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.annotation.TargetApi; +import android.app.Activity; +import android.content.Intent; +import android.content.pm.ActivityInfo; +import android.content.pm.PackageItemInfo; +import android.content.pm.PackageManager; +import android.content.pm.ResolveInfo; +import androidx.annotation.RequiresApi; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.dart.DartExecutor; +import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; +import io.flutter.embedding.engine.systemchannels.ProcessTextChannel; +import io.flutter.plugin.common.BinaryMessenger; +import io.flutter.plugin.common.MethodCall; +import io.flutter.plugin.common.MethodChannel; +import io.flutter.plugin.common.StandardMethodCodec; +import java.lang.reflect.Field; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; + +@RunWith(AndroidJUnit4.class) +@TargetApi(API_LEVELS.API_24) +@RequiresApi(API_LEVELS.API_24) +public class ProcessTextPluginTest { + + private static void sendToBinaryMessageHandler( + BinaryMessenger.BinaryMessageHandler binaryMessageHandler, String method, Object args) { + MethodCall methodCall = new MethodCall(method, args); + ByteBuffer encodedMethodCall = StandardMethodCodec.INSTANCE.encodeMethodCall(methodCall); + binaryMessageHandler.onMessage( + (ByteBuffer) encodedMethodCall.flip(), mock(BinaryMessenger.BinaryReply.class)); + } + + @SuppressWarnings("deprecation") + // setMessageHandler is deprecated. + @Test + public void respondsToProcessTextChannelMessage() { + ArgumentCaptor binaryMessageHandlerCaptor = + ArgumentCaptor.forClass(BinaryMessenger.BinaryMessageHandler.class); + DartExecutor mockBinaryMessenger = mock(DartExecutor.class); + ProcessTextChannel.ProcessTextMethodHandler mockHandler = + mock(ProcessTextChannel.ProcessTextMethodHandler.class); + PackageManager mockPackageManager = mock(PackageManager.class); + ProcessTextChannel processTextChannel = + new ProcessTextChannel(mockBinaryMessenger, mockPackageManager); + + processTextChannel.setMethodHandler(mockHandler); + + verify(mockBinaryMessenger, times(1)) + .setMessageHandler(any(String.class), binaryMessageHandlerCaptor.capture()); + + BinaryMessenger.BinaryMessageHandler binaryMessageHandler = + binaryMessageHandlerCaptor.getValue(); + + sendToBinaryMessageHandler(binaryMessageHandler, "ProcessText.queryTextActions", null); + + verify(mockHandler).queryTextActions(); + } + + @SuppressWarnings("deprecation") + // setMessageHandler is deprecated. + @Test + public void performQueryTextActions() { + DartExecutor mockBinaryMessenger = mock(DartExecutor.class); + PackageManager mockPackageManager = mock(PackageManager.class); + ProcessTextChannel processTextChannel = + new ProcessTextChannel(mockBinaryMessenger, mockPackageManager); + + // Set up mocked result for PackageManager.queryIntentActivities. + ResolveInfo action1 = createFakeResolveInfo("Action1", mockPackageManager); + ResolveInfo action2 = createFakeResolveInfo("Action2", mockPackageManager); + List infos = new ArrayList(Arrays.asList(action1, action2)); + Intent intent = new Intent().setAction(Intent.ACTION_PROCESS_TEXT).setType("text/plain"); + when(mockPackageManager.queryIntentActivities( + any(Intent.class), any(PackageManager.ResolveInfoFlags.class))) + .thenReturn(infos); + + // ProcessTextPlugin should retrieve the mocked text actions. + ProcessTextPlugin processTextPlugin = new ProcessTextPlugin(processTextChannel); + Map textActions = processTextPlugin.queryTextActions(); + final String action1Id = "mockActivityName.Action1"; + final String action2Id = "mockActivityName.Action2"; + assertEquals(textActions, Map.of(action1Id, "Action1", action2Id, "Action2")); + } + + @SuppressWarnings("deprecation") + // setMessageHandler is deprecated. + @Test + public void performProcessTextActionWithNoReturnedValue() { + DartExecutor mockBinaryMessenger = mock(DartExecutor.class); + PackageManager mockPackageManager = mock(PackageManager.class); + ProcessTextChannel processTextChannel = + new ProcessTextChannel(mockBinaryMessenger, mockPackageManager); + + // Set up mocked result for PackageManager.queryIntentActivities. + ResolveInfo action1 = createFakeResolveInfo("Action1", mockPackageManager); + ResolveInfo action2 = createFakeResolveInfo("Action2", mockPackageManager); + List infos = new ArrayList(Arrays.asList(action1, action2)); + when(mockPackageManager.queryIntentActivities( + any(Intent.class), any(PackageManager.ResolveInfoFlags.class))) + .thenReturn(infos); + + // ProcessTextPlugin should retrieve the mocked text actions. + ProcessTextPlugin processTextPlugin = new ProcessTextPlugin(processTextChannel); + Map textActions = processTextPlugin.queryTextActions(); + final String action1Id = "mockActivityName.Action1"; + final String action2Id = "mockActivityName.Action2"; + assertEquals(textActions, Map.of(action1Id, "Action1", action2Id, "Action2")); + + // Set up the activity binding. + ActivityPluginBinding mockActivityPluginBinding = mock(ActivityPluginBinding.class); + Activity mockActivity = mock(Activity.class); + when(mockActivityPluginBinding.getActivity()).thenReturn(mockActivity); + processTextPlugin.onAttachedToActivity(mockActivityPluginBinding); + + // Execute th first action. + String textToBeProcessed = "Flutter!"; + MethodChannel.Result result = mock(MethodChannel.Result.class); + processTextPlugin.processTextAction(action1Id, textToBeProcessed, false, result); + + // Activity.startActivityForResult should have been called. + ArgumentCaptor intentCaptor = ArgumentCaptor.forClass(Intent.class); + verify(mockActivity, times(1)).startActivityForResult(intentCaptor.capture(), anyInt()); + Intent intent = intentCaptor.getValue(); + assertEquals(intent.getStringExtra(Intent.EXTRA_PROCESS_TEXT), textToBeProcessed); + + // Simulate an Android activity answer which does not return a value. + Intent resultIntent = new Intent(); + processTextPlugin.onActivityResult(result.hashCode(), Activity.RESULT_OK, resultIntent); + + // Success with no returned value is expected. + verify(result).success(null); + } + + @SuppressWarnings("deprecation") + // setMessageHandler is deprecated. + @Test + public void performProcessTextActionWithReturnedValue() { + DartExecutor mockBinaryMessenger = mock(DartExecutor.class); + PackageManager mockPackageManager = mock(PackageManager.class); + ProcessTextChannel processTextChannel = + new ProcessTextChannel(mockBinaryMessenger, mockPackageManager); + + // Set up mocked result for PackageManager.queryIntentActivities. + ResolveInfo action1 = createFakeResolveInfo("Action1", mockPackageManager); + ResolveInfo action2 = createFakeResolveInfo("Action2", mockPackageManager); + List infos = new ArrayList(Arrays.asList(action1, action2)); + when(mockPackageManager.queryIntentActivities( + any(Intent.class), any(PackageManager.ResolveInfoFlags.class))) + .thenReturn(infos); + + // ProcessTextPlugin should retrieve the mocked text actions. + ProcessTextPlugin processTextPlugin = new ProcessTextPlugin(processTextChannel); + Map textActions = processTextPlugin.queryTextActions(); + final String action1Id = "mockActivityName.Action1"; + final String action2Id = "mockActivityName.Action2"; + assertEquals(textActions, Map.of(action1Id, "Action1", action2Id, "Action2")); + + // Set up the activity binding. + ActivityPluginBinding mockActivityPluginBinding = mock(ActivityPluginBinding.class); + Activity mockActivity = mock(Activity.class); + when(mockActivityPluginBinding.getActivity()).thenReturn(mockActivity); + processTextPlugin.onAttachedToActivity(mockActivityPluginBinding); + + // Execute the first action. + String textToBeProcessed = "Flutter!"; + MethodChannel.Result result = mock(MethodChannel.Result.class); + processTextPlugin.processTextAction(action1Id, textToBeProcessed, false, result); + + // Activity.startActivityForResult should have been called. + ArgumentCaptor intentCaptor = ArgumentCaptor.forClass(Intent.class); + verify(mockActivity, times(1)).startActivityForResult(intentCaptor.capture(), anyInt()); + Intent intent = intentCaptor.getValue(); + assertEquals(intent.getStringExtra(Intent.EXTRA_PROCESS_TEXT), textToBeProcessed); + + // Simulate an Android activity answer which returns a transformed text. + String processedText = "Flutter!!!"; + Intent resultIntent = new Intent(); + resultIntent.putExtra(Intent.EXTRA_PROCESS_TEXT, processedText); + processTextPlugin.onActivityResult(result.hashCode(), Activity.RESULT_OK, resultIntent); + + // Success with the transformed text is expected. + verify(result).success(processedText); + } + + @SuppressWarnings("deprecation") + // setMessageHandler is deprecated. + @Test + public void doNotCrashOnNonRelatedActivityResult() { + DartExecutor mockBinaryMessenger = mock(DartExecutor.class); + PackageManager mockPackageManager = mock(PackageManager.class); + ProcessTextChannel processTextChannel = + new ProcessTextChannel(mockBinaryMessenger, mockPackageManager); + + // Set up mocked result for PackageManager.queryIntentActivities. + ResolveInfo action1 = createFakeResolveInfo("Action1", mockPackageManager); + ResolveInfo action2 = createFakeResolveInfo("Action2", mockPackageManager); + List infos = new ArrayList(Arrays.asList(action1, action2)); + when(mockPackageManager.queryIntentActivities( + any(Intent.class), any(PackageManager.ResolveInfoFlags.class))) + .thenReturn(infos); + + // ProcessTextPlugin should retrieve the mocked text actions. + ProcessTextPlugin processTextPlugin = new ProcessTextPlugin(processTextChannel); + Map textActions = processTextPlugin.queryTextActions(); + final String action1Id = "mockActivityName.Action1"; + final String action2Id = "mockActivityName.Action2"; + assertEquals(textActions, Map.of(action1Id, "Action1", action2Id, "Action2")); + + // Set up the activity binding. + ActivityPluginBinding mockActivityPluginBinding = mock(ActivityPluginBinding.class); + Activity mockActivity = mock(Activity.class); + when(mockActivityPluginBinding.getActivity()).thenReturn(mockActivity); + processTextPlugin.onAttachedToActivity(mockActivityPluginBinding); + + // Execute the first action. + String textToBeProcessed = "Flutter!"; + MethodChannel.Result result = mock(MethodChannel.Result.class); + processTextPlugin.processTextAction(action1Id, textToBeProcessed, false, result); + + // Activity.startActivityForResult should have been called. + ArgumentCaptor intentCaptor = ArgumentCaptor.forClass(Intent.class); + verify(mockActivity, times(1)).startActivityForResult(intentCaptor.capture(), anyInt()); + Intent intent = intentCaptor.getValue(); + assertEquals(intent.getStringExtra(Intent.EXTRA_PROCESS_TEXT), textToBeProcessed); + + // Result to a request not sent by this plugin should be ignored. + final int externalRequestCode = 42; + processTextPlugin.onActivityResult(externalRequestCode, Activity.RESULT_OK, new Intent()); + + // Simulate an Android activity answer which returns a transformed text. + String processedText = "Flutter!!!"; + Intent resultIntent = new Intent(); + resultIntent.putExtra(Intent.EXTRA_PROCESS_TEXT, processedText); + processTextPlugin.onActivityResult(result.hashCode(), Activity.RESULT_OK, resultIntent); + + // Success with the transformed text is expected. + verify(result).success(processedText); + } + + private ResolveInfo createFakeResolveInfo(String label, PackageManager mockPackageManager) { + ResolveInfo resolveInfo = mock(ResolveInfo.class); + ActivityInfo activityInfo = new ActivityInfo(); + when(resolveInfo.loadLabel(mockPackageManager)).thenReturn(label); + + // Use Java reflection to set required member variables. + try { + Field activityField = ResolveInfo.class.getDeclaredField("activityInfo"); + activityField.setAccessible(true); + activityField.set(resolveInfo, activityInfo); + Field packageNameField = PackageItemInfo.class.getDeclaredField("packageName"); + packageNameField.setAccessible(true); + packageNameField.set(activityInfo, "mockActivityPackageName"); + Field nameField = PackageItemInfo.class.getDeclaredField("name"); + nameField.setAccessible(true); + nameField.set(activityInfo, "mockActivityName." + label); + } catch (Exception ex) { + // Test will failed if reflection APIs throw. + } + + return resolveInfo; + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugins/GeneratedPluginRegistrant.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugins/GeneratedPluginRegistrant.java new file mode 100644 index 0000000000000000000000000000000000000000..387de14de371f0fe713044f402f715cf700c8385 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/plugins/GeneratedPluginRegistrant.java @@ -0,0 +1,55 @@ +package io.flutter.plugins; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.VisibleForTesting; +import io.flutter.embedding.engine.FlutterEngine; +import java.util.ArrayList; +import java.util.List; + +/** + * A fake of the {@code GeneratedPluginRegistrant} normally built by the tool into Flutter apps. + * + *

Used to test engine logic which interacts with the generated class. + */ +@VisibleForTesting +public class GeneratedPluginRegistrant { + private static final List registeredEngines = new ArrayList<>(); + public static @Nullable RuntimeException pluginRegistrationException; + + /** + * The one and only method currently generated by the tool. + * + *

Normally it registers all plugins in an app with the given {@code engine}. This fake tracks + * all registered engines instead. + */ + public static void registerWith(@NonNull FlutterEngine engine) { + if (pluginRegistrationException != null) { + throw pluginRegistrationException; + } + registeredEngines.add(engine); + } + + /** + * Clears the mutable static state regrettably stored in this class. + * + *

{@link #registerWith} is a static call with no visible side effects. In order to verify when + * it's been called we also unfortunately need to store the state statically. This should be + * called before and after each test run accessing this class to make sure the state is clear both + * before and after the run. + */ + public static void clearRegisteredEngines() { + registeredEngines.clear(); + } + + /** + * Returns a list of all the engines registered so far. + * + *

CAUTION: This list is static and must be manually wiped in between test runs. See {@link + * #clearRegisteredEngines()}. + */ + @NonNull + public static List getRegisteredEngines() { + return new ArrayList<>(registeredEngines); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/util/FakeKeyEvent.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/util/FakeKeyEvent.java new file mode 100644 index 0000000000000000000000000000000000000000..35ef6731d6ec899e8cc103f93bebf077b7c7a6e0 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/util/FakeKeyEvent.java @@ -0,0 +1,37 @@ +package io.flutter.util; + +import android.view.KeyEvent; + +// In the test environment, keyEvent.getUnicodeChar throws an exception. This +// class works around the exception by hardcoding the returned value. +public class FakeKeyEvent extends KeyEvent { + public FakeKeyEvent(int action, int keyCode) { + super(action, keyCode); + } + + public FakeKeyEvent(int action, int keyCode, char character) { + super(action, keyCode); + this.character = character; + } + + public FakeKeyEvent( + int action, int scancode, int code, int repeat, char character, int metaState) { + super(0, 0, action, code, repeat, metaState, 0, scancode); + this.character = character; + } + + public FakeKeyEvent( + int action, int scancode, int code, int repeat, char character, int metaState, int source) { + super(0, 0, action, code, repeat, metaState, 0, scancode, 0, source); + this.character = character; + } + + private char character = 0; + + public final int getUnicodeChar() { + if (getKeyCode() == KeyEvent.KEYCODE_BACK) { + return 0; + } + return character; + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/util/HandlerCompatTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/util/HandlerCompatTest.java new file mode 100644 index 0000000000000000000000000000000000000000..9d4538d40565d98e17726fa8dac03b99e798cd88 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/util/HandlerCompatTest.java @@ -0,0 +1,30 @@ +// 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. + +package io.flutter.util; + +import static io.flutter.Build.API_LEVELS; +import static org.junit.Assert.assertTrue; + +import android.os.Handler; +import android.os.Looper; +import android.os.Message; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.annotation.Config; + +@RunWith(RobolectricTestRunner.class) +public class HandlerCompatTest { + @Test + @Config(sdk = API_LEVELS.API_28) + public void createAsync_createsAnAsyncHandler() { + Handler handler = Handler.createAsync(Looper.getMainLooper()); + + Message message = Message.obtain(); + handler.sendMessageAtTime(message, 0); + + assertTrue(message.isAsynchronous()); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/util/KeyCodes.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/util/KeyCodes.java new file mode 100644 index 0000000000000000000000000000000000000000..0f7035b9f3f70b0b03162319efdcc96c293d5a06 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/util/KeyCodes.java @@ -0,0 +1,733 @@ +package io.flutter.util; + +// DO NOT EDIT -- DO NOT EDIT -- DO NOT EDIT +// This file is generated by +// flutter/flutter:dev/tools/gen_keycodes/bin/gen_keycodes.dart and should not +// be edited directly. +// +// Edit the template +// flutter/flutter:dev/tools/gen_keycodes/data/key_codes_java.tmpl +// instead. +// +// See flutter/flutter:dev/tools/gen_keycodes/README.md for more information. + +/** + * This class contains keyboard constants to be used in unit tests. They should not be used in + * production code. + */ +public class KeyCodes { + public static final long PHYSICAL_HYPER = 0x00000010L; + public static final long PHYSICAL_SUPER_KEY = 0x00000011L; + public static final long PHYSICAL_FN = 0x00000012L; + public static final long PHYSICAL_FN_LOCK = 0x00000013L; + public static final long PHYSICAL_SUSPEND = 0x00000014L; + public static final long PHYSICAL_RESUME = 0x00000015L; + public static final long PHYSICAL_TURBO = 0x00000016L; + public static final long PHYSICAL_PRIVACY_SCREEN_TOGGLE = 0x00000017L; + public static final long PHYSICAL_MICROPHONE_MUTE_TOGGLE = 0x00000018L; + public static final long PHYSICAL_SLEEP = 0x00010082L; + public static final long PHYSICAL_WAKE_UP = 0x00010083L; + public static final long PHYSICAL_DISPLAY_TOGGLE_INT_EXT = 0x000100b5L; + public static final long PHYSICAL_GAME_BUTTON1 = 0x0005ff01L; + public static final long PHYSICAL_GAME_BUTTON2 = 0x0005ff02L; + public static final long PHYSICAL_GAME_BUTTON3 = 0x0005ff03L; + public static final long PHYSICAL_GAME_BUTTON4 = 0x0005ff04L; + public static final long PHYSICAL_GAME_BUTTON5 = 0x0005ff05L; + public static final long PHYSICAL_GAME_BUTTON6 = 0x0005ff06L; + public static final long PHYSICAL_GAME_BUTTON7 = 0x0005ff07L; + public static final long PHYSICAL_GAME_BUTTON8 = 0x0005ff08L; + public static final long PHYSICAL_GAME_BUTTON9 = 0x0005ff09L; + public static final long PHYSICAL_GAME_BUTTON10 = 0x0005ff0aL; + public static final long PHYSICAL_GAME_BUTTON11 = 0x0005ff0bL; + public static final long PHYSICAL_GAME_BUTTON12 = 0x0005ff0cL; + public static final long PHYSICAL_GAME_BUTTON13 = 0x0005ff0dL; + public static final long PHYSICAL_GAME_BUTTON14 = 0x0005ff0eL; + public static final long PHYSICAL_GAME_BUTTON15 = 0x0005ff0fL; + public static final long PHYSICAL_GAME_BUTTON16 = 0x0005ff10L; + public static final long PHYSICAL_GAME_BUTTON_A = 0x0005ff11L; + public static final long PHYSICAL_GAME_BUTTON_B = 0x0005ff12L; + public static final long PHYSICAL_GAME_BUTTON_C = 0x0005ff13L; + public static final long PHYSICAL_GAME_BUTTON_LEFT1 = 0x0005ff14L; + public static final long PHYSICAL_GAME_BUTTON_LEFT2 = 0x0005ff15L; + public static final long PHYSICAL_GAME_BUTTON_MODE = 0x0005ff16L; + public static final long PHYSICAL_GAME_BUTTON_RIGHT1 = 0x0005ff17L; + public static final long PHYSICAL_GAME_BUTTON_RIGHT2 = 0x0005ff18L; + public static final long PHYSICAL_GAME_BUTTON_SELECT = 0x0005ff19L; + public static final long PHYSICAL_GAME_BUTTON_START = 0x0005ff1aL; + public static final long PHYSICAL_GAME_BUTTON_THUMB_LEFT = 0x0005ff1bL; + public static final long PHYSICAL_GAME_BUTTON_THUMB_RIGHT = 0x0005ff1cL; + public static final long PHYSICAL_GAME_BUTTON_X = 0x0005ff1dL; + public static final long PHYSICAL_GAME_BUTTON_Y = 0x0005ff1eL; + public static final long PHYSICAL_GAME_BUTTON_Z = 0x0005ff1fL; + public static final long PHYSICAL_USB_RESERVED = 0x00070000L; + public static final long PHYSICAL_USB_ERROR_ROLL_OVER = 0x00070001L; + public static final long PHYSICAL_USB_POST_FAIL = 0x00070002L; + public static final long PHYSICAL_USB_ERROR_UNDEFINED = 0x00070003L; + public static final long PHYSICAL_KEY_A = 0x00070004L; + public static final long PHYSICAL_KEY_B = 0x00070005L; + public static final long PHYSICAL_KEY_C = 0x00070006L; + public static final long PHYSICAL_KEY_D = 0x00070007L; + public static final long PHYSICAL_KEY_E = 0x00070008L; + public static final long PHYSICAL_KEY_F = 0x00070009L; + public static final long PHYSICAL_KEY_G = 0x0007000aL; + public static final long PHYSICAL_KEY_H = 0x0007000bL; + public static final long PHYSICAL_KEY_I = 0x0007000cL; + public static final long PHYSICAL_KEY_J = 0x0007000dL; + public static final long PHYSICAL_KEY_K = 0x0007000eL; + public static final long PHYSICAL_KEY_L = 0x0007000fL; + public static final long PHYSICAL_KEY_M = 0x00070010L; + public static final long PHYSICAL_KEY_N = 0x00070011L; + public static final long PHYSICAL_KEY_O = 0x00070012L; + public static final long PHYSICAL_KEY_P = 0x00070013L; + public static final long PHYSICAL_KEY_Q = 0x00070014L; + public static final long PHYSICAL_KEY_R = 0x00070015L; + public static final long PHYSICAL_KEY_S = 0x00070016L; + public static final long PHYSICAL_KEY_T = 0x00070017L; + public static final long PHYSICAL_KEY_U = 0x00070018L; + public static final long PHYSICAL_KEY_V = 0x00070019L; + public static final long PHYSICAL_KEY_W = 0x0007001aL; + public static final long PHYSICAL_KEY_X = 0x0007001bL; + public static final long PHYSICAL_KEY_Y = 0x0007001cL; + public static final long PHYSICAL_KEY_Z = 0x0007001dL; + public static final long PHYSICAL_DIGIT1 = 0x0007001eL; + public static final long PHYSICAL_DIGIT2 = 0x0007001fL; + public static final long PHYSICAL_DIGIT3 = 0x00070020L; + public static final long PHYSICAL_DIGIT4 = 0x00070021L; + public static final long PHYSICAL_DIGIT5 = 0x00070022L; + public static final long PHYSICAL_DIGIT6 = 0x00070023L; + public static final long PHYSICAL_DIGIT7 = 0x00070024L; + public static final long PHYSICAL_DIGIT8 = 0x00070025L; + public static final long PHYSICAL_DIGIT9 = 0x00070026L; + public static final long PHYSICAL_DIGIT0 = 0x00070027L; + public static final long PHYSICAL_ENTER = 0x00070028L; + public static final long PHYSICAL_ESCAPE = 0x00070029L; + public static final long PHYSICAL_BACKSPACE = 0x0007002aL; + public static final long PHYSICAL_TAB = 0x0007002bL; + public static final long PHYSICAL_SPACE = 0x0007002cL; + public static final long PHYSICAL_MINUS = 0x0007002dL; + public static final long PHYSICAL_EQUAL = 0x0007002eL; + public static final long PHYSICAL_BRACKET_LEFT = 0x0007002fL; + public static final long PHYSICAL_BRACKET_RIGHT = 0x00070030L; + public static final long PHYSICAL_BACKSLASH = 0x00070031L; + public static final long PHYSICAL_SEMICOLON = 0x00070033L; + public static final long PHYSICAL_QUOTE = 0x00070034L; + public static final long PHYSICAL_BACKQUOTE = 0x00070035L; + public static final long PHYSICAL_COMMA = 0x00070036L; + public static final long PHYSICAL_PERIOD = 0x00070037L; + public static final long PHYSICAL_SLASH = 0x00070038L; + public static final long PHYSICAL_CAPS_LOCK = 0x00070039L; + public static final long PHYSICAL_F1 = 0x0007003aL; + public static final long PHYSICAL_F2 = 0x0007003bL; + public static final long PHYSICAL_F3 = 0x0007003cL; + public static final long PHYSICAL_F4 = 0x0007003dL; + public static final long PHYSICAL_F5 = 0x0007003eL; + public static final long PHYSICAL_F6 = 0x0007003fL; + public static final long PHYSICAL_F7 = 0x00070040L; + public static final long PHYSICAL_F8 = 0x00070041L; + public static final long PHYSICAL_F9 = 0x00070042L; + public static final long PHYSICAL_F10 = 0x00070043L; + public static final long PHYSICAL_F11 = 0x00070044L; + public static final long PHYSICAL_F12 = 0x00070045L; + public static final long PHYSICAL_PRINT_SCREEN = 0x00070046L; + public static final long PHYSICAL_SCROLL_LOCK = 0x00070047L; + public static final long PHYSICAL_PAUSE = 0x00070048L; + public static final long PHYSICAL_INSERT = 0x00070049L; + public static final long PHYSICAL_HOME = 0x0007004aL; + public static final long PHYSICAL_PAGE_UP = 0x0007004bL; + public static final long PHYSICAL_DELETE = 0x0007004cL; + public static final long PHYSICAL_END = 0x0007004dL; + public static final long PHYSICAL_PAGE_DOWN = 0x0007004eL; + public static final long PHYSICAL_ARROW_RIGHT = 0x0007004fL; + public static final long PHYSICAL_ARROW_LEFT = 0x00070050L; + public static final long PHYSICAL_ARROW_DOWN = 0x00070051L; + public static final long PHYSICAL_ARROW_UP = 0x00070052L; + public static final long PHYSICAL_NUM_LOCK = 0x00070053L; + public static final long PHYSICAL_NUMPAD_DIVIDE = 0x00070054L; + public static final long PHYSICAL_NUMPAD_MULTIPLY = 0x00070055L; + public static final long PHYSICAL_NUMPAD_SUBTRACT = 0x00070056L; + public static final long PHYSICAL_NUMPAD_ADD = 0x00070057L; + public static final long PHYSICAL_NUMPAD_ENTER = 0x00070058L; + public static final long PHYSICAL_NUMPAD1 = 0x00070059L; + public static final long PHYSICAL_NUMPAD2 = 0x0007005aL; + public static final long PHYSICAL_NUMPAD3 = 0x0007005bL; + public static final long PHYSICAL_NUMPAD4 = 0x0007005cL; + public static final long PHYSICAL_NUMPAD5 = 0x0007005dL; + public static final long PHYSICAL_NUMPAD6 = 0x0007005eL; + public static final long PHYSICAL_NUMPAD7 = 0x0007005fL; + public static final long PHYSICAL_NUMPAD8 = 0x00070060L; + public static final long PHYSICAL_NUMPAD9 = 0x00070061L; + public static final long PHYSICAL_NUMPAD0 = 0x00070062L; + public static final long PHYSICAL_NUMPAD_DECIMAL = 0x00070063L; + public static final long PHYSICAL_INTL_BACKSLASH = 0x00070064L; + public static final long PHYSICAL_CONTEXT_MENU = 0x00070065L; + public static final long PHYSICAL_POWER = 0x00070066L; + public static final long PHYSICAL_NUMPAD_EQUAL = 0x00070067L; + public static final long PHYSICAL_F13 = 0x00070068L; + public static final long PHYSICAL_F14 = 0x00070069L; + public static final long PHYSICAL_F15 = 0x0007006aL; + public static final long PHYSICAL_F16 = 0x0007006bL; + public static final long PHYSICAL_F17 = 0x0007006cL; + public static final long PHYSICAL_F18 = 0x0007006dL; + public static final long PHYSICAL_F19 = 0x0007006eL; + public static final long PHYSICAL_F20 = 0x0007006fL; + public static final long PHYSICAL_F21 = 0x00070070L; + public static final long PHYSICAL_F22 = 0x00070071L; + public static final long PHYSICAL_F23 = 0x00070072L; + public static final long PHYSICAL_F24 = 0x00070073L; + public static final long PHYSICAL_OPEN = 0x00070074L; + public static final long PHYSICAL_HELP = 0x00070075L; + public static final long PHYSICAL_SELECT = 0x00070077L; + public static final long PHYSICAL_AGAIN = 0x00070079L; + public static final long PHYSICAL_UNDO = 0x0007007aL; + public static final long PHYSICAL_CUT = 0x0007007bL; + public static final long PHYSICAL_COPY = 0x0007007cL; + public static final long PHYSICAL_PASTE = 0x0007007dL; + public static final long PHYSICAL_FIND = 0x0007007eL; + public static final long PHYSICAL_AUDIO_VOLUME_MUTE = 0x0007007fL; + public static final long PHYSICAL_AUDIO_VOLUME_UP = 0x00070080L; + public static final long PHYSICAL_AUDIO_VOLUME_DOWN = 0x00070081L; + public static final long PHYSICAL_NUMPAD_COMMA = 0x00070085L; + public static final long PHYSICAL_INTL_RO = 0x00070087L; + public static final long PHYSICAL_KANA_MODE = 0x00070088L; + public static final long PHYSICAL_INTL_YEN = 0x00070089L; + public static final long PHYSICAL_CONVERT = 0x0007008aL; + public static final long PHYSICAL_NON_CONVERT = 0x0007008bL; + public static final long PHYSICAL_LANG1 = 0x00070090L; + public static final long PHYSICAL_LANG2 = 0x00070091L; + public static final long PHYSICAL_LANG3 = 0x00070092L; + public static final long PHYSICAL_LANG4 = 0x00070093L; + public static final long PHYSICAL_LANG5 = 0x00070094L; + public static final long PHYSICAL_ABORT = 0x0007009bL; + public static final long PHYSICAL_PROPS = 0x000700a3L; + public static final long PHYSICAL_NUMPAD_PAREN_LEFT = 0x000700b6L; + public static final long PHYSICAL_NUMPAD_PAREN_RIGHT = 0x000700b7L; + public static final long PHYSICAL_NUMPAD_BACKSPACE = 0x000700bbL; + public static final long PHYSICAL_NUMPAD_MEMORY_STORE = 0x000700d0L; + public static final long PHYSICAL_NUMPAD_MEMORY_RECALL = 0x000700d1L; + public static final long PHYSICAL_NUMPAD_MEMORY_CLEAR = 0x000700d2L; + public static final long PHYSICAL_NUMPAD_MEMORY_ADD = 0x000700d3L; + public static final long PHYSICAL_NUMPAD_MEMORY_SUBTRACT = 0x000700d4L; + public static final long PHYSICAL_NUMPAD_SIGN_CHANGE = 0x000700d7L; + public static final long PHYSICAL_NUMPAD_CLEAR = 0x000700d8L; + public static final long PHYSICAL_NUMPAD_CLEAR_ENTRY = 0x000700d9L; + public static final long PHYSICAL_CONTROL_LEFT = 0x000700e0L; + public static final long PHYSICAL_SHIFT_LEFT = 0x000700e1L; + public static final long PHYSICAL_ALT_LEFT = 0x000700e2L; + public static final long PHYSICAL_META_LEFT = 0x000700e3L; + public static final long PHYSICAL_CONTROL_RIGHT = 0x000700e4L; + public static final long PHYSICAL_SHIFT_RIGHT = 0x000700e5L; + public static final long PHYSICAL_ALT_RIGHT = 0x000700e6L; + public static final long PHYSICAL_META_RIGHT = 0x000700e7L; + public static final long PHYSICAL_INFO = 0x000c0060L; + public static final long PHYSICAL_CLOSED_CAPTION_TOGGLE = 0x000c0061L; + public static final long PHYSICAL_BRIGHTNESS_UP = 0x000c006fL; + public static final long PHYSICAL_BRIGHTNESS_DOWN = 0x000c0070L; + public static final long PHYSICAL_BRIGHTNESS_TOGGLE = 0x000c0072L; + public static final long PHYSICAL_BRIGHTNESS_MINIMUM = 0x000c0073L; + public static final long PHYSICAL_BRIGHTNESS_MAXIMUM = 0x000c0074L; + public static final long PHYSICAL_BRIGHTNESS_AUTO = 0x000c0075L; + public static final long PHYSICAL_KBD_ILLUM_UP = 0x000c0079L; + public static final long PHYSICAL_KBD_ILLUM_DOWN = 0x000c007aL; + public static final long PHYSICAL_MEDIA_LAST = 0x000c0083L; + public static final long PHYSICAL_LAUNCH_PHONE = 0x000c008cL; + public static final long PHYSICAL_PROGRAM_GUIDE = 0x000c008dL; + public static final long PHYSICAL_EXIT = 0x000c0094L; + public static final long PHYSICAL_CHANNEL_UP = 0x000c009cL; + public static final long PHYSICAL_CHANNEL_DOWN = 0x000c009dL; + public static final long PHYSICAL_MEDIA_PLAY = 0x000c00b0L; + public static final long PHYSICAL_MEDIA_PAUSE = 0x000c00b1L; + public static final long PHYSICAL_MEDIA_RECORD = 0x000c00b2L; + public static final long PHYSICAL_MEDIA_FAST_FORWARD = 0x000c00b3L; + public static final long PHYSICAL_MEDIA_REWIND = 0x000c00b4L; + public static final long PHYSICAL_MEDIA_TRACK_NEXT = 0x000c00b5L; + public static final long PHYSICAL_MEDIA_TRACK_PREVIOUS = 0x000c00b6L; + public static final long PHYSICAL_MEDIA_STOP = 0x000c00b7L; + public static final long PHYSICAL_EJECT = 0x000c00b8L; + public static final long PHYSICAL_MEDIA_PLAY_PAUSE = 0x000c00cdL; + public static final long PHYSICAL_SPEECH_INPUT_TOGGLE = 0x000c00cfL; + public static final long PHYSICAL_BASS_BOOST = 0x000c00e5L; + public static final long PHYSICAL_MEDIA_SELECT = 0x000c0183L; + public static final long PHYSICAL_LAUNCH_WORD_PROCESSOR = 0x000c0184L; + public static final long PHYSICAL_LAUNCH_SPREADSHEET = 0x000c0186L; + public static final long PHYSICAL_LAUNCH_MAIL = 0x000c018aL; + public static final long PHYSICAL_LAUNCH_CONTACTS = 0x000c018dL; + public static final long PHYSICAL_LAUNCH_CALENDAR = 0x000c018eL; + public static final long PHYSICAL_LAUNCH_APP2 = 0x000c0192L; + public static final long PHYSICAL_LAUNCH_APP1 = 0x000c0194L; + public static final long PHYSICAL_LAUNCH_INTERNET_BROWSER = 0x000c0196L; + public static final long PHYSICAL_LOG_OFF = 0x000c019cL; + public static final long PHYSICAL_LOCK_SCREEN = 0x000c019eL; + public static final long PHYSICAL_LAUNCH_CONTROL_PANEL = 0x000c019fL; + public static final long PHYSICAL_SELECT_TASK = 0x000c01a2L; + public static final long PHYSICAL_LAUNCH_DOCUMENTS = 0x000c01a7L; + public static final long PHYSICAL_SPELL_CHECK = 0x000c01abL; + public static final long PHYSICAL_LAUNCH_KEYBOARD_LAYOUT = 0x000c01aeL; + public static final long PHYSICAL_LAUNCH_SCREEN_SAVER = 0x000c01b1L; + public static final long PHYSICAL_LAUNCH_AUDIO_BROWSER = 0x000c01b7L; + public static final long PHYSICAL_LAUNCH_ASSISTANT = 0x000c01cbL; + public static final long PHYSICAL_NEW_KEY = 0x000c0201L; + public static final long PHYSICAL_CLOSE = 0x000c0203L; + public static final long PHYSICAL_SAVE = 0x000c0207L; + public static final long PHYSICAL_PRINT = 0x000c0208L; + public static final long PHYSICAL_BROWSER_SEARCH = 0x000c0221L; + public static final long PHYSICAL_BROWSER_HOME = 0x000c0223L; + public static final long PHYSICAL_BROWSER_BACK = 0x000c0224L; + public static final long PHYSICAL_BROWSER_FORWARD = 0x000c0225L; + public static final long PHYSICAL_BROWSER_STOP = 0x000c0226L; + public static final long PHYSICAL_BROWSER_REFRESH = 0x000c0227L; + public static final long PHYSICAL_BROWSER_FAVORITES = 0x000c022aL; + public static final long PHYSICAL_ZOOM_IN = 0x000c022dL; + public static final long PHYSICAL_ZOOM_OUT = 0x000c022eL; + public static final long PHYSICAL_ZOOM_TOGGLE = 0x000c0232L; + public static final long PHYSICAL_REDO = 0x000c0279L; + public static final long PHYSICAL_MAIL_REPLY = 0x000c0289L; + public static final long PHYSICAL_MAIL_FORWARD = 0x000c028bL; + public static final long PHYSICAL_MAIL_SEND = 0x000c028cL; + public static final long PHYSICAL_KEYBOARD_LAYOUT_SELECT = 0x000c029dL; + public static final long PHYSICAL_SHOW_ALL_WINDOWS = 0x000c029fL; + + public static final long LOGICAL_SPACE = 0x00000000020L; + public static final long LOGICAL_EXCLAMATION = 0x00000000021L; + public static final long LOGICAL_QUOTE = 0x00000000022L; + public static final long LOGICAL_NUMBER_SIGN = 0x00000000023L; + public static final long LOGICAL_DOLLAR = 0x00000000024L; + public static final long LOGICAL_PERCENT = 0x00000000025L; + public static final long LOGICAL_AMPERSAND = 0x00000000026L; + public static final long LOGICAL_QUOTE_SINGLE = 0x00000000027L; + public static final long LOGICAL_PARENTHESIS_LEFT = 0x00000000028L; + public static final long LOGICAL_PARENTHESIS_RIGHT = 0x00000000029L; + public static final long LOGICAL_ASTERISK = 0x0000000002aL; + public static final long LOGICAL_ADD = 0x0000000002bL; + public static final long LOGICAL_COMMA = 0x0000000002cL; + public static final long LOGICAL_MINUS = 0x0000000002dL; + public static final long LOGICAL_PERIOD = 0x0000000002eL; + public static final long LOGICAL_SLASH = 0x0000000002fL; + public static final long LOGICAL_DIGIT0 = 0x00000000030L; + public static final long LOGICAL_DIGIT1 = 0x00000000031L; + public static final long LOGICAL_DIGIT2 = 0x00000000032L; + public static final long LOGICAL_DIGIT3 = 0x00000000033L; + public static final long LOGICAL_DIGIT4 = 0x00000000034L; + public static final long LOGICAL_DIGIT5 = 0x00000000035L; + public static final long LOGICAL_DIGIT6 = 0x00000000036L; + public static final long LOGICAL_DIGIT7 = 0x00000000037L; + public static final long LOGICAL_DIGIT8 = 0x00000000038L; + public static final long LOGICAL_DIGIT9 = 0x00000000039L; + public static final long LOGICAL_COLON = 0x0000000003aL; + public static final long LOGICAL_SEMICOLON = 0x0000000003bL; + public static final long LOGICAL_LESS = 0x0000000003cL; + public static final long LOGICAL_EQUAL = 0x0000000003dL; + public static final long LOGICAL_GREATER = 0x0000000003eL; + public static final long LOGICAL_QUESTION = 0x0000000003fL; + public static final long LOGICAL_AT = 0x00000000040L; + public static final long LOGICAL_BRACKET_LEFT = 0x0000000005bL; + public static final long LOGICAL_BACKSLASH = 0x0000000005cL; + public static final long LOGICAL_BRACKET_RIGHT = 0x0000000005dL; + public static final long LOGICAL_CARET = 0x0000000005eL; + public static final long LOGICAL_UNDERSCORE = 0x0000000005fL; + public static final long LOGICAL_BACKQUOTE = 0x00000000060L; + public static final long LOGICAL_KEY_A = 0x00000000061L; + public static final long LOGICAL_KEY_B = 0x00000000062L; + public static final long LOGICAL_KEY_C = 0x00000000063L; + public static final long LOGICAL_KEY_D = 0x00000000064L; + public static final long LOGICAL_KEY_E = 0x00000000065L; + public static final long LOGICAL_KEY_F = 0x00000000066L; + public static final long LOGICAL_KEY_G = 0x00000000067L; + public static final long LOGICAL_KEY_H = 0x00000000068L; + public static final long LOGICAL_KEY_I = 0x00000000069L; + public static final long LOGICAL_KEY_J = 0x0000000006aL; + public static final long LOGICAL_KEY_K = 0x0000000006bL; + public static final long LOGICAL_KEY_L = 0x0000000006cL; + public static final long LOGICAL_KEY_M = 0x0000000006dL; + public static final long LOGICAL_KEY_N = 0x0000000006eL; + public static final long LOGICAL_KEY_O = 0x0000000006fL; + public static final long LOGICAL_KEY_P = 0x00000000070L; + public static final long LOGICAL_KEY_Q = 0x00000000071L; + public static final long LOGICAL_KEY_R = 0x00000000072L; + public static final long LOGICAL_KEY_S = 0x00000000073L; + public static final long LOGICAL_KEY_T = 0x00000000074L; + public static final long LOGICAL_KEY_U = 0x00000000075L; + public static final long LOGICAL_KEY_V = 0x00000000076L; + public static final long LOGICAL_KEY_W = 0x00000000077L; + public static final long LOGICAL_KEY_X = 0x00000000078L; + public static final long LOGICAL_KEY_Y = 0x00000000079L; + public static final long LOGICAL_KEY_Z = 0x0000000007aL; + public static final long LOGICAL_BRACE_LEFT = 0x0000000007bL; + public static final long LOGICAL_BAR = 0x0000000007cL; + public static final long LOGICAL_BRACE_RIGHT = 0x0000000007dL; + public static final long LOGICAL_TILDE = 0x0000000007eL; + public static final long LOGICAL_UNIDENTIFIED = 0x00100000001L; + public static final long LOGICAL_BACKSPACE = 0x00100000008L; + public static final long LOGICAL_TAB = 0x00100000009L; + public static final long LOGICAL_ENTER = 0x0010000000dL; + public static final long LOGICAL_ESCAPE = 0x0010000001bL; + public static final long LOGICAL_DELETE = 0x0010000007fL; + public static final long LOGICAL_ACCEL = 0x00100000101L; + public static final long LOGICAL_ALT_GRAPH = 0x00100000103L; + public static final long LOGICAL_CAPS_LOCK = 0x00100000104L; + public static final long LOGICAL_FN = 0x00100000106L; + public static final long LOGICAL_FN_LOCK = 0x00100000107L; + public static final long LOGICAL_HYPER = 0x00100000108L; + public static final long LOGICAL_NUM_LOCK = 0x0010000010aL; + public static final long LOGICAL_SCROLL_LOCK = 0x0010000010cL; + public static final long LOGICAL_SUPER_KEY = 0x0010000010eL; + public static final long LOGICAL_SYMBOL = 0x0010000010fL; + public static final long LOGICAL_SYMBOL_LOCK = 0x00100000110L; + public static final long LOGICAL_SHIFT_LEVEL5 = 0x00100000111L; + public static final long LOGICAL_ARROW_DOWN = 0x00100000301L; + public static final long LOGICAL_ARROW_LEFT = 0x00100000302L; + public static final long LOGICAL_ARROW_RIGHT = 0x00100000303L; + public static final long LOGICAL_ARROW_UP = 0x00100000304L; + public static final long LOGICAL_END = 0x00100000305L; + public static final long LOGICAL_HOME = 0x00100000306L; + public static final long LOGICAL_PAGE_DOWN = 0x00100000307L; + public static final long LOGICAL_PAGE_UP = 0x00100000308L; + public static final long LOGICAL_CLEAR = 0x00100000401L; + public static final long LOGICAL_COPY = 0x00100000402L; + public static final long LOGICAL_CR_SEL = 0x00100000403L; + public static final long LOGICAL_CUT = 0x00100000404L; + public static final long LOGICAL_ERASE_EOF = 0x00100000405L; + public static final long LOGICAL_EX_SEL = 0x00100000406L; + public static final long LOGICAL_INSERT = 0x00100000407L; + public static final long LOGICAL_PASTE = 0x00100000408L; + public static final long LOGICAL_REDO = 0x00100000409L; + public static final long LOGICAL_UNDO = 0x0010000040aL; + public static final long LOGICAL_ACCEPT = 0x00100000501L; + public static final long LOGICAL_AGAIN = 0x00100000502L; + public static final long LOGICAL_ATTN = 0x00100000503L; + public static final long LOGICAL_CANCEL = 0x00100000504L; + public static final long LOGICAL_CONTEXT_MENU = 0x00100000505L; + public static final long LOGICAL_EXECUTE = 0x00100000506L; + public static final long LOGICAL_FIND = 0x00100000507L; + public static final long LOGICAL_HELP = 0x00100000508L; + public static final long LOGICAL_PAUSE = 0x00100000509L; + public static final long LOGICAL_PLAY = 0x0010000050aL; + public static final long LOGICAL_PROPS = 0x0010000050bL; + public static final long LOGICAL_SELECT = 0x0010000050cL; + public static final long LOGICAL_ZOOM_IN = 0x0010000050dL; + public static final long LOGICAL_ZOOM_OUT = 0x0010000050eL; + public static final long LOGICAL_BRIGHTNESS_DOWN = 0x00100000601L; + public static final long LOGICAL_BRIGHTNESS_UP = 0x00100000602L; + public static final long LOGICAL_CAMERA = 0x00100000603L; + public static final long LOGICAL_EJECT = 0x00100000604L; + public static final long LOGICAL_LOG_OFF = 0x00100000605L; + public static final long LOGICAL_POWER = 0x00100000606L; + public static final long LOGICAL_POWER_OFF = 0x00100000607L; + public static final long LOGICAL_PRINT_SCREEN = 0x00100000608L; + public static final long LOGICAL_HIBERNATE = 0x00100000609L; + public static final long LOGICAL_STANDBY = 0x0010000060aL; + public static final long LOGICAL_WAKE_UP = 0x0010000060bL; + public static final long LOGICAL_ALL_CANDIDATES = 0x00100000701L; + public static final long LOGICAL_ALPHANUMERIC = 0x00100000702L; + public static final long LOGICAL_CODE_INPUT = 0x00100000703L; + public static final long LOGICAL_COMPOSE = 0x00100000704L; + public static final long LOGICAL_CONVERT = 0x00100000705L; + public static final long LOGICAL_FINAL_MODE = 0x00100000706L; + public static final long LOGICAL_GROUP_FIRST = 0x00100000707L; + public static final long LOGICAL_GROUP_LAST = 0x00100000708L; + public static final long LOGICAL_GROUP_NEXT = 0x00100000709L; + public static final long LOGICAL_GROUP_PREVIOUS = 0x0010000070aL; + public static final long LOGICAL_MODE_CHANGE = 0x0010000070bL; + public static final long LOGICAL_NEXT_CANDIDATE = 0x0010000070cL; + public static final long LOGICAL_NON_CONVERT = 0x0010000070dL; + public static final long LOGICAL_PREVIOUS_CANDIDATE = 0x0010000070eL; + public static final long LOGICAL_PROCESS = 0x0010000070fL; + public static final long LOGICAL_SINGLE_CANDIDATE = 0x00100000710L; + public static final long LOGICAL_HANGUL_MODE = 0x00100000711L; + public static final long LOGICAL_HANJA_MODE = 0x00100000712L; + public static final long LOGICAL_JUNJA_MODE = 0x00100000713L; + public static final long LOGICAL_EISU = 0x00100000714L; + public static final long LOGICAL_HANKAKU = 0x00100000715L; + public static final long LOGICAL_HIRAGANA = 0x00100000716L; + public static final long LOGICAL_HIRAGANA_KATAKANA = 0x00100000717L; + public static final long LOGICAL_KANA_MODE = 0x00100000718L; + public static final long LOGICAL_KANJI_MODE = 0x00100000719L; + public static final long LOGICAL_KATAKANA = 0x0010000071aL; + public static final long LOGICAL_ROMAJI = 0x0010000071bL; + public static final long LOGICAL_ZENKAKU = 0x0010000071cL; + public static final long LOGICAL_ZENKAKU_HANKAKU = 0x0010000071dL; + public static final long LOGICAL_F1 = 0x00100000801L; + public static final long LOGICAL_F2 = 0x00100000802L; + public static final long LOGICAL_F3 = 0x00100000803L; + public static final long LOGICAL_F4 = 0x00100000804L; + public static final long LOGICAL_F5 = 0x00100000805L; + public static final long LOGICAL_F6 = 0x00100000806L; + public static final long LOGICAL_F7 = 0x00100000807L; + public static final long LOGICAL_F8 = 0x00100000808L; + public static final long LOGICAL_F9 = 0x00100000809L; + public static final long LOGICAL_F10 = 0x0010000080aL; + public static final long LOGICAL_F11 = 0x0010000080bL; + public static final long LOGICAL_F12 = 0x0010000080cL; + public static final long LOGICAL_F13 = 0x0010000080dL; + public static final long LOGICAL_F14 = 0x0010000080eL; + public static final long LOGICAL_F15 = 0x0010000080fL; + public static final long LOGICAL_F16 = 0x00100000810L; + public static final long LOGICAL_F17 = 0x00100000811L; + public static final long LOGICAL_F18 = 0x00100000812L; + public static final long LOGICAL_F19 = 0x00100000813L; + public static final long LOGICAL_F20 = 0x00100000814L; + public static final long LOGICAL_F21 = 0x00100000815L; + public static final long LOGICAL_F22 = 0x00100000816L; + public static final long LOGICAL_F23 = 0x00100000817L; + public static final long LOGICAL_F24 = 0x00100000818L; + public static final long LOGICAL_SOFT1 = 0x00100000901L; + public static final long LOGICAL_SOFT2 = 0x00100000902L; + public static final long LOGICAL_SOFT3 = 0x00100000903L; + public static final long LOGICAL_SOFT4 = 0x00100000904L; + public static final long LOGICAL_SOFT5 = 0x00100000905L; + public static final long LOGICAL_SOFT6 = 0x00100000906L; + public static final long LOGICAL_SOFT7 = 0x00100000907L; + public static final long LOGICAL_SOFT8 = 0x00100000908L; + public static final long LOGICAL_CLOSE = 0x00100000a01L; + public static final long LOGICAL_MAIL_FORWARD = 0x00100000a02L; + public static final long LOGICAL_MAIL_REPLY = 0x00100000a03L; + public static final long LOGICAL_MAIL_SEND = 0x00100000a04L; + public static final long LOGICAL_MEDIA_PLAY_PAUSE = 0x00100000a05L; + public static final long LOGICAL_MEDIA_STOP = 0x00100000a07L; + public static final long LOGICAL_MEDIA_TRACK_NEXT = 0x00100000a08L; + public static final long LOGICAL_MEDIA_TRACK_PREVIOUS = 0x00100000a09L; + public static final long LOGICAL_NEW_KEY = 0x00100000a0aL; + public static final long LOGICAL_OPEN = 0x00100000a0bL; + public static final long LOGICAL_PRINT = 0x00100000a0cL; + public static final long LOGICAL_SAVE = 0x00100000a0dL; + public static final long LOGICAL_SPELL_CHECK = 0x00100000a0eL; + public static final long LOGICAL_AUDIO_VOLUME_DOWN = 0x00100000a0fL; + public static final long LOGICAL_AUDIO_VOLUME_UP = 0x00100000a10L; + public static final long LOGICAL_AUDIO_VOLUME_MUTE = 0x00100000a11L; + public static final long LOGICAL_LAUNCH_APPLICATION2 = 0x00100000b01L; + public static final long LOGICAL_LAUNCH_CALENDAR = 0x00100000b02L; + public static final long LOGICAL_LAUNCH_MAIL = 0x00100000b03L; + public static final long LOGICAL_LAUNCH_MEDIA_PLAYER = 0x00100000b04L; + public static final long LOGICAL_LAUNCH_MUSIC_PLAYER = 0x00100000b05L; + public static final long LOGICAL_LAUNCH_APPLICATION1 = 0x00100000b06L; + public static final long LOGICAL_LAUNCH_SCREEN_SAVER = 0x00100000b07L; + public static final long LOGICAL_LAUNCH_SPREADSHEET = 0x00100000b08L; + public static final long LOGICAL_LAUNCH_WEB_BROWSER = 0x00100000b09L; + public static final long LOGICAL_LAUNCH_WEB_CAM = 0x00100000b0aL; + public static final long LOGICAL_LAUNCH_WORD_PROCESSOR = 0x00100000b0bL; + public static final long LOGICAL_LAUNCH_CONTACTS = 0x00100000b0cL; + public static final long LOGICAL_LAUNCH_PHONE = 0x00100000b0dL; + public static final long LOGICAL_LAUNCH_ASSISTANT = 0x00100000b0eL; + public static final long LOGICAL_LAUNCH_CONTROL_PANEL = 0x00100000b0fL; + public static final long LOGICAL_BROWSER_BACK = 0x00100000c01L; + public static final long LOGICAL_BROWSER_FAVORITES = 0x00100000c02L; + public static final long LOGICAL_BROWSER_FORWARD = 0x00100000c03L; + public static final long LOGICAL_BROWSER_HOME = 0x00100000c04L; + public static final long LOGICAL_BROWSER_REFRESH = 0x00100000c05L; + public static final long LOGICAL_BROWSER_SEARCH = 0x00100000c06L; + public static final long LOGICAL_BROWSER_STOP = 0x00100000c07L; + public static final long LOGICAL_AUDIO_BALANCE_LEFT = 0x00100000d01L; + public static final long LOGICAL_AUDIO_BALANCE_RIGHT = 0x00100000d02L; + public static final long LOGICAL_AUDIO_BASS_BOOST_DOWN = 0x00100000d03L; + public static final long LOGICAL_AUDIO_BASS_BOOST_UP = 0x00100000d04L; + public static final long LOGICAL_AUDIO_FADER_FRONT = 0x00100000d05L; + public static final long LOGICAL_AUDIO_FADER_REAR = 0x00100000d06L; + public static final long LOGICAL_AUDIO_SURROUND_MODE_NEXT = 0x00100000d07L; + public static final long LOGICAL_AVR_INPUT = 0x00100000d08L; + public static final long LOGICAL_AVR_POWER = 0x00100000d09L; + public static final long LOGICAL_CHANNEL_DOWN = 0x00100000d0aL; + public static final long LOGICAL_CHANNEL_UP = 0x00100000d0bL; + public static final long LOGICAL_COLOR_F0_RED = 0x00100000d0cL; + public static final long LOGICAL_COLOR_F1_GREEN = 0x00100000d0dL; + public static final long LOGICAL_COLOR_F2_YELLOW = 0x00100000d0eL; + public static final long LOGICAL_COLOR_F3_BLUE = 0x00100000d0fL; + public static final long LOGICAL_COLOR_F4_GREY = 0x00100000d10L; + public static final long LOGICAL_COLOR_F5_BROWN = 0x00100000d11L; + public static final long LOGICAL_CLOSED_CAPTION_TOGGLE = 0x00100000d12L; + public static final long LOGICAL_DIMMER = 0x00100000d13L; + public static final long LOGICAL_DISPLAY_SWAP = 0x00100000d14L; + public static final long LOGICAL_EXIT = 0x00100000d15L; + public static final long LOGICAL_FAVORITE_CLEAR0 = 0x00100000d16L; + public static final long LOGICAL_FAVORITE_CLEAR1 = 0x00100000d17L; + public static final long LOGICAL_FAVORITE_CLEAR2 = 0x00100000d18L; + public static final long LOGICAL_FAVORITE_CLEAR3 = 0x00100000d19L; + public static final long LOGICAL_FAVORITE_RECALL0 = 0x00100000d1aL; + public static final long LOGICAL_FAVORITE_RECALL1 = 0x00100000d1bL; + public static final long LOGICAL_FAVORITE_RECALL2 = 0x00100000d1cL; + public static final long LOGICAL_FAVORITE_RECALL3 = 0x00100000d1dL; + public static final long LOGICAL_FAVORITE_STORE0 = 0x00100000d1eL; + public static final long LOGICAL_FAVORITE_STORE1 = 0x00100000d1fL; + public static final long LOGICAL_FAVORITE_STORE2 = 0x00100000d20L; + public static final long LOGICAL_FAVORITE_STORE3 = 0x00100000d21L; + public static final long LOGICAL_GUIDE = 0x00100000d22L; + public static final long LOGICAL_GUIDE_NEXT_DAY = 0x00100000d23L; + public static final long LOGICAL_GUIDE_PREVIOUS_DAY = 0x00100000d24L; + public static final long LOGICAL_INFO = 0x00100000d25L; + public static final long LOGICAL_INSTANT_REPLAY = 0x00100000d26L; + public static final long LOGICAL_LINK = 0x00100000d27L; + public static final long LOGICAL_LIST_PROGRAM = 0x00100000d28L; + public static final long LOGICAL_LIVE_CONTENT = 0x00100000d29L; + public static final long LOGICAL_LOCK = 0x00100000d2aL; + public static final long LOGICAL_MEDIA_APPS = 0x00100000d2bL; + public static final long LOGICAL_MEDIA_FAST_FORWARD = 0x00100000d2cL; + public static final long LOGICAL_MEDIA_LAST = 0x00100000d2dL; + public static final long LOGICAL_MEDIA_PAUSE = 0x00100000d2eL; + public static final long LOGICAL_MEDIA_PLAY = 0x00100000d2fL; + public static final long LOGICAL_MEDIA_RECORD = 0x00100000d30L; + public static final long LOGICAL_MEDIA_REWIND = 0x00100000d31L; + public static final long LOGICAL_MEDIA_SKIP = 0x00100000d32L; + public static final long LOGICAL_NEXT_FAVORITE_CHANNEL = 0x00100000d33L; + public static final long LOGICAL_NEXT_USER_PROFILE = 0x00100000d34L; + public static final long LOGICAL_ON_DEMAND = 0x00100000d35L; + public static final long LOGICAL_P_IN_P_DOWN = 0x00100000d36L; + public static final long LOGICAL_P_IN_P_MOVE = 0x00100000d37L; + public static final long LOGICAL_P_IN_P_TOGGLE = 0x00100000d38L; + public static final long LOGICAL_P_IN_P_UP = 0x00100000d39L; + public static final long LOGICAL_PLAY_SPEED_DOWN = 0x00100000d3aL; + public static final long LOGICAL_PLAY_SPEED_RESET = 0x00100000d3bL; + public static final long LOGICAL_PLAY_SPEED_UP = 0x00100000d3cL; + public static final long LOGICAL_RANDOM_TOGGLE = 0x00100000d3dL; + public static final long LOGICAL_RC_LOW_BATTERY = 0x00100000d3eL; + public static final long LOGICAL_RECORD_SPEED_NEXT = 0x00100000d3fL; + public static final long LOGICAL_RF_BYPASS = 0x00100000d40L; + public static final long LOGICAL_SCAN_CHANNELS_TOGGLE = 0x00100000d41L; + public static final long LOGICAL_SCREEN_MODE_NEXT = 0x00100000d42L; + public static final long LOGICAL_SETTINGS = 0x00100000d43L; + public static final long LOGICAL_SPLIT_SCREEN_TOGGLE = 0x00100000d44L; + public static final long LOGICAL_STB_INPUT = 0x00100000d45L; + public static final long LOGICAL_STB_POWER = 0x00100000d46L; + public static final long LOGICAL_SUBTITLE = 0x00100000d47L; + public static final long LOGICAL_TELETEXT = 0x00100000d48L; + public static final long LOGICAL_TV = 0x00100000d49L; + public static final long LOGICAL_TV_INPUT = 0x00100000d4aL; + public static final long LOGICAL_TV_POWER = 0x00100000d4bL; + public static final long LOGICAL_VIDEO_MODE_NEXT = 0x00100000d4cL; + public static final long LOGICAL_WINK = 0x00100000d4dL; + public static final long LOGICAL_ZOOM_TOGGLE = 0x00100000d4eL; + public static final long LOGICAL_DVR = 0x00100000d4fL; + public static final long LOGICAL_MEDIA_AUDIO_TRACK = 0x00100000d50L; + public static final long LOGICAL_MEDIA_SKIP_BACKWARD = 0x00100000d51L; + public static final long LOGICAL_MEDIA_SKIP_FORWARD = 0x00100000d52L; + public static final long LOGICAL_MEDIA_STEP_BACKWARD = 0x00100000d53L; + public static final long LOGICAL_MEDIA_STEP_FORWARD = 0x00100000d54L; + public static final long LOGICAL_MEDIA_TOP_MENU = 0x00100000d55L; + public static final long LOGICAL_NAVIGATE_IN = 0x00100000d56L; + public static final long LOGICAL_NAVIGATE_NEXT = 0x00100000d57L; + public static final long LOGICAL_NAVIGATE_OUT = 0x00100000d58L; + public static final long LOGICAL_NAVIGATE_PREVIOUS = 0x00100000d59L; + public static final long LOGICAL_PAIRING = 0x00100000d5aL; + public static final long LOGICAL_MEDIA_CLOSE = 0x00100000d5bL; + public static final long LOGICAL_AUDIO_BASS_BOOST_TOGGLE = 0x00100000e02L; + public static final long LOGICAL_AUDIO_TREBLE_DOWN = 0x00100000e04L; + public static final long LOGICAL_AUDIO_TREBLE_UP = 0x00100000e05L; + public static final long LOGICAL_MICROPHONE_TOGGLE = 0x00100000e06L; + public static final long LOGICAL_MICROPHONE_VOLUME_DOWN = 0x00100000e07L; + public static final long LOGICAL_MICROPHONE_VOLUME_UP = 0x00100000e08L; + public static final long LOGICAL_MICROPHONE_VOLUME_MUTE = 0x00100000e09L; + public static final long LOGICAL_SPEECH_CORRECTION_LIST = 0x00100000f01L; + public static final long LOGICAL_SPEECH_INPUT_TOGGLE = 0x00100000f02L; + public static final long LOGICAL_APP_SWITCH = 0x00100001001L; + public static final long LOGICAL_CALL = 0x00100001002L; + public static final long LOGICAL_CAMERA_FOCUS = 0x00100001003L; + public static final long LOGICAL_END_CALL = 0x00100001004L; + public static final long LOGICAL_GO_BACK = 0x00100001005L; + public static final long LOGICAL_GO_HOME = 0x00100001006L; + public static final long LOGICAL_HEADSET_HOOK = 0x00100001007L; + public static final long LOGICAL_LAST_NUMBER_REDIAL = 0x00100001008L; + public static final long LOGICAL_NOTIFICATION = 0x00100001009L; + public static final long LOGICAL_MANNER_MODE = 0x0010000100aL; + public static final long LOGICAL_VOICE_DIAL = 0x0010000100bL; + public static final long LOGICAL_TV3_D_MODE = 0x00100001101L; + public static final long LOGICAL_TV_ANTENNA_CABLE = 0x00100001102L; + public static final long LOGICAL_TV_AUDIO_DESCRIPTION = 0x00100001103L; + public static final long LOGICAL_TV_AUDIO_DESCRIPTION_MIX_DOWN = 0x00100001104L; + public static final long LOGICAL_TV_AUDIO_DESCRIPTION_MIX_UP = 0x00100001105L; + public static final long LOGICAL_TV_CONTENTS_MENU = 0x00100001106L; + public static final long LOGICAL_TV_DATA_SERVICE = 0x00100001107L; + public static final long LOGICAL_TV_INPUT_COMPONENT1 = 0x00100001108L; + public static final long LOGICAL_TV_INPUT_COMPONENT2 = 0x00100001109L; + public static final long LOGICAL_TV_INPUT_COMPOSITE1 = 0x0010000110aL; + public static final long LOGICAL_TV_INPUT_COMPOSITE2 = 0x0010000110bL; + public static final long LOGICAL_TV_INPUT_HD_M1 = 0x0010000110cL; + public static final long LOGICAL_TV_INPUT_HD_M2 = 0x0010000110dL; + public static final long LOGICAL_TV_INPUT_HD_M3 = 0x0010000110eL; + public static final long LOGICAL_TV_INPUT_HD_M4 = 0x0010000110fL; + public static final long LOGICAL_TV_INPUT_V_G1 = 0x00100001110L; + public static final long LOGICAL_TV_MEDIA_CONTEXT = 0x00100001111L; + public static final long LOGICAL_TV_NETWORK = 0x00100001112L; + public static final long LOGICAL_TV_NUMBER_ENTRY = 0x00100001113L; + public static final long LOGICAL_TV_RADIO_SERVICE = 0x00100001114L; + public static final long LOGICAL_TV_SATELLITE = 0x00100001115L; + public static final long LOGICAL_TV_SATELLITE_B_S = 0x00100001116L; + public static final long LOGICAL_TV_SATELLITE_C_S = 0x00100001117L; + public static final long LOGICAL_TV_SATELLITE_TOGGLE = 0x00100001118L; + public static final long LOGICAL_TV_TERRESTRIAL_ANALOG = 0x00100001119L; + public static final long LOGICAL_TV_TERRESTRIAL_DIGITAL = 0x0010000111aL; + public static final long LOGICAL_TV_TIMER = 0x0010000111bL; + public static final long LOGICAL_KEY11 = 0x00100001201L; + public static final long LOGICAL_KEY12 = 0x00100001202L; + public static final long LOGICAL_SUSPEND = 0x00200000000L; + public static final long LOGICAL_RESUME = 0x00200000001L; + public static final long LOGICAL_SLEEP = 0x00200000002L; + public static final long LOGICAL_ABORT = 0x00200000003L; + public static final long LOGICAL_LANG1 = 0x00200000010L; + public static final long LOGICAL_LANG2 = 0x00200000011L; + public static final long LOGICAL_LANG3 = 0x00200000012L; + public static final long LOGICAL_LANG4 = 0x00200000013L; + public static final long LOGICAL_LANG5 = 0x00200000014L; + public static final long LOGICAL_INTL_BACKSLASH = 0x00200000020L; + public static final long LOGICAL_INTL_RO = 0x00200000021L; + public static final long LOGICAL_INTL_YEN = 0x00200000022L; + public static final long LOGICAL_CONTROL_LEFT = 0x00200000100L; + public static final long LOGICAL_CONTROL_RIGHT = 0x00200000101L; + public static final long LOGICAL_SHIFT_LEFT = 0x00200000102L; + public static final long LOGICAL_SHIFT_RIGHT = 0x00200000103L; + public static final long LOGICAL_ALT_LEFT = 0x00200000104L; + public static final long LOGICAL_ALT_RIGHT = 0x00200000105L; + public static final long LOGICAL_META_LEFT = 0x00200000106L; + public static final long LOGICAL_META_RIGHT = 0x00200000107L; + public static final long LOGICAL_CONTROL = 0x002000001f0L; + public static final long LOGICAL_SHIFT = 0x002000001f2L; + public static final long LOGICAL_ALT = 0x002000001f4L; + public static final long LOGICAL_META = 0x002000001f6L; + public static final long LOGICAL_NUMPAD_ENTER = 0x0020000020dL; + public static final long LOGICAL_NUMPAD_PAREN_LEFT = 0x00200000228L; + public static final long LOGICAL_NUMPAD_PAREN_RIGHT = 0x00200000229L; + public static final long LOGICAL_NUMPAD_MULTIPLY = 0x0020000022aL; + public static final long LOGICAL_NUMPAD_ADD = 0x0020000022bL; + public static final long LOGICAL_NUMPAD_COMMA = 0x0020000022cL; + public static final long LOGICAL_NUMPAD_SUBTRACT = 0x0020000022dL; + public static final long LOGICAL_NUMPAD_DECIMAL = 0x0020000022eL; + public static final long LOGICAL_NUMPAD_DIVIDE = 0x0020000022fL; + public static final long LOGICAL_NUMPAD0 = 0x00200000230L; + public static final long LOGICAL_NUMPAD1 = 0x00200000231L; + public static final long LOGICAL_NUMPAD2 = 0x00200000232L; + public static final long LOGICAL_NUMPAD3 = 0x00200000233L; + public static final long LOGICAL_NUMPAD4 = 0x00200000234L; + public static final long LOGICAL_NUMPAD5 = 0x00200000235L; + public static final long LOGICAL_NUMPAD6 = 0x00200000236L; + public static final long LOGICAL_NUMPAD7 = 0x00200000237L; + public static final long LOGICAL_NUMPAD8 = 0x00200000238L; + public static final long LOGICAL_NUMPAD9 = 0x00200000239L; + public static final long LOGICAL_NUMPAD_EQUAL = 0x0020000023dL; + public static final long LOGICAL_GAME_BUTTON1 = 0x00200000301L; + public static final long LOGICAL_GAME_BUTTON2 = 0x00200000302L; + public static final long LOGICAL_GAME_BUTTON3 = 0x00200000303L; + public static final long LOGICAL_GAME_BUTTON4 = 0x00200000304L; + public static final long LOGICAL_GAME_BUTTON5 = 0x00200000305L; + public static final long LOGICAL_GAME_BUTTON6 = 0x00200000306L; + public static final long LOGICAL_GAME_BUTTON7 = 0x00200000307L; + public static final long LOGICAL_GAME_BUTTON8 = 0x00200000308L; + public static final long LOGICAL_GAME_BUTTON9 = 0x00200000309L; + public static final long LOGICAL_GAME_BUTTON10 = 0x0020000030aL; + public static final long LOGICAL_GAME_BUTTON11 = 0x0020000030bL; + public static final long LOGICAL_GAME_BUTTON12 = 0x0020000030cL; + public static final long LOGICAL_GAME_BUTTON13 = 0x0020000030dL; + public static final long LOGICAL_GAME_BUTTON14 = 0x0020000030eL; + public static final long LOGICAL_GAME_BUTTON15 = 0x0020000030fL; + public static final long LOGICAL_GAME_BUTTON16 = 0x00200000310L; + public static final long LOGICAL_GAME_BUTTON_A = 0x00200000311L; + public static final long LOGICAL_GAME_BUTTON_B = 0x00200000312L; + public static final long LOGICAL_GAME_BUTTON_C = 0x00200000313L; + public static final long LOGICAL_GAME_BUTTON_LEFT1 = 0x00200000314L; + public static final long LOGICAL_GAME_BUTTON_LEFT2 = 0x00200000315L; + public static final long LOGICAL_GAME_BUTTON_MODE = 0x00200000316L; + public static final long LOGICAL_GAME_BUTTON_RIGHT1 = 0x00200000317L; + public static final long LOGICAL_GAME_BUTTON_RIGHT2 = 0x00200000318L; + public static final long LOGICAL_GAME_BUTTON_SELECT = 0x00200000319L; + public static final long LOGICAL_GAME_BUTTON_START = 0x0020000031aL; + public static final long LOGICAL_GAME_BUTTON_THUMB_LEFT = 0x0020000031bL; + public static final long LOGICAL_GAME_BUTTON_THUMB_RIGHT = 0x0020000031cL; + public static final long LOGICAL_GAME_BUTTON_X = 0x0020000031dL; + public static final long LOGICAL_GAME_BUTTON_Y = 0x0020000031eL; + public static final long LOGICAL_GAME_BUTTON_Z = 0x0020000031fL; +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/util/PathUtilsTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/util/PathUtilsTest.java new file mode 100644 index 0000000000000000000000000000000000000000..08e5a1aaac990f06b62954c1327ce05d1acdc8cb --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/util/PathUtilsTest.java @@ -0,0 +1,90 @@ +// 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. + +package io.flutter.util; + +import static io.flutter.Build.API_LEVELS; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import android.content.Context; +import android.os.Build; +import java.io.File; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(RobolectricTestRunner.class) +public class PathUtilsTest { + + private static final String APP_DATA_PATH = "/data/data/package_name"; + + @Test + public void canGetFilesDir() { + Context context = mock(Context.class); + when(context.getFilesDir()).thenReturn(new File(APP_DATA_PATH + "/files")); + assertEquals(PathUtils.getFilesDir(context), APP_DATA_PATH + "/files"); + } + + @Test + public void canOnlyGetFilesPathWhenDiskFullAndFilesDirNotCreated() { + Context context = mock(Context.class); + when(context.getFilesDir()).thenReturn(null); + if (Build.VERSION.SDK_INT >= API_LEVELS.API_24) { + when(context.getDataDir()).thenReturn(new File(APP_DATA_PATH)); + } else { + when(context.getApplicationInfo().dataDir).thenReturn(APP_DATA_PATH); + } + assertEquals(PathUtils.getFilesDir(context), APP_DATA_PATH + "/files"); + } + + @Test + public void canGetFlutterDataDir() { + Context context = mock(Context.class); + when(context.getDir("flutter", Context.MODE_PRIVATE)) + .thenReturn(new File(APP_DATA_PATH + "/app_flutter")); + assertEquals(PathUtils.getDataDirectory(context), APP_DATA_PATH + "/app_flutter"); + } + + @Test + public void canOnlyGetFlutterDataPathWhenDiskFullAndFlutterDataDirNotCreated() { + Context context = mock(Context.class); + when(context.getDir("flutter", Context.MODE_PRIVATE)).thenReturn(null); + if (Build.VERSION.SDK_INT >= API_LEVELS.API_24) { + when(context.getDataDir()).thenReturn(new File(APP_DATA_PATH)); + } else { + when(context.getApplicationInfo().dataDir).thenReturn(APP_DATA_PATH); + } + assertEquals(PathUtils.getDataDirectory(context), APP_DATA_PATH + "/app_flutter"); + } + + @Test + public void canGetCacheDir() { + Context context = mock(Context.class); + when(context.getCacheDir()).thenReturn(new File(APP_DATA_PATH + "/cache")); + if (Build.VERSION.SDK_INT >= API_LEVELS.API_21) { + when(context.getCodeCacheDir()).thenReturn(new File(APP_DATA_PATH + "/code_cache")); + } + assertTrue(PathUtils.getCacheDirectory(context).startsWith(APP_DATA_PATH)); + } + + @Test + public void canOnlyGetCachePathWhenDiskFullAndCacheDirNotCreated() { + Context context = mock(Context.class); + when(context.getCacheDir()).thenReturn(null); + if (Build.VERSION.SDK_INT >= API_LEVELS.API_21) { + when(context.getCodeCacheDir()).thenReturn(null); + } + if (Build.VERSION.SDK_INT >= API_LEVELS.API_24) { + when(context.getDataDir()).thenReturn(new File(APP_DATA_PATH)); + } else { + when(context.getApplicationInfo().dataDir).thenReturn(APP_DATA_PATH); + } + assertEquals(PathUtils.getCacheDirectory(context), APP_DATA_PATH + "/cache"); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/util/PreconditionsTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/util/PreconditionsTest.java new file mode 100644 index 0000000000000000000000000000000000000000..64bb548e2f91b72f3bd2d2ca9357eb8ff66a13aa --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/util/PreconditionsTest.java @@ -0,0 +1,35 @@ +// 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. + +package io.flutter.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; + +import androidx.test.ext.junit.runners.AndroidJUnit4; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class PreconditionsTest { + @Test + public void checkNotNull_notNull() { + // Should always return its input. + assertEquals("non-null", Preconditions.checkNotNull("non-null")); + assertEquals(42, (int) Preconditions.checkNotNull(42)); + Object classParam = new Object(); + assertEquals(classParam, Preconditions.checkNotNull(classParam)); + } + + @Test + public void checkNotNull_Null() { + assertThrows( + NullPointerException.class, + () -> { + Preconditions.checkNotNull(null); + }); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/util/ViewUtilsTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/util/ViewUtilsTest.java new file mode 100644 index 0000000000000000000000000000000000000000..2adbc6c2afaba94e6b2d0634808b48deb1704c29 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/util/ViewUtilsTest.java @@ -0,0 +1,81 @@ +// 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. + +package io.flutter.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import android.app.Activity; +import android.content.Context; +import android.content.ContextWrapper; +import android.view.View; +import android.view.ViewGroup; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class ViewUtilsTest { + @Test + public void canGetActivity() { + // Non activity context returns null + Context nonActivityContext = mock(Context.class); + assertEquals(null, ViewUtils.getActivity(nonActivityContext)); + + Activity activity = mock(Activity.class); + assertEquals(activity, ViewUtils.getActivity(activity)); + + ContextWrapper wrapper = new ContextWrapper(new ContextWrapper(activity)); + assertEquals(activity, ViewUtils.getActivity(wrapper)); + } + + @Test + public void childHasFocus_rootHasFocus() { + final View rootView = mock(View.class); + when(rootView.hasFocus()).thenReturn(true); + assertTrue(ViewUtils.childHasFocus(rootView)); + } + + @Test + public void childHasFocus_rootDoesNotHaveFocus() { + final View rootView = mock(View.class); + when(rootView.hasFocus()).thenReturn(false); + assertFalse(ViewUtils.childHasFocus(rootView)); + } + + @Test + public void childHasFocus_rootIsNull() { + assertFalse(ViewUtils.childHasFocus(null)); + } + + @Test + public void childHasFocus_childHasFocus() { + final View childView = mock(View.class); + when(childView.hasFocus()).thenReturn(true); + + final ViewGroup rootView = mock(ViewGroup.class); + when(rootView.getChildCount()).thenReturn(1); + when(rootView.getChildAt(0)).thenReturn(childView); + + assertTrue(ViewUtils.childHasFocus(rootView)); + } + + @Test + public void childHasFocus_childDoesNotHaveFocus() { + final View childView = mock(View.class); + when(childView.hasFocus()).thenReturn(false); + + final ViewGroup rootView = mock(ViewGroup.class); + when(rootView.getChildCount()).thenReturn(1); + when(rootView.getChildAt(0)).thenReturn(childView); + + assertFalse(ViewUtils.childHasFocus(rootView)); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/view/AccessibilityBridgeTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/view/AccessibilityBridgeTest.java new file mode 100644 index 0000000000000000000000000000000000000000..d6674161c0e6b2cca96a7cb55a1f82f5259bb113 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/view/AccessibilityBridgeTest.java @@ -0,0 +1,2466 @@ +// 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. + +package io.flutter.view; + +import static io.flutter.Build.API_LEVELS; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyInt; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.annotation.TargetApi; +import android.app.Activity; +import android.content.ContentResolver; +import android.content.Context; +import android.content.res.Configuration; +import android.content.res.Resources; +import android.database.ContentObserver; +import android.graphics.Rect; +import android.os.Bundle; +import android.provider.Settings; +import android.text.SpannableString; +import android.text.SpannedString; +import android.text.style.LocaleSpan; +import android.text.style.TtsSpan; +import android.text.style.URLSpan; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewParent; +import android.view.Window; +import android.view.WindowInsets; +import android.view.WindowManager; +import android.view.accessibility.AccessibilityEvent; +import android.view.accessibility.AccessibilityManager; +import android.view.accessibility.AccessibilityNodeInfo; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.FlutterJNI; +import io.flutter.embedding.engine.dart.DartExecutor; +import io.flutter.embedding.engine.systemchannels.AccessibilityChannel; +import io.flutter.plugin.common.BasicMessageChannel; +import io.flutter.plugin.platform.PlatformViewsAccessibilityDelegate; +import io.flutter.view.AccessibilityBridge.Action; +import io.flutter.view.AccessibilityBridge.Flag; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.invocation.InvocationOnMock; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class AccessibilityBridgeTest { + + @Test + public void itDescribesNonTextFieldsWithAContentDescription() { + AccessibilityBridge accessibilityBridge = setUpBridge(); + + TestSemanticsNode testSemanticsNode = new TestSemanticsNode(); + testSemanticsNode.label = "Hello, World"; + TestSemanticsUpdate testSemanticsUpdate = testSemanticsNode.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(0); + + assertEquals(nodeInfo.getContentDescription().toString(), "Hello, World"); + assertEquals(nodeInfo.getText(), null); + } + + @Config(sdk = API_LEVELS.API_28) + @TargetApi(API_LEVELS.API_28) + @Test + public void itDescribesTextFieldsWithTextAndHint() { + AccessibilityBridge accessibilityBridge = setUpBridge(); + + TestSemanticsNode testSemanticsNode = new TestSemanticsNode(); + testSemanticsNode.value = "Hello, World"; + testSemanticsNode.label = "some label"; + testSemanticsNode.hint = "some hint"; + testSemanticsNode.addFlag(AccessibilityBridge.Flag.IS_TEXT_FIELD); + TestSemanticsUpdate testSemanticsUpdate = testSemanticsNode.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(0); + + assertEquals(nodeInfo.getContentDescription(), null); + assertEquals(nodeInfo.getText().toString(), "Hello, World"); + assertEquals(nodeInfo.getHintText().toString(), "some label, some hint"); + } + + @Test + public void itTakesGlobalCoordinatesOfFlutterViewIntoAccount() { + 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); + final int position = 88; + // The getBoundsInScreen() in createAccessibilityNodeInfo() needs View.getLocationOnScreen() + doAnswer( + invocation -> { + int[] outLocation = (int[]) invocation.getArguments()[0]; + outLocation[0] = position; + outLocation[1] = position; + return null; + }) + .when(mockRootView) + .getLocationOnScreen(any(int[].class)); + + when(context.getPackageName()).thenReturn("test"); + AccessibilityBridge accessibilityBridge = + setUpBridge(mockRootView, mockManager, mockViewEmbedder); + + TestSemanticsNode testSemanticsNode = new TestSemanticsNode(); + TestSemanticsUpdate testSemanticsUpdate = testSemanticsNode.toUpdate(); + + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(0); + + Rect outBoundsInScreen = new Rect(); + nodeInfo.getBoundsInScreen(outBoundsInScreen); + assertEquals(position, outBoundsInScreen.left); + assertEquals(position, outBoundsInScreen.top); + } + + @Test + public void itSetsAccessibleNavigation() { + 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"); + when(mockManager.isTouchExplorationEnabled()).thenReturn(false); + AccessibilityBridge accessibilityBridge = + setUpBridge( + /*rootAccessibilityView=*/ mockRootView, + /*accessibilityChannel=*/ mockChannel, + /*accessibilityManager=*/ mockManager, + /*contentResolver=*/ null, + /*accessibilityViewEmbedder=*/ mockViewEmbedder, + /*platformViewsAccessibilityDelegate=*/ null); + ArgumentCaptor listenerCaptor = + ArgumentCaptor.forClass(AccessibilityManager.TouchExplorationStateChangeListener.class); + verify(mockManager).addTouchExplorationStateChangeListener(listenerCaptor.capture()); + + assertEquals(accessibilityBridge.getAccessibleNavigation(), false); + verify(mockChannel).setAccessibilityFeatures(0); + reset(mockChannel); + + // Simulate assistive technology accessing accessibility tree. + accessibilityBridge.createAccessibilityNodeInfo(0); + verify(mockChannel).setAccessibilityFeatures(1); + assertEquals(accessibilityBridge.getAccessibleNavigation(), true); + + // Simulate turning off TalkBack. + reset(mockChannel); + listenerCaptor.getValue().onTouchExplorationStateChanged(false); + verify(mockChannel).setAccessibilityFeatures(0); + assertEquals(accessibilityBridge.getAccessibleNavigation(), false); + } + + @Test + public void itDoesNotContainADescriptionIfScopesRoute() { + AccessibilityBridge accessibilityBridge = setUpBridge(); + + TestSemanticsNode testSemanticsNode = new TestSemanticsNode(); + testSemanticsNode.label = "Hello, World"; + testSemanticsNode.addFlag(AccessibilityBridge.Flag.SCOPES_ROUTE); + TestSemanticsUpdate testSemanticsUpdate = testSemanticsNode.toUpdate(); + + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(0); + + assertEquals(nodeInfo.getContentDescription(), null); + assertEquals(nodeInfo.getText(), null); + } + + @Test + public void itCreatesURLSpanForlinkURL() { + AccessibilityBridge accessibilityBridge = setUpBridge(); + + TestSemanticsNode testSemanticsNode = new TestSemanticsNode(); + testSemanticsNode.label = "Hello"; + testSemanticsNode.linkUrl = "https://flutter.dev"; + testSemanticsNode.addFlag(AccessibilityBridge.Flag.IS_LINK); + TestSemanticsUpdate testSemanticsUpdate = testSemanticsNode.toUpdate(); + + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(0); + SpannableString actual = (SpannableString) nodeInfo.getContentDescription(); + assertEquals(actual.toString(), "Hello"); + Object[] objectSpans = actual.getSpans(0, actual.length(), Object.class); + assertEquals(objectSpans.length, 1); + URLSpan span = (URLSpan) objectSpans[0]; + assertEquals(span.getURL(), "https://flutter.dev"); + } + + @Test + public void itUnfocusesPlatformViewWhenPlatformViewGoesAway() { + 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(mockRootView, mockManager, mockViewEmbedder); + + // Sent a11y tree with platform view. + TestSemanticsNode root = new TestSemanticsNode(); + root.id = 0; + TestSemanticsNode platformView = new TestSemanticsNode(); + platformView.id = 1; + platformView.platformViewId = 42; + root.children.add(platformView); + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + + // Set a11y focus to platform view. + View mockView = mock(View.class); + AccessibilityEvent focusEvent = mock(AccessibilityEvent.class); + when(mockViewEmbedder.requestSendAccessibilityEvent(mockView, mockView, focusEvent)) + .thenReturn(true); + when(mockViewEmbedder.getRecordFlutterId(mockView, focusEvent)).thenReturn(42); + when(focusEvent.getEventType()).thenReturn(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); + accessibilityBridge.externalViewRequestSendAccessibilityEvent(mockView, mockView, focusEvent); + + // Replace the platform view. + TestSemanticsNode node = new TestSemanticsNode(); + node.id = 2; + root.children.clear(); + root.children.add(node); + testSemanticsUpdate = root.toUpdate(); + when(mockManager.isEnabled()).thenReturn(true); + ViewParent mockParent = mock(ViewParent.class); + when(mockRootView.getParent()).thenReturn(mockParent); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + + // Check that unfocus event was sent. + ArgumentCaptor eventCaptor = + ArgumentCaptor.forClass(AccessibilityEvent.class); + verify(mockParent, times(2)) + .requestSendAccessibilityEvent(eq(mockRootView), eventCaptor.capture()); + AccessibilityEvent event = eventCaptor.getAllValues().get(0); + assertEquals(event.getEventType(), AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); + } + + @Test + public void itAnnouncesRouteNameWhenAddingNewRoute() { + 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(mockRootView, mockManager, mockViewEmbedder); + ViewParent mockParent = mock(ViewParent.class); + when(mockRootView.getParent()).thenReturn(mockParent); + when(mockManager.isEnabled()).thenReturn(true); + + TestSemanticsNode root = new TestSemanticsNode(); + root.id = 0; + TestSemanticsNode node1 = new TestSemanticsNode(); + node1.id = 1; + node1.addFlag(AccessibilityBridge.Flag.SCOPES_ROUTE); + node1.addFlag(AccessibilityBridge.Flag.NAMES_ROUTE); + node1.label = "node1"; + root.children.add(node1); + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + + verify(mockRootView, times(1)).setAccessibilityPaneTitle(eq("node1")); + + TestSemanticsNode new_root = new TestSemanticsNode(); + new_root.id = 0; + TestSemanticsNode new_node1 = new TestSemanticsNode(); + new_node1.id = 1; + new_node1.addFlag(AccessibilityBridge.Flag.SCOPES_ROUTE); + new_node1.addFlag(AccessibilityBridge.Flag.NAMES_ROUTE); + new_node1.label = "new_node1"; + new_root.children.add(new_node1); + TestSemanticsNode new_node2 = new TestSemanticsNode(); + new_node2.id = 2; + new_node2.addFlag(AccessibilityBridge.Flag.SCOPES_ROUTE); + new_node2.addFlag(AccessibilityBridge.Flag.NAMES_ROUTE); + new_node2.label = "new_node2"; + new_node1.children.add(new_node2); + testSemanticsUpdate = new_root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + + verify(mockRootView, times(1)).setAccessibilityPaneTitle(eq("new_node2")); + } + + @Test + public void itSetsTraversalAfter() { + 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(mockRootView, mockManager, mockViewEmbedder); + ViewParent mockParent = mock(ViewParent.class); + when(mockRootView.getParent()).thenReturn(mockParent); + when(mockManager.isEnabled()).thenReturn(true); + + TestSemanticsNode root = new TestSemanticsNode(); + root.id = 0; + TestSemanticsNode node1 = new TestSemanticsNode(); + node1.id = 1; + node1.label = "node1"; + root.children.add(node1); + TestSemanticsNode node2 = new TestSemanticsNode(); + node2.id = 2; + node2.label = "node2"; + root.children.add(node2); + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + + AccessibilityBridge spyAccessibilityBridge = spy(accessibilityBridge); + AccessibilityNodeInfo mockNodeInfo2 = mock(AccessibilityNodeInfo.class); + + when(spyAccessibilityBridge.obtainAccessibilityNodeInfo(mockRootView, 2)) + .thenReturn(mockNodeInfo2); + spyAccessibilityBridge.createAccessibilityNodeInfo(2); + verify(mockNodeInfo2, times(1)).setTraversalAfter(eq(mockRootView), eq(1)); + } + + @Config(sdk = API_LEVELS.API_24) + @TargetApi(API_LEVELS.API_24) + @Test + public void itSetsRootViewNotImportantForAccessibility() { + 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(mockRootView, mockManager, mockViewEmbedder); + ViewParent mockParent = mock(ViewParent.class); + when(mockRootView.getParent()).thenReturn(mockParent); + when(mockManager.isEnabled()).thenReturn(true); + + TestSemanticsNode root = new TestSemanticsNode(); + root.id = 0; + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + + AccessibilityBridge spyAccessibilityBridge = spy(accessibilityBridge); + AccessibilityNodeInfo mockNodeInfo = mock(AccessibilityNodeInfo.class); + + when(spyAccessibilityBridge.obtainAccessibilityNodeInfo(mockRootView)).thenReturn(mockNodeInfo); + spyAccessibilityBridge.createAccessibilityNodeInfo(View.NO_ID); + verify(mockNodeInfo, times(1)).setImportantForAccessibility(eq(false)); + } + + @Config(sdk = API_LEVELS.API_24) + @TargetApi(API_LEVELS.API_24) + @Test + public void itSetsNodeImportantForAccessibilityIfItHasContent() { + 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(mockRootView, mockManager, mockViewEmbedder); + ViewParent mockParent = mock(ViewParent.class); + when(mockRootView.getParent()).thenReturn(mockParent); + when(mockManager.isEnabled()).thenReturn(true); + + TestSemanticsNode root = new TestSemanticsNode(); + root.id = 0; + root.label = "some label"; + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + + AccessibilityBridge spyAccessibilityBridge = spy(accessibilityBridge); + AccessibilityNodeInfo mockNodeInfo = mock(AccessibilityNodeInfo.class); + + when(spyAccessibilityBridge.obtainAccessibilityNodeInfo(mockRootView, 0)) + .thenReturn(mockNodeInfo); + spyAccessibilityBridge.createAccessibilityNodeInfo(0); + verify(mockNodeInfo, times(1)).setImportantForAccessibility(eq(true)); + } + + @Config(sdk = API_LEVELS.API_24) + @TargetApi(API_LEVELS.API_24) + @Test + public void itSetsNodeImportantForAccessibilityIfItHasActions() { + 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(mockRootView, mockManager, mockViewEmbedder); + ViewParent mockParent = mock(ViewParent.class); + when(mockRootView.getParent()).thenReturn(mockParent); + when(mockManager.isEnabled()).thenReturn(true); + + TestSemanticsNode root = new TestSemanticsNode(); + root.id = 0; + root.addAction(Action.TAP); + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + + AccessibilityBridge spyAccessibilityBridge = spy(accessibilityBridge); + AccessibilityNodeInfo mockNodeInfo = mock(AccessibilityNodeInfo.class); + + when(spyAccessibilityBridge.obtainAccessibilityNodeInfo(mockRootView, 0)) + .thenReturn(mockNodeInfo); + spyAccessibilityBridge.createAccessibilityNodeInfo(0); + verify(mockNodeInfo, times(1)).setImportantForAccessibility(eq(true)); + } + + @Config(sdk = API_LEVELS.API_24) + @TargetApi(API_LEVELS.API_24) + @Test + public void itSetsNodeUnImportantForAccessibilityIfItIsEmpty() { + 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(mockRootView, mockManager, mockViewEmbedder); + ViewParent mockParent = mock(ViewParent.class); + when(mockRootView.getParent()).thenReturn(mockParent); + when(mockManager.isEnabled()).thenReturn(true); + + TestSemanticsNode root = new TestSemanticsNode(); + root.id = 0; + TestSemanticsNode node = new TestSemanticsNode(); + node.id = 1; + root.children.add(node); + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + + AccessibilityBridge spyAccessibilityBridge = spy(accessibilityBridge); + AccessibilityNodeInfo mockNodeInfo = mock(AccessibilityNodeInfo.class); + + when(spyAccessibilityBridge.obtainAccessibilityNodeInfo(mockRootView, 0)) + .thenReturn(mockNodeInfo); + spyAccessibilityBridge.createAccessibilityNodeInfo(0); + verify(mockNodeInfo, times(1)).setImportantForAccessibility(eq(false)); + + AccessibilityNodeInfo mockNodeInfo1 = mock(AccessibilityNodeInfo.class); + + when(spyAccessibilityBridge.obtainAccessibilityNodeInfo(mockRootView, 1)) + .thenReturn(mockNodeInfo1); + spyAccessibilityBridge.createAccessibilityNodeInfo(1); + verify(mockNodeInfo1, times(1)).setImportantForAccessibility(eq(false)); + } + + @SuppressWarnings("deprecation") + // getSystemWindowInset* methods deprecated. + @Config(sdk = API_LEVELS.API_28) + @TargetApi(API_LEVELS.API_28) + @Test + public void itSetCutoutInsetBasedonLayoutModeNever() { + int expectedInsetLeft = 5; + int top = 0; + int left = 0; + int right = 100; + int bottom = 200; + AccessibilityViewEmbedder mockViewEmbedder = mock(AccessibilityViewEmbedder.class); + AccessibilityManager mockManager = mock(AccessibilityManager.class); + View mockRootView = mock(View.class); + Activity context = mock(Activity.class); + Window window = mock(Window.class); + WindowInsets insets = mock(WindowInsets.class); + WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(); + layoutParams.layoutInDisplayCutoutMode = + WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER; + when(mockRootView.getContext()).thenReturn(context); + when(context.getWindow()).thenReturn(window); + when(window.getAttributes()).thenReturn(layoutParams); + when(mockRootView.getRootWindowInsets()).thenReturn(insets); + when(insets.getSystemWindowInsetLeft()).thenReturn(expectedInsetLeft); + when(context.getPackageName()).thenReturn("test"); + AccessibilityBridge accessibilityBridge = + setUpBridge(mockRootView, mockManager, mockViewEmbedder); + ViewParent mockParent = mock(ViewParent.class); + when(mockRootView.getParent()).thenReturn(mockParent); + when(mockManager.isEnabled()).thenReturn(true); + + TestSemanticsNode root = new TestSemanticsNode(); + root.id = 0; + root.left = left; + root.top = top; + root.right = right; + root.bottom = bottom; + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + + AccessibilityBridge spyAccessibilityBridge = spy(accessibilityBridge); + AccessibilityNodeInfo mockNodeInfo = mock(AccessibilityNodeInfo.class); + + when(spyAccessibilityBridge.obtainAccessibilityNodeInfo(mockRootView, 0)) + .thenReturn(mockNodeInfo); + spyAccessibilityBridge.createAccessibilityNodeInfo(0); + verify(mockNodeInfo, times(1)) + .setBoundsInScreen( + new Rect(left + expectedInsetLeft, top, right + expectedInsetLeft, bottom)); + } + + @SuppressWarnings("deprecation") + // getSystemWindowInset* methods deprecated. + @Config(sdk = API_LEVELS.API_28) + @TargetApi(API_LEVELS.API_28) + @Test + public void itSetCutoutInsetBasedonLayoutModeDefault() { + int expectedInsetLeft = 5; + int top = 0; + int left = 0; + int right = 100; + int bottom = 200; + AccessibilityViewEmbedder mockViewEmbedder = mock(AccessibilityViewEmbedder.class); + AccessibilityManager mockManager = mock(AccessibilityManager.class); + View mockRootView = mock(View.class); + Activity context = mock(Activity.class); + Window window = mock(Window.class); + WindowInsets insets = mock(WindowInsets.class); + WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(); + layoutParams.layoutInDisplayCutoutMode = + WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT; + when(mockRootView.getContext()).thenReturn(context); + when(context.getWindow()).thenReturn(window); + when(window.getAttributes()).thenReturn(layoutParams); + when(mockRootView.getRootWindowInsets()).thenReturn(insets); + when(insets.getSystemWindowInsetLeft()).thenReturn(expectedInsetLeft); + when(context.getPackageName()).thenReturn("test"); + AccessibilityBridge accessibilityBridge = + setUpBridge(mockRootView, mockManager, mockViewEmbedder); + ViewParent mockParent = mock(ViewParent.class); + when(mockRootView.getParent()).thenReturn(mockParent); + when(mockManager.isEnabled()).thenReturn(true); + + TestSemanticsNode root = new TestSemanticsNode(); + root.id = 0; + root.left = left; + root.top = top; + root.right = right; + root.bottom = bottom; + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + + AccessibilityBridge spyAccessibilityBridge = spy(accessibilityBridge); + AccessibilityNodeInfo mockNodeInfo = mock(AccessibilityNodeInfo.class); + + when(spyAccessibilityBridge.obtainAccessibilityNodeInfo(mockRootView, 0)) + .thenReturn(mockNodeInfo); + spyAccessibilityBridge.createAccessibilityNodeInfo(0); + verify(mockNodeInfo, times(1)) + .setBoundsInScreen( + new Rect(left + expectedInsetLeft, top, right + expectedInsetLeft, bottom)); + } + + @SuppressWarnings("deprecation") + // getSystemWindowInset* methods deprecated. + @Config(sdk = API_LEVELS.API_28) + @TargetApi(API_LEVELS.API_28) + @Test + public void itSetCutoutInsetBasedonLayoutModeShortEdges() { + int expectedInsetLeft = 5; + int top = 0; + int left = 0; + int right = 100; + int bottom = 200; + AccessibilityViewEmbedder mockViewEmbedder = mock(AccessibilityViewEmbedder.class); + AccessibilityManager mockManager = mock(AccessibilityManager.class); + View mockRootView = mock(View.class); + Activity context = mock(Activity.class); + Window window = mock(Window.class); + WindowInsets insets = mock(WindowInsets.class); + WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(); + layoutParams.layoutInDisplayCutoutMode = + WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES; + when(mockRootView.getContext()).thenReturn(context); + when(context.getWindow()).thenReturn(window); + when(window.getAttributes()).thenReturn(layoutParams); + when(mockRootView.getRootWindowInsets()).thenReturn(insets); + when(insets.getSystemWindowInsetLeft()).thenReturn(expectedInsetLeft); + when(context.getPackageName()).thenReturn("test"); + AccessibilityBridge accessibilityBridge = + setUpBridge(mockRootView, mockManager, mockViewEmbedder); + ViewParent mockParent = mock(ViewParent.class); + when(mockRootView.getParent()).thenReturn(mockParent); + when(mockManager.isEnabled()).thenReturn(true); + + TestSemanticsNode root = new TestSemanticsNode(); + root.id = 0; + root.left = left; + root.top = top; + root.right = right; + root.bottom = bottom; + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + + AccessibilityBridge spyAccessibilityBridge = spy(accessibilityBridge); + AccessibilityNodeInfo mockNodeInfo = mock(AccessibilityNodeInfo.class); + + when(spyAccessibilityBridge.obtainAccessibilityNodeInfo(mockRootView, 0)) + .thenReturn(mockNodeInfo); + spyAccessibilityBridge.createAccessibilityNodeInfo(0); + // Does not apply left inset if the layout mode is `short edges`. + verify(mockNodeInfo, times(1)).setBoundsInScreen(new Rect(left, top, right, bottom)); + } + + @SuppressWarnings("deprecation") + // getSystemWindowInset* methods deprecated. + // fluter#133074 tracks post deprecation work. + @Config(sdk = API_LEVELS.API_30) + @TargetApi(API_LEVELS.API_30) + @Test + public void itSetCutoutInsetBasedonLayoutModeAlways() { + int expectedInsetLeft = 5; + int top = 0; + int left = 0; + int right = 100; + int bottom = 200; + AccessibilityViewEmbedder mockViewEmbedder = mock(AccessibilityViewEmbedder.class); + AccessibilityManager mockManager = mock(AccessibilityManager.class); + View mockRootView = mock(View.class); + Activity context = mock(Activity.class); + Window window = mock(Window.class); + WindowInsets insets = mock(WindowInsets.class); + WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(); + layoutParams.layoutInDisplayCutoutMode = + WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS; + when(mockRootView.getContext()).thenReturn(context); + when(context.getWindow()).thenReturn(window); + when(window.getAttributes()).thenReturn(layoutParams); + when(mockRootView.getRootWindowInsets()).thenReturn(insets); + when(insets.getSystemWindowInsetLeft()).thenReturn(expectedInsetLeft); + when(context.getPackageName()).thenReturn("test"); + AccessibilityBridge accessibilityBridge = + setUpBridge(mockRootView, mockManager, mockViewEmbedder); + ViewParent mockParent = mock(ViewParent.class); + when(mockRootView.getParent()).thenReturn(mockParent); + when(mockManager.isEnabled()).thenReturn(true); + + TestSemanticsNode root = new TestSemanticsNode(); + root.id = 0; + root.left = left; + root.top = top; + root.right = right; + root.bottom = bottom; + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + + AccessibilityBridge spyAccessibilityBridge = spy(accessibilityBridge); + AccessibilityNodeInfo mockNodeInfo = mock(AccessibilityNodeInfo.class); + + when(spyAccessibilityBridge.obtainAccessibilityNodeInfo(mockRootView, 0)) + .thenReturn(mockNodeInfo); + spyAccessibilityBridge.createAccessibilityNodeInfo(0); + // Does not apply left inset if the layout mode is `always`. + verify(mockNodeInfo, times(1)).setBoundsInScreen(new Rect(left, top, right, bottom)); + } + + @Test + public void itIgnoresUnfocusableNodeDuringHitTest() { + 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(mockRootView, mockManager, mockViewEmbedder); + ViewParent mockParent = mock(ViewParent.class); + when(mockRootView.getParent()).thenReturn(mockParent); + when(mockManager.isEnabled()).thenReturn(true); + when(mockManager.isTouchExplorationEnabled()).thenReturn(true); + + TestSemanticsNode root = new TestSemanticsNode(); + root.id = 0; + root.left = 0; + root.top = 0; + root.bottom = 20; + root.right = 20; + TestSemanticsNode ignored = new TestSemanticsNode(); + ignored.id = 1; + ignored.addFlag(AccessibilityBridge.Flag.SCOPES_ROUTE); + ignored.left = 0; + ignored.top = 0; + ignored.bottom = 20; + ignored.right = 20; + root.children.add(ignored); + TestSemanticsNode child = new TestSemanticsNode(); + child.id = 2; + child.label = "label"; + child.left = 0; + child.top = 0; + child.bottom = 20; + child.right = 20; + root.children.add(child); + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + + verify(mockRootView, times(1)).setAccessibilityPaneTitle(eq(" ")); + + // Synthesize an accessibility hit test event. + MotionEvent mockEvent = mock(MotionEvent.class); + when(mockEvent.getX()).thenReturn(10.0f); + when(mockEvent.getY()).thenReturn(10.0f); + when(mockEvent.getAction()).thenReturn(MotionEvent.ACTION_HOVER_ENTER); + boolean hit = accessibilityBridge.onAccessibilityHoverEvent(mockEvent); + + assertEquals(hit, true); + + ArgumentCaptor eventCaptor = + ArgumentCaptor.forClass(AccessibilityEvent.class); + verify(mockParent, times(2)) + .requestSendAccessibilityEvent(eq(mockRootView), eventCaptor.capture()); + AccessibilityEvent event = eventCaptor.getAllValues().get(1); + assertEquals(event.getEventType(), AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); + assertEquals(accessibilityBridge.getHoveredObjectId(), 2); + } + + @Test + public void itFindsPlatformViewsDuringHoverByDefault() { + 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(mockRootView, mockManager, mockViewEmbedder); + ViewParent mockParent = mock(ViewParent.class); + when(mockRootView.getParent()).thenReturn(mockParent); + when(mockManager.isEnabled()).thenReturn(true); + when(mockManager.isTouchExplorationEnabled()).thenReturn(true); + + TestSemanticsNode root = new TestSemanticsNode(); + root.id = 0; + root.left = 0; + root.top = 0; + root.bottom = 20; + root.right = 20; + TestSemanticsNode platformView = new TestSemanticsNode(); + platformView.id = 1; + platformView.platformViewId = 1; + platformView.left = 0; + platformView.top = 0; + platformView.bottom = 20; + platformView.right = 20; + root.addChild(platformView); + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + + // Synthesize an accessibility hit test event. + MotionEvent mockEvent = mock(MotionEvent.class); + when(mockEvent.getX()).thenReturn(10.0f); + when(mockEvent.getY()).thenReturn(10.0f); + when(mockEvent.getAction()).thenReturn(MotionEvent.ACTION_HOVER_ENTER); + + final boolean handled = accessibilityBridge.onAccessibilityHoverEvent(mockEvent); + + assertTrue(handled); + } + + @Test + public void itIgnoresPlatformViewsDuringHoverIfRequested() { + 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(mockRootView, mockManager, mockViewEmbedder); + ViewParent mockParent = mock(ViewParent.class); + when(mockRootView.getParent()).thenReturn(mockParent); + when(mockManager.isEnabled()).thenReturn(true); + when(mockManager.isTouchExplorationEnabled()).thenReturn(true); + + TestSemanticsNode root = new TestSemanticsNode(); + root.id = 0; + root.left = 0; + root.top = 0; + root.bottom = 20; + root.right = 20; + TestSemanticsNode platformView = new TestSemanticsNode(); + platformView.id = 1; + platformView.platformViewId = 1; + platformView.left = 0; + platformView.top = 0; + platformView.bottom = 20; + platformView.right = 20; + root.addChild(platformView); + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + + // Synthesize an accessibility hit test event. + MotionEvent mockEvent = mock(MotionEvent.class); + when(mockEvent.getX()).thenReturn(10.0f); + when(mockEvent.getY()).thenReturn(10.0f); + when(mockEvent.getAction()).thenReturn(MotionEvent.ACTION_HOVER_ENTER); + + final boolean handled = accessibilityBridge.onAccessibilityHoverEvent(mockEvent, true); + + assertFalse(handled); + } + + @Test + public void itAnnouncesRouteNameWhenRemoveARoute() { + 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(mockRootView, mockManager, mockViewEmbedder); + ViewParent mockParent = mock(ViewParent.class); + when(mockRootView.getParent()).thenReturn(mockParent); + when(mockManager.isEnabled()).thenReturn(true); + + TestSemanticsNode root = new TestSemanticsNode(); + root.id = 0; + TestSemanticsNode node1 = new TestSemanticsNode(); + node1.id = 1; + node1.addFlag(AccessibilityBridge.Flag.SCOPES_ROUTE); + node1.addFlag(AccessibilityBridge.Flag.NAMES_ROUTE); + node1.label = "node1"; + root.children.add(node1); + TestSemanticsNode node2 = new TestSemanticsNode(); + node2.id = 2; + node2.addFlag(AccessibilityBridge.Flag.SCOPES_ROUTE); + node2.addFlag(AccessibilityBridge.Flag.NAMES_ROUTE); + node2.label = "node2"; + node1.children.add(node2); + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + + verify(mockRootView, times(1)).setAccessibilityPaneTitle(eq("node2")); + + TestSemanticsNode new_root = new TestSemanticsNode(); + new_root.id = 0; + TestSemanticsNode new_node1 = new TestSemanticsNode(); + new_node1.id = 1; + new_node1.label = "new_node1"; + new_root.children.add(new_node1); + TestSemanticsNode new_node2 = new TestSemanticsNode(); + new_node2.id = 2; + new_node2.addFlag(AccessibilityBridge.Flag.SCOPES_ROUTE); + new_node2.addFlag(AccessibilityBridge.Flag.NAMES_ROUTE); + new_node2.label = "new_node2"; + new_node1.children.add(new_node2); + testSemanticsUpdate = new_root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + + verify(mockRootView, times(1)).setAccessibilityPaneTitle(eq("new_node2")); + } + + @Config(sdk = API_LEVELS.API_21) + @Test + public void itCanPerformSetText() { + 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; + TestSemanticsNode node1 = new TestSemanticsNode(); + node1.id = 1; + node1.addFlag(AccessibilityBridge.Flag.IS_TEXT_FIELD); + root.children.add(node1); + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + 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); + verify(mockChannel) + .dispatchSemanticsAction(1, AccessibilityBridge.Action.SET_TEXT, expectedText); + } + + @Config(sdk = API_LEVELS.API_21) + @Test + public void itCanPredictSetText() { + 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; + TestSemanticsNode node1 = new TestSemanticsNode(); + node1.id = 1; + node1.addFlag(AccessibilityBridge.Flag.IS_TEXT_FIELD); + root.children.add(node1); + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + 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().toString(), expectedText); + } + + @Config(sdk = API_LEVELS.API_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); + } + + @Config(sdk = API_LEVELS.API_21) + @Test + public void itSetsTextCorrectly() { + 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.value = "value"; + TestStringAttribute attribute = new TestStringAttributeSpellOut(); + attribute.start = 1; + attribute.end = 2; + attribute.type = TestStringAttributeType.SPELLOUT; + root.valueAttributes = new ArrayList<>(); + root.valueAttributes.add(attribute); + + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(0); + SpannableString actual = (SpannableString) nodeInfo.getContentDescription(); + assertEquals(actual.toString(), "value"); + Object[] objectSpans = actual.getSpans(0, actual.length(), Object.class); + assertEquals(objectSpans.length, 1); + TtsSpan spellOutSpan = (TtsSpan) objectSpans[0]; + assertEquals(spellOutSpan.getType(), TtsSpan.TYPE_VERBATIM); + assertEquals(actual.getSpanStart(spellOutSpan), 1); + assertEquals(actual.getSpanEnd(spellOutSpan), 2); + + // Perform a set text action. + Bundle bundle = new Bundle(); + String expectedText = "a"; + bundle.putString(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, expectedText); + accessibilityBridge.performAction(0, AccessibilityNodeInfo.ACTION_SET_TEXT, bundle); + + // The action should remove the string attributes. + nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(0); + actual = (SpannableString) nodeInfo.getContentDescription(); + assertEquals(actual.toString(), expectedText); + objectSpans = actual.getSpans(0, actual.length(), Object.class); + assertEquals(objectSpans.length, 0); + } + + @Config(sdk = API_LEVELS.API_28) + @TargetApi(API_LEVELS.API_28) + @Test + public void itSetsTooltipCorrectly() { + 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); + // Create a node with tooltip. + TestSemanticsNode root = new TestSemanticsNode(); + root.id = 0; + root.tooltip = "tooltip"; + + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + + // Test the generated AccessibilityNodeInfo for the node we created + // and verify it has correct tooltip text. + AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(0); + CharSequence actual = nodeInfo.getTooltipText(); + assertEquals(actual.toString(), root.tooltip); + } + + @TargetApi(API_LEVELS.API_28) + @Test + public void itSetsIdentifierCorrectly() { + 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); + // Create a node with identifier. + TestSemanticsNode root = new TestSemanticsNode(); + root.id = 0; + root.identifier = "identifier"; + + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + + // Test the generated AccessibilityNodeInfo for the node we created and + // verify it has correct identifier (i.e. resource-id per Android + // terminology). + AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(0); + CharSequence actual = nodeInfo.getViewIdResourceName(); + assertEquals(actual.toString(), root.identifier); + } + + @Config(sdk = API_LEVELS.API_21) + @Test + public void itCanCreateAccessibilityNodeInfoWithSetText() { + 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; + TestSemanticsNode node1 = new TestSemanticsNode(); + node1.id = 1; + node1.addFlag(AccessibilityBridge.Flag.IS_TEXT_FIELD); + node1.addAction(AccessibilityBridge.Action.SET_TEXT); + root.children.add(node1); + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(1); + List actions = nodeInfo.getActionList(); + assertTrue(actions.contains(AccessibilityNodeInfo.AccessibilityAction.ACTION_SET_TEXT)); + } + + @Test + public void itCanPredictSetSelection() { + 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; + TestSemanticsNode node1 = new TestSemanticsNode(); + node1.id = 1; + node1.value = "some text"; + node1.textSelectionBase = -1; + node1.textSelectionExtent = -1; + node1.addFlag(AccessibilityBridge.Flag.IS_TEXT_FIELD); + root.children.add(node1); + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + Bundle bundle = new Bundle(); + int expectedStart = 1; + int expectedEnd = 3; + bundle.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, expectedStart); + bundle.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, expectedEnd); + accessibilityBridge.performAction(1, AccessibilityNodeInfo.ACTION_SET_SELECTION, bundle); + AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(1); + assertEquals(nodeInfo.getTextSelectionStart(), expectedStart); + assertEquals(nodeInfo.getTextSelectionEnd(), expectedEnd); + } + + @Test + public void itPerformsClearAccessibilityFocusCorrectly() { + BasicMessageChannel mockChannel = mock(BasicMessageChannel.class); + AccessibilityChannel accessibilityChannel = + new AccessibilityChannel(mockChannel, mock(FlutterJNI.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=*/ accessibilityChannel, + /*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 = "root"; + TestSemanticsNode node1 = new TestSemanticsNode(); + node1.id = 1; + node1.value = "some text"; + root.children.add(node1); + + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + accessibilityBridge.performAction(0, AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS, null); + AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(0); + assertTrue(nodeInfo.isAccessibilityFocused()); + + HashMap message = new HashMap<>(); + message.put("type", "didGainFocus"); + message.put("nodeId", 0); + verify(mockChannel).send(message); + // Clear focus on non-focused node shouldn't do anything + accessibilityBridge.performAction( + 1, AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS, null); + nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(0); + assertTrue(nodeInfo.isAccessibilityFocused()); + + // Now, clear the focus for real. + accessibilityBridge.performAction( + 0, AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS, null); + nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(0); + assertFalse(nodeInfo.isAccessibilityFocused()); + } + + @Test + public void itSetsFocusabilityBasedOnFlagsCorrectly() { + 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.addFlag(Flag.HAS_IMPLICIT_SCROLLING); + TestSemanticsNode node1 = new TestSemanticsNode(); + node1.id = 1; + node1.addFlag(Flag.IS_READ_ONLY); + root.children.add(node1); + TestSemanticsNode node2 = new TestSemanticsNode(); + node2.id = 2; + node2.addFlag(Flag.HAS_CHECKED_STATE); + root.children.add(node2); + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + + // Only node 2 is focusable because it has a flag that is not in + // AccessibilityBridge.TRIVIAL_FLAGS. + AccessibilityNodeInfo rootInfo = accessibilityBridge.createAccessibilityNodeInfo(0); + assertFalse(rootInfo.isFocusable()); + AccessibilityNodeInfo node1Info = accessibilityBridge.createAccessibilityNodeInfo(1); + assertFalse(node1Info.isFocusable()); + AccessibilityNodeInfo node2Info = accessibilityBridge.createAccessibilityNodeInfo(2); + assertTrue(node2Info.isFocusable()); + } + + @Config(sdk = API_LEVELS.API_31) + @TargetApi(API_LEVELS.API_31) + @Test + public void itSetsBoldTextFlagCorrectly() { + 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); + Resources resource = mock(Resources.class); + Configuration config = new Configuration(); + config.fontWeightAdjustment = 300; + + when(mockRootView.getContext()).thenReturn(context); + when(mockRootView.getResources()).thenReturn(resource); + when(resource.getConfiguration()).thenReturn(config); + + AccessibilityBridge accessibilityBridge = + setUpBridge( + /*rootAccessibilityView=*/ mockRootView, + /*accessibilityChannel=*/ mockChannel, + /*accessibilityManager=*/ mockManager, + /*contentResolver=*/ null, + /*accessibilityViewEmbedder=*/ mockViewEmbedder, + /*platformViewsAccessibilityDelegate=*/ null); + + verify(mockChannel).setAccessibilityFeatures(1 << 3); + reset(mockChannel); + + // Now verify that clearing the BOLD_TEXT flag doesn't touch any of the other flags. + // Ensure the DISABLE_ANIMATION flag will be set + Settings.Global.putFloat(null, "transition_animation_scale", 0.0f); + // Ensure the BOLD_TEXT flag will be cleared + config.fontWeightAdjustment = 0; + + accessibilityBridge = + setUpBridge( + /*rootAccessibilityView=*/ mockRootView, + /*accessibilityChannel=*/ mockChannel, + /*accessibilityManager=*/ mockManager, + /*contentResolver=*/ null, + /*accessibilityViewEmbedder=*/ mockViewEmbedder, + /*platformViewsAccessibilityDelegate=*/ null); + + // setAccessibilityFeatures() will be called multiple times from AccessibilityBridge's + // constructor, verify that the latest argument is correct + ArgumentCaptor captor = ArgumentCaptor.forClass(Integer.class); + verify(mockChannel, atLeastOnce()).setAccessibilityFeatures(captor.capture()); + assertEquals(1 << 2 /* DISABLE_ANIMATION */, captor.getValue().intValue()); + + // Set back to default + Settings.Global.putFloat(null, "transition_animation_scale", 1.0f); + } + + @Test + public void itSetsFocusedNodeBeforeSendingEvent() { + BasicMessageChannel mockChannel = mock(BasicMessageChannel.class); + AccessibilityChannel accessibilityChannel = + new AccessibilityChannel(mockChannel, mock(FlutterJNI.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=*/ accessibilityChannel, + /*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 = "root"; + + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + + class Verifier { + public Verifier(AccessibilityBridge accessibilityBridge) { + this.accessibilityBridge = accessibilityBridge; + } + + public AccessibilityBridge accessibilityBridge; + public boolean verified = false; + + public boolean verify(InvocationOnMock invocation) { + AccessibilityEvent event = (AccessibilityEvent) invocation.getArguments()[1]; + assertEquals(event.getEventType(), AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); + // The accessibility focus must be set before sending out + // the TYPE_VIEW_ACCESSIBILITY_FOCUSED event. + AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(0); + assertTrue(nodeInfo.isAccessibilityFocused()); + verified = true; + return true; + } + }; + Verifier verifier = new Verifier(accessibilityBridge); + when(mockParent.requestSendAccessibilityEvent(eq(mockRootView), any(AccessibilityEvent.class))) + .thenAnswer(invocation -> verifier.verify(invocation)); + accessibilityBridge.performAction(0, AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS, null); + assertTrue(verifier.verified); + + HashMap message = new HashMap<>(); + message.put("type", "didGainFocus"); + message.put("nodeId", 0); + verify(mockChannel).send(message); + } + + @Test + public void itClearsFocusedNodeBeforeSendingEvent() { + BasicMessageChannel mockChannel = mock(BasicMessageChannel.class); + AccessibilityChannel accessibilityChannel = + new AccessibilityChannel(mockChannel, mock(FlutterJNI.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=*/ accessibilityChannel, + /*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 = "root"; + + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + // Set the focus on root. + accessibilityBridge.performAction(0, AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS, null); + AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(0); + assertTrue(nodeInfo.isAccessibilityFocused()); + HashMap message = new HashMap<>(); + message.put("type", "didGainFocus"); + message.put("nodeId", 0); + verify(mockChannel).send(message); + + class Verifier { + public Verifier(AccessibilityBridge accessibilityBridge) { + this.accessibilityBridge = accessibilityBridge; + } + + public AccessibilityBridge accessibilityBridge; + public boolean verified = false; + + public boolean verify(InvocationOnMock invocation) { + AccessibilityEvent event = (AccessibilityEvent) invocation.getArguments()[1]; + assertEquals( + event.getEventType(), AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); + // The accessibility focus must be cleared before sending out + // the TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED event. + AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(0); + assertFalse(nodeInfo.isAccessibilityFocused()); + verified = true; + return true; + } + }; + Verifier verifier = new Verifier(accessibilityBridge); + when(mockParent.requestSendAccessibilityEvent(eq(mockRootView), any(AccessibilityEvent.class))) + .thenAnswer(invocation -> verifier.verify(invocation)); + accessibilityBridge.performAction( + 0, AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS, null); + assertTrue(verifier.verified); + } + + @Test + public void itCanPredictCursorMovementsWithGranularityWord() { + 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; + TestSemanticsNode node1 = new TestSemanticsNode(); + node1.id = 1; + node1.value = "some text"; + node1.textSelectionBase = 0; + node1.textSelectionExtent = 0; + node1.addFlag(AccessibilityBridge.Flag.IS_TEXT_FIELD); + root.children.add(node1); + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + Bundle bundle = new Bundle(); + bundle.putInt( + AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT, + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD); + bundle.putBoolean(AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN, false); + accessibilityBridge.performAction( + 1, AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY, bundle); + AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(1); + // The seletction should be at the end of 'text' + assertEquals(nodeInfo.getTextSelectionStart(), 9); + assertEquals(nodeInfo.getTextSelectionEnd(), 9); + + bundle = new Bundle(); + bundle.putInt( + AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT, + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD); + bundle.putBoolean(AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN, false); + accessibilityBridge.performAction( + 1, AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY, bundle); + nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(1); + // The seletction should be go to beginning of 'text'. + assertEquals(nodeInfo.getTextSelectionStart(), 5); + assertEquals(nodeInfo.getTextSelectionEnd(), 5); + } + + @Test + public void itAlsoFireSelectionEventWhenPredictCursorMovements() { + 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; + TestSemanticsNode node1 = new TestSemanticsNode(); + node1.id = 1; + node1.value = "some text"; + node1.textSelectionBase = 0; + node1.textSelectionExtent = 0; + node1.addFlag(AccessibilityBridge.Flag.IS_TEXT_FIELD); + root.children.add(node1); + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + Bundle bundle = new Bundle(); + bundle.putInt( + AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT, + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER); + bundle.putBoolean(AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN, false); + accessibilityBridge.performAction( + 1, AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY, bundle); + ArgumentCaptor eventCaptor = + ArgumentCaptor.forClass(AccessibilityEvent.class); + verify(mockParent, times(2)) + .requestSendAccessibilityEvent(eq(mockRootView), eventCaptor.capture()); + AccessibilityEvent event = eventCaptor.getAllValues().get(1); + assertEquals(event.getEventType(), AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); + assertEquals(event.getText().toString(), "[" + node1.value + "]"); + assertEquals(event.getFromIndex(), 1); + assertEquals(event.getToIndex(), 1); + assertEquals(event.getItemCount(), node1.value.length()); + } + + @Test + public void itDoesNotFireSelectionEventWhenPredictCursorMovementsDoesNotChangeSelection() { + 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; + TestSemanticsNode node1 = new TestSemanticsNode(); + node1.id = 1; + node1.value = "some text"; + node1.textSelectionBase = 0; + node1.textSelectionExtent = 0; + node1.addFlag(AccessibilityBridge.Flag.IS_TEXT_FIELD); + root.children.add(node1); + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + Bundle bundle = new Bundle(); + bundle.putInt( + AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT, + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER); + bundle.putBoolean(AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN, false); + accessibilityBridge.performAction( + 1, AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY, bundle); + ArgumentCaptor eventCaptor = + ArgumentCaptor.forClass(AccessibilityEvent.class); + verify(mockParent, times(1)) + .requestSendAccessibilityEvent(eq(mockRootView), eventCaptor.capture()); + assertEquals(eventCaptor.getAllValues().size(), 1); + AccessibilityEvent event = eventCaptor.getAllValues().get(0); + assertNotEquals(event.getEventType(), AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); + } + + @Test + public void itCanPredictCursorMovementsWithGranularityWordUnicode() { + 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; + TestSemanticsNode node1 = new TestSemanticsNode(); + node1.id = 1; + node1.value = "你 好 嗎"; + node1.textSelectionBase = 0; + node1.textSelectionExtent = 0; + node1.addFlag(AccessibilityBridge.Flag.IS_TEXT_FIELD); + root.children.add(node1); + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + Bundle bundle = new Bundle(); + bundle.putInt( + AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT, + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD); + bundle.putBoolean(AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN, false); + accessibilityBridge.performAction( + 1, AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY, bundle); + AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(1); + // The seletction should be at the end of '好' + assertEquals(nodeInfo.getTextSelectionStart(), 3); + assertEquals(nodeInfo.getTextSelectionEnd(), 3); + + bundle = new Bundle(); + bundle.putInt( + AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT, + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD); + bundle.putBoolean(AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN, false); + accessibilityBridge.performAction( + 1, AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY, bundle); + nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(1); + // The seletction should be go to beginning of '好'. + assertEquals(nodeInfo.getTextSelectionStart(), 2); + assertEquals(nodeInfo.getTextSelectionEnd(), 2); + } + + @Test + public void itCanPredictCursorMovementsWithGranularityLine() { + 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; + TestSemanticsNode node1 = new TestSemanticsNode(); + node1.id = 1; + node1.value = "How are you\nI am fine\nThank you"; + // Selection is at the second line. + node1.textSelectionBase = 14; + node1.textSelectionExtent = 14; + node1.addFlag(AccessibilityBridge.Flag.IS_TEXT_FIELD); + root.children.add(node1); + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + Bundle bundle = new Bundle(); + bundle.putInt( + AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT, + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE); + bundle.putBoolean(AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN, false); + accessibilityBridge.performAction( + 1, AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY, bundle); + AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(1); + // The seletction should be at the beginning of the third line. + assertEquals(nodeInfo.getTextSelectionStart(), 21); + assertEquals(nodeInfo.getTextSelectionEnd(), 21); + + bundle = new Bundle(); + bundle.putInt( + AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT, + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE); + bundle.putBoolean(AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN, false); + accessibilityBridge.performAction( + 1, AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY, bundle); + nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(1); + // The seletction should be at the beginning of the second line. + assertEquals(nodeInfo.getTextSelectionStart(), 11); + assertEquals(nodeInfo.getTextSelectionEnd(), 11); + } + + @Test + public void itCanPredictCursorMovementsWithGranularityCharacter() { + 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; + TestSemanticsNode node1 = new TestSemanticsNode(); + node1.id = 1; + node1.value = "some text"; + node1.textSelectionBase = 0; + node1.textSelectionExtent = 0; + node1.addFlag(AccessibilityBridge.Flag.IS_TEXT_FIELD); + root.children.add(node1); + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + Bundle bundle = new Bundle(); + bundle.putInt( + AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT, + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER); + bundle.putBoolean(AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN, false); + accessibilityBridge.performAction( + 1, AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY, bundle); + AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(1); + assertEquals(nodeInfo.getTextSelectionStart(), 1); + assertEquals(nodeInfo.getTextSelectionEnd(), 1); + + bundle = new Bundle(); + bundle.putInt( + AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT, + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER); + bundle.putBoolean(AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN, false); + accessibilityBridge.performAction( + 1, AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY, bundle); + nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(1); + assertEquals(nodeInfo.getTextSelectionStart(), 0); + assertEquals(nodeInfo.getTextSelectionEnd(), 0); + } + + @Test + public void itAnnouncesWhiteSpaceWhenNoNamesRoute() { + 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(mockRootView, mockManager, mockViewEmbedder); + ViewParent mockParent = mock(ViewParent.class); + when(mockRootView.getParent()).thenReturn(mockParent); + when(mockManager.isEnabled()).thenReturn(true); + + // Sent a11y tree with scopeRoute without namesRoute. + TestSemanticsNode root = new TestSemanticsNode(); + root.id = 0; + TestSemanticsNode scopeRoute = new TestSemanticsNode(); + scopeRoute.id = 1; + scopeRoute.addFlag(AccessibilityBridge.Flag.SCOPES_ROUTE); + root.children.add(scopeRoute); + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + + verify(mockRootView, times(1)).setAccessibilityPaneTitle(eq(" ")); + } + + @Test + public void itHoverOverOutOfBoundsDoesNotCrash() { + // SementicsNode.hitTest() returns null when out of bounds. + 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(mockRootView, mockManager, mockViewEmbedder); + + // Sent a11y tree with platform view. + TestSemanticsNode root = new TestSemanticsNode(); + root.id = 0; + TestSemanticsNode platformView = new TestSemanticsNode(); + platformView.id = 1; + platformView.platformViewId = 42; + root.children.add(platformView); + TestSemanticsUpdate testSemanticsUpdate = root.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + + // Pass an out of bounds MotionEvent. + accessibilityBridge.onAccessibilityHoverEvent(MotionEvent.obtain(1, 1, 1, -10, -10, 0)); + } + + @Test + public void itProducesPlatformViewNodeForHybridComposition() { + PlatformViewsAccessibilityDelegate accessibilityDelegate = + mock(PlatformViewsAccessibilityDelegate.class); + + Context context = ApplicationProvider.getApplicationContext(); + View rootAccessibilityView = new View(context); + AccessibilityViewEmbedder accessibilityViewEmbedder = mock(AccessibilityViewEmbedder.class); + AccessibilityBridge accessibilityBridge = + setUpBridge( + rootAccessibilityView, + /*accessibilityChannel=*/ null, + /*accessibilityManager=*/ null, + /*contentResolver=*/ null, + accessibilityViewEmbedder, + accessibilityDelegate); + + TestSemanticsNode root = new TestSemanticsNode(); + root.id = 0; + + TestSemanticsNode platformView = new TestSemanticsNode(); + platformView.id = 1; + platformView.platformViewId = 1; + root.addChild(platformView); + + TestSemanticsUpdate testSemanticsRootUpdate = root.toUpdate(); + testSemanticsRootUpdate.sendUpdateToBridge(accessibilityBridge); + + TestSemanticsUpdate testSemanticsPlatformViewUpdate = platformView.toUpdate(); + testSemanticsPlatformViewUpdate.sendUpdateToBridge(accessibilityBridge); + + View embeddedView = mock(View.class); + when(accessibilityDelegate.getPlatformViewById(1)).thenReturn(embeddedView); + when(accessibilityDelegate.usesVirtualDisplay(1)).thenReturn(false); + + AccessibilityNodeInfo nodeInfo = mock(AccessibilityNodeInfo.class); + when(embeddedView.createAccessibilityNodeInfo()).thenReturn(nodeInfo); + + AccessibilityNodeInfo result = accessibilityBridge.createAccessibilityNodeInfo(0); + assertNotNull(result); + assertEquals(result.getChildCount(), 1); + assertEquals(result.getClassName(), "android.view.View"); + } + + @Test + public void itMakesPlatformViewImportantForAccessibility() { + PlatformViewsAccessibilityDelegate accessibilityDelegate = + mock(PlatformViewsAccessibilityDelegate.class); + + Context context = ApplicationProvider.getApplicationContext(); + View rootAccessibilityView = new View(context); + AccessibilityViewEmbedder accessibilityViewEmbedder = mock(AccessibilityViewEmbedder.class); + AccessibilityBridge accessibilityBridge = + setUpBridge( + rootAccessibilityView, + /*accessibilityChannel=*/ null, + /*accessibilityManager=*/ null, + /*contentResolver=*/ null, + accessibilityViewEmbedder, + accessibilityDelegate); + + TestSemanticsNode root = new TestSemanticsNode(); + root.id = 0; + + TestSemanticsNode platformView = new TestSemanticsNode(); + platformView.id = 1; + platformView.platformViewId = 1; + root.addChild(platformView); + + View embeddedView = mock(View.class); + when(accessibilityDelegate.getPlatformViewById(1)).thenReturn(embeddedView); + when(accessibilityDelegate.usesVirtualDisplay(1)).thenReturn(false); + + TestSemanticsUpdate testSemanticsRootUpdate = root.toUpdate(); + testSemanticsRootUpdate.sendUpdateToBridge(accessibilityBridge); + + verify(embeddedView).setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_AUTO); + } + + @Test + public void itMakesPlatformViewNoImportantForAccessibility() { + PlatformViewsAccessibilityDelegate accessibilityDelegate = + mock(PlatformViewsAccessibilityDelegate.class); + + Context context = ApplicationProvider.getApplicationContext(); + View rootAccessibilityView = new View(context); + AccessibilityViewEmbedder accessibilityViewEmbedder = mock(AccessibilityViewEmbedder.class); + AccessibilityBridge accessibilityBridge = + setUpBridge( + rootAccessibilityView, + /*accessibilityChannel=*/ null, + /*accessibilityManager=*/ null, + /*contentResolver=*/ null, + accessibilityViewEmbedder, + accessibilityDelegate); + + TestSemanticsNode rootWithPlatformView = new TestSemanticsNode(); + rootWithPlatformView.id = 0; + + TestSemanticsNode platformView = new TestSemanticsNode(); + platformView.id = 1; + platformView.platformViewId = 1; + rootWithPlatformView.addChild(platformView); + + View embeddedView = mock(View.class); + when(accessibilityDelegate.getPlatformViewById(1)).thenReturn(embeddedView); + when(accessibilityDelegate.usesVirtualDisplay(1)).thenReturn(false); + + TestSemanticsUpdate testSemanticsRootWithPlatformViewUpdate = rootWithPlatformView.toUpdate(); + testSemanticsRootWithPlatformViewUpdate.sendUpdateToBridge(accessibilityBridge); + + TestSemanticsNode rootWithoutPlatformView = new TestSemanticsNode(); + rootWithoutPlatformView.id = 0; + TestSemanticsUpdate testSemanticsRootWithoutPlatformViewUpdate = + rootWithoutPlatformView.toUpdate(); + testSemanticsRootWithoutPlatformViewUpdate.sendUpdateToBridge(accessibilityBridge); + + verify(embeddedView) + .setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); + } + + @Test + public void itProducesPlatformViewNodeForVirtualDisplay() { + PlatformViewsAccessibilityDelegate accessibilityDelegate = + mock(PlatformViewsAccessibilityDelegate.class); + AccessibilityViewEmbedder accessibilityViewEmbedder = mock(AccessibilityViewEmbedder.class); + AccessibilityBridge accessibilityBridge = + setUpBridge( + /*rootAccessibilityView=*/ null, + /*accessibilityChannel=*/ null, + /*accessibilityManager=*/ null, + /*contentResolver=*/ null, + accessibilityViewEmbedder, + accessibilityDelegate); + + TestSemanticsNode platformView = new TestSemanticsNode(); + platformView.platformViewId = 1; + + TestSemanticsUpdate testSemanticsUpdate = platformView.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + + View embeddedView = mock(View.class); + when(accessibilityDelegate.getPlatformViewById(1)).thenReturn(embeddedView); + when(accessibilityDelegate.usesVirtualDisplay(1)).thenReturn(true); + + accessibilityBridge.createAccessibilityNodeInfo(0); + verify(accessibilityViewEmbedder).getRootNode(eq(embeddedView), eq(0), any(Rect.class)); + } + + @Test + public void testItSetsDisableAnimationsFlagBasedOnTransitionAnimationScale() { + AccessibilityChannel mockChannel = mock(AccessibilityChannel.class); + ContentResolver mockContentResolver = mock(ContentResolver.class); + + AccessibilityBridge accessibilityBridge = + setUpBridge( + /*rootAccessibilityView=*/ null, + /*accessibilityChannel=*/ mockChannel, + /*accessibilityManager=*/ null, + /*contentResolver=*/ mockContentResolver, + /*accessibilityViewEmbedder=*/ null, + /*platformViewsAccessibilityDelegate=*/ null); + + // Capture the observer registered for Settings.Global.TRANSITION_ANIMATION_SCALE + ArgumentCaptor observerCaptor = ArgumentCaptor.forClass(ContentObserver.class); + verify(mockContentResolver) + .registerContentObserver( + eq(Settings.Global.getUriFor(Settings.Global.TRANSITION_ANIMATION_SCALE)), + eq(false), + observerCaptor.capture()); + ContentObserver observer = observerCaptor.getValue(); + + // Initial state + verify(mockChannel).setAccessibilityFeatures(0); + reset(mockChannel); + + // Animations are disabled + Settings.Global.putFloat(mockContentResolver, "transition_animation_scale", 0.0f); + observer.onChange(false); + verify(mockChannel).setAccessibilityFeatures(1 << 2); + reset(mockChannel); + + // Animations are enabled + Settings.Global.putFloat(mockContentResolver, "transition_animation_scale", 1.0f); + observer.onChange(false); + verify(mockChannel).setAccessibilityFeatures(0); + } + + @Test + public void releaseDropsChannelMessageHandler() { + AccessibilityChannel mockChannel = mock(AccessibilityChannel.class); + AccessibilityManager mockManager = mock(AccessibilityManager.class); + ContentResolver mockContentResolver = mock(ContentResolver.class); + when(mockManager.isEnabled()).thenReturn(true); + AccessibilityBridge accessibilityBridge = + setUpBridge(null, mockChannel, mockManager, mockContentResolver, null, null); + verify(mockChannel) + .setAccessibilityMessageHandler( + any(AccessibilityChannel.AccessibilityMessageHandler.class)); + ArgumentCaptor stateListenerCaptor = + ArgumentCaptor.forClass(AccessibilityManager.AccessibilityStateChangeListener.class); + ArgumentCaptor touchListenerCaptor = + ArgumentCaptor.forClass(AccessibilityManager.TouchExplorationStateChangeListener.class); + verify(mockManager).addAccessibilityStateChangeListener(stateListenerCaptor.capture()); + verify(mockManager).addTouchExplorationStateChangeListener(touchListenerCaptor.capture()); + accessibilityBridge.release(); + verify(mockChannel).setAccessibilityMessageHandler(null); + reset(mockChannel); + stateListenerCaptor.getValue().onAccessibilityStateChanged(true); + verify(mockChannel, never()).onAndroidAccessibilityEnabled(); + touchListenerCaptor.getValue().onTouchExplorationStateChanged(true); + verify(mockChannel, never()).setAccessibilityFeatures(anyInt()); + } + + @Test + public void sendFocusAccessibilityEvent() { + AccessibilityManager mockManager = mock(AccessibilityManager.class); + AccessibilityChannel accessibilityChannel = + new AccessibilityChannel(mock(DartExecutor.class), mock(FlutterJNI.class)); + + ContentResolver mockContentResolver = mock(ContentResolver.class); + View mockRootView = mock(View.class); + Context context = mock(Context.class); + when(mockRootView.getContext()).thenReturn(context); + when(context.getPackageName()).thenReturn("test"); + ViewParent mockParent = mock(ViewParent.class); + when(mockRootView.getParent()).thenReturn(mockParent); + when(mockManager.isEnabled()).thenReturn(true); + + AccessibilityBridge accessibilityBridge = + setUpBridge(mockRootView, accessibilityChannel, mockManager, null, null, null); + + HashMap arguments = new HashMap<>(); + arguments.put("type", "focus"); + arguments.put("nodeId", 123); + BasicMessageChannel.Reply reply = mock(BasicMessageChannel.Reply.class); + accessibilityChannel.parsingMessageHandler.onMessage(arguments, reply); + + // Check that focus event was sent. + ArgumentCaptor eventCaptor = + ArgumentCaptor.forClass(AccessibilityEvent.class); + verify(mockParent).requestSendAccessibilityEvent(eq(mockRootView), eventCaptor.capture()); + AccessibilityEvent event = eventCaptor.getAllValues().get(0); + assertEquals(event.getEventType(), AccessibilityEvent.TYPE_VIEW_FOCUSED); + assertEquals(event.getSource(), null); + } + + @Test + public void SetSourceAndPackageNameForAccessibilityEvent() { + AccessibilityManager mockManager = mock(AccessibilityManager.class); + ContentResolver mockContentResolver = mock(ContentResolver.class); + View mockRootView = mock(View.class); + Context context = mock(Context.class); + when(mockRootView.getContext()).thenReturn(context); + when(context.getPackageName()).thenReturn("test"); + when(mockManager.isEnabled()).thenReturn(true); + ViewParent mockParent = mock(ViewParent.class); + when(mockRootView.getParent()).thenReturn(mockParent); + AccessibilityEvent mockEvent = mock(AccessibilityEvent.class); + + AccessibilityBridge accessibilityBridge = + setUpBridge(mockRootView, null, mockManager, null, null, null); + + AccessibilityBridge spyAccessibilityBridge = spy(accessibilityBridge); + + when(spyAccessibilityBridge.obtainAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED)) + .thenReturn(mockEvent); + + spyAccessibilityBridge.sendAccessibilityEvent(123, AccessibilityEvent.TYPE_VIEW_FOCUSED); + + verify(mockEvent).setPackageName("test"); + verify(mockEvent).setSource(eq(mockRootView), eq(123)); + } + + @Test + public void itAddsClickActionToSliderNodeInfo() { + AccessibilityBridge accessibilityBridge = setUpBridge(); + + TestSemanticsNode testSemanticsNode = new TestSemanticsNode(); + testSemanticsNode.addFlag(AccessibilityBridge.Flag.IS_SLIDER); + TestSemanticsUpdate testSemanticsUpdate = testSemanticsNode.toUpdate(); + testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge); + AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(0); + + assertEquals(nodeInfo.isClickable(), true); + List actions = nodeInfo.getActionList(); + assertTrue(actions.contains(AccessibilityNodeInfo.AccessibilityAction.ACTION_CLICK)); + } + + AccessibilityBridge setUpBridge() { + return setUpBridge(null, null, null, null, null, null); + } + + AccessibilityBridge setUpBridge( + View rootAccessibilityView, + AccessibilityManager accessibilityManager, + AccessibilityViewEmbedder accessibilityViewEmbedder) { + return setUpBridge( + rootAccessibilityView, null, accessibilityManager, null, accessibilityViewEmbedder, null); + } + + AccessibilityBridge setUpBridge( + View rootAccessibilityView, + AccessibilityChannel accessibilityChannel, + AccessibilityManager accessibilityManager, + ContentResolver contentResolver, + AccessibilityViewEmbedder accessibilityViewEmbedder, + PlatformViewsAccessibilityDelegate platformViewsAccessibilityDelegate) { + if (rootAccessibilityView == null) { + rootAccessibilityView = mock(View.class); + Context context = mock(Context.class); + when(rootAccessibilityView.getContext()).thenReturn(context); + when(context.getPackageName()).thenReturn("test"); + } + if (accessibilityChannel == null) { + accessibilityChannel = mock(AccessibilityChannel.class); + } + if (accessibilityManager == null) { + accessibilityManager = mock(AccessibilityManager.class); + } + if (contentResolver == null) { + contentResolver = mock(ContentResolver.class); + } + if (accessibilityViewEmbedder == null) { + accessibilityViewEmbedder = mock(AccessibilityViewEmbedder.class); + } + if (platformViewsAccessibilityDelegate == null) { + platformViewsAccessibilityDelegate = mock(PlatformViewsAccessibilityDelegate.class); + } + return new AccessibilityBridge( + rootAccessibilityView, + accessibilityChannel, + accessibilityManager, + contentResolver, + accessibilityViewEmbedder, + platformViewsAccessibilityDelegate); + } + + /// The encoding for semantics is described in platform_view_android.cc + class TestSemanticsUpdate { + 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 { + TestSemanticsNode() {} + + void addFlag(AccessibilityBridge.Flag flag) { + flags |= flag.value; + } + + void addAction(AccessibilityBridge.Action action) { + actions |= action.value; + } + + // These fields are declared in the order they should be + // encoded. + int id = 0; + int flags = 0; + int actions = 0; + int maxValueLength = 0; + int currentValueLength = 0; + int textSelectionBase = 0; + int textSelectionExtent = 0; + int platformViewId = -1; + int scrollChildren = 0; + int scrollIndex = 0; + float scrollPosition = 0.0f; + float scrollExtentMax = 0.0f; + float scrollExtentMin = 0.0f; + String identifier = null; + 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; + String tooltip = null; + String linkUrl = null; + int textDirection = 0; + float left = 0.0f; + float top = 0.0f; + float right = 0.0f; + float bottom = 0.0f; + float[] transform = + new float[] { + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f + }; + final List children = new ArrayList(); + + public void addChild(TestSemanticsNode child) { + children.add(child); + } + // custom actions not supported. + + TestSemanticsUpdate toUpdate() { + ArrayList strings = new ArrayList(); + ByteBuffer bytes = ByteBuffer.allocate(1000); + ArrayList stringAttributeArgs = new ArrayList(); + addToBuffer(bytes, strings, stringAttributeArgs); + bytes.flip(); + return new TestSemanticsUpdate( + bytes, + strings.toArray(new String[strings.size()]), + stringAttributeArgs.toArray(new ByteBuffer[stringAttributeArgs.size()])); + } + + protected void addToBuffer( + ByteBuffer bytes, ArrayList strings, ArrayList stringAttributeArgs) { + bytes.putInt(id); + bytes.putInt(flags); + bytes.putInt(actions); + bytes.putInt(maxValueLength); + bytes.putInt(currentValueLength); + bytes.putInt(textSelectionBase); + bytes.putInt(textSelectionExtent); + bytes.putInt(platformViewId); + bytes.putInt(scrollChildren); + bytes.putInt(scrollIndex); + bytes.putFloat(scrollPosition); + bytes.putFloat(scrollExtentMax); + bytes.putFloat(scrollExtentMin); + if (identifier == null) { + bytes.putInt(-1); + } else { + strings.add(identifier); + bytes.putInt(strings.size() - 1); + } + 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); + if (tooltip == null) { + bytes.putInt(-1); + } else { + strings.add(tooltip); + bytes.putInt(strings.size() - 1); + } + if (linkUrl == null) { + bytes.putInt(-1); + } else { + strings.add(linkUrl); + bytes.putInt(strings.size() - 1); + } + bytes.putInt(textDirection); + bytes.putFloat(left); + bytes.putFloat(top); + bytes.putFloat(right); + bytes.putFloat(bottom); + // transform. + for (int i = 0; i < 16; i++) { + bytes.putFloat(transform[i]); + } + // children in traversal order. + bytes.putInt(children.size()); + for (TestSemanticsNode node : children) { + bytes.putInt(node.id); + } + // children in hit test order. + for (TestSemanticsNode node : children) { + bytes.putInt(node.id); + } + // custom actions + bytes.putInt(0); + // child nodes + for (TestSemanticsNode node : children) { + node.addToBuffer(bytes, strings, stringAttributeArgs); + } + } + } + + 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/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/view/VsyncWaiterTest.java b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/view/VsyncWaiterTest.java new file mode 100644 index 0000000000000000000000000000000000000000..ef56b9936b87bbab851dc822c375e236d6291076 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test/io/flutter/view/VsyncWaiterTest.java @@ -0,0 +1,100 @@ +// 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. + +package io.flutter.view; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.robolectric.Shadows.shadowOf; + +import android.hardware.display.DisplayManager; +import android.os.Looper; +import android.view.Display; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import io.flutter.embedding.engine.FlutterJNI; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.robolectric.annotation.Config; + +@Config(manifest = Config.NONE) +@RunWith(AndroidJUnit4.class) +public class VsyncWaiterTest { + @Before + public void setUp() { + VsyncWaiter.reset(); + } + + @Test + public void itSetsFpsBelowApi17() { + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + VsyncWaiter waiter = VsyncWaiter.getInstance(10.0f, mockFlutterJNI); + verify(mockFlutterJNI, times(1)).setRefreshRateFPS(10.0f); + + waiter.init(); + + ArgumentCaptor delegateCaptor = + ArgumentCaptor.forClass(FlutterJNI.AsyncWaitForVsyncDelegate.class); + verify(mockFlutterJNI, times(1)).setAsyncWaitForVsyncDelegate(delegateCaptor.capture()); + delegateCaptor.getValue().asyncWaitForVsync(1); + shadowOf(Looper.getMainLooper()).idle(); + verify(mockFlutterJNI, times(1)).onVsync(anyLong(), eq(1000000000l / 10l), eq(1l)); + } + + @Test + public void itSetsFpsWhenDisplayManagerUpdates() { + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + DisplayManager mockDisplayManager = mock(DisplayManager.class); + Display mockDisplay = mock(Display.class); + ArgumentCaptor displayListenerCaptor = + ArgumentCaptor.forClass(VsyncWaiter.DisplayListener.class); + when(mockDisplayManager.getDisplay(Display.DEFAULT_DISPLAY)).thenReturn(mockDisplay); + + VsyncWaiter waiter = VsyncWaiter.getInstance(mockDisplayManager, mockFlutterJNI); + verify(mockDisplayManager, times(1)) + .registerDisplayListener(displayListenerCaptor.capture(), isNull()); + + when(mockDisplay.getRefreshRate()).thenReturn(90.0f); + displayListenerCaptor.getValue().onDisplayChanged(Display.DEFAULT_DISPLAY); + verify(mockFlutterJNI, times(1)).setRefreshRateFPS(90.0f); + + waiter.init(); + + ArgumentCaptor delegateCaptor = + ArgumentCaptor.forClass(FlutterJNI.AsyncWaitForVsyncDelegate.class); + verify(mockFlutterJNI, times(1)).setAsyncWaitForVsyncDelegate(delegateCaptor.capture()); + delegateCaptor.getValue().asyncWaitForVsync(1); + shadowOf(Looper.getMainLooper()).idle(); + verify(mockFlutterJNI, times(1)).onVsync(anyLong(), eq(1000000000l / 90l), eq(1l)); + + when(mockDisplay.getRefreshRate()).thenReturn(60.0f); + displayListenerCaptor.getValue().onDisplayChanged(Display.DEFAULT_DISPLAY); + verify(mockFlutterJNI, times(1)).setRefreshRateFPS(60.0f); + + delegateCaptor.getValue().asyncWaitForVsync(1); + shadowOf(Looper.getMainLooper()).idle(); + verify(mockFlutterJNI, times(1)).onVsync(anyLong(), eq(1000000000l / 60l), eq(1l)); + } + + @Test + public void itSetsFpsWhenDisplayManagerDoesNotUpdate() { + FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); + DisplayManager mockDisplayManager = mock(DisplayManager.class); + Display mockDisplay = mock(Display.class); + when(mockDisplayManager.getDisplay(Display.DEFAULT_DISPLAY)).thenReturn(mockDisplay); + when(mockDisplay.getRefreshRate()).thenReturn(90.0f); + + VsyncWaiter waiter = VsyncWaiter.getInstance(mockDisplayManager, mockFlutterJNI); + verify(mockDisplayManager, times(1)).registerDisplayListener(any(), isNull()); + + verify(mockFlutterJNI, times(1)).setRefreshRateFPS(90.0f); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test_runner/build.gradle b/flutter/engine/src/flutter/shell/platform/android/test_runner/build.gradle new file mode 100644 index 0000000000000000000000000000000000000000..2670f953452120d003c10dbee035d0db0edbd5c3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test_runner/build.gradle @@ -0,0 +1,101 @@ +buildscript { + repositories { + google() + mavenCentral() + } + dependencies { + classpath "com.android.tools.build:gradle:8.7.2" + } +} + +repositories { + google() + mavenCentral() +} + +apply plugin: "com.android.library" + +rootProject.buildDir = project.property("build_dir") + +// Shows warnings for usage of deprecated API usages. +// TODO(reidbaker): Expand linter coverage https://github.com/flutter/flutter/issues/133154 +gradle.projectsEvaluated { + tasks.withType(JavaCompile) { + options.compilerArgs << "-Xlint:deprecation" << "-Werror" + } +} + +def availableProcessors = Runtime.runtime.availableProcessors() ?: 1 + +println "==========================================" +println "AVAILABLE PROCESSORS: $availableProcessors" +println "==========================================" + +android { + namespace 'io.flutter.app.test' + compileSdk 35 + + defaultConfig { + minSdkVersion 21 + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + testOptions { + unitTests { + includeAndroidResources = true + } + + unitTests.all { + jvmArgs "-Xmx8g" // Max JVM heap size is 8G/30G available in the CI bot. + maxHeapSize "8g" + maxParallelForks availableProcessors // The CI bot has 8 CPUs. + testLogging { + events "started", "passed", "skipped", "failed", "standardOut", "standardError" + exceptionFormat "full" + showStackTraces true + showStandardStreams true + } + } + } + + dependencies { + // Please *don't* add embedding dependencies to this file. + // The embedding dependencies are configured in tools/androidx/files.json. + // Only add test dependencies. + + implementation files(project.property("flutter_jar")) + testImplementation "androidx.test:core:1.4.0" + testImplementation "com.google.android.play:core:1.8.0" + testImplementation "com.ibm.icu:icu4j:69.1" + testImplementation "org.robolectric:robolectric:4.14.1" + testImplementation "junit:junit:4.13.2" + testImplementation "androidx.test.ext:junit:1.1.4-alpha07" + + def mockitoVersion = "4.7.0" + testImplementation "org.mockito:mockito-core:$mockitoVersion" + testImplementation "org.mockito:mockito-inline:$mockitoVersion" + testImplementation "org.mockito:mockito-android:$mockitoVersion" + } + + // Configure the embedding dependencies. + apply from: new File(rootDir, '../../../../tools/androidx/configure.gradle').absolutePath; + configureDependencies(new File(rootDir, '../../../..')) { dependency -> + dependencies { + testImplementation "$dependency" + } + } + + sourceSets { + main { + test { + java { + srcDirs = ["../test"] + } + } + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/test_runner/gradle.properties b/flutter/engine/src/flutter/shell/platform/android/test_runner/gradle.properties new file mode 100644 index 0000000000000000000000000000000000000000..5bac8ac504623a676070370da81ec518639e4829 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test_runner/gradle.properties @@ -0,0 +1 @@ +android.useAndroidX=true diff --git a/flutter/engine/src/flutter/shell/platform/android/test_runner/src/main/AndroidManifest.xml b/flutter/engine/src/flutter/shell/platform/android/test_runner/src/main/AndroidManifest.xml new file mode 100644 index 0000000000000000000000000000000000000000..65ca9afc7711396c42fd3ca6152e30e0c9b9e773 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test_runner/src/main/AndroidManifest.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/flutter/engine/src/flutter/shell/platform/android/test_runner/src/main/resources/robolectric.properties b/flutter/engine/src/flutter/shell/platform/android/test_runner/src/main/resources/robolectric.properties new file mode 100644 index 0000000000000000000000000000000000000000..7e47f6fb21ee65bc813cdfd57bc9fc85fe3c99e3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/test_runner/src/main/resources/robolectric.properties @@ -0,0 +1,2 @@ +sdk=35 +shadows=io.flutter.CustomShadowContextImpl diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/BUILD.gn b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..91e7120b6573432d315d5c3795b658b79cc548b1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/BUILD.gn @@ -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. + +import("//flutter/testing/testing.gni") +import("core_wrapper_files.gni") + +# Client library build for internal use by the shell implementation. +source_set("client_wrapper") { + sources = core_cpp_client_wrapper_sources + public = core_cpp_client_wrapper_includes + + core_cpp_client_wrapper_internal_headers + + deps = [ "//flutter/shell/platform/common:common_cpp_library_headers" ] + + configs += + [ "//flutter/shell/platform/common:desktop_library_implementation" ] + + public_configs = + [ "//flutter/shell/platform/common:relative_flutter_library_headers" ] +} + +source_set("client_wrapper_library_stubs") { + sources = [ + "testing/stub_flutter_api.cc", + "testing/stub_flutter_api.h", + ] + + defines = [ "FLUTTER_DESKTOP_LIBRARY" ] + + public_deps = [ "//flutter/shell/platform/common:common_cpp_library_headers" ] +} + +test_fixtures("client_wrapper_fixtures") { + fixtures = [] +} + +executable("client_wrapper_unittests") { + testonly = true + + sources = [ + "basic_message_channel_unittests.cc", + "encodable_value_unittests.cc", + "event_channel_unittests.cc", + "method_call_unittests.cc", + "method_channel_unittests.cc", + "method_result_functions_unittests.cc", + "plugin_registrar_unittests.cc", + "standard_message_codec_unittests.cc", + "standard_method_codec_unittests.cc", + "testing/test_codec_extensions.cc", + "testing/test_codec_extensions.h", + "texture_registrar_unittests.cc", + ] + + deps = [ + ":client_wrapper", + ":client_wrapper_fixtures", + ":client_wrapper_library_stubs", + "//flutter/testing", + + # TODO(chunhtai): Consider refactoring flutter_root/testing so that there's a testing + # target that doesn't require a Dart runtime to be linked in. + # https://github.com/flutter/flutter/issues/41414. + "$dart_src/runtime:libdart_jit", + ] + + defines = [ "FLUTTER_DESKTOP_LIBRARY" ] +} diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/README b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/README new file mode 100644 index 0000000000000000000000000000000000000000..56c93050ef075ce1f37e3e0b02546e74876bcb7d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/README @@ -0,0 +1,9 @@ +This code is intended to be built into plugins and applications to provide +higher-level, C++ abstractions for interacting with the Flutter library. + +Over time, the goal is to move more of this code into the library in a way that +provides a usable ABI (e.g., does not use standard library in the interfaces). + +Note that this wrapper is still in early stages. Expect significant churn in +both the APIs and the structure of the wrapper (e.g., the exact set of files +that need to be built). diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/basic_message_channel_unittests.cc b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/basic_message_channel_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..ba24f60b00f1cf8c44a43b4128e6887dee3aa558 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/basic_message_channel_unittests.cc @@ -0,0 +1,165 @@ +// 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/shell/platform/common/client_wrapper/include/flutter/basic_message_channel.h" + +#include +#include + +#include "flutter/shell/platform/common/client_wrapper/include/flutter/binary_messenger.h" +#include "flutter/shell/platform/common/client_wrapper/include/flutter/standard_message_codec.h" +#include "flutter/shell/platform/common/client_wrapper/include/flutter/standard_method_codec.h" +#include "gtest/gtest.h" + +namespace flutter { + +namespace { + +class TestBinaryMessenger : public BinaryMessenger { + public: + void Send(const std::string& channel, + const uint8_t* message, + const size_t message_size, + BinaryReply reply) const override { + send_called_ = true; + int length = static_cast(message_size); + last_message_ = + std::vector(message, message + length * sizeof(uint8_t)); + } + + void SetMessageHandler(const std::string& channel, + BinaryMessageHandler handler) override { + last_message_handler_channel_ = channel; + last_message_handler_ = handler; + } + + bool send_called() { return send_called_; } + + std::string last_message_handler_channel() { + return last_message_handler_channel_; + } + + BinaryMessageHandler last_message_handler() { return last_message_handler_; } + + std::vector last_message() { return last_message_; } + + private: + mutable bool send_called_ = false; + std::string last_message_handler_channel_; + BinaryMessageHandler last_message_handler_; + mutable std::vector last_message_; +}; + +} // namespace + +// Tests that SetMessageHandler sets a handler that correctly interacts with +// the binary messenger. +TEST(BasicMessageChannelTest, Registration) { + TestBinaryMessenger messenger; + const std::string channel_name("some_channel"); + const StandardMessageCodec& codec = StandardMessageCodec::GetInstance(); + BasicMessageChannel channel(&messenger, channel_name, &codec); + + bool callback_called = false; + const std::string message_value("hello"); + channel.SetMessageHandler( + [&callback_called, message_value](const auto& message, auto reply) { + callback_called = true; + // Ensure that the wrapper received a correctly decoded message and a + // reply. + EXPECT_EQ(std::get(message), message_value); + EXPECT_NE(reply, nullptr); + }); + EXPECT_EQ(messenger.last_message_handler_channel(), channel_name); + EXPECT_NE(messenger.last_message_handler(), nullptr); + // Send a test message to trigger the handler test assertions. + auto message = codec.EncodeMessage(EncodableValue(message_value)); + + messenger.last_message_handler()( + message->data(), message->size(), + [](const uint8_t* reply, const size_t reply_size) {}); + EXPECT_EQ(callback_called, true); +} + +// Tests that SetMessageHandler with a null handler unregisters the handler. +TEST(BasicMessageChannelTest, Unregistration) { + TestBinaryMessenger messenger; + const std::string channel_name("some_channel"); + BasicMessageChannel channel(&messenger, channel_name, + &flutter::StandardMessageCodec::GetInstance()); + + channel.SetMessageHandler([](const auto& message, auto reply) {}); + EXPECT_EQ(messenger.last_message_handler_channel(), channel_name); + EXPECT_NE(messenger.last_message_handler(), nullptr); + + channel.SetMessageHandler(nullptr); + EXPECT_EQ(messenger.last_message_handler_channel(), channel_name); + EXPECT_EQ(messenger.last_message_handler(), nullptr); +} + +// Tests that calling Resize generates the binary message expected by the Dart +// implementation. +TEST(BasicMessageChannelTest, Resize) { + TestBinaryMessenger messenger; + const std::string channel_name("flutter/test"); + BasicMessageChannel channel(&messenger, channel_name, + &flutter::StandardMessageCodec::GetInstance()); + + channel.Resize(3); + + // Because the Dart implementation for the control channel implements its own + // custom deserialization logic, this test compares the generated bytes array + // to the expected one (for instance, the deserialization logic expects the + // size parameter of the resize method call to be an uint32). + // + // The expected content was created from the following Dart code: + // MethodCall call = MethodCall('resize', ['flutter/test',3]); + // StandardMethodCodec().encodeMethodCall(call).buffer.asUint8List(); + const int expected_message_size = 29; + + EXPECT_EQ(messenger.send_called(), true); + EXPECT_EQ(static_cast(messenger.last_message().size()), + expected_message_size); + + int expected[expected_message_size] = { + 7, 6, 114, 101, 115, 105, 122, 101, 12, 2, 7, 12, 102, 108, 117, + 116, 116, 101, 114, 47, 116, 101, 115, 116, 3, 3, 0, 0, 0}; + for (int i = 0; i < expected_message_size; i++) { + EXPECT_EQ(messenger.last_message()[i], expected[i]); + } +} + +// Tests that calling SetWarnsOnOverflow generates the binary message expected +// by the Dart implementation. +TEST(BasicMessageChannelTest, SetWarnsOnOverflow) { + TestBinaryMessenger messenger; + + const std::string channel_name("flutter/test"); + BasicMessageChannel channel(&messenger, channel_name, + &flutter::StandardMessageCodec::GetInstance()); + + channel.SetWarnsOnOverflow(false); + + // Because the Dart implementation for the control channel implements its own + // custom deserialization logic, this test compares the generated bytes array + // to the expected one. + // + // The expected content was created from the following Dart code: + // MethodCall call = MethodCall('overflow',['flutter/test', true]); + // StandardMethodCodec().encodeMethodCall(call).buffer.asUint8List(); + const int expected_message_size = 27; + + EXPECT_EQ(messenger.send_called(), true); + EXPECT_EQ(static_cast(messenger.last_message().size()), + expected_message_size); + + int expected[expected_message_size] = { + 7, 8, 111, 118, 101, 114, 102, 108, 111, 119, 12, 2, 7, 12, + 102, 108, 117, 116, 116, 101, 114, 47, 116, 101, 115, 116, 1}; + for (int i = 0; i < expected_message_size; i++) { + EXPECT_EQ(messenger.last_message()[i], expected[i]); + } +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/binary_messenger_impl.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/binary_messenger_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..65586656e7c751b618bdd0b71fb82d0fcff4c8e2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/binary_messenger_impl.h @@ -0,0 +1,50 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_BINARY_MESSENGER_IMPL_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_BINARY_MESSENGER_IMPL_H_ + +#include + +#include +#include + +#include "include/flutter/binary_messenger.h" + +namespace flutter { + +// Wrapper around a FlutterDesktopMessengerRef that implements the +// BinaryMessenger API. +class BinaryMessengerImpl : public BinaryMessenger { + public: + explicit BinaryMessengerImpl(FlutterDesktopMessengerRef core_messenger); + + virtual ~BinaryMessengerImpl(); + + // Prevent copying. + BinaryMessengerImpl(BinaryMessengerImpl const&) = delete; + BinaryMessengerImpl& operator=(BinaryMessengerImpl const&) = delete; + + // |flutter::BinaryMessenger| + void Send(const std::string& channel, + const uint8_t* message, + size_t message_size, + BinaryReply reply) const override; + + // |flutter::BinaryMessenger| + void SetMessageHandler(const std::string& channel, + BinaryMessageHandler handler) override; + + private: + // Handle for interacting with the C API. + FlutterDesktopMessengerRef messenger_; + + // A map from channel names to the BinaryMessageHandler that should be called + // for incoming messages on that channel. + std::map handlers_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_BINARY_MESSENGER_IMPL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/byte_buffer_streams.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/byte_buffer_streams.h new file mode 100644 index 0000000000000000000000000000000000000000..55b01c88312e448a960cffcf1c755e2ab21d7fe8 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/byte_buffer_streams.h @@ -0,0 +1,102 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_BYTE_BUFFER_STREAMS_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_BYTE_BUFFER_STREAMS_H_ + +#include +#include +#include +#include +#include + +#include "include/flutter/byte_streams.h" + +namespace flutter { + +// Implementation of ByteStreamReader base on a byte array. +class ByteBufferStreamReader : public ByteStreamReader { + public: + // Createa a reader reading from |bytes|, which must have a length of |size|. + // |bytes| must remain valid for the lifetime of this object. + explicit ByteBufferStreamReader(const uint8_t* bytes, size_t size) + : bytes_(bytes), size_(size) {} + + virtual ~ByteBufferStreamReader() = default; + + // |ByteStreamReader| + uint8_t ReadByte() override { + if (location_ >= size_) { + std::cerr << "Invalid read in StandardCodecByteStreamReader" << std::endl; + return 0; + } + return bytes_[location_++]; + } + + // |ByteStreamReader| + void ReadBytes(uint8_t* buffer, size_t length) override { + if (location_ + length > size_) { + std::cerr << "Invalid read in StandardCodecByteStreamReader" << std::endl; + return; + } + std::memcpy(buffer, &bytes_[location_], length); + location_ += length; + } + + // |ByteStreamReader| + void ReadAlignment(uint8_t alignment) override { + uint8_t mod = location_ % alignment; + if (mod) { + location_ += alignment - mod; + } + } + + private: + // The buffer to read from. + const uint8_t* bytes_; + // The total size of the buffer. + size_t size_; + // The current read location. + size_t location_ = 0; +}; + +// Implementation of ByteStreamWriter based on a byte array. +class ByteBufferStreamWriter : public ByteStreamWriter { + public: + // Creates a writer that writes into |buffer|. + // |buffer| must remain valid for the lifetime of this object. + explicit ByteBufferStreamWriter(std::vector* buffer) + : bytes_(buffer) { + assert(buffer); + } + + virtual ~ByteBufferStreamWriter() = default; + + // |ByteStreamWriter| + void WriteByte(uint8_t byte) { bytes_->push_back(byte); } + + // |ByteStreamWriter| + void WriteBytes(const uint8_t* bytes, size_t length) { + assert(length > 0); + bytes_->insert(bytes_->end(), bytes, bytes + length); + } + + // |ByteStreamWriter| + void WriteAlignment(uint8_t alignment) { + uint8_t mod = bytes_->size() % alignment; + if (mod) { + for (int i = 0; i < alignment - mod; ++i) { + WriteByte(0); + } + } + } + + private: + // The buffer to write to. + std::vector* bytes_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_BYTE_BUFFER_STREAMS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/core_implementations.cc b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/core_implementations.cc new file mode 100644 index 0000000000000000000000000000000000000000..f682f1b22994eddb83c1161d857b94bb8df5705f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/core_implementations.cc @@ -0,0 +1,284 @@ +// 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. + +// This file contains the implementations of any class in the wrapper that +// - is not fully inline, and +// - is necessary for all clients of the wrapper (either app or plugin). +// It exists instead of the usual structure of having some_class_name.cc files +// so that changes to the set of things that need non-header implementations +// are not breaking changes for the template. +// +// If https://github.com/flutter/flutter/issues/57146 is fixed, this can be +// removed in favor of the normal structure since templates will no longer +// manually include files. + +#include +#include +#include + +#include "binary_messenger_impl.h" +#include "include/flutter/engine_method_result.h" +#include "include/flutter/method_channel.h" +#include "include/flutter/standard_method_codec.h" +#include "texture_registrar_impl.h" + +namespace flutter { + +// ========== binary_messenger_impl.h ========== + +namespace { + +using FlutterDesktopMessengerScopedLock = + std::unique_ptr; + +// Passes |message| to |user_data|, which must be a BinaryMessageHandler, along +// with a BinaryReply that will send a response on |message|'s response handle. +// +// This serves as an adaptor between the function-pointer-based message callback +// interface provided by the C API and the std::function-based message handler +// interface of BinaryMessenger. +void ForwardToHandler(FlutterDesktopMessengerRef messenger, + const FlutterDesktopMessage* message, + void* user_data) { + auto* response_handle = message->response_handle; + auto messenger_ptr = std::shared_ptr( + FlutterDesktopMessengerAddRef(messenger), + &FlutterDesktopMessengerRelease); + BinaryReply reply_handler = [messenger_ptr, response_handle]( + const uint8_t* reply, + size_t reply_size) mutable { + // Note: This lambda can be called on any thread. + auto lock = FlutterDesktopMessengerScopedLock( + FlutterDesktopMessengerLock(messenger_ptr.get()), + &FlutterDesktopMessengerUnlock); + if (!FlutterDesktopMessengerIsAvailable(messenger_ptr.get())) { + // Drop reply if it comes in after the engine is destroyed. + return; + } + if (!response_handle) { + std::cerr << "Error: Response can be set only once. Ignoring " + "duplicate response." + << std::endl; + return; + } + FlutterDesktopMessengerSendResponse(messenger_ptr.get(), response_handle, + reply, reply_size); + // The engine frees the response handle once + // FlutterDesktopSendMessageResponse is called. + response_handle = nullptr; + }; + + const BinaryMessageHandler& message_handler = + *static_cast(user_data); + + message_handler(message->message, message->message_size, + std::move(reply_handler)); +} +} // namespace + +BinaryMessengerImpl::BinaryMessengerImpl( + FlutterDesktopMessengerRef core_messenger) + : messenger_(core_messenger) {} + +BinaryMessengerImpl::~BinaryMessengerImpl() = default; + +void BinaryMessengerImpl::Send(const std::string& channel, + const uint8_t* message, + size_t message_size, + BinaryReply reply) const { + if (reply == nullptr) { + FlutterDesktopMessengerSend(messenger_, channel.c_str(), message, + message_size); + return; + } + struct Captures { + BinaryReply reply; + }; + auto captures = new Captures(); + captures->reply = reply; + + auto message_reply = [](const uint8_t* data, size_t data_size, + void* user_data) { + auto captures = reinterpret_cast(user_data); + captures->reply(data, data_size); + delete captures; + }; + bool result = FlutterDesktopMessengerSendWithReply( + messenger_, channel.c_str(), message, message_size, message_reply, + captures); + if (!result) { + delete captures; + } +} + +void BinaryMessengerImpl::SetMessageHandler(const std::string& channel, + BinaryMessageHandler handler) { + if (!handler) { + handlers_.erase(channel); + FlutterDesktopMessengerSetCallback(messenger_, channel.c_str(), nullptr, + nullptr); + return; + } + // Save the handler, to keep it alive. + handlers_[channel] = std::move(handler); + BinaryMessageHandler* message_handler = &handlers_[channel]; + // Set an adaptor callback that will invoke the handler. + FlutterDesktopMessengerSetCallback(messenger_, channel.c_str(), + ForwardToHandler, message_handler); +} + +// ========== engine_method_result.h ========== + +namespace internal { + +ReplyManager::ReplyManager(BinaryReply reply_handler) + : reply_handler_(std::move(reply_handler)) { + assert(reply_handler_); +} + +ReplyManager::~ReplyManager() { + if (reply_handler_) { + // Warn, rather than send a not-implemented response, since the engine may + // no longer be valid at this point. + std::cerr + << "Warning: Failed to respond to a message. This is a memory leak." + << std::endl; + } +} + +void ReplyManager::SendResponseData(const std::vector* data) { + if (!reply_handler_) { + std::cerr + << "Error: Only one of Success, Error, or NotImplemented can be " + "called," + << " and it can be called exactly once. Ignoring duplicate result." + << std::endl; + return; + } + + const uint8_t* message = data && !data->empty() ? data->data() : nullptr; + size_t message_size = data ? data->size() : 0; + reply_handler_(message, message_size); + reply_handler_ = nullptr; +} + +} // namespace internal + +// ========== method_channel.h ========== + +namespace { + +constexpr char kControlChannelName[] = "dev.flutter/channel-buffers"; +constexpr char kResizeMethod[] = "resize"; +constexpr char kOverflowMethod[] = "overflow"; + +} // namespace + +namespace internal { + +void ResizeChannel(BinaryMessenger* messenger, std::string name, int new_size) { + auto control_channel = std::make_unique>( + messenger, kControlChannelName, &StandardMethodCodec::GetInstance()); + + // The deserialization logic handles only 32 bits values, see + // https://github.com/flutter/engine/blob/93e8901490e78c7ba7e319cce4470d9c6478c6dc/lib/ui/channel_buffers.dart#L495. + control_channel->InvokeMethod( + kResizeMethod, std::make_unique(EncodableList{ + EncodableValue(name), + EncodableValue(static_cast(new_size)), + })); +} + +void SetChannelWarnsOnOverflow(BinaryMessenger* messenger, + std::string name, + bool warns) { + auto control_channel = std::make_unique>( + messenger, kControlChannelName, &StandardMethodCodec::GetInstance()); + + control_channel->InvokeMethod(kOverflowMethod, + std::make_unique(EncodableList{ + EncodableValue(name), + EncodableValue(!warns), + })); +} + +} // namespace internal + +// ========== texture_registrar_impl.h ========== + +TextureRegistrarImpl::TextureRegistrarImpl( + FlutterDesktopTextureRegistrarRef texture_registrar_ref) + : texture_registrar_ref_(texture_registrar_ref) {} + +TextureRegistrarImpl::~TextureRegistrarImpl() = default; + +int64_t TextureRegistrarImpl::RegisterTexture(TextureVariant* texture) { + FlutterDesktopTextureInfo info = {}; + if (auto pixel_buffer_texture = std::get_if(texture)) { + info.type = kFlutterDesktopPixelBufferTexture; + info.pixel_buffer_config.user_data = pixel_buffer_texture; + info.pixel_buffer_config.callback = + [](size_t width, size_t height, + void* user_data) -> const FlutterDesktopPixelBuffer* { + auto texture = static_cast(user_data); + return texture->CopyPixelBuffer(width, height); + }; + } else if (auto gpu_surface_texture = + std::get_if(texture)) { + info.type = kFlutterDesktopGpuSurfaceTexture; + info.gpu_surface_config.struct_size = + sizeof(FlutterDesktopGpuSurfaceTextureConfig); + info.gpu_surface_config.type = gpu_surface_texture->surface_type(); + info.gpu_surface_config.user_data = gpu_surface_texture; + info.gpu_surface_config.callback = + [](size_t width, size_t height, + void* user_data) -> const FlutterDesktopGpuSurfaceDescriptor* { + auto texture = static_cast(user_data); + return texture->ObtainDescriptor(width, height); + }; + } else { + std::cerr << "Attempting to register unknown texture variant." << std::endl; + return -1; + } + + int64_t texture_id = FlutterDesktopTextureRegistrarRegisterExternalTexture( + texture_registrar_ref_, &info); + return texture_id; +} // namespace flutter + +bool TextureRegistrarImpl::MarkTextureFrameAvailable(int64_t texture_id) { + return FlutterDesktopTextureRegistrarMarkExternalTextureFrameAvailable( + texture_registrar_ref_, texture_id); +} + +void TextureRegistrarImpl::UnregisterTexture(int64_t texture_id, + std::function callback) { + if (callback == nullptr) { + FlutterDesktopTextureRegistrarUnregisterExternalTexture( + texture_registrar_ref_, texture_id, nullptr, nullptr); + return; + } + + struct Captures { + std::function callback; + }; + auto captures = new Captures(); + captures->callback = std::move(callback); + FlutterDesktopTextureRegistrarUnregisterExternalTexture( + texture_registrar_ref_, texture_id, + [](void* opaque) { + auto captures = reinterpret_cast(opaque); + captures->callback(); + delete captures; + }, + captures); +} + +bool TextureRegistrarImpl::UnregisterTexture(int64_t texture_id) { + UnregisterTexture(texture_id, nullptr); + return true; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/core_wrapper_files.gni b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/core_wrapper_files.gni new file mode 100644 index 0000000000000000000000000000000000000000..c2ee524e0f117f3e4fdca3f055a373effa479c49 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/core_wrapper_files.gni @@ -0,0 +1,54 @@ +# 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. + +core_cpp_client_wrapper_includes = + get_path_info([ + "include/flutter/basic_message_channel.h", + "include/flutter/binary_messenger.h", + "include/flutter/byte_streams.h", + "include/flutter/encodable_value.h", + "include/flutter/engine_method_result.h", + "include/flutter/event_channel.h", + "include/flutter/event_sink.h", + "include/flutter/event_stream_handler_functions.h", + "include/flutter/event_stream_handler.h", + "include/flutter/message_codec.h", + "include/flutter/method_call.h", + "include/flutter/method_channel.h", + "include/flutter/method_codec.h", + "include/flutter/method_result_functions.h", + "include/flutter/method_result.h", + "include/flutter/plugin_registrar.h", + "include/flutter/plugin_registry.h", + "include/flutter/standard_codec_serializer.h", + "include/flutter/standard_message_codec.h", + "include/flutter/standard_method_codec.h", + "include/flutter/texture_registrar.h", + ], + "abspath") + +# Headers that aren't public for clients of the wrapper, but are considered +# public for the purpose of BUILD dependencies (e.g., to allow +# windows/client_wrapper implementation files to include them). +core_cpp_client_wrapper_internal_headers = + get_path_info([ + "binary_messenger_impl.h", + "byte_buffer_streams.h", + "texture_registrar_impl.h", + ], + "abspath") + +# TODO: Once the wrapper API is more stable, consolidate to as few files as is +# reasonable (without forcing different kinds of clients to take unnecessary +# code) to simplify use. +core_cpp_client_wrapper_sources = get_path_info([ + "core_implementations.cc", + "plugin_registrar.cc", + "standard_codec.cc", + ], + "abspath") + +# Temporary shim, published for backwards compatibility. +# See comment in the file for more detail. +temporary_shim_files = get_path_info([ "engine_method_result.cc" ], "abspath") diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/encodable_value_unittests.cc b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/encodable_value_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..5c1616f0dff54cfa6804cacd4a27024bab7e96cf --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/encodable_value_unittests.cc @@ -0,0 +1,333 @@ +// 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/shell/platform/common/client_wrapper/include/flutter/encodable_value.h" + +#include + +#include "gtest/gtest.h" + +namespace flutter { + +TEST(EncodableValueTest, Null) { + EncodableValue value; + value.IsNull(); +} + +TEST(EncodableValueTest, Bool) { + EncodableValue value(false); + + EXPECT_FALSE(std::get(value)); + value = true; + EXPECT_TRUE(std::get(value)); +} + +TEST(EncodableValueTest, Int) { + EncodableValue value(42); + + EXPECT_EQ(std::get(value), 42); + value = std::numeric_limits::max(); + EXPECT_EQ(std::get(value), std::numeric_limits::max()); +} + +// Test the int/long convenience wrapper. +TEST(EncodableValueTest, LongValue) { + const EncodableValue int_value(std::numeric_limits::max()); + EXPECT_EQ(int_value.LongValue(), std::numeric_limits::max()); + const EncodableValue long_value(std::numeric_limits::max()); + EXPECT_EQ(long_value.LongValue(), std::numeric_limits::max()); +} + +TEST(EncodableValueTest, Long) { + EncodableValue value(INT64_C(42)); + + EXPECT_EQ(std::get(value), 42); + value = std::numeric_limits::max(); + EXPECT_EQ(std::get(value), std::numeric_limits::max()); +} + +TEST(EncodableValueTest, Double) { + EncodableValue value(3.14); + + EXPECT_EQ(std::get(value), 3.14); + value = std::numeric_limits::max(); + EXPECT_EQ(std::get(value), std::numeric_limits::max()); +} + +TEST(EncodableValueTest, String) { + std::string hello("Hello, world!"); + EncodableValue value(hello); + + EXPECT_EQ(std::get(value), hello); + value = std::string("Goodbye"); + EXPECT_EQ(std::get(value), "Goodbye"); +} + +// Explicitly verify that the overrides to prevent char*->bool conversions work. +TEST(EncodableValueTest, CString) { + const char* hello = "Hello, world!"; + EncodableValue value(hello); + + EXPECT_EQ(std::get(value), hello); + value = "Goodbye"; + EXPECT_EQ(std::get(value), "Goodbye"); +} + +TEST(EncodableValueTest, UInt8List) { + std::vector data = {0, 2}; + EncodableValue value(data); + + auto& list_value = std::get>(value); + list_value.push_back(std::numeric_limits::max()); + EXPECT_EQ(list_value[0], 0); + EXPECT_EQ(list_value[1], 2); + + ASSERT_EQ(list_value.size(), 3u); + EXPECT_EQ(data.size(), 2u); + EXPECT_EQ(list_value[2], std::numeric_limits::max()); +} + +TEST(EncodableValueTest, Int32List) { + std::vector data = {-10, 2}; + EncodableValue value(data); + + auto& list_value = std::get>(value); + list_value.push_back(std::numeric_limits::max()); + EXPECT_EQ(list_value[0], -10); + EXPECT_EQ(list_value[1], 2); + + ASSERT_EQ(list_value.size(), 3u); + EXPECT_EQ(data.size(), 2u); + EXPECT_EQ(list_value[2], std::numeric_limits::max()); +} + +TEST(EncodableValueTest, Int64List) { + std::vector data = {-10, 2}; + EncodableValue value(data); + + auto& list_value = std::get>(value); + list_value.push_back(std::numeric_limits::max()); + EXPECT_EQ(list_value[0], -10); + EXPECT_EQ(list_value[1], 2); + + ASSERT_EQ(list_value.size(), 3u); + EXPECT_EQ(data.size(), 2u); + EXPECT_EQ(list_value[2], std::numeric_limits::max()); +} + +TEST(EncodableValueTest, DoubleList) { + std::vector data = {-10.0, 2.0}; + EncodableValue value(data); + + auto& list_value = std::get>(value); + list_value.push_back(std::numeric_limits::max()); + EXPECT_EQ(list_value[0], -10.0); + EXPECT_EQ(list_value[1], 2.0); + + ASSERT_EQ(list_value.size(), 3u); + EXPECT_EQ(data.size(), 2u); + EXPECT_EQ(list_value[2], std::numeric_limits::max()); +} + +TEST(EncodableValueTest, List) { + EncodableList encodables = { + EncodableValue(1), + EncodableValue(2.0), + EncodableValue("Three"), + }; + EncodableValue value(encodables); + + auto& list_value = std::get(value); + EXPECT_EQ(std::get(list_value[0]), 1); + EXPECT_EQ(std::get(list_value[1]), 2.0); + EXPECT_EQ(std::get(list_value[2]), "Three"); + + // Ensure that it's a modifiable copy of the original array. + list_value.push_back(EncodableValue(true)); + ASSERT_EQ(list_value.size(), 4u); + EXPECT_EQ(encodables.size(), 3u); + EXPECT_EQ(std::get(std::get(value)[3]), true); +} + +TEST(EncodableValueTest, Map) { + EncodableMap encodables = { + {EncodableValue(), EncodableValue(std::vector{1, 2, 3})}, + {EncodableValue(1), EncodableValue(INT64_C(10000))}, + {EncodableValue("two"), EncodableValue(7)}, + }; + EncodableValue value(encodables); + + auto& map_value = std::get(value); + EXPECT_EQ( + std::holds_alternative>(map_value[EncodableValue()]), + true); + EXPECT_EQ(std::get(map_value[EncodableValue(1)]), INT64_C(10000)); + EXPECT_EQ(std::get(map_value[EncodableValue("two")]), 7); + + // Ensure that it's a modifiable copy of the original map. + map_value[EncodableValue(true)] = EncodableValue(false); + ASSERT_EQ(map_value.size(), 4u); + EXPECT_EQ(encodables.size(), 3u); + EXPECT_EQ(std::get(map_value[EncodableValue(true)]), false); +} + +// Tests that the < operator meets the requirements of using EncodableValue as +// a map key. +TEST(EncodableValueTest, Comparison) { + EncodableList values = { + // Null + EncodableValue(), + // Bool + EncodableValue(true), + EncodableValue(false), + // Int + EncodableValue(-7), + EncodableValue(0), + EncodableValue(100), + // Long + EncodableValue(INT64_C(-7)), + EncodableValue(INT64_C(0)), + EncodableValue(INT64_C(100)), + // Double + EncodableValue(-7.0), + EncodableValue(0.0), + EncodableValue(100.0), + // String + EncodableValue("one"), + EncodableValue("two"), + // ByteList + EncodableValue(std::vector{0, 1}), + EncodableValue(std::vector{0, 10}), + // IntList + EncodableValue(std::vector{0, 1}), + EncodableValue(std::vector{0, 100}), + // LongList + EncodableValue(std::vector{0, INT64_C(1)}), + EncodableValue(std::vector{0, INT64_C(100)}), + // DoubleList + EncodableValue(std::vector{0, INT64_C(1)}), + EncodableValue(std::vector{0, INT64_C(100)}), + // List + EncodableValue(EncodableList{EncodableValue(), EncodableValue(true)}), + EncodableValue(EncodableList{EncodableValue(), EncodableValue(1.0)}), + // Map + EncodableValue(EncodableMap{{EncodableValue(), EncodableValue(true)}, + {EncodableValue(7), EncodableValue(7.0)}}), + EncodableValue( + EncodableMap{{EncodableValue(), EncodableValue(1.0)}, + {EncodableValue("key"), EncodableValue("value")}}), + // FloatList + EncodableValue(std::vector{0, 1}), + EncodableValue(std::vector{0, 100}), + }; + + for (size_t i = 0; i < values.size(); ++i) { + const auto& a = values[i]; + for (size_t j = 0; j < values.size(); ++j) { + const auto& b = values[j]; + if (i == j) { + // Identical objects should always be equal. + EXPECT_FALSE(a < b); + EXPECT_FALSE(b < a); + } else { + // All other comparisons should be consistent, but the direction doesn't + // matter. + EXPECT_NE(a < b, b < a) << "Indexes: " << i << ", " << j; + } + } + + // Copies should always be equal. + EncodableValue copy(a); + EXPECT_FALSE(a < copy || copy < a); + } +} + +// Tests that structures are deep-copied. +TEST(EncodableValueTest, DeepCopy) { + EncodableList original = { + EncodableValue(EncodableMap{ + {EncodableValue(), EncodableValue(std::vector{1, 2, 3})}, + {EncodableValue(1), EncodableValue(INT64_C(0000))}, + {EncodableValue("two"), EncodableValue(7)}, + }), + EncodableValue(EncodableList{ + EncodableValue(), + EncodableValue(), + EncodableValue( + EncodableMap{{EncodableValue("a"), EncodableValue("b")}}), + }), + }; + + EncodableValue copy(original); + ASSERT_TRUE(std::holds_alternative(copy)); + + // Spot-check innermost collection values. + auto& root_list = std::get(copy); + auto& first_child = std::get(root_list[0]); + EXPECT_EQ(std::get(first_child[EncodableValue("two")]), 7); + auto& second_child = std::get(root_list[1]); + auto& innermost_map = std::get(second_child[2]); + EXPECT_EQ(std::get(innermost_map[EncodableValue("a")]), "b"); + + // Modify those values in the original structure. + first_child[EncodableValue("two")] = EncodableValue(); + innermost_map[EncodableValue("a")] = 99; + + // Re-check innermost collection values of the original to ensure that they + // haven't changed. + first_child = std::get(original[0]); + EXPECT_EQ(std::get(first_child[EncodableValue("two")]), 7); + second_child = std::get(original[1]); + innermost_map = std::get(second_child[2]); + EXPECT_EQ(std::get(innermost_map[EncodableValue("a")]), "b"); +} + +// Simple class for testing custom encodable values +class TestCustomValue { + public: + TestCustomValue() : x_(0), y_(0) {} + TestCustomValue(int x, int y) : x_(x), y_(y) {} + ~TestCustomValue() = default; + + int x() const { return x_; } + int y() const { return y_; } + + private: + int x_; + int y_; +}; + +TEST(EncodableValueTest, TypeIndexesCorrect) { + // Null + EXPECT_EQ(EncodableValue().index(), 0u); + // Bool + EXPECT_EQ(EncodableValue(true).index(), 1u); + // Int32 + EXPECT_EQ(EncodableValue(100).index(), 2u); + // Int64 + EXPECT_EQ(EncodableValue(INT64_C(100)).index(), 3u); + // Double + EXPECT_EQ(EncodableValue(7.0).index(), 4u); + // String + EXPECT_EQ(EncodableValue("one").index(), 5u); + // ByteList + EXPECT_EQ(EncodableValue(std::vector()).index(), 6u); + // IntList + EXPECT_EQ(EncodableValue(std::vector()).index(), 7u); + // LongList + EXPECT_EQ(EncodableValue(std::vector()).index(), 8u); + // DoubleList + EXPECT_EQ(EncodableValue(std::vector()).index(), 9u); + // List + EXPECT_EQ(EncodableValue(EncodableList()).index(), 10u); + // Map + EXPECT_EQ(EncodableValue(EncodableMap()).index(), 11u); + // Custom type + TestCustomValue customValue; + EXPECT_EQ(((EncodableValue)CustomEncodableValue(customValue)).index(), 12u); + // FloatList + EXPECT_EQ(EncodableValue(std::vector()).index(), 13u); +} // namespace flutter + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/engine_method_result.cc b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/engine_method_result.cc new file mode 100644 index 0000000000000000000000000000000000000000..65eaf5d4358cb4577cd241e5e95e5817e9c1062e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/engine_method_result.cc @@ -0,0 +1,11 @@ +// 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. + +// This file is deprecated in favor of core_implementations.cc. This is a +// temporary forwarding implementation so that the switch to +// core_implementations.cc isn't an immediate breaking change, allowing for the +// template to be updated to include it and update the template version before +// removing this file. + +#include "core_implementations.cc" diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/event_channel_unittests.cc b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/event_channel_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..0d68b10c83a5b421fd9ca4f75b4423a02533587c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/event_channel_unittests.cc @@ -0,0 +1,303 @@ +// 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/shell/platform/common/client_wrapper/include/flutter/event_channel.h" + +#include +#include + +#include "flutter/shell/platform/common/client_wrapper/include/flutter/binary_messenger.h" +#include "flutter/shell/platform/common/client_wrapper/include/flutter/event_stream_handler_functions.h" +#include "flutter/shell/platform/common/client_wrapper/include/flutter/standard_method_codec.h" +#include "gtest/gtest.h" + +namespace flutter { + +namespace { + +class TestBinaryMessenger : public BinaryMessenger { + public: + void Send(const std::string& channel, + const uint8_t* message, + const size_t message_size, + BinaryReply reply) const override {} + + void SetMessageHandler(const std::string& channel, + BinaryMessageHandler handler) override { + last_message_handler_channel_ = channel; + last_message_handler_ = handler; + } + + std::string last_message_handler_channel() { + return last_message_handler_channel_; + } + + const BinaryMessageHandler& last_message_handler() { + return last_message_handler_; + } + + private: + std::string last_message_handler_channel_; + BinaryMessageHandler last_message_handler_; +}; + +} // namespace + +// Tests that SetStreamHandler sets a handler that correctly interacts with +// the binary messenger. +TEST(EventChannelTest, Registration) { + TestBinaryMessenger messenger; + const std::string channel_name("some_channel"); + const StandardMethodCodec& codec = StandardMethodCodec::GetInstance(); + EventChannel channel(&messenger, channel_name, &codec); + + bool on_listen_called = false; + auto handler = std::make_unique>( + [&on_listen_called](const EncodableValue* arguments, + std::unique_ptr>&& events) + -> std::unique_ptr> { + on_listen_called = true; + return nullptr; + }, + [](const EncodableValue* arguments) + -> std::unique_ptr> { return nullptr; }); + channel.SetStreamHandler(std::move(handler)); + EXPECT_EQ(messenger.last_message_handler_channel(), channel_name); + EXPECT_NE(messenger.last_message_handler(), nullptr); + + // Send test listen message. + MethodCall<> call("listen", nullptr); + auto message = codec.EncodeMethodCall(call); + messenger.last_message_handler()( + message->data(), message->size(), + [](const uint8_t* reply, const size_t reply_size) {}); + + // Check results. + EXPECT_EQ(on_listen_called, true); +} + +// Tests that SetStreamHandler with a null handler unregisters the handler. +TEST(EventChannelTest, Unregistration) { + TestBinaryMessenger messenger; + const std::string channel_name("some_channel"); + const StandardMethodCodec& codec = StandardMethodCodec::GetInstance(); + EventChannel channel(&messenger, channel_name, &codec); + + auto handler = std::make_unique>( + [](const EncodableValue* arguments, std::unique_ptr>&& events) + -> std::unique_ptr> { return nullptr; }, + [](const EncodableValue* arguments) + -> std::unique_ptr> { return nullptr; }); + channel.SetStreamHandler(std::move(handler)); + EXPECT_EQ(messenger.last_message_handler_channel(), channel_name); + EXPECT_NE(messenger.last_message_handler(), nullptr); + + channel.SetStreamHandler(nullptr); + EXPECT_EQ(messenger.last_message_handler_channel(), channel_name); + EXPECT_EQ(messenger.last_message_handler(), nullptr); +} + +// Test that OnCancel callback sequence. +TEST(EventChannelTest, Cancel) { + TestBinaryMessenger messenger; + const std::string channel_name("some_channel"); + const StandardMethodCodec& codec = StandardMethodCodec::GetInstance(); + EventChannel channel(&messenger, channel_name, &codec); + + bool on_listen_called = false; + bool on_cancel_called = false; + auto handler = std::make_unique>( + [&on_listen_called](const EncodableValue* arguments, + std::unique_ptr>&& events) + -> std::unique_ptr> { + on_listen_called = true; + return nullptr; + }, + [&on_cancel_called](const EncodableValue* arguments) + -> std::unique_ptr> { + on_cancel_called = true; + return nullptr; + }); + channel.SetStreamHandler(std::move(handler)); + EXPECT_EQ(messenger.last_message_handler_channel(), channel_name); + EXPECT_NE(messenger.last_message_handler(), nullptr); + + // Send test listen message. + MethodCall<> call_listen("listen", nullptr); + auto message = codec.EncodeMethodCall(call_listen); + messenger.last_message_handler()( + message->data(), message->size(), + [](const uint8_t* reply, const size_t reply_size) {}); + EXPECT_EQ(on_listen_called, true); + + // Send test cancel message. + MethodCall<> call_cancel("cancel", nullptr); + message = codec.EncodeMethodCall(call_cancel); + messenger.last_message_handler()( + message->data(), message->size(), + [](const uint8_t* reply, const size_t reply_size) {}); + + // Check results. + EXPECT_EQ(on_cancel_called, true); +} + +// Tests that OnCancel in not called on registration. +TEST(EventChannelTest, ListenNotCancel) { + TestBinaryMessenger messenger; + const std::string channel_name("some_channel"); + const StandardMethodCodec& codec = StandardMethodCodec::GetInstance(); + EventChannel channel(&messenger, channel_name, &codec); + + bool on_listen_called = false; + bool on_cancel_called = false; + auto handler = std::make_unique>( + [&on_listen_called](const EncodableValue* arguments, + std::unique_ptr>&& events) + -> std::unique_ptr> { + on_listen_called = true; + return nullptr; + }, + [&on_cancel_called](const EncodableValue* arguments) + -> std::unique_ptr> { + on_cancel_called = true; + return nullptr; + }); + channel.SetStreamHandler(std::move(handler)); + EXPECT_EQ(messenger.last_message_handler_channel(), channel_name); + EXPECT_NE(messenger.last_message_handler(), nullptr); + + // Send test listen message. + MethodCall<> call_listen("listen", nullptr); + auto message = codec.EncodeMethodCall(call_listen); + messenger.last_message_handler()( + message->data(), message->size(), + [](const uint8_t* reply, const size_t reply_size) {}); + + // Check results. + EXPECT_EQ(on_listen_called, true); + EXPECT_EQ(on_cancel_called, false); +} + +// Pseudo test when user re-registers or call OnListen to the same channel. +// Confirm that OnCancel is called and OnListen is called again +// when user re-registers the same channel that has already started +// communication. +TEST(EventChannelTest, ReRegistration) { + TestBinaryMessenger messenger; + const std::string channel_name("some_channel"); + const StandardMethodCodec& codec = StandardMethodCodec::GetInstance(); + EventChannel channel(&messenger, channel_name, &codec); + + bool on_listen_called = false; + bool on_cancel_called = false; + auto handler = std::make_unique>( + [&on_listen_called](const EncodableValue* arguments, + std::unique_ptr>&& events) + -> std::unique_ptr> { + on_listen_called = true; + return nullptr; + }, + [&on_cancel_called](const EncodableValue* arguments) + -> std::unique_ptr> { + on_cancel_called = true; + return nullptr; + }); + channel.SetStreamHandler(std::move(handler)); + EXPECT_EQ(messenger.last_message_handler_channel(), channel_name); + EXPECT_NE(messenger.last_message_handler(), nullptr); + + // Send test listen message. + MethodCall<> call("listen", nullptr); + auto message = codec.EncodeMethodCall(call); + messenger.last_message_handler()( + message->data(), message->size(), + [](const uint8_t* reply, const size_t reply_size) {}); + EXPECT_EQ(on_listen_called, true); + + // Send second test message to test StreamHandler's OnCancel + // method is called before OnListen method is called. + on_listen_called = false; + message = codec.EncodeMethodCall(call); + messenger.last_message_handler()( + message->data(), message->size(), + [](const uint8_t* reply, const size_t reply_size) {}); + + // Check results. + EXPECT_EQ(on_cancel_called, true); + EXPECT_EQ(on_listen_called, true); +} + +// Test that the handler is called even if the event channel is destroyed. +TEST(EventChannelTest, HandlerOutlivesEventChannel) { + TestBinaryMessenger messenger; + const std::string channel_name("some_channel"); + const StandardMethodCodec& codec = StandardMethodCodec::GetInstance(); + + bool on_listen_called = false; + bool on_cancel_called = false; + { + EventChannel channel(&messenger, channel_name, &codec); + auto handler = std::make_unique>( + [&on_listen_called](const EncodableValue* arguments, + std::unique_ptr>&& events) + -> std::unique_ptr> { + on_listen_called = true; + return nullptr; + }, + [&on_cancel_called](const EncodableValue* arguments) + -> std::unique_ptr> { + on_cancel_called = true; + return nullptr; + }); + channel.SetStreamHandler(std::move(handler)); + } + + // The event channel was destroyed but the handler should still be alive. + EXPECT_EQ(messenger.last_message_handler_channel(), channel_name); + EXPECT_NE(messenger.last_message_handler(), nullptr); + + // Send test listen message. + MethodCall<> call_listen("listen", nullptr); + auto message = codec.EncodeMethodCall(call_listen); + messenger.last_message_handler()( + message->data(), message->size(), + [](const uint8_t* reply, const size_t reply_size) {}); + EXPECT_EQ(on_listen_called, true); + + // Send test cancel message. + MethodCall<> call_cancel("cancel", nullptr); + message = codec.EncodeMethodCall(call_cancel); + messenger.last_message_handler()( + message->data(), message->size(), + [](const uint8_t* reply, const size_t reply_size) {}); + EXPECT_EQ(on_cancel_called, true); +} + +TEST(EventChannelTest, StreamHandlerErrorPassByValue) { + std::unique_ptr> error = nullptr; + + { + std::string code = "Code"; + std::string msg = "Message"; + std::unique_ptr details = + std::make_unique("Details"); + error = + std::make_unique>(code, msg, std::move(details)); + } + + ASSERT_NE(error.get(), nullptr); + EXPECT_EQ(error->error_code, "Code"); + EXPECT_EQ(error->error_message, "Message"); + EXPECT_EQ(std::get(*error->error_details), "Details"); +} + +TEST(EventChannelTest, StreamHandlerErrorNullptr) { + std::unique_ptr> error = + std::make_unique>("Code", "Message", nullptr); + + ASSERT_NE(error.get(), nullptr); + EXPECT_FALSE(error->error_details); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/basic_message_channel.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/basic_message_channel.h new file mode 100644 index 0000000000000000000000000000000000000000..27c6cc93d6f50114ee6d1c16b33e3cf29da9719b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/basic_message_channel.h @@ -0,0 +1,149 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_BASIC_MESSAGE_CHANNEL_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_BASIC_MESSAGE_CHANNEL_H_ + +#include +#include +#include + +#include "binary_messenger.h" +#include "message_codec.h" + +namespace flutter { + +namespace internal { +// Internal helper functions used by BasicMessageChannel and MethodChannel. + +// Adjusts the number of messages that will get buffered when sending messages +// to channels that aren't fully set up yet. For example, the engine isn't +// running yet or the channel's message handler isn't set up on the Dart side +// yet. +void ResizeChannel(BinaryMessenger* messenger, std::string name, int new_size); + +// Defines whether the channel should show warning messages when discarding +// messages due to overflow. +// +// When |warns| is false, the channel is expected to overflow and warning +// messages will not be shown. +void SetChannelWarnsOnOverflow(BinaryMessenger* messenger, + std::string name, + bool warns); + +} // namespace internal + +class EncodableValue; + +// A message reply callback. +// +// Used for submitting a reply back to a Flutter message sender. +template +using MessageReply = std::function; + +// A handler for receiving a message from the Flutter engine. +// +// Implementations must asynchronously call reply exactly once with the reply +// to the message. +template +using MessageHandler = + std::function& reply)>; + +// A channel for communicating with the Flutter engine by sending asynchronous +// messages. +template +class BasicMessageChannel { + public: + // Creates an instance that sends and receives method calls on the channel + // named |name|, encoded with |codec| and dispatched via |messenger|. + BasicMessageChannel(BinaryMessenger* messenger, + const std::string& name, + const MessageCodec* codec) + : messenger_(messenger), name_(name), codec_(codec) {} + + ~BasicMessageChannel() = default; + + // Prevent copying. + BasicMessageChannel(BasicMessageChannel const&) = delete; + BasicMessageChannel& operator=(BasicMessageChannel const&) = delete; + + // Sends a message to the Flutter engine on this channel. + void Send(const T& message) { + std::unique_ptr> raw_message = + codec_->EncodeMessage(message); + messenger_->Send(name_, raw_message->data(), raw_message->size()); + } + + // Sends a message to the Flutter engine on this channel expecting a reply. + void Send(const T& message, BinaryReply reply) { + std::unique_ptr> raw_message = + codec_->EncodeMessage(message); + messenger_->Send(name_, raw_message->data(), raw_message->size(), + std::move(reply)); + } + + // Registers a handler that should be called any time a message is + // received on this channel. A null handler will remove any previous handler. + // + // Note that the BasicMessageChannel does not own the handler, and will not + // unregister it on destruction, so the caller is responsible for + // unregistering explicitly if it should no longer be called. + void SetMessageHandler(const MessageHandler& handler) const { + if (!handler) { + messenger_->SetMessageHandler(name_, nullptr); + return; + } + const auto* codec = codec_; + std::string channel_name = name_; + BinaryMessageHandler binary_handler = [handler, codec, channel_name]( + const uint8_t* binary_message, + const size_t binary_message_size, + const BinaryReply& binary_reply) { + // Use this channel's codec to decode the message and build a reply + // handler. + std::unique_ptr message = + codec->DecodeMessage(binary_message, binary_message_size); + if (!message) { + std::cerr << "Unable to decode message on channel " << channel_name + << std::endl; + binary_reply(nullptr, 0); + return; + } + + MessageReply unencoded_reply = [binary_reply, + codec](const T& unencoded_response) { + auto binary_response = codec->EncodeMessage(unencoded_response); + binary_reply(binary_response->data(), binary_response->size()); + }; + handler(*message, std::move(unencoded_reply)); + }; + messenger_->SetMessageHandler(name_, std::move(binary_handler)); + } + + // Adjusts the number of messages that will get buffered when sending messages + // to channels that aren't fully set up yet. For example, the engine isn't + // running yet or the channel's message handler isn't set up on the Dart side + // yet. + void Resize(int new_size) { + internal::ResizeChannel(messenger_, name_, new_size); + } + + // Defines whether the channel should show warning messages when discarding + // messages due to overflow. + // + // When |warns| is false, the channel is expected to overflow and warning + // messages will not be shown. + void SetWarnsOnOverflow(bool warns) { + internal::SetChannelWarnsOnOverflow(messenger_, name_, warns); + } + + private: + BinaryMessenger* messenger_; + std::string name_; + const MessageCodec* codec_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_BASIC_MESSAGE_CHANNEL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/binary_messenger.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/binary_messenger.h new file mode 100644 index 0000000000000000000000000000000000000000..d552b499ee2334f50f61481da5088bde40a1803c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/binary_messenger.h @@ -0,0 +1,52 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_BINARY_MESSENGER_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_BINARY_MESSENGER_H_ + +#include +#include + +namespace flutter { + +// A binary message reply callback. +// +// Used for submitting a binary reply back to a Flutter message sender. +typedef std::function + BinaryReply; + +// A message handler callback. +// +// Used for receiving messages from Flutter and providing an asynchronous reply. +typedef std::function< + void(const uint8_t* message, size_t message_size, BinaryReply reply)> + BinaryMessageHandler; + +// A protocol for a class that handles communication of binary data on named +// channels to and from the Flutter engine. +class BinaryMessenger { + public: + virtual ~BinaryMessenger() = default; + + // Sends a binary message to the Flutter engine on the specified channel. + // + // If |reply| is provided, it will be called back with the response from the + // engine. + virtual void Send(const std::string& channel, + const uint8_t* message, + size_t message_size, + BinaryReply reply = nullptr) const = 0; + + // Registers a message handler for incoming binary messages from the Flutter + // side on the specified channel. + // + // Replaces any existing handler. Provide a null handler to unregister the + // existing handler. + virtual void SetMessageHandler(const std::string& channel, + BinaryMessageHandler handler) = 0; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_BINARY_MESSENGER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/byte_streams.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/byte_streams.h new file mode 100644 index 0000000000000000000000000000000000000000..3360bab945da38392ba8b677ef67eaa09ce6db27 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/byte_streams.h @@ -0,0 +1,85 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_BYTE_STREAMS_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_BYTE_STREAMS_H_ + +// Interfaces for interacting with a stream of bytes, for use in codecs. + +namespace flutter { + +// An interface for a class that reads from a byte stream. +class ByteStreamReader { + public: + explicit ByteStreamReader() = default; + virtual ~ByteStreamReader() = default; + + // Reads and returns the next byte from the stream. + virtual uint8_t ReadByte() = 0; + + // Reads the next |length| bytes from the stream into |buffer|. The caller + // is responsible for ensuring that |buffer| is large enough. + virtual void ReadBytes(uint8_t* buffer, size_t length) = 0; + + // Advances the read cursor to the next multiple of |alignment| relative to + // the start of the stream, unless it is already aligned. + virtual void ReadAlignment(uint8_t alignment) = 0; + + // Reads and returns the next 32-bit integer from the stream. + int32_t ReadInt32() { + int32_t value = 0; + ReadBytes(reinterpret_cast(&value), 4); + return value; + } + + // Reads and returns the next 64-bit integer from the stream. + int64_t ReadInt64() { + int64_t value = 0; + ReadBytes(reinterpret_cast(&value), 8); + return value; + } + + // Reads and returns the next 64-bit floating point number from the stream. + double ReadDouble() { + double value = 0; + ReadBytes(reinterpret_cast(&value), 8); + return value; + } +}; + +// An interface for a class that writes to a byte stream. +class ByteStreamWriter { + public: + explicit ByteStreamWriter() = default; + virtual ~ByteStreamWriter() = default; + + // Writes |byte| to the stream. + virtual void WriteByte(uint8_t byte) = 0; + + // Writes the next |length| bytes from |bytes| to the stream + virtual void WriteBytes(const uint8_t* bytes, size_t length) = 0; + + // Writes 0s until the next multiple of |alignment| relative to the start + // of the stream, unless the write positition is already aligned. + virtual void WriteAlignment(uint8_t alignment) = 0; + + // Writes the given 32-bit int to the stream. + void WriteInt32(int32_t value) { + WriteBytes(reinterpret_cast(&value), 4); + } + + // Writes the given 64-bit int to the stream. + void WriteInt64(int64_t value) { + WriteBytes(reinterpret_cast(&value), 8); + } + + // Writes the given 36-bit double to the stream. + void WriteDouble(double value) { + WriteBytes(reinterpret_cast(&value), 8); + } +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_BYTE_STREAMS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/encodable_value.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/encodable_value.h new file mode 100644 index 0000000000000000000000000000000000000000..3a191205bbef20769d02ae99eeb92128568e5bfa --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/encodable_value.h @@ -0,0 +1,229 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_ENCODABLE_VALUE_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_ENCODABLE_VALUE_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +// Unless overridden, attempt to detect the RTTI state from the compiler. +#ifndef FLUTTER_ENABLE_RTTI +#if defined(_MSC_VER) +#ifdef _CPPRTTI +#define FLUTTER_ENABLE_RTTI 1 +#endif +#elif defined(__clang__) +#if __has_feature(cxx_rtti) +#define FLUTTER_ENABLE_RTTI 1 +#endif +#elif defined(__GNUC__) +#ifdef __GXX_RTTI +#define FLUTTER_ENABLE_RTTI 1 +#endif +#endif +#endif // #ifndef FLUTTER_ENABLE_RTTI + +namespace flutter { + +static_assert(sizeof(double) == 8, "EncodableValue requires a 64-bit double"); + +// A container for arbitrary types in EncodableValue. +// +// This is used in conjunction with StandardCodecExtension to allow using other +// types with a StandardMethodCodec/StandardMessageCodec. It is implicitly +// convertible to EncodableValue, so constructing an EncodableValue from a +// custom type can generally be written as: +// CustomEncodableValue(MyType(...)) +// rather than: +// EncodableValue(CustomEncodableValue(MyType(...))) +// +// For extracting received custom types, it is implicitly convertible to +// std::any. For example: +// const MyType& my_type_value = +// std::any_cast(std::get(value)); +// +// If RTTI is enabled, different extension types can be checked with type(): +// if (custom_value->type() == typeid(SomeData)) { ... } +// Clients that wish to disable RTTI would need to decide on another approach +// for distinguishing types (e.g., in StandardCodecExtension::WriteValueOfType) +// if multiple custom types are needed. For instance, wrapping all of the +// extension types in an EncodableValue-style variant, and only ever storing +// that variant in CustomEncodableValue. +class CustomEncodableValue { + public: + explicit CustomEncodableValue(const std::any& value) : value_(value) {} + ~CustomEncodableValue() = default; + + // Allow implicit conversion to std::any to allow direct use of any_cast. + // NOLINTNEXTLINE(google-explicit-constructor) + operator std::any&() { return value_; } + // NOLINTNEXTLINE(google-explicit-constructor) + operator const std::any&() const { return value_; } + +#if defined(FLUTTER_ENABLE_RTTI) && FLUTTER_ENABLE_RTTI + // Passthrough to std::any's type(). + const std::type_info& type() const noexcept { return value_.type(); } +#endif + + // This operator exists only to provide a stable ordering for use as a + // std::map key, to satisfy the compiler requirements for EncodableValue. + // It does not attempt to provide useful ordering semantics, and using a + // custom value as a map key is not recommended. + bool operator<(const CustomEncodableValue& other) const { + return this < &other; + } + bool operator==(const CustomEncodableValue& other) const { + return this == &other; + } + + private: + std::any value_; +}; + +class EncodableValue; + +// Convenience type aliases. +using EncodableList = std::vector; +using EncodableMap = std::map; + +namespace internal { +// The base class for EncodableValue. Do not use this directly; it exists only +// for EncodableValue to inherit from. +// +// Do not change the order or indexes of the items here; see the comment on +// EncodableValue +using EncodableValueVariant = std::variant, + std::vector, + std::vector, + std::vector, + EncodableList, + EncodableMap, + CustomEncodableValue, + std::vector>; +} // namespace internal + +// An object that can contain any value or collection type supported by +// Flutter's standard method codec. +// +// For details, see: +// https://api.flutter.dev/flutter/services/StandardMessageCodec-class.html +// +// As an example, the following Dart structure: +// { +// 'flag': true, +// 'name': 'Thing', +// 'values': [1, 2.0, 4], +// } +// would correspond to: +// EncodableValue(EncodableMap{ +// {EncodableValue("flag"), EncodableValue(true)}, +// {EncodableValue("name"), EncodableValue("Thing")}, +// {EncodableValue("values"), EncodableValue(EncodableList{ +// EncodableValue(1), +// EncodableValue(2.0), +// EncodableValue(4), +// })}, +// }) +// +// The primary API surface for this object is std::variant. For instance, +// getting a string value from an EncodableValue, with type checking: +// if (std::holds_alternative(value)) { +// std::string some_string = std::get(value); +// } +// +// The order/indexes of the variant types is part of the API surface, and is +// guaranteed not to change. +// +// The variant types are mapped with Dart types in following ways: +// std::monostate -> null +// bool -> bool +// int32_t -> int +// int64_t -> int +// double -> double +// std::string -> String +// std::vector -> Uint8List +// std::vector -> Int32List +// std::vector -> Int64List +// std::vector -> Float32List +// std::vector -> Float64List +// EncodableList -> List +// EncodableMap -> Map +class EncodableValue : public internal::EncodableValueVariant { + public: + // Rely on std::variant for most of the constructors/operators. + using super = internal::EncodableValueVariant; + using super::super; + using super::operator=; + + explicit EncodableValue() = default; + + // Avoid the C++17 pitfall of conversion from char* to bool. Should not be + // needed for C++20. + explicit EncodableValue(const char* string) : super(std::string(string)) {} + EncodableValue& operator=(const char* other) { + *this = std::string(other); + return *this; + } + + // Allow implicit conversion from CustomEncodableValue; the only reason to + // make a CustomEncodableValue (which can only be constructed explicitly) is + // to use it with EncodableValue, so the risk of unintended conversions is + // minimal, and it avoids the need for the verbose: + // EncodableValue(CustomEncodableValue(...)). + // NOLINTNEXTLINE(google-explicit-constructor) + EncodableValue(const CustomEncodableValue& v) : super(v) {} + + // Override the conversion constructors from std::variant to make them + // explicit, to avoid implicit conversion. + // + // While implicit conversion can be convenient in some cases, it can have very + // surprising effects. E.g., calling a function that takes an EncodableValue + // but accidentally passing an EncodableValue* would, instead of failing to + // compile, go through a pointer->bool->EncodableValue(bool) chain and + // silently call the function with a temp-constructed EncodableValue(true). + template + constexpr explicit EncodableValue(T&& t) noexcept : super(t) {} + + // Returns true if the value is null. Convenience wrapper since unlike the + // other types, std::monostate uses aren't self-documenting. + bool IsNull() const { return std::holds_alternative(*this); } + + // Convenience method to simplify handling objects received from Flutter + // where the values may be larger than 32-bit, since they have the same type + // on the Dart side, but will be either 32-bit or 64-bit here depending on + // the value. + // + // Calling this method if the value doesn't contain either an int32_t or an + // int64_t will throw an exception. + int64_t LongValue() const { + if (std::holds_alternative(*this)) { + return std::get(*this); + } + return std::get(*this); + } + + // Explicitly provide operator<, delegating to std::variant's operator<. + // There are issues with with the way the standard library-provided + // < and <=> comparisons interact with classes derived from variant. + friend bool operator<(const EncodableValue& lhs, const EncodableValue& rhs) { + return static_cast(lhs) < static_cast(rhs); + } +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_ENCODABLE_VALUE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/engine_method_result.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/engine_method_result.h new file mode 100644 index 0000000000000000000000000000000000000000..3cc8b6a22c35b5ebd689e7f62980aa391bada0bf --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/engine_method_result.h @@ -0,0 +1,86 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_ENGINE_METHOD_RESULT_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_ENGINE_METHOD_RESULT_H_ + +#include +#include +#include + +#include "binary_messenger.h" +#include "method_codec.h" +#include "method_result.h" + +namespace flutter { + +namespace internal { +// Manages the one-time sending of response data. This is an internal helper +// class for EngineMethodResult, separated out since the implementation doesn't +// vary based on the template type. +class ReplyManager { + public: + explicit ReplyManager(BinaryReply reply_handler_); + ~ReplyManager(); + + // Prevent copying. + ReplyManager(ReplyManager const&) = delete; + ReplyManager& operator=(ReplyManager const&) = delete; + + // Sends the given response data (which must either be nullptr, which + // indicates an unhandled method, or a response serialized with |codec_|) to + // the engine. + void SendResponseData(const std::vector* data); + + private: + BinaryReply reply_handler_; +}; +} // namespace internal + +// Implemention of MethodResult that sends a response to the Flutter engine +// exactly once, encoded using a given codec. +template +class EngineMethodResult : public MethodResult { + public: + // Creates a result object that will send results to |reply_handler|, encoded + // using |codec|. The |codec| pointer must remain valid for as long as this + // object exists. + EngineMethodResult(BinaryReply reply_handler, const MethodCodec* codec) + : reply_manager_( + std::make_unique(std::move(reply_handler))), + codec_(codec) {} + + ~EngineMethodResult() = default; + + protected: + // |flutter::MethodResult| + void SuccessInternal(const T* result) override { + std::unique_ptr> data = + codec_->EncodeSuccessEnvelope(result); + reply_manager_->SendResponseData(data.get()); + } + + // |flutter::MethodResult| + void ErrorInternal(const std::string& error_code, + const std::string& error_message, + const T* error_details) override { + std::unique_ptr> data = + codec_->EncodeErrorEnvelope(error_code, error_message, error_details); + reply_manager_->SendResponseData(data.get()); + } + + // |flutter::MethodResult| + void NotImplementedInternal() override { + reply_manager_->SendResponseData(nullptr); + } + + private: + std::unique_ptr reply_manager_; + + const MethodCodec* codec_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_ENGINE_METHOD_RESULT_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/event_channel.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/event_channel.h new file mode 100644 index 0000000000000000000000000000000000000000..7d0d2598861fb9f847d75e14bb6a9917907a4911 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/event_channel.h @@ -0,0 +1,181 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_EVENT_CHANNEL_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_EVENT_CHANNEL_H_ + +#include +#include +#include + +#include "binary_messenger.h" +#include "engine_method_result.h" +#include "event_sink.h" +#include "event_stream_handler.h" + +namespace flutter { + +class EncodableValue; + +// A named channel for communicating with the Flutter application using +// asynchronous event streams. Incoming requests for event stream setup are +// decoded from binary on receipt, and C++ responses and events are encoded into +// binary before being transmitted back to Flutter. The MethodCodec used must be +// compatible with the one used by the Flutter application. This can be achieved +// by creating an EventChannel +// ("https://api.flutter.dev/flutter/services/EventChannel-class.html") +// counterpart of this channel on the Dart side. +// The C++ type of stream configuration arguments, events, and error details are +// templated, but only values supported by the specified MethodCodec can be +// used. +template +class EventChannel { + public: + // Creates an instance that sends and receives event handler on the channel + // named |name|, encoded with |codec| and dispatched via |messenger|. + EventChannel(BinaryMessenger* messenger, + const std::string& name, + const MethodCodec* codec) + : messenger_(messenger), name_(name), codec_(codec) {} + ~EventChannel() = default; + + // Prevent copying. + EventChannel(EventChannel const&) = delete; + EventChannel& operator=(EventChannel const&) = delete; + + // Registers a stream handler on this channel. + // If no handler has been registered, any incoming stream setup requests will + // be handled silently by providing an empty stream. + // + // Note that the EventChannel does not own the handler and will not + // unregister it on destruction. The caller is responsible for unregistering + // the handler if it should no longer be called. + void SetStreamHandler(std::unique_ptr> handler) { + if (!handler) { + messenger_->SetMessageHandler(name_, nullptr); + return; + } + + // std::function requires a copyable lambda, so convert to a shared pointer. + // This is safe since only one copy of the shared_pointer will ever be + // accessed. + std::shared_ptr> shared_handler(handler.release()); + const MethodCodec* codec = codec_; + const std::string channel_name = name_; + const BinaryMessenger* messenger = messenger_; + BinaryMessageHandler binary_handler = + [shared_handler, codec, channel_name, messenger, + // Mutable state to track the handler's listening status. + is_listening = false](const uint8_t* message, + const size_t message_size, + const BinaryReply& reply) mutable { + constexpr char kOnListenMethod[] = "listen"; + constexpr char kOnCancelMethod[] = "cancel"; + + std::unique_ptr> method_call = + codec->DecodeMethodCall(message, message_size); + if (!method_call) { + std::cerr + << "Unable to construct method call from message on channel: " + << channel_name << std::endl; + reply(nullptr, 0); + return; + } + + const std::string& method = method_call->method_name(); + if (method.compare(kOnListenMethod) == 0) { + if (is_listening) { + std::unique_ptr> error = + shared_handler->OnCancel(nullptr); + if (error) { + std::cerr << "Failed to cancel existing stream: " + << (error->error_code) << ", " + << (error->error_message) << ", " + << (error->error_details); + } + } + is_listening = true; + + std::unique_ptr> result; + auto sink = std::make_unique( + messenger, channel_name, codec); + std::unique_ptr> error = + shared_handler->OnListen(method_call->arguments(), + std::move(sink)); + if (error) { + result = codec->EncodeErrorEnvelope(error->error_code, + error->error_message, + error->error_details.get()); + } else { + result = codec->EncodeSuccessEnvelope(); + } + reply(result->data(), result->size()); + } else if (method.compare(kOnCancelMethod) == 0) { + std::unique_ptr> result; + if (is_listening) { + std::unique_ptr> error = + shared_handler->OnCancel(method_call->arguments()); + if (error) { + result = codec->EncodeErrorEnvelope(error->error_code, + error->error_message, + error->error_details.get()); + } else { + result = codec->EncodeSuccessEnvelope(); + } + is_listening = false; + } else { + result = codec->EncodeErrorEnvelope( + "error", "No active stream to cancel", nullptr); + } + reply(result->data(), result->size()); + } else { + reply(nullptr, 0); + } + }; + messenger_->SetMessageHandler(name_, std::move(binary_handler)); + } + + private: + class EventSinkImplementation : public EventSink { + public: + EventSinkImplementation(const BinaryMessenger* messenger, + const std::string& name, + const MethodCodec* codec) + : messenger_(messenger), name_(name), codec_(codec) {} + ~EventSinkImplementation() = default; + + // Prevent copying. + EventSinkImplementation(EventSinkImplementation const&) = delete; + EventSinkImplementation& operator=(EventSinkImplementation const&) = delete; + + private: + const BinaryMessenger* messenger_; + const std::string name_; + const MethodCodec* codec_; + + protected: + void SuccessInternal(const T* event = nullptr) override { + auto result = codec_->EncodeSuccessEnvelope(event); + messenger_->Send(name_, result->data(), result->size()); + } + + void ErrorInternal(const std::string& error_code, + const std::string& error_message, + const T* error_details) override { + auto result = + codec_->EncodeErrorEnvelope(error_code, error_message, error_details); + messenger_->Send(name_, result->data(), result->size()); + } + + void EndOfStreamInternal() override { messenger_->Send(name_, nullptr, 0); } + }; + + BinaryMessenger* messenger_; + const std::string name_; + const MethodCodec* codec_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_EVENT_CHANNEL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/event_sink.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/event_sink.h new file mode 100644 index 0000000000000000000000000000000000000000..789be1eb967a4ed206edd6a745d9fa9cb3a0aa5e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/event_sink.h @@ -0,0 +1,62 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_EVENT_SINK_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_EVENT_SINK_H_ + +namespace flutter { + +class EncodableValue; + +// Event callback. Events to be sent to Flutter application +// act as clients of this interface for sending events. +template +class EventSink { + public: + EventSink() = default; + virtual ~EventSink() = default; + + // Prevent copying. + EventSink(EventSink const&) = delete; + EventSink& operator=(EventSink const&) = delete; + + // Consumes a successful event + void Success(const T& event) { SuccessInternal(&event); } + + // Consumes a successful event. + void Success() { SuccessInternal(nullptr); } + + // Consumes an error event. + void Error(const std::string& error_code, + const std::string& error_message, + const T& error_details) { + ErrorInternal(error_code, error_message, &error_details); + } + + // Consumes an error event. + void Error(const std::string& error_code, + const std::string& error_message = "") { + ErrorInternal(error_code, error_message, nullptr); + } + + // Consumes end of stream. Ensuing calls to Success() or + // Error(), if any, are ignored. + void EndOfStream() { EndOfStreamInternal(); } + + protected: + // Implementation of the public interface, to be provided by subclasses. + virtual void SuccessInternal(const T* event = nullptr) = 0; + + // Implementation of the public interface, to be provided by subclasses. + virtual void ErrorInternal(const std::string& error_code, + const std::string& error_message, + const T* error_details) = 0; + + // Implementation of the public interface, to be provided by subclasses. + virtual void EndOfStreamInternal() = 0; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_EVENT_SINK_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/event_stream_handler.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/event_stream_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..166733dd0661b95c82080ddf85d41d11f1e1e96f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/event_stream_handler.h @@ -0,0 +1,77 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_EVENT_STREAM_HANDLER_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_EVENT_STREAM_HANDLER_H_ + +#include +#include + +#include "event_sink.h" + +namespace flutter { + +class EncodableValue; + +template +struct StreamHandlerError { + const std::string error_code; + const std::string error_message; + const std::unique_ptr error_details; + + StreamHandlerError(const std::string& error_code, + const std::string& error_message, + std::unique_ptr&& error_details) + : error_code(error_code), + error_message(error_message), + error_details(std::move(error_details)) {} +}; + +// Handler for stream setup and teardown requests. +// Implementations must be prepared to accept sequences of alternating calls to +// OnListen() and OnCancel(). Implementations should ideally consume no +// resources when the last such call is not OnListen(). In typical situations, +// this means that the implementation should register itself with +// platform-specific event sources OnListen() and deregister again OnCancel(). +template +class StreamHandler { + public: + StreamHandler() = default; + virtual ~StreamHandler() = default; + + // Prevent copying. + StreamHandler(StreamHandler const&) = delete; + StreamHandler& operator=(StreamHandler const&) = delete; + + // Handles a request to set up an event stream. Returns nullptr on success, + // or an error on failure. + // |arguments| is stream configuration arguments and + // |events| is an EventSink for emitting events to the Flutter receiver. + std::unique_ptr> OnListen( + const T* arguments, + std::unique_ptr>&& events) { + return OnListenInternal(arguments, std::move(events)); + } + + // Handles a request to tear down the most recently created event stream. + // Returns nullptr on success, or an error on failure. + // |arguments| is stream configuration arguments. + std::unique_ptr> OnCancel(const T* arguments) { + return OnCancelInternal(arguments); + } + + protected: + // Implementation of the public interface, to be provided by subclasses. + virtual std::unique_ptr> OnListenInternal( + const T* arguments, + std::unique_ptr>&& events) = 0; + + // Implementation of the public interface, to be provided by subclasses. + virtual std::unique_ptr> OnCancelInternal( + const T* arguments) = 0; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_EVENT_STREAM_HANDLER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/event_stream_handler_functions.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/event_stream_handler_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..fde4ce4410d2572c08cf3f6d13f4babefea19622 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/event_stream_handler_functions.h @@ -0,0 +1,78 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_EVENT_STREAM_HANDLER_FUNCTIONS_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_EVENT_STREAM_HANDLER_FUNCTIONS_H_ + +#include + +#include "event_sink.h" +#include "event_stream_handler.h" + +namespace flutter { + +class EncodableValue; + +// Handler types for each of the StreamHandler setup and teardown +// requests. +template +using StreamHandlerListen = + std::function>( + const T* arguments, + std::unique_ptr>&& events)>; + +template +using StreamHandlerCancel = + std::function>(const T* arguments)>; + +// An implementation of StreamHandler that pass calls through to +// provided function objects. +template +class StreamHandlerFunctions : public StreamHandler { + public: + // Creates a handler object that calls the provided functions + // for the corresponding StreamHandler outcomes. + StreamHandlerFunctions(StreamHandlerListen on_listen, + StreamHandlerCancel on_cancel) + : on_listen_(on_listen), on_cancel_(on_cancel) {} + + virtual ~StreamHandlerFunctions() = default; + + // Prevent copying. + StreamHandlerFunctions(StreamHandlerFunctions const&) = delete; + StreamHandlerFunctions& operator=(StreamHandlerFunctions const&) = delete; + + protected: + // |flutter::StreamHandler| + std::unique_ptr> OnListenInternal( + const T* arguments, + std::unique_ptr>&& events) override { + if (on_listen_) { + return on_listen_(arguments, std::move(events)); + } + + auto error = std::make_unique>( + "error", "No OnListen handler set", nullptr); + return std::move(error); + } + + // |flutter::StreamHandler| + std::unique_ptr> OnCancelInternal( + const T* arguments) override { + if (on_cancel_) { + return on_cancel_(arguments); + } + + auto error = std::make_unique>( + "error", "No OnCancel handler set", nullptr); + return std::move(error); + } + + StreamHandlerListen on_listen_; + StreamHandlerCancel on_cancel_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_EVENT_STREAM_HANDLER_FUNCTIONS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/message_codec.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/message_codec.h new file mode 100644 index 0000000000000000000000000000000000000000..c84d25f2415b33e211bbb740c44b0333f3a51f35 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/message_codec.h @@ -0,0 +1,62 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_MESSAGE_CODEC_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_MESSAGE_CODEC_H_ + +#include +#include +#include + +namespace flutter { + +// Translates between a binary message and higher-level method call and +// response/error objects. +template +class MessageCodec { + public: + MessageCodec() = default; + + virtual ~MessageCodec() = default; + + // Prevent copying. + MessageCodec(MessageCodec const&) = delete; + MessageCodec& operator=(MessageCodec const&) = delete; + + // Returns the message encoded in |binary_message|, or nullptr if it cannot be + // decoded by this codec. + std::unique_ptr DecodeMessage(const uint8_t* binary_message, + const size_t message_size) const { + return std::move(DecodeMessageInternal(binary_message, message_size)); + } + + // Returns the message encoded in |binary_message|, or nullptr if it cannot be + // decoded by this codec. + std::unique_ptr DecodeMessage( + const std::vector& binary_message) const { + size_t size = binary_message.size(); + const uint8_t* data = size > 0 ? &binary_message[0] : nullptr; + return std::move(DecodeMessageInternal(data, size)); + } + + // Returns a binary encoding of the given |message|, or nullptr if the + // message cannot be serialized by this codec. + std::unique_ptr> EncodeMessage(const T& message) const { + return std::move(EncodeMessageInternal(message)); + } + + protected: + // Implementation of the public interface, to be provided by subclasses. + virtual std::unique_ptr DecodeMessageInternal( + const uint8_t* binary_message, + const size_t message_size) const = 0; + + // Implementation of the public interface, to be provided by subclasses. + virtual std::unique_ptr> EncodeMessageInternal( + const T& message) const = 0; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_MESSAGE_CODEC_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/method_call.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/method_call.h new file mode 100644 index 0000000000000000000000000000000000000000..3ddf71cefa7f48964078cb927d5b0cec24e80240 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/method_call.h @@ -0,0 +1,43 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_CALL_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_CALL_H_ + +#include +#include + +namespace flutter { + +class EncodableValue; + +// An object encapsulating a method call from Flutter whose arguments are of +// type T. +template +class MethodCall { + public: + // Creates a MethodCall with the given name and arguments. + MethodCall(const std::string& method_name, std::unique_ptr arguments) + : method_name_(method_name), arguments_(std::move(arguments)) {} + + virtual ~MethodCall() = default; + + // Prevent copying. + MethodCall(MethodCall const&) = delete; + MethodCall& operator=(MethodCall const&) = delete; + + // The name of the method being called. + const std::string& method_name() const { return method_name_; } + + // The arguments to the method call, or NULL if there are none. + const T* arguments() const { return arguments_.get(); } + + private: + std::string method_name_; + std::unique_ptr arguments_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_CALL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/method_channel.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/method_channel.h new file mode 100644 index 0000000000000000000000000000000000000000..a4029fccf7a5c1da51dcdabf13aacff0074428e7 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/method_channel.h @@ -0,0 +1,151 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_CHANNEL_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_CHANNEL_H_ + +#include +#include + +#include "basic_message_channel.h" +#include "binary_messenger.h" +#include "engine_method_result.h" +#include "method_call.h" +#include "method_codec.h" +#include "method_result.h" + +namespace flutter { + +class EncodableValue; + +// A handler for receiving a method call from the Flutter engine. +// +// Implementations must asynchronously call exactly one of the methods on +// |result| to indicate the result of the method call. +template +using MethodCallHandler = + std::function& call, + std::unique_ptr> result)>; + +// A channel for communicating with the Flutter engine using invocation of +// asynchronous methods. +template +class MethodChannel { + public: + // Creates an instance that sends and receives method calls on the channel + // named |name|, encoded with |codec| and dispatched via |messenger|. + MethodChannel(BinaryMessenger* messenger, + const std::string& name, + const MethodCodec* codec) + : messenger_(messenger), name_(name), codec_(codec) {} + + ~MethodChannel() = default; + + // Prevent copying. + MethodChannel(MethodChannel const&) = delete; + MethodChannel& operator=(MethodChannel const&) = delete; + + // Sends a message to the Flutter engine on this channel. + // + // If |result| is provided, one of its methods will be invoked with the + // response from the engine. + void InvokeMethod(const std::string& method, + std::unique_ptr arguments, + std::unique_ptr> result = nullptr) { + MethodCall method_call(method, std::move(arguments)); + std::unique_ptr> message = + codec_->EncodeMethodCall(method_call); + if (!result) { + messenger_->Send(name_, message->data(), message->size(), nullptr); + return; + } + + // std::function requires a copyable lambda, so convert to a shared pointer. + // This is safe since only one copy of the shared_pointer will ever be + // accessed. + std::shared_ptr> shared_result(result.release()); + const auto* codec = codec_; + std::string channel_name = name_; + BinaryReply reply_handler = [shared_result, codec, channel_name]( + const uint8_t* reply, size_t reply_size) { + if (reply_size == 0) { + shared_result->NotImplemented(); + return; + } + // Use this channel's codec to decode and handle the + // reply. + bool decoded = codec->DecodeAndProcessResponseEnvelope( + reply, reply_size, shared_result.get()); + if (!decoded) { + std::cerr << "Unable to decode reply to method " + "invocation on channel " + << channel_name << std::endl; + shared_result->NotImplemented(); + } + }; + + messenger_->Send(name_, message->data(), message->size(), + std::move(reply_handler)); + } + + // Registers a handler that should be called any time a method call is + // received on this channel. A null handler will remove any previous handler. + // + // The handler will be owned by the underlying BinaryMessageHandler. + // Destroying the MethodChannel will not unregister the handler, so + // the caller is responsible for unregistering explicitly if the handler + // stops being valid before the engine is destroyed. + void SetMethodCallHandler(MethodCallHandler handler) const { + if (!handler) { + messenger_->SetMessageHandler(name_, nullptr); + return; + } + const auto* codec = codec_; + std::string channel_name = name_; + BinaryMessageHandler binary_handler = [handler, codec, channel_name]( + const uint8_t* message, + size_t message_size, + BinaryReply reply) { + // Use this channel's codec to decode the call and build a result handler. + auto result = + std::make_unique>(std::move(reply), codec); + std::unique_ptr> method_call = + codec->DecodeMethodCall(message, message_size); + if (!method_call) { + std::cerr << "Unable to construct method call from message on channel " + << channel_name << std::endl; + result->NotImplemented(); + return; + } + handler(*method_call, std::move(result)); + }; + messenger_->SetMessageHandler(name_, std::move(binary_handler)); + } + + // Adjusts the number of messages that will get buffered when sending messages + // to channels that aren't fully set up yet. For example, the engine isn't + // running yet or the channel's message handler isn't set up on the Dart side + // yet. + void Resize(int new_size) { + internal::ResizeChannel(messenger_, name_, new_size); + } + + // Defines whether the channel should show warning messages when discarding + // messages due to overflow. + // + // When |warns| is false, the channel is expected to overflow and warning + // messages will not be shown. + void SetWarnsOnOverflow(bool warns) { + internal::SetChannelWarnsOnOverflow(messenger_, name_, warns); + } + + private: + BinaryMessenger* messenger_; + std::string name_; + const MethodCodec* codec_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_CHANNEL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/method_codec.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/method_codec.h new file mode 100644 index 0000000000000000000000000000000000000000..b40fa640c929563d7f3c68dcd012f9d59705abb6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/method_codec.h @@ -0,0 +1,111 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_CODEC_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_CODEC_H_ + +#include +#include +#include + +#include "method_call.h" +#include "method_result.h" + +namespace flutter { + +// Translates between a binary message and higher-level method call and +// response/error objects. +template +class MethodCodec { + public: + MethodCodec() = default; + + virtual ~MethodCodec() = default; + + // Prevent copying. + MethodCodec(MethodCodec const&) = delete; + MethodCodec& operator=(MethodCodec const&) = delete; + + // Returns the MethodCall encoded in |message|, or nullptr if it cannot be + // decoded. + std::unique_ptr> DecodeMethodCall(const uint8_t* message, + size_t message_size) const { + return std::move(DecodeMethodCallInternal(message, message_size)); + } + + // Returns the MethodCall encoded in |message|, or nullptr if it cannot be + // decoded. + std::unique_ptr> DecodeMethodCall( + const std::vector& message) const { + size_t size = message.size(); + const uint8_t* data = size > 0 ? &message[0] : nullptr; + return std::move(DecodeMethodCallInternal(data, size)); + } + + // Returns a binary encoding of the given |method_call|, or nullptr if the + // method call cannot be serialized by this codec. + std::unique_ptr> EncodeMethodCall( + const MethodCall& method_call) const { + return std::move(EncodeMethodCallInternal(method_call)); + } + + // Returns a binary encoding of |result|. |result| must be a type supported + // by the codec. + std::unique_ptr> EncodeSuccessEnvelope( + const T* result = nullptr) const { + return std::move(EncodeSuccessEnvelopeInternal(result)); + } + + // Returns a binary encoding of |error|. The |error_details| must be a type + // supported by the codec. + std::unique_ptr> EncodeErrorEnvelope( + const std::string& error_code, + const std::string& error_message = "", + const T* error_details = nullptr) const { + return std::move( + EncodeErrorEnvelopeInternal(error_code, error_message, error_details)); + } + + // Decodes the response envelope encoded in |response|, calling the + // appropriate method on |result|. + // + // Returns false if |response| cannot be decoded. In that case the caller is + // responsible for calling a |result| method. + bool DecodeAndProcessResponseEnvelope(const uint8_t* response, + size_t response_size, + MethodResult* result) const { + return DecodeAndProcessResponseEnvelopeInternal(response, response_size, + result); + } + + protected: + // Implementation of the public interface, to be provided by subclasses. + virtual std::unique_ptr> DecodeMethodCallInternal( + const uint8_t* message, + size_t message_size) const = 0; + + // Implementation of the public interface, to be provided by subclasses. + virtual std::unique_ptr> EncodeMethodCallInternal( + const MethodCall& method_call) const = 0; + + // Implementation of the public interface, to be provided by subclasses. + virtual std::unique_ptr> EncodeSuccessEnvelopeInternal( + const T* result) const = 0; + + // Implementation of the public interface, to be provided by subclasses. + virtual std::unique_ptr> EncodeErrorEnvelopeInternal( + const std::string& error_code, + const std::string& error_message, + const T* error_details) const = 0; + + // Implementation of the public interface, to be provided by subclasses. + virtual bool DecodeAndProcessResponseEnvelopeInternal( + const uint8_t* response, + size_t response_size, + MethodResult* result) const = 0; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_CODEC_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/method_result.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/method_result.h new file mode 100644 index 0000000000000000000000000000000000000000..05c7fe96874b78c48e464ea76e0b046519e00288 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/method_result.h @@ -0,0 +1,76 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_RESULT_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_RESULT_H_ + +#include + +namespace flutter { + +class EncodableValue; + +// Encapsulates a result returned from a MethodCall. Only one method should be +// called on any given instance. +template +class MethodResult { + public: + MethodResult() = default; + + virtual ~MethodResult() = default; + + // Prevent copying. + MethodResult(MethodResult const&) = delete; + MethodResult& operator=(MethodResult const&) = delete; + + // Sends a success response, indicating that the call completed successfully + // with the given result. + void Success(const T& result) { SuccessInternal(&result); } + + // Sends a success response, indicating that the call completed successfully + // with no result. + void Success() { SuccessInternal(nullptr); } + + // Sends an error response, indicating that the call was understood but + // handling failed in some way. + // + // error_code: A string error code describing the error. + // error_message: A user-readable error message. + // error_details: Arbitrary extra details about the error. + void Error(const std::string& error_code, + const std::string& error_message, + const T& error_details) { + ErrorInternal(error_code, error_message, &error_details); + } + + // Sends an error response, indicating that the call was understood but + // handling failed in some way. + // + // error_code: A string error code describing the error. + // error_message: A user-readable error message (optional). + void Error(const std::string& error_code, + const std::string& error_message = "") { + ErrorInternal(error_code, error_message, nullptr); + } + + // Sends a not-implemented response, indicating that the method either was not + // recognized, or has not been implemented. + void NotImplemented() { NotImplementedInternal(); } + + protected: + // Implementation of the public interface, to be provided by subclasses. + virtual void SuccessInternal(const T* result) = 0; + + // Implementation of the public interface, to be provided by subclasses. + virtual void ErrorInternal(const std::string& error_code, + const std::string& error_message, + const T* error_details) = 0; + + // Implementation of the public interface, to be provided by subclasses. + virtual void NotImplementedInternal() = 0; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_RESULT_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/method_result_functions.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/method_result_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..57f6d0e9b88629ba3b4a25aadeb61c70faa1a788 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/method_result_functions.h @@ -0,0 +1,80 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_RESULT_FUNCTIONS_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_RESULT_FUNCTIONS_H_ + +#include +#include +#include + +#include "method_result.h" + +namespace flutter { + +class EncodableValue; + +// Handler types for each of the MethodResult outcomes. +template +using ResultHandlerSuccess = std::function; +template +using ResultHandlerError = std::function; +template +using ResultHandlerNotImplemented = std::function; + +// An implementation of MethodResult that pass calls through to provided +// function objects, for ease of constructing one-off result handlers. +template +class MethodResultFunctions : public MethodResult { + public: + // Creates a result object that calls the provided functions for the + // corresponding MethodResult outcomes. + MethodResultFunctions(ResultHandlerSuccess on_success, + ResultHandlerError on_error, + ResultHandlerNotImplemented on_not_implemented) + : on_success_(on_success), + on_error_(on_error), + on_not_implemented_(std::move(on_not_implemented)) {} + + virtual ~MethodResultFunctions() = default; + + // Prevent copying. + MethodResultFunctions(MethodResultFunctions const&) = delete; + MethodResultFunctions& operator=(MethodResultFunctions const&) = delete; + + protected: + // |flutter::MethodResult| + void SuccessInternal(const T* result) override { + if (on_success_) { + on_success_(result); + } + } + + // |flutter::MethodResult| + void ErrorInternal(const std::string& error_code, + const std::string& error_message, + const T* error_details) override { + if (on_error_) { + on_error_(error_code, error_message, error_details); + } + } + + // |flutter::MethodResult| + void NotImplementedInternal() override { + if (on_not_implemented_) { + on_not_implemented_(); + } + } + + private: + ResultHandlerSuccess on_success_; + ResultHandlerError on_error_; + ResultHandlerNotImplemented on_not_implemented_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_RESULT_FUNCTIONS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/plugin_registrar.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/plugin_registrar.h new file mode 100644 index 0000000000000000000000000000000000000000..e21f472b6be0a5d5a64e057e05e845e26662699d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/plugin_registrar.h @@ -0,0 +1,131 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRAR_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRAR_H_ + +#include + +#include +#include +#include +#include + +#include "binary_messenger.h" +#include "texture_registrar.h" + +namespace flutter { + +class Plugin; + +// A object managing the registration of a plugin for various events. +// +// Currently this class has very limited functionality, but is expected to +// expand over time to more closely match the functionality of +// the Flutter mobile plugin APIs' plugin registrars. +class PluginRegistrar { + public: + // Creates a new PluginRegistrar. |core_registrar| and the messenger it + // provides must remain valid as long as this object exists. + explicit PluginRegistrar(FlutterDesktopPluginRegistrarRef core_registrar); + + virtual ~PluginRegistrar(); + + // Prevent copying. + PluginRegistrar(PluginRegistrar const&) = delete; + PluginRegistrar& operator=(PluginRegistrar const&) = delete; + + // Returns the messenger to use for creating channels to communicate with the + // Flutter engine. + // + // This pointer will remain valid for the lifetime of this instance. + BinaryMessenger* messenger() { return messenger_.get(); } + + // Returns the texture registrar to use for the plugin to render a pixel + // buffer. + TextureRegistrar* texture_registrar() { return texture_registrar_.get(); } + + // Takes ownership of |plugin|. + // + // Plugins are not required to call this method if they have other lifetime + // management, but this is a convenient place for plugins to be owned to + // ensure that they stay valid for any registered callbacks. + void AddPlugin(std::unique_ptr plugin); + + protected: + FlutterDesktopPluginRegistrarRef registrar() const { return registrar_; } + + // Destroys all owned plugins. Subclasses should call this at the beginning of + // their destructors to prevent the possibility of an owned plugin trying to + // access destroyed state during its own destruction. + void ClearPlugins(); + + private: + // Handle for interacting with the C API's registrar. + FlutterDesktopPluginRegistrarRef registrar_; + + std::unique_ptr messenger_; + + std::unique_ptr texture_registrar_; + + // Plugins registered for ownership. + std::set> plugins_; +}; + +// A plugin that can be registered for ownership by a PluginRegistrar. +class Plugin { + public: + virtual ~Plugin() = default; +}; + +// A singleton to own PluginRegistrars. This is intended for use in plugins, +// where there is no higher-level object to own a PluginRegistrar that can +// own plugin instances and ensure that they live as long as the engine they +// are registered with. +class PluginRegistrarManager { + public: + static PluginRegistrarManager* GetInstance(); + + // Prevent copying. + PluginRegistrarManager(PluginRegistrarManager const&) = delete; + PluginRegistrarManager& operator=(PluginRegistrarManager const&) = delete; + + // Returns a plugin registrar wrapper of type T, which must be a kind of + // PluginRegistrar, creating it if necessary. The returned registrar will + // live as long as the underlying FlutterDesktopPluginRegistrarRef, so + // can be used to own plugin instances. + // + // Calling this multiple times for the same registrar_ref with different + // template types results in undefined behavior. + template + T* GetRegistrar(FlutterDesktopPluginRegistrarRef registrar_ref) { + auto insert_result = + registrars_.emplace(registrar_ref, std::make_unique(registrar_ref)); + auto& registrar_pair = *(insert_result.first); + FlutterDesktopPluginRegistrarSetDestructionHandler(registrar_pair.first, + OnRegistrarDestroyed); + return static_cast(registrar_pair.second.get()); + } + + // Destroys all registrar wrappers created by the manager. + // + // This is intended primarily for use in tests. + void Reset() { registrars_.clear(); } + + private: + PluginRegistrarManager(); + + using WrapperMap = std::map>; + + static void OnRegistrarDestroyed(FlutterDesktopPluginRegistrarRef registrar); + + WrapperMap* registrars() { return ®istrars_; } + + WrapperMap registrars_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRAR_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/plugin_registry.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/plugin_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..ffc548b4140980d8d985628394f65840c620235c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/plugin_registry.h @@ -0,0 +1,37 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRY_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRY_H_ + +#include + +#include + +namespace flutter { + +// Vends PluginRegistrars for named plugins. +// +// Plugins are identified by unique string keys, typically the name of the +// plugin's main class. +class PluginRegistry { + public: + PluginRegistry() = default; + virtual ~PluginRegistry() = default; + + // Prevent copying. + PluginRegistry(PluginRegistry const&) = delete; + PluginRegistry& operator=(PluginRegistry const&) = delete; + + // Returns the FlutterDesktopPluginRegistrarRef to register a plugin with the + // given name. + // + // The name must be unique across the application. + virtual FlutterDesktopPluginRegistrarRef GetRegistrarForPlugin( + const std::string& plugin_name) = 0; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRY_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/standard_codec_serializer.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/standard_codec_serializer.h new file mode 100644 index 0000000000000000000000000000000000000000..a6001037f9e481f51a34f718be2fd0e1658393d5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/standard_codec_serializer.h @@ -0,0 +1,76 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_STANDARD_CODEC_SERIALIZER_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_STANDARD_CODEC_SERIALIZER_H_ + +#include "byte_streams.h" +#include "encodable_value.h" + +namespace flutter { + +// Encapsulates the logic for encoding/decoding EncodableValues to/from the +// standard codec binary representation. +// +// This can be subclassed to extend the standard codec with support for new +// types. +class StandardCodecSerializer { + public: + virtual ~StandardCodecSerializer(); + + // Returns the shared serializer instance. + static const StandardCodecSerializer& GetInstance(); + + // Prevent copying. + StandardCodecSerializer(StandardCodecSerializer const&) = delete; + StandardCodecSerializer& operator=(StandardCodecSerializer const&) = delete; + + // Reads and returns the next value from |stream|. + EncodableValue ReadValue(ByteStreamReader* stream) const; + + // Writes the encoding of |value| to |stream|, including the initial type + // discrimination byte. + // + // Can be overridden by a subclass to extend the codec. + virtual void WriteValue(const EncodableValue& value, + ByteStreamWriter* stream) const; + + protected: + // Codecs require long-lived serializers, so clients should always use + // GetInstance(). + StandardCodecSerializer(); + + // Reads and returns the next value from |stream|, whose discrimination byte + // was |type|. + // + // The discrimination byte will already have been read from the stream when + // this is called. + // + // Can be overridden by a subclass to extend the codec. + virtual EncodableValue ReadValueOfType(uint8_t type, + ByteStreamReader* stream) const; + + // Reads the variable-length size from the current position in |stream|. + size_t ReadSize(ByteStreamReader* stream) const; + + // Writes the variable-length size encoding to |stream|. + void WriteSize(size_t size, ByteStreamWriter* stream) const; + + private: + // Reads a fixed-type list whose values are of type T from the current + // position in |stream|, and returns it as the corresponding EncodableValue. + // |T| must correspond to one of the supported list value types of + // EncodableValue. + template + EncodableValue ReadVector(ByteStreamReader* stream) const; + + // Writes |vector| to |stream| as a fixed-type list. |T| must correspond to + // one of the supported list value types of EncodableValue. + template + void WriteVector(const std::vector vector, ByteStreamWriter* stream) const; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_STANDARD_CODEC_SERIALIZER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/standard_message_codec.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/standard_message_codec.h new file mode 100644 index 0000000000000000000000000000000000000000..568b3917b3c29590b7bdc0ec79b3ee3728570b22 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/standard_message_codec.h @@ -0,0 +1,57 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_STANDARD_MESSAGE_CODEC_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_STANDARD_MESSAGE_CODEC_H_ + +#include + +#include "encodable_value.h" +#include "message_codec.h" +#include "standard_codec_serializer.h" + +namespace flutter { + +// A binary message encoding/decoding mechanism for communications to/from the +// Flutter engine via message channels. +class StandardMessageCodec : public MessageCodec { + public: + // Returns an instance of the codec, optionally using a custom serializer to + // add support for more types. + // + // If provided, |serializer| must be long-lived. If no serializer is provided, + // the default will be used. + // + // The instance returned for a given |serializer| will be shared, and + // any instance returned from this will be long-lived, and can be safely + // passed to, e.g., channel constructors. + static const StandardMessageCodec& GetInstance( + const StandardCodecSerializer* serializer = nullptr); + + ~StandardMessageCodec(); + + // Prevent copying. + StandardMessageCodec(StandardMessageCodec const&) = delete; + StandardMessageCodec& operator=(StandardMessageCodec const&) = delete; + + protected: + // |flutter::MessageCodec| + std::unique_ptr DecodeMessageInternal( + const uint8_t* binary_message, + const size_t message_size) const override; + + // |flutter::MessageCodec| + std::unique_ptr> EncodeMessageInternal( + const EncodableValue& message) const override; + + private: + // Instances should be obtained via GetInstance. + explicit StandardMessageCodec(const StandardCodecSerializer* serializer); + + const StandardCodecSerializer* serializer_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_STANDARD_MESSAGE_CODEC_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/standard_method_codec.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/standard_method_codec.h new file mode 100644 index 0000000000000000000000000000000000000000..b6db35ec97ceafd3a6ad93965bdb94d1087dcb5a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/standard_method_codec.h @@ -0,0 +1,73 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_STANDARD_METHOD_CODEC_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_STANDARD_METHOD_CODEC_H_ + +#include + +#include "encodable_value.h" +#include "method_call.h" +#include "method_codec.h" +#include "standard_codec_serializer.h" + +namespace flutter { + +// An implementation of MethodCodec that uses a binary serialization. +class StandardMethodCodec : public MethodCodec { + public: + // Returns an instance of the codec, optionally using a custom serializer to + // add support for more types. + // + // If provided, |serializer| must be long-lived. If no serializer is provided, + // the default will be used. + // + // The instance returned for a given |extension| will be shared, and + // any instance returned from this will be long-lived, and can be safely + // passed to, e.g., channel constructors. + static const StandardMethodCodec& GetInstance( + const StandardCodecSerializer* serializer = nullptr); + + ~StandardMethodCodec(); + + // Prevent copying. + StandardMethodCodec(StandardMethodCodec const&) = delete; + StandardMethodCodec& operator=(StandardMethodCodec const&) = delete; + + protected: + // |flutter::MethodCodec| + std::unique_ptr> DecodeMethodCallInternal( + const uint8_t* message, + size_t message_size) const override; + + // |flutter::MethodCodec| + std::unique_ptr> EncodeMethodCallInternal( + const MethodCall& method_call) const override; + + // |flutter::MethodCodec| + std::unique_ptr> EncodeSuccessEnvelopeInternal( + const EncodableValue* result) const override; + + // |flutter::MethodCodec| + std::unique_ptr> EncodeErrorEnvelopeInternal( + const std::string& error_code, + const std::string& error_message, + const EncodableValue* error_details) const override; + + // |flutter::MethodCodec| + bool DecodeAndProcessResponseEnvelopeInternal( + const uint8_t* response, + size_t response_size, + MethodResult* result) const override; + + private: + // Instances should be obtained via GetInstance. + explicit StandardMethodCodec(const StandardCodecSerializer* serializer); + + const StandardCodecSerializer* serializer_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_STANDARD_METHOD_CODEC_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/texture_registrar.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/texture_registrar.h new file mode 100644 index 0000000000000000000000000000000000000000..a536dcfa01b87068036741580922c95f1bd96646 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/include/flutter/texture_registrar.h @@ -0,0 +1,111 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_TEXTURE_REGISTRAR_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_TEXTURE_REGISTRAR_H_ + +#include + +#include +#include +#include +#include +#include + +namespace flutter { + +// A pixel buffer texture. +class PixelBufferTexture { + public: + // A callback used for retrieving pixel buffers. + typedef std::function + CopyBufferCallback; + + // Creates a pixel buffer texture that uses the provided |copy_buffer_cb| to + // retrieve the buffer. + // As the callback is usually invoked from the render thread, the callee must + // take care of proper synchronization. It also needs to be ensured that the + // returned buffer isn't released prior to unregistering this texture. + explicit PixelBufferTexture(CopyBufferCallback copy_buffer_callback) + : copy_buffer_callback_(std::move(copy_buffer_callback)) {} + + // Returns the callback-provided FlutterDesktopPixelBuffer that contains the + // actual pixel data. The intended surface size is specified by |width| and + // |height|. + const FlutterDesktopPixelBuffer* CopyPixelBuffer(size_t width, + size_t height) const { + return copy_buffer_callback_(width, height); + } + + private: + const CopyBufferCallback copy_buffer_callback_; +}; + +// A GPU surface-based texture. +class GpuSurfaceTexture { + public: + // A callback used for retrieving surface descriptors. + typedef std::function< + const FlutterDesktopGpuSurfaceDescriptor*(size_t width, size_t height)> + ObtainDescriptorCallback; + + GpuSurfaceTexture(FlutterDesktopGpuSurfaceType surface_type, + ObtainDescriptorCallback obtain_descriptor_callback) + : surface_type_(surface_type), + obtain_descriptor_callback_(std::move(obtain_descriptor_callback)) {} + + // Returns the callback-provided FlutterDesktopGpuSurfaceDescriptor that + // contains the surface handle. The intended surface size is specified by + // |width| and |height|. + const FlutterDesktopGpuSurfaceDescriptor* ObtainDescriptor( + size_t width, + size_t height) const { + return obtain_descriptor_callback_(width, height); + } + + // Gets the surface type. + FlutterDesktopGpuSurfaceType surface_type() const { return surface_type_; } + + private: + const FlutterDesktopGpuSurfaceType surface_type_; + const ObtainDescriptorCallback obtain_descriptor_callback_; +}; + +// The available texture variants. +// Only PixelBufferTexture is currently implemented. +// Other variants are expected to be added in the future. +typedef std::variant TextureVariant; + +// An object keeping track of external textures. +// +// Thread safety: +// It's safe to call the member methods from any thread. +class TextureRegistrar { + public: + virtual ~TextureRegistrar() = default; + + // Registers a |texture| object and returns the ID for that texture. + virtual int64_t RegisterTexture(TextureVariant* texture) = 0; + + // Notifies the flutter engine that the texture object corresponding + // to |texure_id| needs to render a new frame. + // + // For PixelBufferTextures, this will effectively make the engine invoke + // the callback that was provided upon creating the texture. + virtual bool MarkTextureFrameAvailable(int64_t texture_id) = 0; + + // Asynchronously unregisters an existing texture object. + // Upon completion, the optional |callback| gets invoked. + virtual void UnregisterTexture(int64_t texture_id, + std::function callback) = 0; + + // Unregisters an existing texture object. + // DEPRECATED: Use UnregisterTexture(texture_id, optional_callback) instead. + virtual bool UnregisterTexture(int64_t texture_id) = 0; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_TEXTURE_REGISTRAR_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/method_call_unittests.cc b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/method_call_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..19e9eb36aeb810155498399380efd4000a6f405d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/method_call_unittests.cc @@ -0,0 +1,23 @@ +// 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/shell/platform/common/client_wrapper/include/flutter/method_call.h" + +#include +#include + +#include "gtest/gtest.h" + +namespace flutter { + +TEST(MethodCallTest, Basic) { + const std::string method_name("method_name"); + const int argument = 42; + MethodCall method_call(method_name, std::make_unique(argument)); + EXPECT_EQ(method_call.method_name(), method_name); + ASSERT_NE(method_call.arguments(), nullptr); + EXPECT_EQ(*method_call.arguments(), 42); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/method_channel_unittests.cc b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/method_channel_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..2edce72a566c6aa2c47cbd07507ae232ed6fa59f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/method_channel_unittests.cc @@ -0,0 +1,225 @@ +// 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/shell/platform/common/client_wrapper/include/flutter/method_channel.h" + +#include +#include + +#include "flutter/shell/platform/common/client_wrapper/include/flutter/binary_messenger.h" +#include "flutter/shell/platform/common/client_wrapper/include/flutter/method_result_functions.h" +#include "flutter/shell/platform/common/client_wrapper/include/flutter/standard_method_codec.h" +#include "gtest/gtest.h" + +namespace flutter { + +namespace { + +class TestBinaryMessenger : public BinaryMessenger { + public: + void Send(const std::string& channel, + const uint8_t* message, + size_t message_size, + BinaryReply reply) const override { + send_called_ = true; + last_reply_handler_ = reply; + int length = static_cast(message_size); + last_message_ = + std::vector(message, message + length * sizeof(uint8_t)); + } + + void SetMessageHandler(const std::string& channel, + BinaryMessageHandler handler) override { + last_message_handler_channel_ = channel; + last_message_handler_ = handler; + } + + bool send_called() { return send_called_; } + + BinaryReply last_reply_handler() { return last_reply_handler_; } + + std::string last_message_handler_channel() { + return last_message_handler_channel_; + } + + BinaryMessageHandler last_message_handler() { return last_message_handler_; } + + std::vector last_message() { return last_message_; } + + private: + mutable bool send_called_ = false; + mutable BinaryReply last_reply_handler_; + std::string last_message_handler_channel_; + BinaryMessageHandler last_message_handler_; + mutable std::vector last_message_; +}; + +} // namespace + +// Tests that SetMethodCallHandler sets a handler that correctly interacts with +// the binary messenger. +TEST(MethodChannelTest, Registration) { + TestBinaryMessenger messenger; + const std::string channel_name("some_channel"); + const StandardMethodCodec& codec = StandardMethodCodec::GetInstance(); + MethodChannel channel(&messenger, channel_name, &codec); + + bool callback_called = false; + const std::string method_name("hello"); + channel.SetMethodCallHandler( + [&callback_called, method_name](const auto& call, auto result) { + callback_called = true; + // Ensure that the wrapper received a correctly decoded call and a + // result. + EXPECT_EQ(call.method_name(), method_name); + EXPECT_NE(result, nullptr); + result->Success(); + }); + EXPECT_EQ(messenger.last_message_handler_channel(), channel_name); + EXPECT_NE(messenger.last_message_handler(), nullptr); + // Send a test message to trigger the handler test assertions. + MethodCall<> call(method_name, nullptr); + auto message = codec.EncodeMethodCall(call); + + messenger.last_message_handler()( + message->data(), message->size(), + [](const uint8_t* reply, size_t reply_size) {}); + EXPECT_TRUE(callback_called); +} + +// Tests that SetMethodCallHandler with a null handler unregisters the handler. +TEST(MethodChannelTest, Unregistration) { + TestBinaryMessenger messenger; + const std::string channel_name("some_channel"); + MethodChannel channel(&messenger, channel_name, + &StandardMethodCodec::GetInstance()); + + channel.SetMethodCallHandler([](const auto& call, auto result) {}); + EXPECT_EQ(messenger.last_message_handler_channel(), channel_name); + EXPECT_NE(messenger.last_message_handler(), nullptr); + + channel.SetMethodCallHandler(nullptr); + EXPECT_EQ(messenger.last_message_handler_channel(), channel_name); + EXPECT_EQ(messenger.last_message_handler(), nullptr); +} + +TEST(MethodChannelTest, InvokeWithoutResponse) { + TestBinaryMessenger messenger; + const std::string channel_name("some_channel"); + MethodChannel channel(&messenger, channel_name, + &StandardMethodCodec::GetInstance()); + + channel.InvokeMethod("foo", nullptr); + EXPECT_TRUE(messenger.send_called()); + EXPECT_EQ(messenger.last_reply_handler(), nullptr); +} + +TEST(MethodChannelTest, InvokeWithResponse) { + TestBinaryMessenger messenger; + const std::string channel_name("some_channel"); + MethodChannel channel(&messenger, channel_name, + &StandardMethodCodec::GetInstance()); + + bool received_reply = false; + const std::string reply = "bar"; + auto result_handler = std::make_unique>( + [&received_reply, reply](const EncodableValue* success_value) { + received_reply = true; + EXPECT_EQ(std::get(*success_value), reply); + }, + nullptr, nullptr); + + channel.InvokeMethod("foo", nullptr, std::move(result_handler)); + EXPECT_TRUE(messenger.send_called()); + ASSERT_NE(messenger.last_reply_handler(), nullptr); + + // Call the underlying reply handler to ensure it's processed correctly. + EncodableValue reply_value(reply); + std::unique_ptr> encoded_reply = + StandardMethodCodec::GetInstance().EncodeSuccessEnvelope(&reply_value); + messenger.last_reply_handler()(encoded_reply->data(), encoded_reply->size()); + EXPECT_TRUE(received_reply); +} + +TEST(MethodChannelTest, InvokeNotImplemented) { + TestBinaryMessenger messenger; + const std::string channel_name("some_channel"); + MethodChannel channel(&messenger, channel_name, + &StandardMethodCodec::GetInstance()); + + bool received_not_implemented = false; + auto result_handler = std::make_unique>( + nullptr, nullptr, + [&received_not_implemented]() { received_not_implemented = true; }); + + channel.InvokeMethod("foo", nullptr, std::move(result_handler)); + EXPECT_EQ(messenger.send_called(), true); + ASSERT_NE(messenger.last_reply_handler(), nullptr); + + // Call the underlying reply handler to ensure it's reported as unimplemented. + messenger.last_reply_handler()(nullptr, 0); + EXPECT_TRUE(received_not_implemented); +} + +// Tests that calling Resize generates the binary message expected by the Dart +// implementation. +TEST(MethodChannelTest, Resize) { + TestBinaryMessenger messenger; + const std::string channel_name("flutter/test"); + MethodChannel channel(&messenger, channel_name, + &StandardMethodCodec::GetInstance()); + + channel.Resize(3); + + // Because the Dart implementation for the control channel implements its own + // custom deserialization logic, this test compares the generated bytes array + // to the expected one (for instance, the deserialization logic expects the + // size parameter of the resize method call to be an uint32). + // + // The expected content was created from the following Dart code: + // MethodCall call = MethodCall('resize', ['flutter/test',3]); + // StandardMethodCodec().encodeMethodCall(call).buffer.asUint8List(); + const int expected_message_size = 29; + + EXPECT_EQ(messenger.send_called(), true); + EXPECT_EQ(static_cast(messenger.last_message().size()), + expected_message_size); + + int expected[expected_message_size] = { + 7, 6, 114, 101, 115, 105, 122, 101, 12, 2, 7, 12, 102, 108, 117, + 116, 116, 101, 114, 47, 116, 101, 115, 116, 3, 3, 0, 0, 0}; + for (int i = 0; i < expected_message_size; i++) { + EXPECT_EQ(messenger.last_message()[i], expected[i]); + } +} + +// Tests that calling SetWarnsOnOverflow generates the binary message expected +// by the Dart implementation. +TEST(MethodChannelTest, SetWarnsOnOverflow) { + TestBinaryMessenger messenger; + + const std::string channel_name("flutter/test"); + MethodChannel channel(&messenger, channel_name, + &StandardMethodCodec::GetInstance()); + + channel.SetWarnsOnOverflow(false); + + // The expected content was created from the following Dart code: + // MethodCall call = MethodCall('overflow',['flutter/test', true]); + // StandardMethodCodec().encodeMethodCall(call).buffer.asUint8List(); + const int expected_message_size = 27; + + EXPECT_EQ(messenger.send_called(), true); + EXPECT_EQ(static_cast(messenger.last_message().size()), + expected_message_size); + + int expected[expected_message_size] = { + 7, 8, 111, 118, 101, 114, 102, 108, 111, 119, 12, 2, 7, 12, + 102, 108, 117, 116, 116, 101, 114, 47, 116, 101, 115, 116, 1}; + for (int i = 0; i < expected_message_size; i++) { + EXPECT_EQ(messenger.last_message()[i], expected[i]); + } +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/method_result_functions_unittests.cc b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/method_result_functions_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..199a90265b899c2a3756ed558fb0547a3fa57d7c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/method_result_functions_unittests.cc @@ -0,0 +1,66 @@ +// 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/shell/platform/common/client_wrapper/include/flutter/method_result_functions.h" + +#include +#include + +#include "gtest/gtest.h" + +namespace flutter { + +// Tests that unset handlers don't cause crashes. +TEST(MethodChannelTest, NoHandlers) { + MethodResultFunctions result(nullptr, nullptr, nullptr); + result.Success(); + result.Error("error"); + result.NotImplemented(); +} + +// Tests that Success calls through to handler. +TEST(MethodChannelTest, Success) { + bool called = false; + int value = 1; + MethodResultFunctions result( + [&called, value](const int* i) { + called = true; + EXPECT_EQ(*i, value); + }, + nullptr, nullptr); + result.Success(value); + EXPECT_TRUE(called); +} + +// Tests that Error calls through to handler. +TEST(MethodChannelTest, Error) { + bool called = false; + std::string error_code = "a"; + std::string error_message = "b"; + int error_details = 1; + MethodResultFunctions result( + nullptr, + [&called, error_code, error_message, error_details]( + const std::string& code, const std::string& message, + const int* details) { + called = true; + EXPECT_EQ(code, error_code); + EXPECT_EQ(message, error_message); + EXPECT_EQ(*details, error_details); + }, + nullptr); + result.Error(error_code, error_message, error_details); + EXPECT_TRUE(called); +} + +// Tests that NotImplemented calls through to handler. +TEST(MethodChannelTest, NotImplemented) { + bool called = false; + MethodResultFunctions result(nullptr, nullptr, + [&called]() { called = true; }); + result.NotImplemented(); + EXPECT_TRUE(called); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/plugin_registrar.cc b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/plugin_registrar.cc new file mode 100644 index 0000000000000000000000000000000000000000..65fef5cccfa287c23d1ef9be2fcc2b96b487293d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/plugin_registrar.cc @@ -0,0 +1,62 @@ +// 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 "include/flutter/plugin_registrar.h" + +#include +#include + +#include "binary_messenger_impl.h" +#include "include/flutter/engine_method_result.h" +#include "include/flutter/method_channel.h" +#include "texture_registrar_impl.h" + +namespace flutter { + +// ===== PluginRegistrar ===== + +PluginRegistrar::PluginRegistrar(FlutterDesktopPluginRegistrarRef registrar) + : registrar_(registrar) { + auto core_messenger = FlutterDesktopPluginRegistrarGetMessenger(registrar_); + messenger_ = std::make_unique(core_messenger); + + auto texture_registrar = + FlutterDesktopRegistrarGetTextureRegistrar(registrar_); + texture_registrar_ = + std::make_unique(texture_registrar); +} + +PluginRegistrar::~PluginRegistrar() { + // This must always be the first call. + ClearPlugins(); + + // Explicitly cleared to facilitate testing of destruction order. + messenger_.reset(); +} + +void PluginRegistrar::AddPlugin(std::unique_ptr plugin) { + plugins_.insert(std::move(plugin)); +} + +void PluginRegistrar::ClearPlugins() { + plugins_.clear(); +} + +// ===== PluginRegistrarManager ===== + +// static +PluginRegistrarManager* PluginRegistrarManager::GetInstance() { + static PluginRegistrarManager* instance = new PluginRegistrarManager(); + return instance; +} + +PluginRegistrarManager::PluginRegistrarManager() = default; + +// static +void PluginRegistrarManager::OnRegistrarDestroyed( + FlutterDesktopPluginRegistrarRef registrar) { + GetInstance()->registrars()->erase(registrar); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/plugin_registrar_unittests.cc b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/plugin_registrar_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..1884c6488718b96ad289914690ad103e90ef0118 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/plugin_registrar_unittests.cc @@ -0,0 +1,228 @@ +// 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/shell/platform/common/client_wrapper/include/flutter/plugin_registrar.h" + +#include +#include + +#include "flutter/shell/platform/common/client_wrapper/testing/stub_flutter_api.h" +#include "gtest/gtest.h" + +namespace flutter { + +namespace { + +// Stub implementation to validate calls to the API. +class TestApi : public testing::StubFlutterApi { + public: + // |flutter::testing::StubFlutterApi| + bool MessengerSend(const char* channel, + const uint8_t* message, + const size_t message_size) override { + last_data_sent_ = message; + return message_engine_result; + } + + bool MessengerSendWithReply(const char* channel, + const uint8_t* message, + const size_t message_size, + const FlutterDesktopBinaryReply reply, + void* user_data) override { + last_data_sent_ = message; + return message_engine_result; + } + + void MessengerSetCallback(const char* channel, + FlutterDesktopMessageCallback callback, + void* user_data) override { + last_message_callback_set_ = callback; + } + + void PluginRegistrarSetDestructionHandler( + FlutterDesktopOnPluginRegistrarDestroyed callback) override { + last_destruction_callback_set_ = callback; + } + + const uint8_t* last_data_sent() { return last_data_sent_; } + FlutterDesktopMessageCallback last_message_callback_set() { + return last_message_callback_set_; + } + FlutterDesktopOnPluginRegistrarDestroyed last_destruction_callback_set() { + return last_destruction_callback_set_; + } + + private: + const uint8_t* last_data_sent_ = nullptr; + FlutterDesktopMessageCallback last_message_callback_set_ = nullptr; + FlutterDesktopOnPluginRegistrarDestroyed last_destruction_callback_set_ = + nullptr; +}; + +// A PluginRegistrar whose destruction can be watched for by tests. +class TestPluginRegistrar : public PluginRegistrar { + public: + explicit TestPluginRegistrar(FlutterDesktopPluginRegistrarRef core_registrar) + : PluginRegistrar(core_registrar) {} + + virtual ~TestPluginRegistrar() { + if (destruction_callback_) { + destruction_callback_(); + } + } + + void SetDestructionCallback(std::function callback) { + destruction_callback_ = std::move(callback); + } + + private: + std::function destruction_callback_; +}; + +// A test plugin that tries to access registrar state during destruction and +// reports it out via a flag provided at construction. +class TestPlugin : public Plugin { + public: + // registrar_valid_at_destruction will be set at destruction to indicate + // whether or not |registrar->messenger()| was non-null. + TestPlugin(PluginRegistrar* registrar, bool* registrar_valid_at_destruction) + : registrar_(registrar), + registrar_valid_at_destruction_(registrar_valid_at_destruction) {} + virtual ~TestPlugin() { + *registrar_valid_at_destruction_ = registrar_->messenger() != nullptr; + } + + private: + PluginRegistrar* registrar_; + bool* registrar_valid_at_destruction_; +}; + +} // namespace + +// Tests that the registrar runs plugin destructors before its own teardown. +TEST(PluginRegistrarTest, PluginDestroyedBeforeRegistrar) { + auto dummy_registrar_handle = + reinterpret_cast(1); + bool registrar_valid_at_destruction = false; + { + PluginRegistrar registrar(dummy_registrar_handle); + + auto plugin = std::make_unique(®istrar, + ®istrar_valid_at_destruction); + registrar.AddPlugin(std::move(plugin)); + } + EXPECT_TRUE(registrar_valid_at_destruction); +} + +// Tests that the registrar returns a messenger that passes Send through to the +// C API. +TEST(PluginRegistrarTest, MessengerSend) { + testing::ScopedStubFlutterApi scoped_api_stub(std::make_unique()); + auto test_api = static_cast(scoped_api_stub.stub()); + + auto dummy_registrar_handle = + reinterpret_cast(1); + PluginRegistrar registrar(dummy_registrar_handle); + BinaryMessenger* messenger = registrar.messenger(); + + std::vector message = {1, 2, 3, 4}; + messenger->Send("some_channel", &message[0], message.size()); + EXPECT_EQ(test_api->last_data_sent(), &message[0]); +} + +// Tests that the registrar returns a messenger that passes callback +// registration and unregistration through to the C API. +TEST(PluginRegistrarTest, MessengerSetMessageHandler) { + testing::ScopedStubFlutterApi scoped_api_stub(std::make_unique()); + auto test_api = static_cast(scoped_api_stub.stub()); + + auto dummy_registrar_handle = + reinterpret_cast(1); + PluginRegistrar registrar(dummy_registrar_handle); + BinaryMessenger* messenger = registrar.messenger(); + const std::string channel_name("foo"); + + // Register. + BinaryMessageHandler binary_handler = [](const uint8_t* message, + const size_t message_size, + const BinaryReply& reply) {}; + messenger->SetMessageHandler(channel_name, std::move(binary_handler)); + EXPECT_NE(test_api->last_message_callback_set(), nullptr); + + // Unregister. + messenger->SetMessageHandler(channel_name, nullptr); + EXPECT_EQ(test_api->last_message_callback_set(), nullptr); +} + +// Tests that the registrar manager returns the same instance when getting +// the wrapper for the same reference. +TEST(PluginRegistrarTest, ManagerSameInstance) { + PluginRegistrarManager* manager = PluginRegistrarManager::GetInstance(); + manager->Reset(); + + testing::ScopedStubFlutterApi scoped_api_stub(std::make_unique()); + + auto dummy_registrar_handle = + reinterpret_cast(1); + + EXPECT_EQ(manager->GetRegistrar(dummy_registrar_handle), + manager->GetRegistrar(dummy_registrar_handle)); +} + +// Tests that the registrar manager returns different objects for different +// references. +TEST(PluginRegistrarTest, ManagerDifferentInstances) { + PluginRegistrarManager* manager = PluginRegistrarManager::GetInstance(); + manager->Reset(); + + testing::ScopedStubFlutterApi scoped_api_stub(std::make_unique()); + + auto dummy_registrar_handle_a = + reinterpret_cast(1); + auto dummy_registrar_handle_b = + reinterpret_cast(2); + + EXPECT_NE(manager->GetRegistrar(dummy_registrar_handle_a), + manager->GetRegistrar(dummy_registrar_handle_b)); +} + +// Tests that the registrar manager deletes wrappers when the underlying +// reference is destroyed. +TEST(PluginRegistrarTest, ManagerRemovesOnDestruction) { + PluginRegistrarManager* manager = PluginRegistrarManager::GetInstance(); + manager->Reset(); + + testing::ScopedStubFlutterApi scoped_api_stub(std::make_unique()); + auto test_api = static_cast(scoped_api_stub.stub()); + + auto dummy_registrar_handle = + reinterpret_cast(1); + auto* wrapper = + manager->GetRegistrar(dummy_registrar_handle); + + // Simulate destruction of the reference, and ensure that the wrapper + // is destroyed. + EXPECT_NE(test_api->last_destruction_callback_set(), nullptr); + bool destroyed = false; + wrapper->SetDestructionCallback([&destroyed]() { destroyed = true; }); + test_api->last_destruction_callback_set()(dummy_registrar_handle); + EXPECT_EQ(destroyed, true); + + // Requesting the wrapper should now create a new object. + EXPECT_NE(manager->GetRegistrar(dummy_registrar_handle), + nullptr); +} + +// Tests that the texture registrar getter returns a non-null TextureRegistrar +TEST(PluginRegistrarTest, TextureRegistrarNotNull) { + auto dummy_registrar_handle = + reinterpret_cast(1); + PluginRegistrar registrar(dummy_registrar_handle); + + TextureRegistrar* texture_registrar = registrar.texture_registrar(); + + ASSERT_NE(texture_registrar, nullptr); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/publish.gni b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/publish.gni new file mode 100644 index 0000000000000000000000000000000000000000..907197b6cced67fe377321dded43b3c16589cdf1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/publish.gni @@ -0,0 +1,104 @@ +# 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. + +import("core_wrapper_files.gni") + +# Publishes client wrapper files to the output directory for distribution. +# This can be used multiple times to combine various portions of a wrapper +# library into one cohesive library for clients to consume. +# +# Files that should be built by clients go into 'sources', while headers meant +# to be included by the consuming code go into 'public'. +# +# All public code is assumed to be in the 'flutter' namespace. +template("publish_client_wrapper") { + forward_variables_from(invoker, [ "directory_suffix" ]) + if (defined(directory_suffix)) { + publish_dir_root = "$root_out_dir/cpp_client_wrapper_$directory_suffix" + } else { + publish_dir_root = "$root_out_dir/cpp_client_wrapper" + } + template_target_name = target_name + namespace = "flutter" + + group(template_target_name) { + forward_variables_from(invoker, + [ + "public_deps", + "visibility", + ]) + deps = [ + ":${template_target_name}_publish_includes", + ":${template_target_name}_publish_sources", + ] + if (defined(invoker.deps)) { + deps += invoker.deps + } + } + + copy("${template_target_name}_publish_includes") { + visibility = [ + ":$template_target_name", + ":${template_target_name}_publish_sources", + ] + + sources = invoker.public + outputs = [ "$publish_dir_root/include/$namespace/{{source_file_part}}" ] + } + + copy("${template_target_name}_publish_sources") { + visibility = [ ":$template_target_name" ] + + sources = invoker.sources + outputs = [ "$publish_dir_root/{{source_file_part}}" ] + + # GN on Windows appears to do #include checks even for copy + # targets, so add the dependency to the headers to satisfy + # the check. + deps = [ ":${template_target_name}_publish_includes" ] + } +} + +_wrapper_readme = get_path_info("README", "abspath") + +# Copies the client wrapper code to the output directory. +template("publish_client_wrapper_core") { + publish_client_wrapper(target_name) { + forward_variables_from(invoker, + [ + "directory_suffix", + "visibility", + ]) + public = core_cpp_client_wrapper_includes + sources = core_cpp_client_wrapper_sources + + core_cpp_client_wrapper_internal_headers + [ _wrapper_readme ] + + temporary_shim_files + } +} + +# A wrapper for publish_client_wrapper that will also +# publish_client_wrapper_core into the same directory. +# +# This is a convenience utility for the common case of wanting to publish +# the core wrapper and a single set of extra wrapper files corresponding to +# the platform. +template("publish_client_wrapper_extension") { + extension_target_name = target_name + core_target_name = "${target_name}_core" + + publish_client_wrapper_core(core_target_name) { + visibility = [ ":$extension_target_name" ] + forward_variables_from(invoker, [ "directory_suffix" ]) + } + + publish_client_wrapper(extension_target_name) { + forward_variables_from(invoker, + [ + "public", + "sources", + "directory_suffix", + ]) + public_deps = [ ":$core_target_name" ] + } +} diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/standard_codec.cc b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/standard_codec.cc new file mode 100644 index 0000000000000000000000000000000000000000..d5f4b2fd156c5a51deadc8bec73f43c45fd85f5c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/standard_codec.cc @@ -0,0 +1,468 @@ +// 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. + +// This file contains what would normally be standard_codec_serializer.cc, +// standard_message_codec.cc, and standard_method_codec.cc. They are grouped +// together to simplify use of the client wrapper, since the common case is +// that any client that needs one of these files needs all three. + +#include +#include +#include +#include +#include +#include + +#include "byte_buffer_streams.h" +#include "include/flutter/standard_codec_serializer.h" +#include "include/flutter/standard_message_codec.h" +#include "include/flutter/standard_method_codec.h" + +namespace flutter { + +// ===== standard_codec_serializer.h ===== + +namespace { + +// The order/values here must match the constants in message_codecs.dart. +enum class EncodedType { + kNull = 0, + kTrue, + kFalse, + kInt32, + kInt64, + kLargeInt, // No longer used. If encountered, treat as kString. + kFloat64, + kString, + kUInt8List, + kInt32List, + kInt64List, + kFloat64List, + kList, + kMap, + kFloat32List, +}; + +// Returns the encoded type that should be written when serializing |value|. +EncodedType EncodedTypeForValue(const EncodableValue& value) { + switch (value.index()) { + case 0: + return EncodedType::kNull; + case 1: + return std::get(value) ? EncodedType::kTrue : EncodedType::kFalse; + case 2: + return EncodedType::kInt32; + case 3: + return EncodedType::kInt64; + case 4: + return EncodedType::kFloat64; + case 5: + return EncodedType::kString; + case 6: + return EncodedType::kUInt8List; + case 7: + return EncodedType::kInt32List; + case 8: + return EncodedType::kInt64List; + case 9: + return EncodedType::kFloat64List; + case 10: + return EncodedType::kList; + case 11: + return EncodedType::kMap; + case 13: + return EncodedType::kFloat32List; + } + assert(false); + return EncodedType::kNull; +} + +} // namespace + +StandardCodecSerializer::StandardCodecSerializer() = default; + +StandardCodecSerializer::~StandardCodecSerializer() = default; + +const StandardCodecSerializer& StandardCodecSerializer::GetInstance() { + static StandardCodecSerializer sInstance; + return sInstance; +}; + +EncodableValue StandardCodecSerializer::ReadValue( + ByteStreamReader* stream) const { + uint8_t type = stream->ReadByte(); + return ReadValueOfType(type, stream); +} + +void StandardCodecSerializer::WriteValue(const EncodableValue& value, + ByteStreamWriter* stream) const { + stream->WriteByte(static_cast(EncodedTypeForValue(value))); + // TODO(cbracken): Consider replacing this with std::visit. + switch (value.index()) { + case 0: + case 1: + // Null and bool are encoded directly in the type. + break; + case 2: + stream->WriteInt32(std::get(value)); + break; + case 3: + stream->WriteInt64(std::get(value)); + break; + case 4: + stream->WriteAlignment(8); + stream->WriteDouble(std::get(value)); + break; + case 5: { + const auto& string_value = std::get(value); + size_t size = string_value.size(); + WriteSize(size, stream); + if (size > 0) { + stream->WriteBytes( + reinterpret_cast(string_value.data()), size); + } + break; + } + case 6: + WriteVector(std::get>(value), stream); + break; + case 7: + WriteVector(std::get>(value), stream); + break; + case 8: + WriteVector(std::get>(value), stream); + break; + case 9: + WriteVector(std::get>(value), stream); + break; + case 10: { + const auto& list = std::get(value); + WriteSize(list.size(), stream); + for (const auto& item : list) { + WriteValue(item, stream); + } + break; + } + case 11: { + const auto& map = std::get(value); + WriteSize(map.size(), stream); + for (const auto& pair : map) { + WriteValue(pair.first, stream); + WriteValue(pair.second, stream); + } + break; + } + case 12: + std::cerr + << "Unhandled custom type in StandardCodecSerializer::WriteValue. " + << "Custom types require codec extensions." << std::endl; + break; + case 13: { + WriteVector(std::get>(value), stream); + break; + } + } +} + +EncodableValue StandardCodecSerializer::ReadValueOfType( + uint8_t type, + ByteStreamReader* stream) const { + switch (static_cast(type)) { + case EncodedType::kNull: + return EncodableValue(); + case EncodedType::kTrue: + return EncodableValue(true); + case EncodedType::kFalse: + return EncodableValue(false); + case EncodedType::kInt32: + return EncodableValue(stream->ReadInt32()); + case EncodedType::kInt64: + return EncodableValue(stream->ReadInt64()); + case EncodedType::kFloat64: + stream->ReadAlignment(8); + return EncodableValue(stream->ReadDouble()); + case EncodedType::kLargeInt: + case EncodedType::kString: { + size_t size = ReadSize(stream); + std::string string_value; + string_value.resize(size); + stream->ReadBytes(reinterpret_cast(&string_value[0]), size); + return EncodableValue(string_value); + } + case EncodedType::kUInt8List: + return ReadVector(stream); + case EncodedType::kInt32List: + return ReadVector(stream); + case EncodedType::kInt64List: + return ReadVector(stream); + case EncodedType::kFloat64List: + return ReadVector(stream); + case EncodedType::kList: { + size_t length = ReadSize(stream); + EncodableList list_value; + list_value.reserve(length); + for (size_t i = 0; i < length; ++i) { + list_value.push_back(ReadValue(stream)); + } + return EncodableValue(list_value); + } + case EncodedType::kMap: { + size_t length = ReadSize(stream); + EncodableMap map_value; + for (size_t i = 0; i < length; ++i) { + EncodableValue key = ReadValue(stream); + EncodableValue value = ReadValue(stream); + map_value.emplace(std::move(key), std::move(value)); + } + return EncodableValue(map_value); + } + case EncodedType::kFloat32List: { + return ReadVector(stream); + } + } + std::cerr << "Unknown type in StandardCodecSerializer::ReadValueOfType: " + << static_cast(type) << std::endl; + return EncodableValue(); +} + +size_t StandardCodecSerializer::ReadSize(ByteStreamReader* stream) const { + uint8_t byte = stream->ReadByte(); + if (byte < 254) { + return byte; + } else if (byte == 254) { + uint16_t value = 0; + stream->ReadBytes(reinterpret_cast(&value), 2); + return value; + } else { + uint32_t value = 0; + stream->ReadBytes(reinterpret_cast(&value), 4); + return value; + } +} + +void StandardCodecSerializer::WriteSize(size_t size, + ByteStreamWriter* stream) const { + if (size < 254) { + stream->WriteByte(static_cast(size)); + } else if (size <= 0xffff) { + stream->WriteByte(254); + uint16_t value = static_cast(size); + stream->WriteBytes(reinterpret_cast(&value), 2); + } else { + stream->WriteByte(255); + uint32_t value = static_cast(size); + stream->WriteBytes(reinterpret_cast(&value), 4); + } +} + +template +EncodableValue StandardCodecSerializer::ReadVector( + ByteStreamReader* stream) const { + size_t count = ReadSize(stream); + std::vector vector; + vector.resize(count); + uint8_t type_size = static_cast(sizeof(T)); + if (type_size > 1) { + stream->ReadAlignment(type_size); + } + stream->ReadBytes(reinterpret_cast(vector.data()), + count * type_size); + return EncodableValue(vector); +} + +template +void StandardCodecSerializer::WriteVector(const std::vector vector, + ByteStreamWriter* stream) const { + size_t count = vector.size(); + WriteSize(count, stream); + if (count == 0) { + return; + } + uint8_t type_size = static_cast(sizeof(T)); + if (type_size > 1) { + stream->WriteAlignment(type_size); + } + stream->WriteBytes(reinterpret_cast(vector.data()), + count * type_size); +} + +// ===== standard_message_codec.h ===== + +// static +const StandardMessageCodec& StandardMessageCodec::GetInstance( + const StandardCodecSerializer* serializer) { + if (!serializer) { + serializer = &StandardCodecSerializer::GetInstance(); + } + static auto* sInstances = new std::map>; + auto it = sInstances->find(serializer); + if (it == sInstances->end()) { + // Uses new due to private constructor (to prevent API clients from + // accidentally passing temporary codec instances to channels). + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) + auto emplace_result = sInstances->emplace( + serializer, std::unique_ptr( + new StandardMessageCodec(serializer))); + it = emplace_result.first; + } + return *(it->second); +} + +StandardMessageCodec::StandardMessageCodec( + const StandardCodecSerializer* serializer) + : serializer_(serializer) {} + +StandardMessageCodec::~StandardMessageCodec() = default; + +std::unique_ptr StandardMessageCodec::DecodeMessageInternal( + const uint8_t* binary_message, + size_t message_size) const { + if (!binary_message) { + return std::make_unique(); + } + ByteBufferStreamReader stream(binary_message, message_size); + return std::make_unique(serializer_->ReadValue(&stream)); +} + +std::unique_ptr> +StandardMessageCodec::EncodeMessageInternal( + const EncodableValue& message) const { + auto encoded = std::make_unique>(); + ByteBufferStreamWriter stream(encoded.get()); + serializer_->WriteValue(message, &stream); + return encoded; +} + +// ===== standard_method_codec.h ===== + +// static +const StandardMethodCodec& StandardMethodCodec::GetInstance( + const StandardCodecSerializer* serializer) { + if (!serializer) { + serializer = &StandardCodecSerializer::GetInstance(); + } + static auto* sInstances = new std::map>; + auto it = sInstances->find(serializer); + if (it == sInstances->end()) { + // Uses new due to private constructor (to prevent API clients from + // accidentally passing temporary codec instances to channels). + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) + auto emplace_result = sInstances->emplace( + serializer, std::unique_ptr( + new StandardMethodCodec(serializer))); + it = emplace_result.first; + } + return *(it->second); +} + +StandardMethodCodec::StandardMethodCodec( + const StandardCodecSerializer* serializer) + : serializer_(serializer) {} + +StandardMethodCodec::~StandardMethodCodec() = default; + +std::unique_ptr> +StandardMethodCodec::DecodeMethodCallInternal(const uint8_t* message, + size_t message_size) const { + ByteBufferStreamReader stream(message, message_size); + EncodableValue method_name_value = serializer_->ReadValue(&stream); + const auto* method_name = std::get_if(&method_name_value); + if (!method_name) { + std::cerr << "Invalid method call; method name is not a string." + << std::endl; + return nullptr; + } + auto arguments = + std::make_unique(serializer_->ReadValue(&stream)); + return std::make_unique>(*method_name, + std::move(arguments)); +} + +std::unique_ptr> +StandardMethodCodec::EncodeMethodCallInternal( + const MethodCall& method_call) const { + auto encoded = std::make_unique>(); + ByteBufferStreamWriter stream(encoded.get()); + serializer_->WriteValue(EncodableValue(method_call.method_name()), &stream); + if (method_call.arguments()) { + serializer_->WriteValue(*method_call.arguments(), &stream); + } else { + serializer_->WriteValue(EncodableValue(), &stream); + } + return encoded; +} + +std::unique_ptr> +StandardMethodCodec::EncodeSuccessEnvelopeInternal( + const EncodableValue* result) const { + auto encoded = std::make_unique>(); + ByteBufferStreamWriter stream(encoded.get()); + stream.WriteByte(0); + if (result) { + serializer_->WriteValue(*result, &stream); + } else { + serializer_->WriteValue(EncodableValue(), &stream); + } + return encoded; +} + +std::unique_ptr> +StandardMethodCodec::EncodeErrorEnvelopeInternal( + const std::string& error_code, + const std::string& error_message, + const EncodableValue* error_details) const { + auto encoded = std::make_unique>(); + ByteBufferStreamWriter stream(encoded.get()); + stream.WriteByte(1); + serializer_->WriteValue(EncodableValue(error_code), &stream); + if (error_message.empty()) { + serializer_->WriteValue(EncodableValue(), &stream); + } else { + serializer_->WriteValue(EncodableValue(error_message), &stream); + } + if (error_details) { + serializer_->WriteValue(*error_details, &stream); + } else { + serializer_->WriteValue(EncodableValue(), &stream); + } + return encoded; +} + +bool StandardMethodCodec::DecodeAndProcessResponseEnvelopeInternal( + const uint8_t* response, + size_t response_size, + MethodResult* result) const { + ByteBufferStreamReader stream(response, response_size); + uint8_t flag = stream.ReadByte(); + switch (flag) { + case 0: { + EncodableValue value = serializer_->ReadValue(&stream); + if (value.IsNull()) { + result->Success(); + } else { + result->Success(value); + } + return true; + } + case 1: { + EncodableValue code = serializer_->ReadValue(&stream); + EncodableValue message = serializer_->ReadValue(&stream); + EncodableValue details = serializer_->ReadValue(&stream); + const std::string& message_string = + message.IsNull() ? "" : std::get(message); + if (details.IsNull()) { + result->Error(std::get(code), message_string); + } else { + result->Error(std::get(code), message_string, details); + } + return true; + } + default: + return false; + } +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/standard_message_codec_unittests.cc b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/standard_message_codec_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..afe7247025f58f9d989a868f442a0971e72b2e09 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/standard_message_codec_unittests.cc @@ -0,0 +1,265 @@ +// 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/shell/platform/common/client_wrapper/include/flutter/standard_message_codec.h" + +#include +#include + +#include "flutter/shell/platform/common/client_wrapper/testing/test_codec_extensions.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +namespace flutter { + +namespace { + +class MockStandardCodecSerializer : public StandardCodecSerializer { + public: + MOCK_METHOD(void, + WriteValue, + (const EncodableValue& value, ByteStreamWriter* stream), + (const, override)); + MOCK_METHOD(EncodableValue, + ReadValueOfType, + (uint8_t type, ByteStreamReader* stream), + (const, override)); +}; +} // namespace + +// Validates round-trip encoding and decoding of |value|, and checks that the +// encoded value matches |expected_encoding|. +// +// If testing with CustomEncodableValues, |serializer| must be provided to +// handle the encoding/decoding, and |custom_comparator| must be provided to +// validate equality since CustomEncodableValue doesn't define a useful ==. +static void CheckEncodeDecode( + const EncodableValue& value, + const std::vector& expected_encoding, + const StandardCodecSerializer* serializer = nullptr, + const std::function& + custom_comparator = nullptr) { + const StandardMessageCodec& codec = + StandardMessageCodec::GetInstance(serializer); + auto encoded = codec.EncodeMessage(value); + ASSERT_TRUE(encoded); + EXPECT_EQ(*encoded, expected_encoding); + + auto decoded = codec.DecodeMessage(*encoded); + if (custom_comparator) { + EXPECT_TRUE(custom_comparator(value, *decoded)); + } else { + EXPECT_EQ(value, *decoded); + } +} + +// Validates round-trip encoding and decoding of |value|, and checks that the +// encoded value has the given prefix and length. +// +// This should be used only for Map, where asserting the order of the elements +// in a test is undesirable. +static void CheckEncodeDecodeWithEncodePrefix( + const EncodableValue& value, + const std::vector& expected_encoding_prefix, + size_t expected_encoding_length) { + EXPECT_TRUE(std::holds_alternative(value)); + const StandardMessageCodec& codec = StandardMessageCodec::GetInstance(); + auto encoded = codec.EncodeMessage(value); + ASSERT_TRUE(encoded); + + EXPECT_EQ(encoded->size(), expected_encoding_length); + ASSERT_GT(encoded->size(), expected_encoding_prefix.size()); + EXPECT_TRUE(std::equal( + encoded->begin(), encoded->begin() + expected_encoding_prefix.size(), + expected_encoding_prefix.begin(), expected_encoding_prefix.end())); + + auto decoded = codec.DecodeMessage(*encoded); + + EXPECT_EQ(value, *decoded); +} + +TEST(StandardMessageCodec, GetInstanceCachesInstance) { + const StandardMessageCodec& codec_a = + StandardMessageCodec::GetInstance(nullptr); + const StandardMessageCodec& codec_b = + StandardMessageCodec::GetInstance(nullptr); + EXPECT_EQ(&codec_a, &codec_b); +} + +TEST(StandardMessageCodec, CanEncodeAndDecodeNull) { + std::vector bytes = {0x00}; + CheckEncodeDecode(EncodableValue(), bytes); +} + +TEST(StandardMessageCodec, CanDecodeEmptyBytesAsNullWithoutCallingSerializer) { + std::vector bytes = {}; + const MockStandardCodecSerializer serializer; + const StandardMessageCodec& codec = + StandardMessageCodec::GetInstance(&serializer); + + auto decoded = codec.DecodeMessage(bytes); + + EXPECT_EQ(EncodableValue(), *decoded); + EXPECT_CALL(serializer, ReadValueOfType(::testing::_, ::testing::_)).Times(0); +} + +TEST(StandardMessageCodec, CanEncodeAndDecodeTrue) { + std::vector bytes = {0x01}; + CheckEncodeDecode(EncodableValue(true), bytes); +} + +TEST(StandardMessageCodec, CanEncodeAndDecodeFalse) { + std::vector bytes = {0x02}; + CheckEncodeDecode(EncodableValue(false), bytes); +} + +TEST(StandardMessageCodec, CanEncodeAndDecodeInt32) { + std::vector bytes = {0x03, 0x78, 0x56, 0x34, 0x12}; + CheckEncodeDecode(EncodableValue(0x12345678), bytes); +} + +TEST(StandardMessageCodec, CanEncodeAndDecodeInt64) { + std::vector bytes = {0x04, 0xef, 0xcd, 0xab, 0x90, + 0x78, 0x56, 0x34, 0x12}; + CheckEncodeDecode(EncodableValue(INT64_C(0x1234567890abcdef)), bytes); +} + +TEST(StandardMessageCodec, CanEncodeAndDecodeDouble) { + std::vector bytes = {0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x18, 0x2d, 0x44, 0x54, 0xfb, 0x21, 0x09, 0x40}; + CheckEncodeDecode(EncodableValue(3.14159265358979311599796346854), bytes); +} + +TEST(StandardMessageCodec, CanEncodeAndDecodeString) { + std::vector bytes = {0x07, 0x0b, 0x68, 0x65, 0x6c, 0x6c, 0x6f, + 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64}; + CheckEncodeDecode(EncodableValue(u8"hello world"), bytes); +} + +TEST(StandardMessageCodec, CanEncodeAndDecodeStringWithNonAsciiCodePoint) { + std::vector bytes = {0x07, 0x05, 0x68, 0xe2, 0x98, 0xba, 0x77}; + CheckEncodeDecode(EncodableValue(u8"h\u263Aw"), bytes); +} + +TEST(StandardMessageCodec, CanEncodeAndDecodeStringWithNonBMPCodePoint) { + std::vector bytes = {0x07, 0x06, 0x68, 0xf0, 0x9f, 0x98, 0x82, 0x77}; + CheckEncodeDecode(EncodableValue(u8"h\U0001F602w"), bytes); +} + +TEST(StandardMessageCodec, CanEncodeAndDecodeEmptyString) { + std::vector bytes = {0x07, 0x00}; + CheckEncodeDecode(EncodableValue(u8""), bytes); +} + +TEST(StandardMessageCodec, CanEncodeAndDecodeList) { + std::vector bytes = { + 0x0c, 0x05, 0x00, 0x07, 0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x06, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x85, 0xeb, 0x51, 0xb8, 0x1e, + 0x09, 0x40, 0x03, 0x2f, 0x00, 0x00, 0x00, 0x0c, 0x02, 0x03, 0x2a, + 0x00, 0x00, 0x00, 0x07, 0x06, 0x6e, 0x65, 0x73, 0x74, 0x65, 0x64, + }; + EncodableValue value(EncodableList{ + EncodableValue(), + EncodableValue("hello"), + EncodableValue(3.14), + EncodableValue(47), + EncodableValue(EncodableList{ + EncodableValue(42), + EncodableValue("nested"), + }), + }); + CheckEncodeDecode(value, bytes); +} + +TEST(StandardMessageCodec, CanEncodeAndDecodeEmptyList) { + std::vector bytes = {0x0c, 0x00}; + CheckEncodeDecode(EncodableValue(EncodableList{}), bytes); +} + +TEST(StandardMessageCodec, CanEncodeAndDecodeMap) { + std::vector bytes_prefix = {0x0d, 0x04}; + EncodableValue value(EncodableMap{ + {EncodableValue("a"), EncodableValue(3.14)}, + {EncodableValue("b"), EncodableValue(47)}, + {EncodableValue(), EncodableValue()}, + {EncodableValue(3.14), EncodableValue(EncodableList{ + EncodableValue("nested"), + })}, + }); + CheckEncodeDecodeWithEncodePrefix(value, bytes_prefix, 48); +} + +TEST(StandardMessageCodec, CanEncodeAndDecodeByteArray) { + std::vector bytes = {0x08, 0x04, 0xba, 0x5e, 0xba, 0x11}; + EncodableValue value(std::vector{0xba, 0x5e, 0xba, 0x11}); + CheckEncodeDecode(value, bytes); +} + +TEST(StandardMessageCodec, CanEncodeAndDecodeInt32Array) { + std::vector bytes = {0x09, 0x03, 0x00, 0x00, 0x78, 0x56, 0x34, 0x12, + 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00}; + EncodableValue value(std::vector{0x12345678, -1, 0}); + CheckEncodeDecode(value, bytes); +} + +TEST(StandardMessageCodec, CanEncodeAndDecodeInt64Array) { + std::vector bytes = {0x0a, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xef, 0xcd, 0xab, 0x90, 0x78, 0x56, 0x34, 0x12, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; + EncodableValue value(std::vector{0x1234567890abcdef, -1}); + CheckEncodeDecode(value, bytes); +} + +TEST(StandardMessageCodec, CanEncodeAndDecodeFloat32Array) { + std::vector bytes = {0x0e, 0x02, 0x00, 0x00, 0xd8, 0x0f, + 0x49, 0x40, 0x00, 0x00, 0x7a, 0x44}; + EncodableValue value(std::vector{3.1415920257568359375f, 1000.0f}); + CheckEncodeDecode(value, bytes); +} + +TEST(StandardMessageCodec, CanEncodeAndDecodeFloat64Array) { + std::vector bytes = {0x0b, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x18, 0x2d, 0x44, 0x54, 0xfb, 0x21, 0x09, 0x40, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x8f, 0x40}; + EncodableValue value( + std::vector{3.14159265358979311599796346854, 1000.0}); + CheckEncodeDecode(value, bytes); +} + +TEST(StandardMessageCodec, CanEncodeAndDecodeSimpleCustomType) { + std::vector bytes = {0x80, 0x09, 0x00, 0x00, 0x00, + 0x10, 0x00, 0x00, 0x00}; + auto point_comparator = [](const EncodableValue& a, const EncodableValue& b) { + const Point& a_point = + std::any_cast(std::get(a)); + const Point& b_point = + std::any_cast(std::get(b)); + return a_point == b_point; + }; + CheckEncodeDecode(CustomEncodableValue(Point(9, 16)), bytes, + &PointExtensionSerializer::GetInstance(), point_comparator); +} + +TEST(StandardMessageCodec, CanEncodeAndDecodeVariableLengthCustomType) { + std::vector bytes = { + 0x81, // custom type + 0x06, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, // data + 0x07, 0x04, // string type and length + 0x74, 0x65, 0x73, 0x74 // string characters + }; + auto some_data_comparator = [](const EncodableValue& a, + const EncodableValue& b) { + const SomeData& data_a = + std::any_cast(std::get(a)); + const SomeData& data_b = + std::any_cast(std::get(b)); + return data_a.data() == data_b.data() && data_a.label() == data_b.label(); + }; + CheckEncodeDecode(CustomEncodableValue( + SomeData("test", {0x00, 0x01, 0x02, 0x03, 0x04, 0x05})), + bytes, &SomeDataExtensionSerializer::GetInstance(), + some_data_comparator); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/standard_method_codec_unittests.cc b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/standard_method_codec_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..a3c2fb43141ec4f078519d7c76a3d929267385c9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/standard_method_codec_unittests.cc @@ -0,0 +1,183 @@ +// 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/shell/platform/common/client_wrapper/include/flutter/standard_method_codec.h" + +#include "flutter/shell/platform/common/client_wrapper/include/flutter/method_result_functions.h" +#include "flutter/shell/platform/common/client_wrapper/testing/test_codec_extensions.h" +#include "gtest/gtest.h" + +namespace flutter { + +namespace { + +// Returns true if the given method calls have the same method name, and their +// arguments have equivalent values. +bool MethodCallsAreEqual(const MethodCall<>& a, const MethodCall<>& b) { + if (a.method_name() != b.method_name()) { + return false; + } + // Treat nullptr and Null as equivalent. + if ((!a.arguments() || a.arguments()->IsNull()) && + (!b.arguments() || b.arguments()->IsNull())) { + return true; + } + // If only one is nullptr, fail early rather than throw below. + if (!a.arguments() || !b.arguments()) { + return false; + } + return *a.arguments() == *b.arguments(); +} + +} // namespace + +TEST(StandardMethodCodec, GetInstanceCachesInstance) { + const StandardMethodCodec& codec_a = + StandardMethodCodec::GetInstance(nullptr); + const StandardMethodCodec& codec_b = + StandardMethodCodec::GetInstance(nullptr); + EXPECT_EQ(&codec_a, &codec_b); +} + +TEST(StandardMethodCodec, HandlesMethodCallsWithNullArguments) { + const StandardMethodCodec& codec = StandardMethodCodec::GetInstance(); + MethodCall<> call("hello", nullptr); + auto encoded = codec.EncodeMethodCall(call); + ASSERT_NE(encoded.get(), nullptr); + std::unique_ptr> decoded = codec.DecodeMethodCall(*encoded); + ASSERT_NE(decoded.get(), nullptr); + EXPECT_TRUE(MethodCallsAreEqual(call, *decoded)); +} + +TEST(StandardMethodCodec, HandlesMethodCallsWithArgument) { + const StandardMethodCodec& codec = StandardMethodCodec::GetInstance(); + MethodCall<> call("hello", std::make_unique(EncodableList{ + EncodableValue(42), + EncodableValue("world"), + })); + auto encoded = codec.EncodeMethodCall(call); + ASSERT_NE(encoded.get(), nullptr); + std::unique_ptr> decoded = codec.DecodeMethodCall(*encoded); + ASSERT_NE(decoded.get(), nullptr); + EXPECT_TRUE(MethodCallsAreEqual(call, *decoded)); +} + +TEST(StandardMethodCodec, HandlesSuccessEnvelopesWithNullResult) { + const StandardMethodCodec& codec = StandardMethodCodec::GetInstance(); + auto encoded = codec.EncodeSuccessEnvelope(); + ASSERT_NE(encoded.get(), nullptr); + std::vector bytes = {0x00, 0x00}; + EXPECT_EQ(*encoded, bytes); + + bool decoded_successfully = false; + MethodResultFunctions<> result_handler( + [&decoded_successfully](const EncodableValue* result) { + decoded_successfully = true; + EXPECT_EQ(result, nullptr); + }, + nullptr, nullptr); + codec.DecodeAndProcessResponseEnvelope(encoded->data(), encoded->size(), + &result_handler); + EXPECT_TRUE(decoded_successfully); +} + +TEST(StandardMethodCodec, HandlesSuccessEnvelopesWithResult) { + const StandardMethodCodec& codec = StandardMethodCodec::GetInstance(); + EncodableValue result(42); + auto encoded = codec.EncodeSuccessEnvelope(&result); + ASSERT_NE(encoded.get(), nullptr); + std::vector bytes = {0x00, 0x03, 0x2a, 0x00, 0x00, 0x00}; + EXPECT_EQ(*encoded, bytes); + + bool decoded_successfully = false; + MethodResultFunctions<> result_handler( + [&decoded_successfully](const EncodableValue* result) { + decoded_successfully = true; + EXPECT_EQ(std::get(*result), 42); + }, + nullptr, nullptr); + codec.DecodeAndProcessResponseEnvelope(encoded->data(), encoded->size(), + &result_handler); + EXPECT_TRUE(decoded_successfully); +} + +TEST(StandardMethodCodec, HandlesErrorEnvelopesWithNulls) { + const StandardMethodCodec& codec = StandardMethodCodec::GetInstance(); + auto encoded = codec.EncodeErrorEnvelope("errorCode"); + ASSERT_NE(encoded.get(), nullptr); + std::vector bytes = {0x01, 0x07, 0x09, 0x65, 0x72, 0x72, 0x6f, + 0x72, 0x43, 0x6f, 0x64, 0x65, 0x00, 0x00}; + EXPECT_EQ(*encoded, bytes); + + bool decoded_successfully = false; + MethodResultFunctions<> result_handler( + nullptr, + [&decoded_successfully](const std::string& code, + const std::string& message, + const EncodableValue* details) { + decoded_successfully = true; + EXPECT_EQ(code, "errorCode"); + EXPECT_EQ(message, ""); + EXPECT_EQ(details, nullptr); + }, + nullptr); + codec.DecodeAndProcessResponseEnvelope(encoded->data(), encoded->size(), + &result_handler); + EXPECT_TRUE(decoded_successfully); +} + +TEST(StandardMethodCodec, HandlesErrorEnvelopesWithDetails) { + const StandardMethodCodec& codec = StandardMethodCodec::GetInstance(); + EncodableValue details(EncodableList{ + EncodableValue("a"), + EncodableValue(42), + }); + auto encoded = + codec.EncodeErrorEnvelope("errorCode", "something failed", &details); + ASSERT_NE(encoded.get(), nullptr); + std::vector bytes = { + 0x01, 0x07, 0x09, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x43, 0x6f, + 0x64, 0x65, 0x07, 0x10, 0x73, 0x6f, 0x6d, 0x65, 0x74, 0x68, + 0x69, 0x6e, 0x67, 0x20, 0x66, 0x61, 0x69, 0x6c, 0x65, 0x64, + 0x0c, 0x02, 0x07, 0x01, 0x61, 0x03, 0x2a, 0x00, 0x00, 0x00, + }; + EXPECT_EQ(*encoded, bytes); + + bool decoded_successfully = false; + MethodResultFunctions<> result_handler( + nullptr, + [&decoded_successfully](const std::string& code, + const std::string& message, + const EncodableValue* details) { + decoded_successfully = true; + EXPECT_EQ(code, "errorCode"); + EXPECT_EQ(message, "something failed"); + const auto* details_list = std::get_if(details); + ASSERT_NE(details_list, nullptr); + EXPECT_EQ(std::get((*details_list)[0]), "a"); + EXPECT_EQ(std::get((*details_list)[1]), 42); + }, + nullptr); + codec.DecodeAndProcessResponseEnvelope(encoded->data(), encoded->size(), + &result_handler); + EXPECT_TRUE(decoded_successfully); +} + +TEST(StandardMethodCodec, HandlesCustomTypeArguments) { + const StandardMethodCodec& codec = StandardMethodCodec::GetInstance( + &PointExtensionSerializer::GetInstance()); + Point point(7, 9); + MethodCall<> call( + "hello", std::make_unique(CustomEncodableValue(point))); + auto encoded = codec.EncodeMethodCall(call); + ASSERT_NE(encoded.get(), nullptr); + std::unique_ptr> decoded = codec.DecodeMethodCall(*encoded); + ASSERT_NE(decoded.get(), nullptr); + + const Point& decoded_point = std::any_cast( + std::get(*decoded->arguments())); + EXPECT_EQ(point, decoded_point); +}; + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/testing/stub_flutter_api.cc b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/testing/stub_flutter_api.cc new file mode 100644 index 0000000000000000000000000000000000000000..28b01d70ea209f5db90491e2f84e706d1005905e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/testing/stub_flutter_api.cc @@ -0,0 +1,161 @@ +// 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/shell/platform/common/client_wrapper/testing/stub_flutter_api.h" + +#include + +static flutter::testing::StubFlutterApi* s_stub_implementation; + +namespace flutter { +namespace testing { + +// static +void StubFlutterApi::SetTestStub(StubFlutterApi* stub) { + s_stub_implementation = stub; +} + +// static +StubFlutterApi* StubFlutterApi::GetTestStub() { + return s_stub_implementation; +} + +ScopedStubFlutterApi::ScopedStubFlutterApi(std::unique_ptr stub) + : stub_(std::move(stub)) { + previous_stub_ = StubFlutterApi::GetTestStub(); + StubFlutterApi::SetTestStub(stub_.get()); +} + +ScopedStubFlutterApi::~ScopedStubFlutterApi() { + StubFlutterApi::SetTestStub(previous_stub_); +} + +} // namespace testing +} // namespace flutter + +// Forwarding dummy implementations of the C API. + +FlutterDesktopMessengerRef FlutterDesktopPluginRegistrarGetMessenger( + FlutterDesktopPluginRegistrarRef registrar) { + // The stub ignores this, so just return an arbitrary non-zero value. + return reinterpret_cast(1); +} + +void FlutterDesktopPluginRegistrarSetDestructionHandler( + FlutterDesktopPluginRegistrarRef registrar, + FlutterDesktopOnPluginRegistrarDestroyed callback) { + if (s_stub_implementation) { + s_stub_implementation->PluginRegistrarSetDestructionHandler(callback); + } +} + +bool FlutterDesktopMessengerSend(FlutterDesktopMessengerRef messenger, + const char* channel, + const uint8_t* message, + const size_t message_size) { + bool result = false; + if (s_stub_implementation) { + result = + s_stub_implementation->MessengerSend(channel, message, message_size); + } + return result; +} + +bool FlutterDesktopMessengerSendWithReply(FlutterDesktopMessengerRef messenger, + const char* channel, + const uint8_t* message, + const size_t message_size, + const FlutterDesktopBinaryReply reply, + void* user_data) { + bool result = false; + if (s_stub_implementation) { + result = s_stub_implementation->MessengerSendWithReply( + channel, message, message_size, reply, user_data); + } + return result; +} + +void FlutterDesktopMessengerSendResponse( + FlutterDesktopMessengerRef messenger, + const FlutterDesktopMessageResponseHandle* handle, + const uint8_t* data, + size_t data_length) { + if (s_stub_implementation) { + s_stub_implementation->MessengerSendResponse(handle, data, data_length); + } +} + +void FlutterDesktopMessengerSetCallback(FlutterDesktopMessengerRef messenger, + const char* channel, + FlutterDesktopMessageCallback callback, + void* user_data) { + if (s_stub_implementation) { + s_stub_implementation->MessengerSetCallback(channel, callback, user_data); + } +} + +FlutterDesktopMessengerRef FlutterDesktopMessengerAddRef( + FlutterDesktopMessengerRef messenger) { + assert(false); // not implemented + return nullptr; +} + +void FlutterDesktopMessengerRelease(FlutterDesktopMessengerRef messenger) { + assert(false); // not implemented +} + +bool FlutterDesktopMessengerIsAvailable(FlutterDesktopMessengerRef messenger) { + assert(false); // not implemented + return false; +} + +FlutterDesktopMessengerRef FlutterDesktopMessengerLock( + FlutterDesktopMessengerRef messenger) { + assert(false); // not implemented + return nullptr; +} + +void FlutterDesktopMessengerUnlock(FlutterDesktopMessengerRef messenger) { + assert(false); // not implemented +} + +FlutterDesktopTextureRegistrarRef FlutterDesktopRegistrarGetTextureRegistrar( + FlutterDesktopPluginRegistrarRef registrar) { + return reinterpret_cast(1); +} + +int64_t FlutterDesktopTextureRegistrarRegisterExternalTexture( + FlutterDesktopTextureRegistrarRef texture_registrar, + const FlutterDesktopTextureInfo* info) { + uint64_t result = -1; + if (s_stub_implementation) { + result = + s_stub_implementation->TextureRegistrarRegisterExternalTexture(info); + } + return result; +} + +void FlutterDesktopTextureRegistrarUnregisterExternalTexture( + FlutterDesktopTextureRegistrarRef texture_registrar, + int64_t texture_id, + void (*callback)(void* user_data), + void* user_data) { + if (s_stub_implementation) { + s_stub_implementation->TextureRegistrarUnregisterExternalTexture( + texture_id, callback, user_data); + } else if (callback) { + callback(user_data); + } +} + +bool FlutterDesktopTextureRegistrarMarkExternalTextureFrameAvailable( + FlutterDesktopTextureRegistrarRef texture_registrar, + int64_t texture_id) { + bool result = false; + if (s_stub_implementation) { + result = s_stub_implementation->TextureRegistrarMarkTextureFrameAvailable( + texture_id); + } + return result; +} diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/testing/stub_flutter_api.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/testing/stub_flutter_api.h new file mode 100644 index 0000000000000000000000000000000000000000..0c1c94b8d27aea7735df165296c3b295570138da --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/testing/stub_flutter_api.h @@ -0,0 +1,107 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_TESTING_STUB_FLUTTER_API_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_TESTING_STUB_FLUTTER_API_H_ + +#include + +#include "flutter/shell/platform/common/public/flutter_messenger.h" +#include "flutter/shell/platform/common/public/flutter_plugin_registrar.h" + +namespace flutter { +namespace testing { + +// Base class for a object that provides test implementations of the APIs in +// the headers in platform/common/public/. + +// Linking this class into a test binary will provide dummy forwarding +// implementations of that C API, so that the wrapper can be tested separately +// from the actual library. +class StubFlutterApi { + public: + // Used by the callers to simulate a result from the engine when sending a + // message. + bool message_engine_result = true; + + // Sets |stub| as the instance to which calls to the Flutter library C APIs + // will be forwarded. + static void SetTestStub(StubFlutterApi* stub); + + // Returns the current stub, as last set by SetTestFlutterStub. + static StubFlutterApi* GetTestStub(); + + virtual ~StubFlutterApi() {} + + // Called for FlutterDesktopPluginRegistrarSetDestructionHandler. + virtual void PluginRegistrarSetDestructionHandler( + FlutterDesktopOnPluginRegistrarDestroyed callback) {} + + // Called for FlutterDesktopMessengerSend. + virtual bool MessengerSend(const char* channel, + const uint8_t* message, + const size_t message_size) { + return message_engine_result; + } + + // Called for FlutterDesktopMessengerSendWithReply. + virtual bool MessengerSendWithReply(const char* channel, + const uint8_t* message, + const size_t message_size, + const FlutterDesktopBinaryReply reply, + void* user_data) { + return message_engine_result; + } + + // Called for FlutterDesktopMessengerSendResponse. + virtual void MessengerSendResponse( + const FlutterDesktopMessageResponseHandle* handle, + const uint8_t* data, + size_t data_length) {} + + // Called for FlutterDesktopMessengerSetCallback. + virtual void MessengerSetCallback(const char* channel, + FlutterDesktopMessageCallback callback, + void* user_data) {} + + // Called for FlutterDesktopTextureRegistrarRegisterExternalTexture. + virtual int64_t TextureRegistrarRegisterExternalTexture( + const FlutterDesktopTextureInfo* info) { + return -1; + } + + // Called for FlutterDesktopTextureRegistrarUnregisterExternalTexture. + virtual void TextureRegistrarUnregisterExternalTexture( + int64_t texture_id, + void (*callback)(void* user_data), + void* user_data) {} + + // Called for FlutterDesktopTextureRegistrarMarkExternalTextureFrameAvailable. + virtual bool TextureRegistrarMarkTextureFrameAvailable(int64_t texture_id) { + return false; + } +}; + +// A test helper that owns a stub implementation, making it the test stub for +// the lifetime of the object, then restoring the previous value. +class ScopedStubFlutterApi { + public: + // Calls SetTestFlutterStub with |stub|. + explicit ScopedStubFlutterApi(std::unique_ptr stub); + + // Restores the previous test stub. + ~ScopedStubFlutterApi(); + + StubFlutterApi* stub() { return stub_.get(); } + + private: + std::unique_ptr stub_; + // The previous stub. + StubFlutterApi* previous_stub_; +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_TESTING_STUB_FLUTTER_API_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/testing/test_codec_extensions.cc b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/testing/test_codec_extensions.cc new file mode 100644 index 0000000000000000000000000000000000000000..caccb3adb2deb0ab6aade87bf13a724004c9d7bf --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/testing/test_codec_extensions.cc @@ -0,0 +1,80 @@ +// 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/shell/platform/common/client_wrapper/testing/test_codec_extensions.h" + +namespace flutter { + +PointExtensionSerializer::PointExtensionSerializer() = default; +PointExtensionSerializer::~PointExtensionSerializer() = default; + +// static +const PointExtensionSerializer& PointExtensionSerializer::GetInstance() { + static PointExtensionSerializer sInstance; + return sInstance; +} + +EncodableValue PointExtensionSerializer::ReadValueOfType( + uint8_t type, + ByteStreamReader* stream) const { + if (type == kPointType) { + int32_t x = stream->ReadInt32(); + int32_t y = stream->ReadInt32(); + return CustomEncodableValue(Point(x, y)); + } + return StandardCodecSerializer::ReadValueOfType(type, stream); +} + +void PointExtensionSerializer::WriteValue(const EncodableValue& value, + ByteStreamWriter* stream) const { + auto custom_value = std::get_if(&value); + if (!custom_value) { + StandardCodecSerializer::WriteValue(value, stream); + return; + } + stream->WriteByte(kPointType); + const Point& point = std::any_cast(*custom_value); + stream->WriteInt32(point.x()); + stream->WriteInt32(point.y()); +} + +SomeDataExtensionSerializer::SomeDataExtensionSerializer() = default; +SomeDataExtensionSerializer::~SomeDataExtensionSerializer() = default; + +// static +const SomeDataExtensionSerializer& SomeDataExtensionSerializer::GetInstance() { + static SomeDataExtensionSerializer sInstance; + return sInstance; +} + +EncodableValue SomeDataExtensionSerializer::ReadValueOfType( + uint8_t type, + ByteStreamReader* stream) const { + if (type == kSomeDataType) { + size_t size = ReadSize(stream); + std::vector data; + data.resize(size); + stream->ReadBytes(data.data(), size); + EncodableValue label = ReadValue(stream); + return CustomEncodableValue(SomeData(std::get(label), data)); + } + return StandardCodecSerializer::ReadValueOfType(type, stream); +} + +void SomeDataExtensionSerializer::WriteValue(const EncodableValue& value, + ByteStreamWriter* stream) const { + auto custom_value = std::get_if(&value); + if (!custom_value) { + StandardCodecSerializer::WriteValue(value, stream); + return; + } + stream->WriteByte(kSomeDataType); + const SomeData& some_data = std::any_cast(*custom_value); + size_t data_size = some_data.data().size(); + WriteSize(data_size, stream); + stream->WriteBytes(some_data.data().data(), data_size); + WriteValue(EncodableValue(some_data.label()), stream); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/testing/test_codec_extensions.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/testing/test_codec_extensions.h new file mode 100644 index 0000000000000000000000000000000000000000..7b10dd47fbe32a88a6d993e5fd81eb7e026c8ff0 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/testing/test_codec_extensions.h @@ -0,0 +1,89 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_TESTING_TEST_CODEC_EXTENSIONS_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_TESTING_TEST_CODEC_EXTENSIONS_H_ + +#include "flutter/shell/platform/common/client_wrapper/include/flutter/encodable_value.h" +#include "flutter/shell/platform/common/client_wrapper/include/flutter/standard_codec_serializer.h" + +namespace flutter { + +// A representation of a point, for custom type testing of a simple type. +class Point { + public: + Point(int x, int y) : x_(x), y_(y) {} + ~Point() = default; + + int x() const { return x_; } + int y() const { return y_; } + + bool operator==(const Point& other) const { + return x_ == other.x_ && y_ == other.y_; + } + + private: + int x_; + int y_; +}; + +// A typed binary data object with extra fields, for custom type testing of a +// variable-length type that includes types handled by the core standard codec. +class SomeData { + public: + SomeData(const std::string& label, const std::vector& data) + : label_(label), data_(data) {} + ~SomeData() = default; + + const std::string& label() const { return label_; } + const std::vector& data() const { return data_; } + + private: + std::string label_; + std::vector data_; +}; + +// Codec extension for Point. +class PointExtensionSerializer : public StandardCodecSerializer { + public: + PointExtensionSerializer(); + virtual ~PointExtensionSerializer(); + + static const PointExtensionSerializer& GetInstance(); + + // |TestCodecSerializer| + EncodableValue ReadValueOfType(uint8_t type, + ByteStreamReader* stream) const override; + + // |TestCodecSerializer| + void WriteValue(const EncodableValue& value, + ByteStreamWriter* stream) const override; + + private: + static constexpr uint8_t kPointType = 128; +}; + +// Codec extension for SomeData. +class SomeDataExtensionSerializer : public StandardCodecSerializer { + public: + SomeDataExtensionSerializer(); + virtual ~SomeDataExtensionSerializer(); + + static const SomeDataExtensionSerializer& GetInstance(); + + // |TestCodecSerializer| + EncodableValue ReadValueOfType(uint8_t type, + ByteStreamReader* stream) const override; + + // |TestCodecSerializer| + void WriteValue(const EncodableValue& value, + ByteStreamWriter* stream) const override; + + private: + static constexpr uint8_t kSomeDataType = 129; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_TESTING_TEST_CODEC_EXTENSIONS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/texture_registrar_impl.h b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/texture_registrar_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..bd01839d40f42a3b886a986e36086131f614c0b5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/texture_registrar_impl.h @@ -0,0 +1,44 @@ +// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_TEXTURE_REGISTRAR_IMPL_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_TEXTURE_REGISTRAR_IMPL_H_ + +#include "include/flutter/texture_registrar.h" + +namespace flutter { + +// Wrapper around a FlutterDesktopTextureRegistrarRef that implements the +// TextureRegistrar API. +class TextureRegistrarImpl : public TextureRegistrar { + public: + explicit TextureRegistrarImpl( + FlutterDesktopTextureRegistrarRef texture_registrar_ref); + virtual ~TextureRegistrarImpl(); + + // Prevent copying. + TextureRegistrarImpl(TextureRegistrarImpl const&) = delete; + TextureRegistrarImpl& operator=(TextureRegistrarImpl const&) = delete; + + // |flutter::TextureRegistrar| + int64_t RegisterTexture(TextureVariant* texture) override; + + // |flutter::TextureRegistrar| + bool MarkTextureFrameAvailable(int64_t texture_id) override; + + // |flutter::TextureRegistrar| + void UnregisterTexture(int64_t texture_id, + std::function callback) override; + + // |flutter::TextureRegistrar| + bool UnregisterTexture(int64_t texture_id) override; + + private: + // Handle for interacting with the C API. + FlutterDesktopTextureRegistrarRef texture_registrar_ref_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_TEXTURE_REGISTRAR_IMPL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/client_wrapper/texture_registrar_unittests.cc b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/texture_registrar_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..e770f06611c775528c21393f00f927b2695d6577 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/client_wrapper/texture_registrar_unittests.cc @@ -0,0 +1,154 @@ +// 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/shell/platform/common/client_wrapper/include/flutter/texture_registrar.h" + +#include +#include +#include + +#include "flutter/fml/synchronization/waitable_event.h" +#include "flutter/shell/platform/common/client_wrapper/include/flutter/plugin_registrar.h" +#include "flutter/shell/platform/common/client_wrapper/testing/stub_flutter_api.h" +#include "gtest/gtest.h" + +namespace flutter { + +namespace { + +// Stub implementation to validate calls to the API. +class TestApi : public testing::StubFlutterApi { + public: + struct FakePixelBufferTexture { + int64_t texture_id; + int32_t mark_count; + FlutterDesktopPixelBufferTextureCallback texture_callback; + void* user_data; + }; + + public: + int64_t TextureRegistrarRegisterExternalTexture( + const FlutterDesktopTextureInfo* info) override { + last_texture_id_++; + + auto texture = std::make_unique(); + texture->texture_callback = info->pixel_buffer_config.callback; + texture->user_data = info->pixel_buffer_config.user_data; + texture->mark_count = 0; + texture->texture_id = last_texture_id_; + + textures_[last_texture_id_] = std::move(texture); + return last_texture_id_; + } + + void TextureRegistrarUnregisterExternalTexture( + int64_t texture_id, + void (*callback)(void* user_data), + void* user_data) override { + auto it = textures_.find(texture_id); + if (it != textures_.end()) { + textures_.erase(it); + } + if (callback) { + callback(user_data); + } + } + + bool TextureRegistrarMarkTextureFrameAvailable(int64_t texture_id) override { + auto it = textures_.find(texture_id); + if (it != textures_.end()) { + it->second->mark_count++; + return true; + } + return false; + } + + FakePixelBufferTexture* GetFakeTexture(int64_t texture_id) { + auto it = textures_.find(texture_id); + if (it != textures_.end()) { + return it->second.get(); + } + return nullptr; + } + + int64_t last_texture_id() { return last_texture_id_; } + + size_t textures_size() { return textures_.size(); } + + private: + int64_t last_texture_id_ = -1; + std::map> textures_; +}; + +} // namespace + +// Tests thats textures can be registered and unregistered. +TEST(TextureRegistrarTest, RegisterUnregisterTexture) { + testing::ScopedStubFlutterApi scoped_api_stub(std::make_unique()); + auto test_api = static_cast(scoped_api_stub.stub()); + + auto dummy_registrar_handle = + reinterpret_cast(1); + PluginRegistrar registrar(dummy_registrar_handle); + TextureRegistrar* textures = registrar.texture_registrar(); + ASSERT_NE(textures, nullptr); + + EXPECT_EQ(test_api->last_texture_id(), -1); + auto texture = test_api->GetFakeTexture(0); + EXPECT_EQ(texture, nullptr); + + auto pixel_buffer_texture = std::make_unique( + PixelBufferTexture([](size_t width, size_t height) { return nullptr; })); + int64_t texture_id = textures->RegisterTexture(pixel_buffer_texture.get()); + EXPECT_EQ(test_api->last_texture_id(), texture_id); + EXPECT_EQ(test_api->textures_size(), static_cast(1)); + + texture = test_api->GetFakeTexture(texture_id); + EXPECT_EQ(texture->texture_id, texture_id); + EXPECT_EQ(texture->user_data, + std::get_if(pixel_buffer_texture.get())); + + textures->MarkTextureFrameAvailable(texture_id); + textures->MarkTextureFrameAvailable(texture_id); + bool success = textures->MarkTextureFrameAvailable(texture_id); + EXPECT_TRUE(success); + EXPECT_EQ(texture->mark_count, 3); + + fml::AutoResetWaitableEvent unregister_latch; + textures->UnregisterTexture(texture_id, [&]() { unregister_latch.Signal(); }); + unregister_latch.Wait(); + + texture = test_api->GetFakeTexture(texture_id); + EXPECT_EQ(texture, nullptr); + EXPECT_EQ(test_api->textures_size(), static_cast(0)); +} + +// Tests that the unregister callback gets also invoked when attempting to +// unregister a texture with an unknown id. +TEST(TextureRegistrarTest, UnregisterInvalidTexture) { + auto dummy_registrar_handle = + reinterpret_cast(1); + PluginRegistrar registrar(dummy_registrar_handle); + + TextureRegistrar* textures = registrar.texture_registrar(); + + fml::AutoResetWaitableEvent latch; + textures->UnregisterTexture(42, [&]() { latch.Signal(); }); + latch.Wait(); +} + +// Tests that claiming a new frame being available for an unknown texture +// returns false. +TEST(TextureRegistrarTest, MarkFrameAvailableInvalidTexture) { + auto dummy_registrar_handle = + reinterpret_cast(1); + PluginRegistrar registrar(dummy_registrar_handle); + + TextureRegistrar* textures = registrar.texture_registrar(); + + bool success = textures->MarkTextureFrameAvailable(42); + EXPECT_FALSE(success); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/public/flutter_export.h b/flutter/engine/src/flutter/shell/platform/common/public/flutter_export.h new file mode 100644 index 0000000000000000000000000000000000000000..d71b3fb5607aa36ffb72fcba18fa7d6328dc86b7 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/public/flutter_export.h @@ -0,0 +1,28 @@ +// 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_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_EXPORT_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_EXPORT_H_ + +#ifdef FLUTTER_DESKTOP_LIBRARY + +// Add visibility/export annotations when building the library. +#ifdef _WIN32 +#define FLUTTER_EXPORT __declspec(dllexport) +#else +#define FLUTTER_EXPORT __attribute__((visibility("default"))) +#endif + +#else // FLUTTER_DESKTOP_LIBRARY + +// Add import annotations when consuming the library. +#ifdef _WIN32 +#define FLUTTER_EXPORT __declspec(dllimport) +#else +#define FLUTTER_EXPORT +#endif + +#endif // FLUTTER_DESKTOP_LIBRARY + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_EXPORT_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/public/flutter_macros.h b/flutter/engine/src/flutter/shell/platform/common/public/flutter_macros.h new file mode 100644 index 0000000000000000000000000000000000000000..7b60cb488b0b2efd55e71cd9d1a857be84e7a54e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/public/flutter_macros.h @@ -0,0 +1,24 @@ +// 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_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_MACROS_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_MACROS_H_ + +#ifdef FLUTTER_DESKTOP_LIBRARY + +// Do not add deprecation annotations when building the library. +#define FLUTTER_DEPRECATED(message) + +#else // FLUTTER_DESKTOP_LIBRARY + +// Add deprecation warning for users of the library. +#ifdef _WIN32 +#define FLUTTER_DEPRECATED(message) __declspec(deprecated(message)) +#else +#define FLUTTER_DEPRECATED(message) __attribute__((deprecated(message))) +#endif + +#endif // FLUTTER_DESKTOP_LIBRARY + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_MACROS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/public/flutter_messenger.h b/flutter/engine/src/flutter/shell/platform/common/public/flutter_messenger.h new file mode 100644 index 0000000000000000000000000000000000000000..ddf800a5cdf25b2cc865ac7336e02f42c451318e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/public/flutter_messenger.h @@ -0,0 +1,144 @@ +// 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_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_MESSENGER_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_MESSENGER_H_ + +#include +#include +#include + +#include "flutter_export.h" + +#if defined(__cplusplus) +extern "C" { +#endif // defined(__cplusplus) + +// Opaque reference to a Flutter engine messenger. +typedef struct FlutterDesktopMessenger* FlutterDesktopMessengerRef; + +// Opaque handle for tracking responses to messages. +typedef struct _FlutterPlatformMessageResponseHandle + FlutterDesktopMessageResponseHandle; + +// The callback expected as a response of a binary message. +typedef void (*FlutterDesktopBinaryReply)(const uint8_t* data, + size_t data_size, + void* user_data); + +// A message received from Flutter. +typedef struct { + // Size of this struct as created by Flutter. + size_t struct_size; + // The name of the channel used for this message. + const char* channel; + // The raw message data. + const uint8_t* message; + // The length of |message|. + size_t message_size; + // The response handle. If non-null, the receiver of this message must call + // FlutterDesktopSendMessageResponse exactly once with this handle. + const FlutterDesktopMessageResponseHandle* response_handle; +} FlutterDesktopMessage; + +// Function pointer type for message handler callback registration. +// +// The user data will be whatever was passed to FlutterDesktopSetMessageHandler +// for the channel the message is received on. +typedef void (*FlutterDesktopMessageCallback)( + FlutterDesktopMessengerRef /* messenger */, + const FlutterDesktopMessage* /* message*/, + void* /* user data */); + +// Sends a binary message to the Flutter side on the specified channel. +FLUTTER_EXPORT bool FlutterDesktopMessengerSend( + FlutterDesktopMessengerRef messenger, + const char* channel, + const uint8_t* message, + const size_t message_size); + +// Sends a binary message to the Flutter side on the specified channel. +// The |reply| callback will be executed when a response is received. +FLUTTER_EXPORT bool FlutterDesktopMessengerSendWithReply( + FlutterDesktopMessengerRef messenger, + const char* channel, + const uint8_t* message, + const size_t message_size, + const FlutterDesktopBinaryReply reply, + void* user_data); + +// Sends a reply to a FlutterDesktopMessage for the given response handle. +// +// Once this has been called, |handle| is invalid and must not be used again. +FLUTTER_EXPORT void FlutterDesktopMessengerSendResponse( + FlutterDesktopMessengerRef messenger, + const FlutterDesktopMessageResponseHandle* handle, + const uint8_t* data, + size_t data_length); + +// Registers a callback function for incoming binary messages from the Flutter +// side on the specified channel. +// +// Replaces any existing callback. Provide a null handler to unregister the +// existing callback. +// +// If |user_data| is provided, it will be passed in |callback| calls. +FLUTTER_EXPORT void FlutterDesktopMessengerSetCallback( + FlutterDesktopMessengerRef messenger, + const char* channel, + FlutterDesktopMessageCallback callback, + void* user_data); + +// Increments the reference count for the |messenger|. +// +// Operation is thread-safe. +// +// See also: |FlutterDesktopMessengerRelease| +FLUTTER_EXPORT FlutterDesktopMessengerRef FlutterDesktopMessengerAddRef( + FlutterDesktopMessengerRef messenger); + +// Decrements the reference count for the |messenger|. +// +// Operation is thread-safe. +// +// See also: |FlutterDesktopMessengerAddRef| +FLUTTER_EXPORT void FlutterDesktopMessengerRelease( + FlutterDesktopMessengerRef messenger); + +// Returns `true` if the |FlutterDesktopMessengerRef| still references a running +// engine. +// +// This check should be made inside of a |FlutterDesktopMessengerLock| and +// before any other calls are made to the FlutterDesktopMessengerRef when using +// it from a thread other than the platform thread. +FLUTTER_EXPORT bool FlutterDesktopMessengerIsAvailable( + FlutterDesktopMessengerRef messenger); + +// Locks the `FlutterDesktopMessengerRef` ensuring that +// |FlutterDesktopMessengerIsAvailable| does not change while locked. +// +// All calls to the FlutterDesktopMessengerRef from threads other than the +// platform thread should happen inside of a lock. +// +// Operation is thread-safe. +// +// Returns the |messenger| value. +// +// See also: |FlutterDesktopMessengerUnlock| +FLUTTER_EXPORT FlutterDesktopMessengerRef FlutterDesktopMessengerLock( + FlutterDesktopMessengerRef messenger); + +// Unlocks the `FlutterDesktopMessengerRef`. +// +// Operation is thread-safe. +// +// See also: |FlutterDesktopMessengerLock| +FLUTTER_EXPORT void FlutterDesktopMessengerUnlock( + FlutterDesktopMessengerRef messenger); + +#if defined(__cplusplus) +} // extern "C" +#endif + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_MESSENGER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/public/flutter_plugin_registrar.h b/flutter/engine/src/flutter/shell/platform/common/public/flutter_plugin_registrar.h new file mode 100644 index 0000000000000000000000000000000000000000..b0847069404053093cb091bef8d6126220a72c7e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/public/flutter_plugin_registrar.h @@ -0,0 +1,45 @@ +// 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_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_PLUGIN_REGISTRAR_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_PLUGIN_REGISTRAR_H_ + +#include +#include + +#include "flutter_export.h" +#include "flutter_messenger.h" +#include "flutter_texture_registrar.h" + +#if defined(__cplusplus) +extern "C" { +#endif // defined(__cplusplus) + +// Opaque reference to a plugin registrar. +typedef struct FlutterDesktopPluginRegistrar* FlutterDesktopPluginRegistrarRef; + +// Function pointer type for registrar destruction callback. +typedef void (*FlutterDesktopOnPluginRegistrarDestroyed)( + FlutterDesktopPluginRegistrarRef); + +// Returns the engine messenger associated with this registrar. +FLUTTER_EXPORT FlutterDesktopMessengerRef +FlutterDesktopPluginRegistrarGetMessenger( + FlutterDesktopPluginRegistrarRef registrar); + +// Returns the texture registrar associated with this registrar. +FLUTTER_EXPORT FlutterDesktopTextureRegistrarRef +FlutterDesktopRegistrarGetTextureRegistrar( + FlutterDesktopPluginRegistrarRef registrar); + +// Registers a callback to be called when the plugin registrar is destroyed. +FLUTTER_EXPORT void FlutterDesktopPluginRegistrarSetDestructionHandler( + FlutterDesktopPluginRegistrarRef registrar, + FlutterDesktopOnPluginRegistrarDestroyed callback); + +#if defined(__cplusplus) +} // extern "C" +#endif + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_PLUGIN_REGISTRAR_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/public/flutter_texture_registrar.h b/flutter/engine/src/flutter/shell/platform/common/public/flutter_texture_registrar.h new file mode 100644 index 0000000000000000000000000000000000000000..9979e9a2c15fcbcf1c57308244021585672c6ddb --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/public/flutter_texture_registrar.h @@ -0,0 +1,187 @@ +// 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_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_TEXTURE_REGISTRAR_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_TEXTURE_REGISTRAR_H_ + +#include +#include + +#include "flutter_export.h" + +#if defined(__cplusplus) +extern "C" { +#endif + +struct FlutterDesktopTextureRegistrar; +// Opaque reference to a texture registrar. +typedef struct FlutterDesktopTextureRegistrar* + FlutterDesktopTextureRegistrarRef; + +// Possible values for the type specified in FlutterDesktopTextureInfo. +// Additional types may be added in the future. +typedef enum { + // A Pixel buffer-based texture. + kFlutterDesktopPixelBufferTexture, + // A platform-specific GPU surface-backed texture. + kFlutterDesktopGpuSurfaceTexture +} FlutterDesktopTextureType; + +// Supported GPU surface types. +typedef enum { + // Uninitialized. + kFlutterDesktopGpuSurfaceTypeNone, + // A DXGI shared texture handle (Windows only). + // See + // https://docs.microsoft.com/en-us/windows/win32/api/dxgi/nf-dxgi-idxgiresource-getsharedhandle + kFlutterDesktopGpuSurfaceTypeDxgiSharedHandle, + // A |ID3D11Texture2D| (Windows only). + kFlutterDesktopGpuSurfaceTypeD3d11Texture2D +} FlutterDesktopGpuSurfaceType; + +// Supported pixel formats. +typedef enum { + // Uninitialized. + kFlutterDesktopPixelFormatNone, + // Represents a 32-bit RGBA color format with 8 bits each for red, green, blue + // and alpha. + kFlutterDesktopPixelFormatRGBA8888, + // Represents a 32-bit BGRA color format with 8 bits each for blue, green, red + // and alpha. + kFlutterDesktopPixelFormatBGRA8888 +} FlutterDesktopPixelFormat; + +// An image buffer object. +typedef struct { + // The pixel data buffer. + const uint8_t* buffer; + // Width of the pixel buffer. + size_t width; + // Height of the pixel buffer. + size_t height; + // An optional callback that gets invoked when the |buffer| can be released. + void (*release_callback)(void* release_context); + // Opaque data passed to |release_callback|. + void* release_context; +} FlutterDesktopPixelBuffer; + +// A GPU surface descriptor. +typedef struct { + // The size of this struct. Must be + // sizeof(FlutterDesktopGpuSurfaceDescriptor). + size_t struct_size; + // The surface handle. The expected type depends on the + // |FlutterDesktopGpuSurfaceType|. + // + // Provide a |ID3D11Texture2D*| when using + // |kFlutterDesktopGpuSurfaceTypeD3d11Texture2D| or a |HANDLE| when using + // |kFlutterDesktopGpuSurfaceTypeDxgiSharedHandle|. + // + // The referenced resource needs to stay valid until it has been opened by + // Flutter. Consider incrementing the resource's reference count in the + // |FlutterDesktopGpuSurfaceTextureCallback| and registering a + // |release_callback| for decrementing the reference count once it has been + // opened. + void* handle; + // The physical width. + size_t width; + // The physical height. + size_t height; + // The visible width. + // It might be less or equal to the physical |width|. + size_t visible_width; + // The visible height. + // It might be less or equal to the physical |height|. + size_t visible_height; + // The pixel format which might be optional depending on the surface type. + FlutterDesktopPixelFormat format; + // An optional callback that gets invoked when the |handle| has been opened. + void (*release_callback)(void* release_context); + // Opaque data passed to |release_callback|. + void* release_context; +} FlutterDesktopGpuSurfaceDescriptor; + +// The pixel buffer copy callback definition provided to +// the Flutter engine to copy the texture. +// It is invoked with the intended surface size specified by |width| and +// |height| and the |user_data| held by +// |FlutterDesktopPixelBufferTextureConfig|. +// +// As this is usually called from the render thread, the callee must take +// care of proper synchronization. It also needs to be ensured that the +// returned |FlutterDesktopPixelBuffer| isn't released prior to unregistering +// the corresponding texture. +typedef const FlutterDesktopPixelBuffer* ( + *FlutterDesktopPixelBufferTextureCallback)(size_t width, + size_t height, + void* user_data); + +// The GPU surface callback definition provided to the Flutter engine to obtain +// the surface. It is invoked with the intended surface size specified by +// |width| and |height| and the |user_data| held by +// |FlutterDesktopGpuSurfaceTextureConfig|. +typedef const FlutterDesktopGpuSurfaceDescriptor* ( + *FlutterDesktopGpuSurfaceTextureCallback)(size_t width, + size_t height, + void* user_data); + +// An object used to configure pixel buffer textures. +typedef struct { + // The callback used by the engine to copy the pixel buffer object. + FlutterDesktopPixelBufferTextureCallback callback; + // Opaque data that will get passed to the provided |callback|. + void* user_data; +} FlutterDesktopPixelBufferTextureConfig; + +// An object used to configure GPU-surface textures. +typedef struct { + // The size of this struct. Must be + // sizeof(FlutterDesktopGpuSurfaceTextureConfig). + size_t struct_size; + // The concrete surface type (e.g. + // |kFlutterDesktopGpuSurfaceTypeDxgiSharedHandle|) + FlutterDesktopGpuSurfaceType type; + // The callback used by the engine to obtain the surface descriptor. + FlutterDesktopGpuSurfaceTextureCallback callback; + // Opaque data that will get passed to the provided |callback|. + void* user_data; +} FlutterDesktopGpuSurfaceTextureConfig; + +typedef struct { + FlutterDesktopTextureType type; + union { + FlutterDesktopPixelBufferTextureConfig pixel_buffer_config; + FlutterDesktopGpuSurfaceTextureConfig gpu_surface_config; + }; +} FlutterDesktopTextureInfo; + +// Registers a new texture with the Flutter engine and returns the texture ID. +// This function can be called from any thread. +FLUTTER_EXPORT int64_t FlutterDesktopTextureRegistrarRegisterExternalTexture( + FlutterDesktopTextureRegistrarRef texture_registrar, + const FlutterDesktopTextureInfo* info); + +// Asynchronously unregisters the texture identified by |texture_id| from the +// Flutter engine. +// An optional |callback| gets invoked upon completion. +// This function can be called from any thread. +FLUTTER_EXPORT void FlutterDesktopTextureRegistrarUnregisterExternalTexture( + FlutterDesktopTextureRegistrarRef texture_registrar, + int64_t texture_id, + void (*callback)(void* user_data), + void* user_data); + +// Marks that a new texture frame is available for a given |texture_id|. +// Returns true on success or false if the specified texture doesn't exist. +// This function can be called from any thread. +FLUTTER_EXPORT bool +FlutterDesktopTextureRegistrarMarkExternalTextureFrameAvailable( + FlutterDesktopTextureRegistrarRef texture_registrar, + int64_t texture_id); + +#if defined(__cplusplus) +} // extern "C" +#endif + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_TEXTURE_REGISTRAR_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/BUILD.gn b/flutter/engine/src/flutter/shell/platform/darwin/common/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..3881e6df3f227e875f291c646433cbafeed4a8f5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/BUILD.gn @@ -0,0 +1,134 @@ +# 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. + +assert(is_mac || is_ios) + +import("//flutter/common/config.gni") +import("//flutter/testing/testing.gni") +import("framework_common.gni") + +source_set("common") { + cflags_objc = flutter_cflags_objc + cflags_objcc = flutter_cflags_objcc + + sources = [ + "buffer_conversions.h", + "buffer_conversions.mm", + "command_line.h", + "command_line.mm", + ] + + deps = [ + ":availability_version_check", + "//flutter/fml", + ] + + public_configs = [ "//flutter:config" ] +} + +# Provides an implementation for _availability_version_check. +# +# This is required due to an upstream compiler builtin (runtime) change +# that marked this function as weakly-linked via __attribute__((weak import)) +# As such, no linking failure occurs when the function is unavailable at +# link time. Since the symbol is no longer linked in, App Store review blocks +# publishing due to relying on a private symbol. Instead we link in our own +# implementation, which provides the exact implementation used in clang prior +# to the upstream change. +# +# See: Upstream clang change: https://reviews.llvm.org/D150397 +# See: https://github.com/flutter/flutter/issues/133777 +source_set("availability_version_check") { + sources = [ "availability_version_check.cc" ] + + deps = [ "//flutter/fml" ] + + public_configs = [ "//flutter:config" ] +} + +test_fixtures("availability_version_check_fixtures") { + fixtures = [] +} + +executable("availability_version_check_unittests") { + testonly = true + + sources = [ "availability_version_check_unittests.cc" ] + + deps = [ + ":availability_version_check", + ":availability_version_check_fixtures", + "//flutter/fml", + "//flutter/testing", + ] + + public_configs = [ "//flutter:config" ] +} + +# Shared framework headers end up in the same folder as platform-specific +# framework headers when consumed by clients, so the include paths assume they +# are next to each other. +config("framework_relative_headers") { + include_dirs = [ "framework/Headers" ] +} + +# Framework code shared between iOS and macOS. +source_set("framework_common") { + cflags_objc = flutter_cflags_objc + cflags_objcc = flutter_cflags_objcc + + sources = [ + "framework/Source/FlutterBinaryMessengerRelay.mm", + "framework/Source/FlutterChannels.mm", + "framework/Source/FlutterCodecs.mm", + "framework/Source/FlutterHourFormat.mm", + "framework/Source/FlutterNSBundleUtils.h", + "framework/Source/FlutterNSBundleUtils.mm", + "framework/Source/FlutterStandardCodec.mm", + "framework/Source/FlutterStandardCodecHelper.cc", + "framework/Source/FlutterStandardCodec_Internal.h", + ] + + public = framework_common_headers + + public += [ "framework/Source/FlutterNSBundleUtils.h" ] + + defines = [ "FLUTTER_FRAMEWORK" ] + + public_configs = [ + "//flutter:config", + ":framework_relative_headers", + ] + + deps = [ "//flutter/fml" ] +} + +test_fixtures("framework_common_fixtures") { + fixtures = [] +} + +# Unit tests for channels. +executable("framework_common_unittests") { + testonly = true + cflags_objc = flutter_cflags_objc + cflags_objcc = flutter_cflags_objcc + ldflags = [ "-ObjC" ] + + sources = [ + "framework/Source/FlutterBinaryMessengerRelayTest.mm", + "framework/Source/FlutterTestUtils.mm", + "framework/Source/flutter_codecs_unittest.mm", + "framework/Source/flutter_standard_codec_unittest.mm", + ] + + deps = [ + ":framework_common", + ":framework_common_fixtures", + "$dart_src/runtime:libdart_jit", + "//flutter/testing", + "//flutter/third_party/ocmock:ocmock", + ] + + public_configs = [ "//flutter:config" ] +} diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/availability_version_check.cc b/flutter/engine/src/flutter/shell/platform/darwin/common/availability_version_check.cc new file mode 100644 index 0000000000000000000000000000000000000000..1564bec4335f0e93421633c52f518a1bb1ab04fc --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/availability_version_check.cc @@ -0,0 +1,197 @@ +// 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/shell/platform/darwin/common/availability_version_check.h" + +#include +#include +#include + +#include +#include +#include + +#include "flutter/fml/build_config.h" +#include "flutter/fml/file.h" +#include "flutter/fml/logging.h" +#include "flutter/fml/mapping.h" +#include "flutter/fml/platform/darwin/cf_utils.h" + +// The implementation of _availability_version_check defined in this file is +// based on the code in the clang-rt library at: +// +// https://github.com/llvm/llvm-project/blob/e315bf25a843582de39257e1345408a10dc08224/compiler-rt/lib/builtins/os_version_check.c +// +// Flutter provides its own implementation due to an issue introduced in recent +// versions of Clang following Clang 18 in which the clang-rt library declares +// weak linkage against the _availability_version_check symbol. This declaration +// causes apps to be rejected from the App Store. When Flutter statically links +// the implementation below, the weak linkage is satisfied at Engine build time, +// the symbol is no longer exposed from the Engine dylib, and apps will then +// not be rejected from the App Store. +// +// The implementation of _availability_version_check can delegate to the +// dynamically looked-up symbol on recent iOS versions, but the lookup will fail +// on iOS 11 and 12. When the lookup fails, the current OS version must be +// retrieved from a plist file at a well-known path. The logic for this below is +// copied from the clang-rt implementation and adapted for the Engine. + +// See more context in https://github.com/flutter/flutter/issues/132130 and +// https://github.com/flutter/engine/pull/44711. + +// TODO(zanderso): Remove this after Clang 18 rolls into Xcode. +// https://github.com/flutter/flutter/issues/133203. + +#define CF_PROPERTY_LIST_IMMUTABLE 0 + +namespace flutter { + +// This function parses the platform's version information out of a plist file +// at a well-known path. It parses the plist file using CoreFoundation functions +// to match the implementation in the clang-rt library. +std::optional ProductVersionFromSystemVersionPList() { + std::string plist_path = "/System/Library/CoreServices/SystemVersion.plist"; +#if FML_OS_IOS_SIMULATOR + char* plist_path_prefix = getenv("IPHONE_SIMULATOR_ROOT"); + if (!plist_path_prefix) { + FML_DLOG(ERROR) << "Failed to getenv IPHONE_SIMULATOR_ROOT"; + return std::nullopt; + } + plist_path = std::string(plist_path_prefix) + plist_path; +#endif // FML_OS_IOS_SIMULATOR + + auto plist_mapping = fml::FileMapping::CreateReadOnly(plist_path); + + // Get the file buffer into CF's format. We pass in a null allocator here * + // because we free PListBuf ourselves + auto file_contents = fml::CFRef(CFDataCreateWithBytesNoCopy( + nullptr, plist_mapping->GetMapping(), + static_cast(plist_mapping->GetSize()), kCFAllocatorNull)); + if (!file_contents) { + FML_DLOG(ERROR) << "Failed to CFDataCreateWithBytesNoCopyFunc"; + return std::nullopt; + } + + auto plist = fml::CFRef( + reinterpret_cast(CFPropertyListCreateWithData( + nullptr, file_contents, CF_PROPERTY_LIST_IMMUTABLE, nullptr, + nullptr))); + if (!plist) { + FML_DLOG(ERROR) << "Failed to CFPropertyListCreateWithDataFunc or " + "CFPropertyListCreateFromXMLDataFunc"; + return std::nullopt; + } + + auto product_version = + fml::CFRef(CFStringCreateWithCStringNoCopy( + nullptr, "ProductVersion", kCFStringEncodingASCII, kCFAllocatorNull)); + if (!product_version) { + FML_DLOG(ERROR) << "Failed to CFStringCreateWithCStringNoCopyFunc"; + return std::nullopt; + } + CFTypeRef opaque_value = CFDictionaryGetValue(plist, product_version); + if (!opaque_value || CFGetTypeID(opaque_value) != CFStringGetTypeID()) { + FML_DLOG(ERROR) << "Failed to CFDictionaryGetValueFunc"; + return std::nullopt; + } + + char version_str[32]; + if (!CFStringGetCString(reinterpret_cast(opaque_value), + version_str, sizeof(version_str), + kCFStringEncodingUTF8)) { + FML_DLOG(ERROR) << "Failed to CFStringGetCStringFunc"; + return std::nullopt; + } + + int32_t major = 0; + int32_t minor = 0; + int32_t subminor = 0; + int matches = sscanf(version_str, "%d.%d.%d", &major, &minor, &subminor); + // A major version number is sufficient. The minor and subminor numbers might + // not be present. + if (matches < 1) { + FML_DLOG(ERROR) << "Failed to match product version string: " + << version_str; + return std::nullopt; + } + + return ProductVersion{major, minor, subminor}; +} + +bool IsEncodedVersionLessThanOrSame(uint32_t encoded_lhs, ProductVersion rhs) { + // Parse the values out of encoded_lhs, then compare against rhs. + const int32_t major = (encoded_lhs >> 16) & 0xffff; + const int32_t minor = (encoded_lhs >> 8) & 0xff; + const int32_t subminor = encoded_lhs & 0xff; + auto lhs = ProductVersion{major, minor, subminor}; + + return lhs <= rhs; +} + +} // namespace flutter + +namespace { + +// The host's OS version when the dynamic lookup of _availability_version_check +// has failed. +static flutter::ProductVersion g_version; + +typedef uint32_t dyld_platform_t; + +typedef struct { + dyld_platform_t platform; + uint32_t version; +} dyld_build_version_t; + +typedef bool (*AvailabilityVersionCheckFn)(uint32_t count, + dyld_build_version_t versions[]); + +AvailabilityVersionCheckFn AvailabilityVersionCheck; + +dispatch_once_t DispatchOnceCounter; + +void InitializeAvailabilityCheck(void* unused) { + if (AvailabilityVersionCheck) { + return; + } + AvailabilityVersionCheck = reinterpret_cast( + dlsym(RTLD_DEFAULT, "_availability_version_check")); + if (AvailabilityVersionCheck) { + return; + } + + // If _availability_version_check can't be dynamically loaded, then version + // information must be parsed out of a system plist file. + auto product_version = flutter::ProductVersionFromSystemVersionPList(); + if (product_version.has_value()) { + g_version = product_version.value(); + } else { + // If reading version info out of the system plist file fails, then + // fall back to the minimum version that Flutter supports. +#if FML_OS_IOS || FML_OS_IOS_SIMULATOR + g_version = std::make_tuple(11, 0, 0); +#elif FML_OS_MACOSX + g_version = std::make_tuple(10, 14, 0); +#endif // FML_OS_MACOSX + } +} + +extern "C" bool _availability_version_check(uint32_t count, + dyld_build_version_t versions[]) { + dispatch_once_f(&DispatchOnceCounter, NULL, InitializeAvailabilityCheck); + if (AvailabilityVersionCheck) { + return AvailabilityVersionCheck(count, versions); + } + + if (count == 0) { + return true; + } + + // This function is called in only one place in the clang-rt implementation + // where there is only one element in the array. + return flutter::IsEncodedVersionLessThanOrSame(versions[0].version, + g_version); +} + +} // namespace diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/availability_version_check.h b/flutter/engine/src/flutter/shell/platform/darwin/common/availability_version_check.h new file mode 100644 index 0000000000000000000000000000000000000000..97b2aab761a86df1c37114b2b54027bd8b88a7cd --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/availability_version_check.h @@ -0,0 +1,23 @@ +// 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_SHELL_PLATFORM_DARWIN_COMMON_AVAILABILITY_VERSION_CHECK_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_AVAILABILITY_VERSION_CHECK_H_ + +#include +#include +#include + +namespace flutter { + +using ProductVersion = + std::tuple; + +std::optional ProductVersionFromSystemVersionPList(); + +bool IsEncodedVersionLessThanOrSame(uint32_t encoded_lhs, ProductVersion rhs); + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_AVAILABILITY_VERSION_CHECK_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/availability_version_check_unittests.cc b/flutter/engine/src/flutter/shell/platform/darwin/common/availability_version_check_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..7753d1cfa522d3646d911519037313ff9db25a08 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/availability_version_check_unittests.cc @@ -0,0 +1,35 @@ +// 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 + +#include "flutter/shell/platform/darwin/common/availability_version_check.h" + +#include "gtest/gtest.h" + +TEST(AvailabilityVersionCheck, CanDecodeSystemPlist) { + auto maybe_product_version = flutter::ProductVersionFromSystemVersionPList(); + ASSERT_TRUE(maybe_product_version.has_value()); + if (maybe_product_version.has_value()) { + auto product_version = maybe_product_version.value(); + ASSERT_GT(product_version, std::make_tuple(0, 0, 0)); + } +} + +static inline uint32_t ConstructVersion(uint32_t major, + uint32_t minor, + uint32_t subminor) { + return ((major & 0xffff) << 16) | ((minor & 0xff) << 8) | (subminor & 0xff); +} + +TEST(AvailabilityVersionCheck, CanParseAndCompareVersions) { + auto rhs_version = std::make_tuple(17, 2, 0); + uint32_t encoded_lower_version = ConstructVersion(12, 3, 7); + ASSERT_TRUE(flutter::IsEncodedVersionLessThanOrSame(encoded_lower_version, + rhs_version)); + + uint32_t encoded_higher_version = ConstructVersion(42, 0, 1); + ASSERT_FALSE(flutter::IsEncodedVersionLessThanOrSame(encoded_higher_version, + rhs_version)); +} diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/buffer_conversions.h b/flutter/engine/src/flutter/shell/platform/darwin/common/buffer_conversions.h new file mode 100644 index 0000000000000000000000000000000000000000..819eddcae80176c34135bbdaa42aeb536a1c2f3e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/buffer_conversions.h @@ -0,0 +1,26 @@ +// 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_SHELL_PLATFORM_DARWIN_COMMON_BUFFER_CONVERSIONS_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_BUFFER_CONVERSIONS_H_ + +#include + +#include + +#include "flutter/fml/mapping.h" + +namespace flutter { + +fml::MallocMapping CopyNSDataToMapping(NSData* data); + +NSData* ConvertMappingToNSData(fml::MallocMapping buffer); + +std::unique_ptr ConvertNSDataToMappingPtr(NSData* data); + +NSData* CopyMappingPtrToNSData(std::unique_ptr mapping); + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_BUFFER_CONVERSIONS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/buffer_conversions.mm b/flutter/engine/src/flutter/shell/platform/darwin/common/buffer_conversions.mm new file mode 100644 index 0000000000000000000000000000000000000000..6a44c2ca56c6dc9173fc92200cbc4bde0a660037 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/buffer_conversions.mm @@ -0,0 +1,47 @@ +// 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. + +#import "flutter/shell/platform/darwin/common/buffer_conversions.h" + +#include "flutter/fml/macros.h" + +static_assert(__has_feature(objc_arc), "ARC must be enabled."); + +namespace flutter { +namespace { +class NSDataMapping : public fml::Mapping { + public: + explicit NSDataMapping(NSData* data) : data_(data) {} + + size_t GetSize() const override { return data_.length; } + + const uint8_t* GetMapping() const override { return static_cast(data_.bytes); } + + bool IsDontNeedSafe() const override { return false; } + + private: + NSData* data_; + FML_DISALLOW_COPY_AND_ASSIGN(NSDataMapping); +}; +} // namespace + +fml::MallocMapping CopyNSDataToMapping(NSData* data) { + const uint8_t* bytes = static_cast(data.bytes); + return fml::MallocMapping::Copy(bytes, data.length); +} + +NSData* ConvertMappingToNSData(fml::MallocMapping buffer) { + size_t size = buffer.GetSize(); + return [NSData dataWithBytesNoCopy:buffer.Release() length:size]; +} + +std::unique_ptr ConvertNSDataToMappingPtr(NSData* data) { + return std::make_unique(data); +} + +NSData* CopyMappingPtrToNSData(std::unique_ptr mapping) { + return [NSData dataWithBytes:mapping->GetMapping() length:mapping->GetSize()]; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/command_line.h b/flutter/engine/src/flutter/shell/platform/darwin/common/command_line.h new file mode 100644 index 0000000000000000000000000000000000000000..43f3afac6d37f76fc9032f742aaa84961797bb65 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/command_line.h @@ -0,0 +1,21 @@ +// 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_SHELL_PLATFORM_DARWIN_COMMON_COMMAND_LINE_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_COMMAND_LINE_H_ + +#import + +#include "flutter/fml/command_line.h" + +#include "flutter/fml/macros.h" + +namespace flutter { + +fml::CommandLine CommandLineFromNSProcessInfo( + NSProcessInfo* processInfoOrNil = nil); + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_COMMAND_LINE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/command_line.mm b/flutter/engine/src/flutter/shell/platform/darwin/common/command_line.mm new file mode 100644 index 0000000000000000000000000000000000000000..47c8ef2b8ede188fc910f2c0434ae0970be9578b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/command_line.mm @@ -0,0 +1,24 @@ +// 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. + +#import "flutter/shell/platform/darwin/common/command_line.h" + +#import + +static_assert(__has_feature(objc_arc), "ARC must be enabled."); + +namespace flutter { + +fml::CommandLine CommandLineFromNSProcessInfo(NSProcessInfo* processInfoOrNil) { + std::vector args_vector; + auto processInfo = processInfoOrNil ? processInfoOrNil : [NSProcessInfo processInfo]; + + for (NSString* arg in processInfo.arguments) { + args_vector.emplace_back(arg.UTF8String); + } + + return fml::CommandLineFromIterators(args_vector.begin(), args_vector.end()); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h new file mode 100644 index 0000000000000000000000000000000000000000..eb0186fd223c56e45717e44c01932b4e88c510f3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h @@ -0,0 +1,106 @@ +// 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_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERBINARYMESSENGER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERBINARYMESSENGER_H_ + +#import + +#import "FlutterMacros.h" + +NS_ASSUME_NONNULL_BEGIN +/** + * A message reply callback. + * + * Used for submitting a binary reply back to a Flutter message sender. Also used + * in for handling a binary message reply received from Flutter. + * + * @param reply The reply. + */ +typedef void (^FlutterBinaryReply)(NSData* _Nullable reply); + +/** + * A strategy for handling incoming binary messages from Flutter and to send + * asynchronous replies back to Flutter. + * + * @param message The message. + * @param reply A callback for submitting an asynchronous reply to the sender. + */ +typedef void (^FlutterBinaryMessageHandler)(NSData* _Nullable message, FlutterBinaryReply reply); + +typedef int64_t FlutterBinaryMessengerConnection; + +@protocol FlutterTaskQueue +@end + +/** + * A facility for communicating with the Flutter side using asynchronous message + * passing with binary messages. + * + * Implementated by: + * - `FlutterBasicMessageChannel`, which supports communication using structured + * messages. + * - `FlutterMethodChannel`, which supports communication using asynchronous + * method calls. + * - `FlutterEventChannel`, which supports commuication using event streams. + */ +FLUTTER_DARWIN_EXPORT +@protocol FlutterBinaryMessenger +/// TODO(gaaclarke): Remove optional when macos supports Background Platform Channels. +@optional +- (NSObject*)makeBackgroundTaskQueue; + +- (FlutterBinaryMessengerConnection) + setMessageHandlerOnChannel:(NSString*)channel + binaryMessageHandler:(FlutterBinaryMessageHandler _Nullable)handler + taskQueue:(NSObject* _Nullable)taskQueue; + +@required +/** + * Sends a binary message to the Flutter side on the specified channel, expecting + * no reply. + * + * @param channel The channel name. + * @param message The message. + */ +- (void)sendOnChannel:(NSString*)channel message:(NSData* _Nullable)message; + +/** + * Sends a binary message to the Flutter side on the specified channel, expecting + * an asynchronous reply. + * + * @param channel The channel name. + * @param message The message. + * @param callback A callback for receiving a reply. + */ +- (void)sendOnChannel:(NSString*)channel + message:(NSData* _Nullable)message + binaryReply:(FlutterBinaryReply _Nullable)callback; + +/** + * Registers a message handler for incoming binary messages from the Flutter side + * on the specified channel. + * + * Replaces any existing handler. Use a `nil` handler for unregistering the + * existing handler. + * + * @param channel The channel name. + * @param handler The message handler. + * @return An identifier that represents the connection that was just created to the channel. + */ +- (FlutterBinaryMessengerConnection)setMessageHandlerOnChannel:(NSString*)channel + binaryMessageHandler: + (FlutterBinaryMessageHandler _Nullable)handler; + +/** + * Clears out a channel's message handler if that handler is still the one that + * was created as a result of + * `setMessageHandlerOnChannel:binaryMessageHandler:`. + * + * @param connection The result from `setMessageHandlerOnChannel:binaryMessageHandler:`. + */ +- (void)cleanUpConnection:(FlutterBinaryMessengerConnection)connection; +@end +NS_ASSUME_NONNULL_END +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERBINARYMESSENGER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h new file mode 100644 index 0000000000000000000000000000000000000000..b88b78a901afa7aebdad42890aa360340949ed53 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h @@ -0,0 +1,487 @@ +// 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_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERCHANNELS_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERCHANNELS_H_ + +#import "FlutterBinaryMessenger.h" +#import "FlutterCodecs.h" + +NS_ASSUME_NONNULL_BEGIN +/** + * A message reply callback. + * + * Used for submitting a reply back to a Flutter message sender. Also used in + * the dual capacity for handling a message reply received from Flutter. + * + * @param reply The reply. + */ +typedef void (^FlutterReply)(id _Nullable reply); + +/** + * A strategy for handling incoming messages from Flutter and to send + * asynchronous replies back to Flutter. + * + * @param message The message. + * @param callback A callback for submitting a reply to the sender which can be invoked from any + * thread. + */ +typedef void (^FlutterMessageHandler)(id _Nullable message, FlutterReply callback); + +/** + * A channel for communicating with the Flutter side using basic, asynchronous + * message passing. + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterBasicMessageChannel : NSObject +/** + * Creates a `FlutterBasicMessageChannel` with the specified name and binary + * messenger. + * + * The channel name logically identifies the channel; identically named channels + * interfere with each other's communication. + * + * The binary messenger is a facility for sending raw, binary messages to the + * Flutter side. This protocol is implemented by `FlutterEngine` and `FlutterViewController`. + * + * The channel uses `FlutterStandardMessageCodec` to encode and decode messages. + * + * @param name The channel name. + * @param messenger The binary messenger. + */ ++ (instancetype)messageChannelWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger; + +/** + * Creates a `FlutterBasicMessageChannel` with the specified name, binary + * messenger, and message codec. + * + * The channel name logically identifies the channel; identically named channels + * interfere with each other's communication. + * + * The binary messenger is a facility for sending raw, binary messages to the + * Flutter side. This protocol is implemented by `FlutterEngine` and `FlutterViewController`. + * + * @param name The channel name. + * @param messenger The binary messenger. + * @param codec The message codec. + */ ++ (instancetype)messageChannelWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger + codec:(NSObject*)codec; + +/** + * Initializes a `FlutterBasicMessageChannel` with the specified name, binary + * messenger, and message codec. + * + * The channel name logically identifies the channel; identically named channels + * interfere with each other's communication. + * + * The binary messenger is a facility for sending raw, binary messages to the + * Flutter side. This protocol is implemented by `FlutterEngine` and `FlutterViewController`. + * + * @param name The channel name. + * @param messenger The binary messenger. + * @param codec The message codec. + */ +- (instancetype)initWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger + codec:(NSObject*)codec; + +/** + * Initializes a `FlutterBasicMessageChannel` with the specified name, binary + * messenger, and message codec. + * + * The channel name logically identifies the channel; identically named channels + * interfere with each other's communication. + * + * The binary messenger is a facility for sending raw, binary messages to the + * Flutter side. This protocol is implemented by `FlutterEngine` and `FlutterViewController`. + * + * @param name The channel name. + * @param messenger The binary messenger. + * @param codec The message codec. + * @param taskQueue The FlutterTaskQueue that executes the handler (see + -[FlutterBinaryMessenger makeBackgroundTaskQueue]). + */ +- (instancetype)initWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger + codec:(NSObject*)codec + taskQueue:(NSObject* _Nullable)taskQueue; + +/** + * Sends the specified message to the Flutter side, ignoring any reply. + * + * @param message The message. Must be supported by the codec of this + * channel. + */ +- (void)sendMessage:(id _Nullable)message; + +/** + * Sends the specified message to the Flutter side, expecting an asynchronous + * reply. + * + * @param message The message. Must be supported by the codec of this channel. + * @param callback A callback to be invoked with the message reply from Flutter. + */ +- (void)sendMessage:(id _Nullable)message reply:(FlutterReply _Nullable)callback; + +/** + * Registers a message handler with this channel. + * + * Replaces any existing handler. Use a `nil` handler for unregistering the + * existing handler. + * + * @param handler The message handler. + */ +- (void)setMessageHandler:(FlutterMessageHandler _Nullable)handler; + +/** + * Adjusts the number of messages that will get buffered when sending messages to + * channels that aren't fully set up yet. For example, the engine isn't running + * yet or the channel's message handler isn't set up on the Dart side yet. + * + * @param name The channel name. + * @param messenger The binary messenger. + * @param newSize The number of messages that will get buffered. + */ ++ (void)resizeChannelWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger + size:(NSInteger)newSize; + +/** + * Adjusts the number of messages that will get buffered when sending messages to + * channels that aren't fully set up yet. For example, the engine isn't running + * yet or the channel's message handler isn't set up on the Dart side yet. + * + * @param newSize The number of messages that will get buffered. + */ +- (void)resizeChannelBuffer:(NSInteger)newSize; + +/** + * Defines whether the channel should show warning messages when discarding messages + * due to overflow. + * + * @param warns When false, the channel is expected to overflow and warning messages + * will not be shown. + * @param name The channel name. + * @param messenger The binary messenger. + */ ++ (void)setWarnsOnOverflow:(BOOL)warns + forChannelWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger; + +/** + * Defines whether the channel should show warning messages when discarding messages + * due to overflow. + * + * @param warns When false, the channel is expected to overflow and warning messages + * will not be shown. + */ +- (void)setWarnsOnOverflow:(BOOL)warns; + +@end + +/** + * A method call result callback. + * + * Used for submitting a method call result back to a Flutter caller. Also used in + * the dual capacity for handling a method call result received from Flutter. + * + * @param result The result. + */ +typedef void (^FlutterResult)(id _Nullable result); + +/** + * A strategy for handling method calls. + * + * @param call The incoming method call. + * @param result A callback to asynchronously submit the result of the call. + * Invoke the callback with a `FlutterError` to indicate that the call failed. + * Invoke the callback with `FlutterMethodNotImplemented` to indicate that the + * method was unknown. Any other values, including `nil`, are interpreted as + * successful results. This can be invoked from any thread. + */ +typedef void (^FlutterMethodCallHandler)(FlutterMethodCall* call, FlutterResult result); + +/** + * A constant used with `FlutterMethodCallHandler` to respond to the call of an + * unknown method. + */ +FLUTTER_DARWIN_EXPORT +extern NSObject const* FlutterMethodNotImplemented; + +/** + * A channel for communicating with the Flutter side using invocation of + * asynchronous methods. + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterMethodChannel : NSObject +/** + * Creates a `FlutterMethodChannel` with the specified name and binary messenger. + * + * The channel name logically identifies the channel; identically named channels + * interfere with each other's communication. + * + * The binary messenger is a facility for sending raw, binary messages to the + * Flutter side. This protocol is implemented by `FlutterEngine` and `FlutterViewController`. + * + * The channel uses `FlutterStandardMethodCodec` to encode and decode method calls + * and result envelopes. + * + * @param name The channel name. + * @param messenger The binary messenger. + */ ++ (instancetype)methodChannelWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger; + +/** + * Creates a `FlutterMethodChannel` with the specified name, binary messenger, and + * method codec. + * + * The channel name logically identifies the channel; identically named channels + * interfere with each other's communication. + * + * The binary messenger is a facility for sending raw, binary messages to the + * Flutter side. This protocol is implemented by `FlutterEngine` and `FlutterViewController`. + * + * @param name The channel name. + * @param messenger The binary messenger. + * @param codec The method codec. + */ ++ (instancetype)methodChannelWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger + codec:(NSObject*)codec; + +/** + * Initializes a `FlutterMethodChannel` with the specified name, binary messenger, + * and method codec. + * + * The channel name logically identifies the channel; identically named channels + * interfere with each other's communication. + * + * The binary messenger is a facility for sending raw, binary messages to the + * Flutter side. This protocol is implemented by `FlutterEngine` and `FlutterViewController`. + * + * @param name The channel name. + * @param messenger The binary messenger. + * @param codec The method codec. + */ +- (instancetype)initWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger + codec:(NSObject*)codec; + +/** + * Initializes a `FlutterMethodChannel` with the specified name, binary messenger, + * method codec, and task queue. + * + * The channel name logically identifies the channel; identically named channels + * interfere with each other's communication. + * + * The binary messenger is a facility for sending raw, binary messages to the + * Flutter side. This protocol is implemented by `FlutterEngine` and `FlutterViewController`. + * + * @param name The channel name. + * @param messenger The binary messenger. + * @param codec The method codec. + * @param taskQueue The FlutterTaskQueue that executes the handler (see + -[FlutterBinaryMessenger makeBackgroundTaskQueue]). + */ +- (instancetype)initWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger + codec:(NSObject*)codec + taskQueue:(NSObject* _Nullable)taskQueue; + +// clang-format off +/** + * Invokes the specified Flutter method with the specified arguments, expecting + * no results. + * + * @see [MethodChannel.setMethodCallHandler](https://api.flutter.dev/flutter/services/MethodChannel/setMethodCallHandler.html) + * + * @param method The name of the method to invoke. + * @param arguments The arguments. Must be a value supported by the codec of this + * channel. + */ +// clang-format on +- (void)invokeMethod:(NSString*)method arguments:(id _Nullable)arguments; + +/** + * Invokes the specified Flutter method with the specified arguments, expecting + * an asynchronous result. + * + * @param method The name of the method to invoke. + * @param arguments The arguments. Must be a value supported by the codec of this + * channel. + * @param callback A callback that will be invoked with the asynchronous result. + * The result will be a `FlutterError` instance, if the method call resulted + * in an error on the Flutter side. Will be `FlutterMethodNotImplemented`, if + * the method called was not implemented on the Flutter side. Any other value, + * including `nil`, should be interpreted as successful results. + */ +- (void)invokeMethod:(NSString*)method + arguments:(id _Nullable)arguments + result:(FlutterResult _Nullable)callback; +/** + * Registers a handler for method calls from the Flutter side. + * + * Replaces any existing handler. Use a `nil` handler for unregistering the + * existing handler. + * + * @param handler The method call handler. + */ +- (void)setMethodCallHandler:(FlutterMethodCallHandler _Nullable)handler; + +/** + * Adjusts the number of messages that will get buffered when sending messages to + * channels that aren't fully set up yet. For example, the engine isn't running + * yet or the channel's message handler isn't set up on the Dart side yet. + */ +- (void)resizeChannelBuffer:(NSInteger)newSize; + +@end + +/** + * An event sink callback. + * + * @param event The event. + */ +typedef void (^FlutterEventSink)(id _Nullable event); + +/** + * A strategy for exposing an event stream to the Flutter side. + */ +FLUTTER_DARWIN_EXPORT +@protocol FlutterStreamHandler +/** + * Sets up an event stream and begin emitting events. + * + * Invoked when the first listener is registered with the Stream associated to + * this channel on the Flutter side. + * + * @param arguments Arguments for the stream. + * @param events A callback to asynchronously emit events. Invoke the + * callback with a `FlutterError` to emit an error event. Invoke the + * callback with `FlutterEndOfEventStream` to indicate that no more + * events will be emitted. Any other value, including `nil` are emitted as + * successful events. + * @return A FlutterError instance, if setup fails. + */ +- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments + eventSink:(FlutterEventSink)events; + +/** + * Tears down an event stream. + * + * Invoked when the last listener is deregistered from the Stream associated to + * this channel on the Flutter side. + * + * The channel implementation may call this method with `nil` arguments + * to separate a pair of two consecutive set up requests. Such request pairs + * may occur during Flutter hot restart. + * + * @param arguments Arguments for the stream. + * @return A FlutterError instance, if teardown fails. + */ +- (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments; +@end + +/** + * A constant used with `FlutterEventChannel` to indicate end of stream. + */ +FLUTTER_DARWIN_EXPORT +extern NSObject const* FlutterEndOfEventStream; + +/** + * A channel for communicating with the Flutter side using event streams. + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterEventChannel : NSObject +/** + * Creates a `FlutterEventChannel` with the specified name and binary messenger. + * + * The channel name logically identifies the channel; identically named channels + * interfere with each other's communication. + * + * The binary messenger is a facility for sending raw, binary messages to the + * Flutter side. This protocol is implemented by `FlutterViewController`. + * + * The channel uses `FlutterStandardMethodCodec` to decode stream setup and + * teardown requests, and to encode event envelopes. + * + * @param name The channel name. + * @param messenger The binary messenger. + */ ++ (instancetype)eventChannelWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger; + +/** + * Creates a `FlutterEventChannel` with the specified name, binary messenger, + * and method codec. + * + * The channel name logically identifies the channel; identically named channels + * interfere with each other's communication. + * + * The binary messenger is a facility for sending raw, binary messages to the + * Flutter side. This protocol is implemented by `FlutterViewController`. + * + * @param name The channel name. + * @param messenger The binary messenger. + * @param codec The method codec. + */ ++ (instancetype)eventChannelWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger + codec:(NSObject*)codec; + +/** + * Initializes a `FlutterEventChannel` with the specified name, binary messenger, + * and method codec. + * + * The channel name logically identifies the channel; identically named channels + * interfere with each other's communication. + * + * The binary messenger is a facility for sending raw, binary messages to the + * Flutter side. This protocol is implemented by `FlutterEngine` and `FlutterViewController`. + * + * @param name The channel name. + * @param messenger The binary messenger. + * @param codec The method codec. + */ +- (instancetype)initWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger + codec:(NSObject*)codec; + +/** + * Initializes a `FlutterEventChannel` with the specified name, binary messenger, + * method codec and task queue. + * + * The channel name logically identifies the channel; identically named channels + * interfere with each other's communication. + * + * The binary messenger is a facility for sending raw, binary messages to the + * Flutter side. This protocol is implemented by `FlutterEngine` and `FlutterViewController`. + * + * @param name The channel name. + * @param messenger The binary messenger. + * @param codec The method codec. + * @param taskQueue The FlutterTaskQueue that executes the handler (see + -[FlutterBinaryMessenger makeBackgroundTaskQueue]). + */ +- (instancetype)initWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger + codec:(NSObject*)codec + taskQueue:(NSObject* _Nullable)taskQueue; +/** + * Registers a handler for stream setup requests from the Flutter side. + * + * Replaces any existing handler. Use a `nil` handler for unregistering the + * existing handler. + * + * @param handler The stream handler. + */ +- (void)setStreamHandler:(NSObject* _Nullable)handler; +@end +NS_ASSUME_NONNULL_END + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERCHANNELS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h new file mode 100644 index 0000000000000000000000000000000000000000..93e1d32d93ebd605a6c7794b638f4642b820f31a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h @@ -0,0 +1,478 @@ +// 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_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERCODECS_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERCODECS_H_ + +#import + +#import "FlutterMacros.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * A message encoding/decoding mechanism. + */ +FLUTTER_DARWIN_EXPORT +@protocol FlutterMessageCodec +/** + * Returns a shared instance of this `FlutterMessageCodec`. + */ ++ (instancetype)sharedInstance; + +/** + * Encodes the specified message into binary. + * + * @param message The message. + * @return The binary encoding, or `nil`, if `message` was `nil`. + */ +- (NSData* _Nullable)encode:(id _Nullable)message; + +/** + * Decodes the specified message from binary. + * + * @param message The message. + * @return The decoded message, or `nil`, if `message` was `nil`. + */ +- (id _Nullable)decode:(NSData* _Nullable)message; +@end + +/** + * A `FlutterMessageCodec` using unencoded binary messages, represented as + * `NSData` instances. + * + * This codec is guaranteed to be compatible with the corresponding + * [BinaryCodec](https://api.flutter.dev/flutter/services/BinaryCodec-class.html) + * on the Dart side. These parts of the Flutter SDK are evolved synchronously. + * + * On the Dart side, messages are represented using `ByteData`. + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterBinaryCodec : NSObject +@end + +/** + * A `FlutterMessageCodec` using UTF-8 encoded `NSString` messages. + * + * This codec is guaranteed to be compatible with the corresponding + * [StringCodec](https://api.flutter.dev/flutter/services/StringCodec-class.html) + * on the Dart side. These parts of the Flutter SDK are evolved synchronously. + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterStringCodec : NSObject +@end + +/** + * A `FlutterMessageCodec` using UTF-8 encoded JSON messages. + * + * This codec is guaranteed to be compatible with the corresponding + * [JSONMessageCodec](https://api.flutter.dev/flutter/services/JSONMessageCodec-class.html) + * on the Dart side. These parts of the Flutter SDK are evolved synchronously. + * + * Supports values accepted by `NSJSONSerialization` plus top-level + * `nil`, `NSNumber`, and `NSString`. + * + * On the Dart side, JSON messages are handled by the JSON facilities of the + * [`dart:convert`](https://api.dartlang.org/stable/dart-convert/JSON-constant.html) + * package. + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterJSONMessageCodec : NSObject +@end + +/** + * A writer of the Flutter standard binary encoding. + * + * See `FlutterStandardMessageCodec` for details on the encoding. + * + * The encoding is extensible via subclasses overriding `writeValue`. + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterStandardWriter : NSObject +/** + * Create a `FlutterStandardWriter` who will write to \p data. + */ +- (instancetype)initWithData:(NSMutableData*)data; +/** Write a 8-bit byte. */ +- (void)writeByte:(UInt8)value; +/** Write an array of \p bytes of size \p length. */ +- (void)writeBytes:(const void*)bytes length:(NSUInteger)length; +/** Write an array of bytes contained in \p data. */ +- (void)writeData:(NSData*)data; +/** Write 32-bit unsigned integer that represents a \p size of a collection. */ +- (void)writeSize:(UInt32)size; +/** Write zero padding until data is aligned with \p alignment. */ +- (void)writeAlignment:(UInt8)alignment; +/** Write a string with UTF-8 encoding. */ +- (void)writeUTF8:(NSString*)value; +/** Introspects into an object and writes its representation. + * + * Supported Data Types: + * - NSNull + * - NSNumber + * - NSString (as UTF-8) + * - FlutterStandardTypedData + * - NSArray of supported types + * - NSDictionary of supporte types + * + * NSAsserts on failure. + */ +- (void)writeValue:(id)value; +@end + +/** + * A reader of the Flutter standard binary encoding. + * + * See `FlutterStandardMessageCodec` for details on the encoding. + * + * The encoding is extensible via subclasses overriding `readValueOfType`. + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterStandardReader : NSObject +/** + * Create a new `FlutterStandardReader` who reads from \p data. + */ +- (instancetype)initWithData:(NSData*)data; +/** Returns YES when the reader hasn't reached the end of its data. */ +- (BOOL)hasMore; +/** Reads a byte value and increments the position. */ +- (UInt8)readByte; +/** Reads a sequence of byte values of \p length and increments the position. */ +- (void)readBytes:(void*)destination length:(NSUInteger)length; +/** Reads a sequence of byte values of \p length and increments the position. */ +- (NSData*)readData:(NSUInteger)length; +/** Reads a 32-bit unsigned integer representing a collection size and increments the position.*/ +- (UInt32)readSize; +/** Advances the read position until it is aligned with \p alignment. */ +- (void)readAlignment:(UInt8)alignment; +/** Read a null terminated string encoded with UTF-8/ */ +- (NSString*)readUTF8; +/** + * Reads a byte for `FlutterStandardField` the decodes a value matching that type. + * + * See also: -[FlutterStandardWriter writeValue] + */ +- (nullable id)readValue; +/** + * Decodes a value matching the \p type specified. + * + * See also: + * - `FlutterStandardField` + * - `-[FlutterStandardWriter writeValue]` + */ +- (nullable id)readValueOfType:(UInt8)type; +@end + +/** + * A factory of compatible reader/writer instances using the Flutter standard + * binary encoding or extensions thereof. + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterStandardReaderWriter : NSObject +/** + * Create a new `FlutterStandardWriter` for writing to \p data. + */ +- (FlutterStandardWriter*)writerWithData:(NSMutableData*)data; +/** + * Create a new `FlutterStandardReader` for reading from \p data. + */ +- (FlutterStandardReader*)readerWithData:(NSData*)data; +@end + +/** + * A `FlutterMessageCodec` using the Flutter standard binary encoding. + * + * This codec is guaranteed to be compatible with the corresponding + * [StandardMessageCodec](https://api.flutter.dev/flutter/services/StandardMessageCodec-class.html) + * on the Dart side. These parts of the Flutter SDK are evolved synchronously. + * + * Supported messages are acyclic values of these forms: + * + * - `nil` or `NSNull` + * - `NSNumber` (including their representation of Boolean values) + * - `NSString` + * - `FlutterStandardTypedData` + * - `NSArray` of supported values + * - `NSDictionary` with supported keys and values + * + * On the Dart side, these values are represented as follows: + * + * - `nil` or `NSNull`: null + * - `NSNumber`: `bool`, `int`, or `double`, depending on the contained value. + * - `NSString`: `String` + * - `FlutterStandardTypedData`: `Uint8List`, `Int32List`, `Int64List`, or `Float64List` + * - `NSArray`: `List` + * - `NSDictionary`: `Map` + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterStandardMessageCodec : NSObject +/** + * Create a `FlutterStandardMessageCodec` who will read and write to \p readerWriter. + */ ++ (instancetype)codecWithReaderWriter:(FlutterStandardReaderWriter*)readerWriter; +@end + +/** + * Command object representing a method call on a `FlutterMethodChannel`. + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterMethodCall : NSObject +/** + * Creates a method call for invoking the specified named method with the + * specified arguments. + * + * @param method the name of the method to call. + * @param arguments the arguments value. + */ ++ (instancetype)methodCallWithMethodName:(NSString*)method arguments:(id _Nullable)arguments; + +/** + * The method name. + */ +@property(readonly, nonatomic) NSString* method; + +/** + * The arguments. + */ +@property(readonly, nonatomic, nullable) id arguments; +@end + +/** + * Error object representing an unsuccessful outcome of invoking a method + * on a `FlutterMethodChannel`, or an error event on a `FlutterEventChannel`. + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterError : NSObject +/** + * Creates a `FlutterError` with the specified error code, message, and details. + * + * @param code An error code string for programmatic use. + * @param message A human-readable error message. + * @param details Custom error details. + */ ++ (instancetype)errorWithCode:(NSString*)code + message:(NSString* _Nullable)message + details:(id _Nullable)details; +/** + The error code. + */ +@property(readonly, nonatomic) NSString* code; + +/** + The error message. + */ +@property(readonly, nonatomic, nullable) NSString* message; + +/** + The error details. + */ +@property(readonly, nonatomic, nullable) id details; +@end + +/** + * Type of numeric data items encoded in a `FlutterStandardDataType`. + * + * - FlutterStandardDataTypeUInt8: plain bytes + * - FlutterStandardDataTypeInt32: 32-bit signed integers + * - FlutterStandardDataTypeInt64: 64-bit signed integers + * - FlutterStandardDataTypeFloat64: 64-bit floats + */ +typedef NS_ENUM(NSInteger, FlutterStandardDataType) { + // NOLINTBEGIN(readability-identifier-naming) + FlutterStandardDataTypeUInt8, + FlutterStandardDataTypeInt32, + FlutterStandardDataTypeInt64, + FlutterStandardDataTypeFloat32, + FlutterStandardDataTypeFloat64, + // NOLINTEND(readability-identifier-naming) +}; + +/** + * A byte buffer holding `UInt8`, `SInt32`, `SInt64`, or `Float64` values, used + * with `FlutterStandardMessageCodec` and `FlutterStandardMethodCodec`. + * + * Two's complement encoding is used for signed integers. IEEE754 + * double-precision representation is used for floats. The platform's native + * endianness is assumed. + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterStandardTypedData : NSObject +/** + * Creates a `FlutterStandardTypedData` which interprets the specified data + * as plain bytes. + * + * @param data the byte data. + */ ++ (instancetype)typedDataWithBytes:(NSData*)data; + +/** + * Creates a `FlutterStandardTypedData` which interprets the specified data + * as 32-bit signed integers. + * + * @param data the byte data. The length must be divisible by 4. + */ ++ (instancetype)typedDataWithInt32:(NSData*)data; + +/** + * Creates a `FlutterStandardTypedData` which interprets the specified data + * as 64-bit signed integers. + * + * @param data the byte data. The length must be divisible by 8. + */ ++ (instancetype)typedDataWithInt64:(NSData*)data; + +/** + * Creates a `FlutterStandardTypedData` which interprets the specified data + * as 32-bit floats. + * + * @param data the byte data. The length must be divisible by 8. + */ ++ (instancetype)typedDataWithFloat32:(NSData*)data; + +/** + * Creates a `FlutterStandardTypedData` which interprets the specified data + * as 64-bit floats. + * + * @param data the byte data. The length must be divisible by 8. + */ ++ (instancetype)typedDataWithFloat64:(NSData*)data; + +/** + * The raw underlying data buffer. + */ +@property(readonly, nonatomic) NSData* data; + +/** + * The type of the encoded values. + */ +@property(readonly, nonatomic, assign) FlutterStandardDataType type; + +/** + * The number of value items encoded. + */ +@property(readonly, nonatomic, assign) UInt32 elementCount; + +/** + * The number of bytes used by the encoding of a single value item. + */ +@property(readonly, nonatomic, assign) UInt8 elementSize; +@end + +/** + * An arbitrarily large integer value, used with `FlutterStandardMessageCodec` + * and `FlutterStandardMethodCodec`. + */ +FLUTTER_DARWIN_EXPORT +FLUTTER_UNAVAILABLE("Unavailable on 2018-08-31. Deprecated on 2018-01-09. " + "FlutterStandardBigInteger was needed because the Dart 1.0 int type had no " + "size limit. With Dart 2.0, the int type is a fixed-size, 64-bit signed " + "integer. If you need to communicate larger integers, use NSString encoding " + "instead.") +@interface FlutterStandardBigInteger : NSObject +@end + +/** + * A codec for method calls and enveloped results. + * + * Method calls are encoded as binary messages with enough structure that the + * codec can extract a method name `NSString` and an arguments `NSObject`, + * possibly `nil`. These data items are used to populate a `FlutterMethodCall`. + * + * Result envelopes are encoded as binary messages with enough structure that + * the codec can determine whether the result was successful or an error. In + * the former case, the codec can extract the result `NSObject`, possibly `nil`. + * In the latter case, the codec can extract an error code `NSString`, a + * human-readable `NSString` error message (possibly `nil`), and a custom + * error details `NSObject`, possibly `nil`. These data items are used to + * populate a `FlutterError`. + */ +FLUTTER_DARWIN_EXPORT +@protocol FlutterMethodCodec +/** + * Provides access to a shared instance this codec. + * + * @return The shared instance. + */ ++ (instancetype)sharedInstance; + +/** + * Encodes the specified method call into binary. + * + * @param methodCall The method call. The arguments value + * must be supported by this codec. + * @return The binary encoding. + */ +- (NSData*)encodeMethodCall:(FlutterMethodCall*)methodCall; + +/** + * Decodes the specified method call from binary. + * + * @param methodCall The method call to decode. + * @return The decoded method call. + */ +- (FlutterMethodCall*)decodeMethodCall:(NSData*)methodCall; + +/** + * Encodes the specified successful result into binary. + * + * @param result The result. Must be a value supported by this codec. + * @return The binary encoding. + */ +- (NSData*)encodeSuccessEnvelope:(id _Nullable)result; + +/** + * Encodes the specified error result into binary. + * + * @param error The error object. The error details value must be supported + * by this codec. + * @return The binary encoding. + */ +- (NSData*)encodeErrorEnvelope:(FlutterError*)error; + +/** + * Deccodes the specified result envelope from binary. + * + * @param envelope The error object. + * @return The result value, if the envelope represented a successful result, + * or a `FlutterError` instance, if not. + */ +- (id _Nullable)decodeEnvelope:(NSData*)envelope; +@end + +/** + * A `FlutterMethodCodec` using UTF-8 encoded JSON method calls and result + * envelopes. + * + * This codec is guaranteed to be compatible with the corresponding + * [JSONMethodCodec](https://api.flutter.dev/flutter/services/JSONMethodCodec-class.html) + * on the Dart side. These parts of the Flutter SDK are evolved synchronously. + * + * Values supported as methods arguments and result payloads are + * those supported as top-level or leaf values by `FlutterJSONMessageCodec`. + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterJSONMethodCodec : NSObject +@end + +/** + * A `FlutterMethodCodec` using the Flutter standard binary encoding. + * + * This codec is guaranteed to be compatible with the corresponding + * [StandardMethodCodec](https://api.flutter.dev/flutter/services/StandardMethodCodec-class.html) + * on the Dart side. These parts of the Flutter SDK are evolved synchronously. + * + * Values supported as method arguments and result payloads are those supported by + * `FlutterStandardMessageCodec`. + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterStandardMethodCodec : NSObject +/** + * Create a `FlutterStandardMethodCodec` who will read and write to \p readerWriter. + */ ++ (instancetype)codecWithReaderWriter:(FlutterStandardReaderWriter*)readerWriter; +@end + +NS_ASSUME_NONNULL_END + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERCODECS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Headers/FlutterDartProject.h b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Headers/FlutterDartProject.h new file mode 100644 index 0000000000000000000000000000000000000000..c1fd8db5053b82b9e474daff07b30aa3e144f21b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Headers/FlutterDartProject.h @@ -0,0 +1,102 @@ +// 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_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERDARTPROJECT_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERDARTPROJECT_H_ + +#import + +#import "FlutterMacros.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * A set of Flutter and Dart assets used by a `FlutterEngine` to initialize execution. + * + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterDartProject : NSObject + +/** + * Initializes a Flutter Dart project from a bundle. + * + * The bundle must either contain a flutter_assets resource directory, or set the Info.plist key + * FLTAssetsPath to override that name (if you are doing a custom build using a different name). + * + * @param bundle The bundle containing the Flutter assets directory. If nil, the App framework + * created by Flutter will be used. + */ +- (instancetype)initWithPrecompiledDartBundle:(nullable NSBundle*)bundle NS_DESIGNATED_INITIALIZER; +/** + * Unavailable - use `init` instead. + */ +- (instancetype)initFromDefaultSourceForConfiguration API_UNAVAILABLE(macos) + FLUTTER_UNAVAILABLE("Use -init instead."); + +/** + * Returns the default identifier for the bundle where we expect to find the Flutter Dart + * application. + */ ++ (NSString*)defaultBundleIdentifier; + +/** + * An NSArray of NSStrings to be passed as command line arguments to the Dart entrypoint. + * + * If this is not explicitly set, this will default to the contents of + * [NSProcessInfo arguments], without the binary name. + * + * Set this to nil to pass no arguments to the Dart entrypoint. + */ +@property(nonatomic, nullable, copy) + NSArray* dartEntrypointArguments API_UNAVAILABLE(ios); + +/** + * Returns the file name for the given asset. If the bundle with the identifier + * "io.flutter.flutter.app" exists, it will try use that bundle; otherwise, it + * will use the main bundle. To specify a different bundle, use + * `+lookupKeyForAsset:fromBundle`. + * + * @param asset The name of the asset. The name can be hierarchical. + * @return the file name to be used for lookup in the main bundle. + */ ++ (NSString*)lookupKeyForAsset:(NSString*)asset; + +/** + * Returns the file name for the given asset. + * The returned file name can be used to access the asset in the supplied bundle. + * + * @param asset The name of the asset. The name can be hierarchical. + * @param bundle The `NSBundle` to use for looking up the asset. + * @return the file name to be used for lookup in the main bundle. + */ ++ (NSString*)lookupKeyForAsset:(NSString*)asset fromBundle:(nullable NSBundle*)bundle; + +/** + * Returns the file name for the given asset which originates from the specified package. + * The returned file name can be used to access the asset in the application's main bundle. + * + * @param asset The name of the asset. The name can be hierarchical. + * @param package The name of the package from which the asset originates. + * @return the file name to be used for lookup in the main bundle. + */ ++ (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package; + +/** + * Returns the file name for the given asset which originates from the specified package. + * The returned file name can be used to access the asset in the specified bundle. + * + * @param asset The name of the asset. The name can be hierarchical. + * @param package The name of the package from which the asset originates. + * @param bundle The bundle to use when doing the lookup. + * @return the file name to be used for lookup in the main bundle. + */ ++ (NSString*)lookupKeyForAsset:(NSString*)asset + fromPackage:(NSString*)package + fromBundle:(nullable NSBundle*)bundle; + +@end + +NS_ASSUME_NONNULL_END + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERDARTPROJECT_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Headers/FlutterHourFormat.h b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Headers/FlutterHourFormat.h new file mode 100644 index 0000000000000000000000000000000000000000..e33e1a0ac66a62b7c8990066f9dc9903598e739c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Headers/FlutterHourFormat.h @@ -0,0 +1,15 @@ +// 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_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERHOURFORMAT_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERHOURFORMAT_H_ + +#import + +@interface FlutterHourFormat : NSObject ++ (BOOL)isAlwaysUse24HourFormat; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERHOURFORMAT_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h new file mode 100644 index 0000000000000000000000000000000000000000..7f53b41334ab8d8299578b0aae9483074b9f05ef --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h @@ -0,0 +1,48 @@ +// 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_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERMACROS_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERMACROS_H_ + +#if defined(FLUTTER_FRAMEWORK) + +#define FLUTTER_DARWIN_EXPORT __attribute__((visibility("default"))) + +#else // defined(FLUTTER_SDK) + +#define FLUTTER_DARWIN_EXPORT + +#endif // defined(FLUTTER_SDK) + +#ifndef NS_ASSUME_NONNULL_BEGIN +#define NS_ASSUME_NONNULL_BEGIN _Pragma("clang assume_nonnull begin") +#define NS_ASSUME_NONNULL_END _Pragma("clang assume_nonnull end") +#endif // defined(NS_ASSUME_NONNULL_BEGIN) + +/** + * Indicates that the API has been deprecated for the specified reason. Code + * that uses the deprecated API will continue to work as before. However, the + * API will soon become unavailable and users are encouraged to immediately take + * the appropriate action mentioned in the deprecation message and the BREAKING + * CHANGES section present in the Flutter.h umbrella header. + */ +#define FLUTTER_DEPRECATED(msg) __attribute__((__deprecated__(msg))) + +/** + * Indicates that the previously deprecated API is now unavailable. Code that + * uses the API will not work and the declaration of the API is only a stub + * meant to display the given message detailing the actions for the user to take + * immediately. + */ +#define FLUTTER_UNAVAILABLE(msg) __attribute__((__unavailable__(msg))) + +#if __has_feature(objc_arc) +#define FLUTTER_ASSERT_ARC +#define FLUTTER_ASSERT_NOT_ARC #error ARC must be disabled ! +#else +#define FLUTTER_ASSERT_ARC #error ARC must be enabled ! +#define FLUTTER_ASSERT_NOT_ARC +#endif + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERMACROS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Headers/FlutterTexture.h b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Headers/FlutterTexture.h new file mode 100644 index 0000000000000000000000000000000000000000..1fa7a0ef6c2051952d33f2f8a2b9aa22f28670a9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Headers/FlutterTexture.h @@ -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. + +#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERTEXTURE_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERTEXTURE_H_ + +#import +#import + +#import "FlutterMacros.h" + +NS_ASSUME_NONNULL_BEGIN + +FLUTTER_DARWIN_EXPORT +/** + * Represents a texture that can be shared with Flutter. + * + * See also: https://github.com/flutter/plugins/tree/master/packages/camera + */ +@protocol FlutterTexture +/** + * Copy the contents of the texture into a `CVPixelBuffer`. + * + * The type of the pixel buffer is one of the following: + * - `kCVPixelFormatType_32BGRA` + * - `kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange` + * - `kCVPixelFormatType_420YpCbCr8BiPlanarFullRange` + */ +- (CVPixelBufferRef _Nullable)copyPixelBuffer; + +/** + * Called when the texture is unregistered. + * + * Called on the raster thread. + */ +@optional +- (void)onTextureUnregistered:(NSObject*)texture; +@end + +FLUTTER_DARWIN_EXPORT +/** + * A collection of registered `FlutterTexture`'s. + */ +@protocol FlutterTextureRegistry +/** + * Registers a `FlutterTexture` for usage in Flutter and returns an id that can be used to reference + * that texture when calling into Flutter with channels. Textures must be registered on the + * platform thread. On success returns the pointer to the registered texture, else returns 0. + */ +- (int64_t)registerTexture:(NSObject*)texture; +/** + * Notifies Flutter that the content of the previously registered texture has been updated. + * + * This will trigger a call to `-[FlutterTexture copyPixelBuffer]` on the raster thread. + */ +- (void)textureFrameAvailable:(int64_t)textureId; +/** + * Unregisters a `FlutterTexture` that has previously regeistered with `registerTexture:`. Textures + * must be unregistered on the platform thread. + * + * @param textureId The result that was previously returned from `registerTexture:`. + */ +- (void)unregisterTexture:(int64_t)textureId; +@end + +NS_ASSUME_NONNULL_END + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERTEXTURE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.h b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.h new file mode 100644 index 0000000000000000000000000000000000000000..48d91f88cd3b961272e99fa148e8117fbaa9c607 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.h @@ -0,0 +1,19 @@ +// 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_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_SOURCE_FLUTTERBINARYMESSENGERRELAY_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_SOURCE_FLUTTERBINARYMESSENGERRELAY_H_ + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" + +#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG +FLUTTER_DARWIN_EXPORT +#endif +@interface FlutterBinaryMessengerRelay : NSObject +@property(nonatomic, weak) NSObject* parent; +- (instancetype)initWithParent:(NSObject*)parent; +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_SOURCE_FLUTTERBINARYMESSENGERRELAY_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.mm b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.mm new file mode 100644 index 0000000000000000000000000000000000000000..4b13093666c8c5b9f8d7c8f12e9a47cc3d190c39 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.mm @@ -0,0 +1,81 @@ +// 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. + +#import "flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.h" + +#include "flutter/fml/logging.h" + +FLUTTER_ASSERT_ARC + +@implementation FlutterBinaryMessengerRelay +#pragma mark - FlutterBinaryMessenger + +- (instancetype)initWithParent:(NSObject*)parent { + self = [super init]; + if (self != nil) { + _parent = parent; + } + return self; +} + +- (void)sendOnChannel:(NSString*)channel message:(NSData*)message { + if (self.parent) { + [self.parent sendOnChannel:channel message:message binaryReply:nil]; + } else { + FML_LOG(WARNING) << "Communicating on a dead channel."; + } +} + +- (void)sendOnChannel:(NSString*)channel + message:(NSData*)message + binaryReply:(FlutterBinaryReply)callback { + if (self.parent) { + [self.parent sendOnChannel:channel message:message binaryReply:callback]; + } else { + FML_LOG(WARNING) << "Communicating on a dead channel."; + } +} + +- (NSObject*)makeBackgroundTaskQueue { + if (self.parent) { + return [self.parent makeBackgroundTaskQueue]; + } else { + return nil; + }; +} + +- (FlutterBinaryMessengerConnection)setMessageHandlerOnChannel:(NSString*)channel + binaryMessageHandler: + (FlutterBinaryMessageHandler)handler { + if (self.parent) { + return [self.parent setMessageHandlerOnChannel:channel binaryMessageHandler:handler]; + } else { + FML_LOG(WARNING) << "Communicating on a dead channel."; + return -1; + } +} + +- (FlutterBinaryMessengerConnection)setMessageHandlerOnChannel:(NSString*)channel + binaryMessageHandler:(FlutterBinaryMessageHandler)handler + taskQueue: + (NSObject*)taskQueue { + if (self.parent) { + return [self.parent setMessageHandlerOnChannel:channel + binaryMessageHandler:handler + taskQueue:taskQueue]; + } else { + FML_LOG(WARNING) << "Communicating on a dead channel."; + return -1; + } +} + +- (void)cleanUpConnection:(FlutterBinaryMessengerConnection)connection { + if (self.parent) { + return [self.parent cleanUpConnection:connection]; + } else { + FML_LOG(WARNING) << "Communicating on a dead channel."; + } +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelayTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelayTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..b73989d581c96d1c2b27029498d9829324ea129c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelayTest.mm @@ -0,0 +1,104 @@ +// 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. + +#import "flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.h" + +#import + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/common/framework/Source/FlutterTestUtils.h" +#import "flutter/shell/platform/darwin/ios/flutter_task_queue_dispatch.h" +#import "flutter/testing/testing.h" +#include "gtest/gtest.h" + +FLUTTER_ASSERT_ARC + +@interface FlutterBinaryMessengerRelayTest : NSObject +@end + +@implementation FlutterBinaryMessengerRelayTest + +- (void)testCreate { + id messenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + FlutterBinaryMessengerRelay* relay = + [[FlutterBinaryMessengerRelay alloc] initWithParent:messenger]; + EXPECT_NE(relay, nil); + EXPECT_EQ(messenger, relay.parent); +} + +- (void)testPassesCallOn { + id messenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + FlutterBinaryMessengerRelay* relay = + [[FlutterBinaryMessengerRelay alloc] initWithParent:messenger]; + char messageData[] = {'a', 'a', 'r', 'o', 'n'}; + NSData* message = [NSData dataWithBytes:messageData length:sizeof(messageData)]; + NSString* channel = @"foobar"; + [relay sendOnChannel:channel message:message binaryReply:nil]; + OCMVerify([messenger sendOnChannel:channel message:message binaryReply:nil]); +} + +- (void)testDoesntPassCallOn { + id messenger = OCMStrictProtocolMock(@protocol(FlutterBinaryMessenger)); + FlutterBinaryMessengerRelay* relay = + [[FlutterBinaryMessengerRelay alloc] initWithParent:messenger]; + char messageData[] = {'a', 'a', 'r', 'o', 'n'}; + NSData* message = [NSData dataWithBytes:messageData length:sizeof(messageData)]; + NSString* channel = @"foobar"; + relay.parent = nil; + [relay sendOnChannel:channel message:message binaryReply:nil]; +} + +- (void)testSetMessageHandlerWithTaskQueue { + id messenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + FlutterBinaryMessengerRelay* relay = + [[FlutterBinaryMessengerRelay alloc] initWithParent:messenger]; + NSString* channel = @"foobar"; + NSObject* taskQueue = OCMProtocolMock(@protocol(FlutterTaskQueueDispatch)); + FlutterBinaryMessageHandler handler = ^(NSData* _Nullable, FlutterBinaryReply _Nonnull) { + }; + [relay setMessageHandlerOnChannel:channel binaryMessageHandler:handler taskQueue:taskQueue]; + OCMVerify([messenger setMessageHandlerOnChannel:channel + binaryMessageHandler:handler + taskQueue:taskQueue]); +} + +- (void)testMakeBackgroundTaskQueue { + id messenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + FlutterBinaryMessengerRelay* relay = + [[FlutterBinaryMessengerRelay alloc] initWithParent:messenger]; + [relay makeBackgroundTaskQueue]; + OCMVerify([messenger makeBackgroundTaskQueue]); +} + +@end + +TEST(FlutterBinaryMessengerRelayTest, Create) { + ASSERT_FALSE(FLTThrowsObjcException(^{ + [[FlutterBinaryMessengerRelayTest alloc] testCreate]; + })); +} + +TEST(FlutterBinaryMessengerRelayTest, PassesCallOn) { + ASSERT_FALSE(FLTThrowsObjcException(^{ + [[FlutterBinaryMessengerRelayTest alloc] testPassesCallOn]; + })); +} + +TEST(FlutterBinaryMessengerRelayTest, DoesntPassCallOn) { + ASSERT_FALSE(FLTThrowsObjcException(^{ + [[FlutterBinaryMessengerRelayTest alloc] testDoesntPassCallOn]; + })); +} + +TEST(FlutterBinaryMessengerRelayTest, SetMessageHandlerWithTaskQueue) { + ASSERT_FALSE(FLTThrowsObjcException(^{ + [[FlutterBinaryMessengerRelayTest alloc] testSetMessageHandlerWithTaskQueue]; + })); +} + +TEST(FlutterBinaryMessengerRelayTest, SetMakeBackgroundTaskQueue) { + ASSERT_FALSE(FLTThrowsObjcException(^{ + [[FlutterBinaryMessengerRelayTest alloc] testMakeBackgroundTaskQueue]; + })); +} diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterChannels.mm b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterChannels.mm new file mode 100644 index 0000000000000000000000000000000000000000..78d5c08404227d0068080b7b60e4b106a04b8696 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterChannels.mm @@ -0,0 +1,438 @@ +// 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. + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" + +FLUTTER_ASSERT_ARC + +#pragma mark - Basic message channel + +static NSString* const kFlutterChannelBuffersChannel = @"dev.flutter/channel-buffers"; +static NSString* const kResizeMethod = @"resize"; +static NSString* const kOverflowMethod = @"overflow"; + +static void ResizeChannelBuffer(NSObject* binaryMessenger, + NSString* channel, + NSInteger newSize) { + NSCAssert(newSize >= 0, @"Channel buffer size must be non-negative"); + // Cast newSize to int because the deserialization logic handles only 32 bits values, + // see + // https://github.com/flutter/engine/blob/93e8901490e78c7ba7e319cce4470d9c6478c6dc/lib/ui/channel_buffers.dart#L495. + NSArray* args = @[ channel, @(static_cast(newSize)) ]; + FlutterMethodCall* resizeMethodCall = [FlutterMethodCall methodCallWithMethodName:kResizeMethod + arguments:args]; + NSObject* codec = [FlutterStandardMethodCodec sharedInstance]; + NSData* message = [codec encodeMethodCall:resizeMethodCall]; + [binaryMessenger sendOnChannel:kFlutterChannelBuffersChannel message:message]; +} + +/** + * Defines whether a channel should show warning messages when discarding messages + * due to overflow. + * + * @param binaryMessenger The binary messenger. + * @param channel The channel name. + * @param warns When false, the channel is expected to overflow and warning messages + * will not be shown. + */ +static void SetWarnsOnOverflow(NSObject* binaryMessenger, + NSString* channel, + BOOL warns) { + FlutterMethodCall* overflowMethodCall = + [FlutterMethodCall methodCallWithMethodName:kOverflowMethod + arguments:@[ channel, @(!warns) ]]; + NSObject* codec = [FlutterStandardMethodCodec sharedInstance]; + NSData* message = [codec encodeMethodCall:overflowMethodCall]; + [binaryMessenger sendOnChannel:kFlutterChannelBuffersChannel message:message]; +} + +static FlutterBinaryMessengerConnection SetMessageHandler( + NSObject* messenger, + NSString* name, + FlutterBinaryMessageHandler handler, + NSObject* taskQueue) { + if (taskQueue) { + NSCAssert([messenger respondsToSelector:@selector(setMessageHandlerOnChannel: + binaryMessageHandler:taskQueue:)], + @""); + return [messenger setMessageHandlerOnChannel:name + binaryMessageHandler:handler + taskQueue:taskQueue]; + } else { + return [messenger setMessageHandlerOnChannel:name binaryMessageHandler:handler]; + } +} + +//////////////////////////////////////////////////////////////////////////////// +@implementation FlutterBasicMessageChannel { + NSObject* _messenger; + NSString* _name; + NSObject* _codec; + FlutterBinaryMessengerConnection _connection; + NSObject* _taskQueue; +} ++ (instancetype)messageChannelWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger { + NSObject* codec = [FlutterStandardMessageCodec sharedInstance]; + return [FlutterBasicMessageChannel messageChannelWithName:name + binaryMessenger:messenger + codec:codec]; +} ++ (instancetype)messageChannelWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger + codec:(NSObject*)codec { + return [[FlutterBasicMessageChannel alloc] initWithName:name + binaryMessenger:messenger + codec:codec]; +} + +- (instancetype)initWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger + codec:(NSObject*)codec { + self = [self initWithName:name binaryMessenger:messenger codec:codec taskQueue:nil]; + return self; +} + +- (instancetype)initWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger + codec:(NSObject*)codec + taskQueue:(NSObject*)taskQueue { + self = [super init]; + NSAssert(self, @"Super init cannot be nil"); + _name = [name copy]; + _messenger = messenger; + _codec = codec; + _taskQueue = taskQueue; + return self; +} + +- (void)sendMessage:(id)message { + [_messenger sendOnChannel:_name message:[_codec encode:message]]; +} + +- (void)sendMessage:(id)message reply:(FlutterReply)callback { + FlutterBinaryReply reply = ^(NSData* data) { + if (callback) { + callback([_codec decode:data]); + } + }; + [_messenger sendOnChannel:_name message:[_codec encode:message] binaryReply:reply]; +} + +- (void)setMessageHandler:(FlutterMessageHandler)handler { + if (!handler) { + if (_connection > 0) { + [_messenger cleanUpConnection:_connection]; + _connection = 0; + } else { + [_messenger setMessageHandlerOnChannel:_name binaryMessageHandler:nil]; + } + return; + } + + // Grab reference to avoid retain on self. + // `self` might be released before the block, so the block needs to retain the codec to + // make sure it is not released with `self` + NSObject* codec = _codec; + FlutterBinaryMessageHandler messageHandler = ^(NSData* message, FlutterBinaryReply callback) { + handler([codec decode:message], ^(id reply) { + callback([codec encode:reply]); + }); + }; + _connection = SetMessageHandler(_messenger, _name, messageHandler, _taskQueue); +} + ++ (void)resizeChannelWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger + size:(NSInteger)newSize { + ResizeChannelBuffer(messenger, name, newSize); +} + +- (void)resizeChannelBuffer:(NSInteger)newSize { + ResizeChannelBuffer(_messenger, _name, newSize); +} + ++ (void)setWarnsOnOverflow:(BOOL)warns + forChannelWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger { + SetWarnsOnOverflow(messenger, name, warns); +} + +- (void)setWarnsOnOverflow:(BOOL)warns { + SetWarnsOnOverflow(_messenger, _name, warns); +} + +@end + +#pragma mark - Method channel + +//////////////////////////////////////////////////////////////////////////////// +@implementation FlutterError ++ (instancetype)errorWithCode:(NSString*)code message:(NSString*)message details:(id)details { + return [[FlutterError alloc] initWithCode:code message:message details:details]; +} + +- (instancetype)initWithCode:(NSString*)code message:(NSString*)message details:(id)details { + NSAssert(code, @"Code cannot be nil"); + self = [super init]; + NSAssert(self, @"Super init cannot be nil"); + _code = [code copy]; + _message = [message copy]; + _details = details; + return self; +} + +- (BOOL)isEqual:(id)object { + if (self == object) { + return YES; + } + if (![object isKindOfClass:[FlutterError class]]) { + return NO; + } + FlutterError* other = (FlutterError*)object; + return [self.code isEqual:other.code] && + ((!self.message && !other.message) || [self.message isEqual:other.message]) && + ((!self.details && !other.details) || [self.details isEqual:other.details]); +} + +- (NSUInteger)hash { + return [self.code hash] ^ [self.message hash] ^ [self.details hash]; +} +@end + +//////////////////////////////////////////////////////////////////////////////// +@implementation FlutterMethodCall ++ (instancetype)methodCallWithMethodName:(NSString*)method arguments:(id)arguments { + return [[FlutterMethodCall alloc] initWithMethodName:method arguments:arguments]; +} + +- (instancetype)initWithMethodName:(NSString*)method arguments:(id)arguments { + NSAssert(method, @"Method name cannot be nil"); + self = [super init]; + NSAssert(self, @"Super init cannot be nil"); + _method = [method copy]; + _arguments = arguments; + return self; +} + +- (BOOL)isEqual:(id)object { + if (self == object) { + return YES; + } + if (![object isKindOfClass:[FlutterMethodCall class]]) { + return NO; + } + FlutterMethodCall* other = (FlutterMethodCall*)object; + return [self.method isEqual:[other method]] && + ((!self.arguments && !other.arguments) || [self.arguments isEqual:other.arguments]); +} + +- (NSUInteger)hash { + return [self.method hash] ^ [self.arguments hash]; +} +@end + +NSObject const* FlutterMethodNotImplemented = [[NSObject alloc] init]; + +//////////////////////////////////////////////////////////////////////////////// +@implementation FlutterMethodChannel { + NSObject* _messenger; + NSString* _name; + NSObject* _codec; + FlutterBinaryMessengerConnection _connection; + NSObject* _taskQueue; +} + ++ (instancetype)methodChannelWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger { + NSObject* codec = [FlutterStandardMethodCodec sharedInstance]; + return [FlutterMethodChannel methodChannelWithName:name binaryMessenger:messenger codec:codec]; +} + ++ (instancetype)methodChannelWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger + codec:(NSObject*)codec { + return [[FlutterMethodChannel alloc] initWithName:name binaryMessenger:messenger codec:codec]; +} + +- (instancetype)initWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger + codec:(NSObject*)codec { + self = [self initWithName:name binaryMessenger:messenger codec:codec taskQueue:nil]; + return self; +} +- (instancetype)initWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger + codec:(NSObject*)codec + taskQueue:(NSObject*)taskQueue { + self = [super init]; + NSAssert(self, @"Super init cannot be nil"); + _name = [name copy]; + _messenger = messenger; + _codec = codec; + _taskQueue = taskQueue; + return self; +} + +- (void)invokeMethod:(NSString*)method arguments:(id)arguments { + FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:method + arguments:arguments]; + NSData* message = [_codec encodeMethodCall:methodCall]; + [_messenger sendOnChannel:_name message:message]; +} + +- (void)invokeMethod:(NSString*)method arguments:(id)arguments result:(FlutterResult)callback { + FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:method + arguments:arguments]; + NSData* message = [_codec encodeMethodCall:methodCall]; + FlutterBinaryReply reply = ^(NSData* data) { + if (callback) { + callback((data == nil) ? FlutterMethodNotImplemented : [_codec decodeEnvelope:data]); + } + }; + [_messenger sendOnChannel:_name message:message binaryReply:reply]; +} + +- (void)setMethodCallHandler:(FlutterMethodCallHandler)handler { + if (!handler) { + if (_connection > 0) { + [_messenger cleanUpConnection:_connection]; + _connection = 0; + } else { + [_messenger setMessageHandlerOnChannel:_name binaryMessageHandler:nil]; + } + return; + } + // Make sure the block captures the codec, not self. + // `self` might be released before the block, so the block needs to retain the codec to + // make sure it is not released with `self` + NSObject* codec = _codec; + FlutterBinaryMessageHandler messageHandler = ^(NSData* message, FlutterBinaryReply callback) { + FlutterMethodCall* call = [codec decodeMethodCall:message]; + handler(call, ^(id result) { + if (result == FlutterMethodNotImplemented) { + callback(nil); + } else if ([result isKindOfClass:[FlutterError class]]) { + callback([codec encodeErrorEnvelope:(FlutterError*)result]); + } else { + callback([codec encodeSuccessEnvelope:result]); + } + }); + }; + _connection = SetMessageHandler(_messenger, _name, messageHandler, _taskQueue); +} + +- (void)resizeChannelBuffer:(NSInteger)newSize { + ResizeChannelBuffer(_messenger, _name, newSize); +} + +@end + +#pragma mark - Event channel + +NSObject const* FlutterEndOfEventStream = [[NSObject alloc] init]; + +//////////////////////////////////////////////////////////////////////////////// +@implementation FlutterEventChannel { + NSObject* _messenger; + NSString* _name; + NSObject* _codec; + NSObject* _taskQueue; + FlutterBinaryMessengerConnection _connection; +} ++ (instancetype)eventChannelWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger { + NSObject* codec = [FlutterStandardMethodCodec sharedInstance]; + return [FlutterEventChannel eventChannelWithName:name binaryMessenger:messenger codec:codec]; +} + ++ (instancetype)eventChannelWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger + codec:(NSObject*)codec { + return [[FlutterEventChannel alloc] initWithName:name binaryMessenger:messenger codec:codec]; +} + +- (instancetype)initWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger + codec:(NSObject*)codec { + return [self initWithName:name binaryMessenger:messenger codec:codec taskQueue:nil]; +} + +- (instancetype)initWithName:(NSString*)name + binaryMessenger:(NSObject*)messenger + codec:(NSObject*)codec + taskQueue:(NSObject* _Nullable)taskQueue { + self = [super init]; + NSAssert(self, @"Super init cannot be nil"); + _name = [name copy]; + _messenger = messenger; + _codec = codec; + _taskQueue = taskQueue; + return self; +} + +static FlutterBinaryMessengerConnection SetStreamHandlerMessageHandlerOnChannel( + NSObject* handler, + NSString* name, + NSObject* messenger, + NSObject* codec, + NSObject* taskQueue) { + __block FlutterEventSink currentSink = nil; + FlutterBinaryMessageHandler messageHandler = ^(NSData* message, FlutterBinaryReply callback) { + FlutterMethodCall* call = [codec decodeMethodCall:message]; + if ([call.method isEqual:@"listen"]) { + if (currentSink) { + FlutterError* error = [handler onCancelWithArguments:nil]; + if (error) { + NSLog(@"Failed to cancel existing stream: %@. %@ (%@)", error.code, error.message, + error.details); + } + } + currentSink = ^(id event) { + if (event == FlutterEndOfEventStream) { + [messenger sendOnChannel:name message:nil]; + } else if ([event isKindOfClass:[FlutterError class]]) { + [messenger sendOnChannel:name message:[codec encodeErrorEnvelope:(FlutterError*)event]]; + } else { + [messenger sendOnChannel:name message:[codec encodeSuccessEnvelope:event]]; + } + }; + FlutterError* error = [handler onListenWithArguments:call.arguments eventSink:currentSink]; + if (error) { + callback([codec encodeErrorEnvelope:error]); + } else { + callback([codec encodeSuccessEnvelope:nil]); + } + } else if ([call.method isEqual:@"cancel"]) { + if (!currentSink) { + callback( + [codec encodeErrorEnvelope:[FlutterError errorWithCode:@"error" + message:@"No active stream to cancel" + details:nil]]); + return; + } + currentSink = nil; + FlutterError* error = [handler onCancelWithArguments:call.arguments]; + if (error) { + callback([codec encodeErrorEnvelope:error]); + } else { + callback([codec encodeSuccessEnvelope:nil]); + } + } else { + callback(nil); + } + }; + return SetMessageHandler(messenger, name, messageHandler, taskQueue); +} + +- (void)setStreamHandler:(NSObject*)handler { + if (!handler) { + [_messenger cleanUpConnection:_connection]; + _connection = 0; + return; + } + _connection = + SetStreamHandlerMessageHandlerOnChannel(handler, _name, _messenger, _codec, _taskQueue); +} +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterChannelsTest.m b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterChannelsTest.m new file mode 100644 index 0000000000000000000000000000000000000000..bb8af64ad460ebc6993bd054dfb0d0e39fe67991 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterChannelsTest.m @@ -0,0 +1,385 @@ +// 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. + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" +#import "flutter/shell/platform/darwin/ios/flutter_task_queue_dispatch.h" + +#import +#import + +FLUTTER_ASSERT_ARC + +@interface MockBinaryMessenger : NSObject +@property(nonatomic, copy) NSString* channel; +@property(nonatomic, strong) NSData* message; +@property(nonatomic, strong) NSMutableDictionary* handlers; +@end +@implementation MockBinaryMessenger +- (instancetype)init { + self = [super init]; + if (self) { + _handlers = [[NSMutableDictionary alloc] init]; + } + return self; +} + +- (void)sendOnChannel:(NSString*)channel message:(NSData* _Nullable)message { + [self sendOnChannel:channel message:message binaryReply:nil]; +} + +- (void)sendOnChannel:(NSString*)channel + message:(NSData* _Nullable)message + binaryReply:(FlutterBinaryReply _Nullable)callback { + self.channel = channel; + self.message = message; +} + +- (FlutterBinaryMessengerConnection)setMessageHandlerOnChannel:(NSString*)channel + binaryMessageHandler: + (FlutterBinaryMessageHandler _Nullable)handler { + [self.handlers setObject:handler forKey:channel]; + return 0; +} + +- (void)cleanUpConnection:(FlutterBinaryMessengerConnection)connection { +} + +@end + +@interface FlutterChannelsTest : XCTestCase +@end + +@implementation FlutterChannelsTest + +- (void)testMethodInvoke { + NSString* channelName = @"foo"; + id binaryMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + id codec = OCMProtocolMock(@protocol(FlutterMethodCodec)); + FlutterMethodChannel* channel = [[FlutterMethodChannel alloc] initWithName:channelName + binaryMessenger:binaryMessenger + codec:codec]; + XCTAssertNotNil(channel); + NSData* encodedMethodCall = [@"hey" dataUsingEncoding:NSUTF8StringEncoding]; + OCMStub([codec encodeMethodCall:[OCMArg any]]).andReturn(encodedMethodCall); + [channel invokeMethod:@"foo" arguments:@[ @(1) ]]; + OCMVerify([binaryMessenger sendOnChannel:channelName message:encodedMethodCall]); +} + +- (void)testMethodInvokeWithReply { + NSString* channelName = @"foo"; + id binaryMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + id codec = OCMProtocolMock(@protocol(FlutterMethodCodec)); + FlutterMethodChannel* channel = [[FlutterMethodChannel alloc] initWithName:channelName + binaryMessenger:binaryMessenger + codec:codec]; + XCTAssertNotNil(channel); + NSData* encodedMethodCall = [@"hey" dataUsingEncoding:NSUTF8StringEncoding]; + OCMStub([codec encodeMethodCall:[OCMArg any]]).andReturn(encodedMethodCall); + XCTestExpectation* didCallReply = [self expectationWithDescription:@"didCallReply"]; + OCMExpect([binaryMessenger sendOnChannel:channelName + message:encodedMethodCall + binaryReply:[OCMArg checkWithBlock:^BOOL(id obj) { + FlutterBinaryReply reply = obj; + reply(nil); + return YES; + }]]); + [channel invokeMethod:@"foo" + arguments:@[ @1 ] + result:^(id _Nullable result) { + [didCallReply fulfill]; + XCTAssertEqual(FlutterMethodNotImplemented, result); + }]; + OCMVerifyAll(binaryMessenger); + [self waitForExpectationsWithTimeout:1.0 handler:nil]; +} + +- (void)testMethodMessageHandler { + NSString* channelName = @"foo"; + id binaryMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + id codec = OCMProtocolMock(@protocol(FlutterMethodCodec)); + FlutterMethodChannel* channel = [[FlutterMethodChannel alloc] initWithName:channelName + binaryMessenger:binaryMessenger + codec:codec]; + XCTAssertNotNil(channel); + + NSData* encodedMethodCall = [@"hey" dataUsingEncoding:NSUTF8StringEncoding]; + OCMStub([codec encodeMethodCall:[OCMArg any]]).andReturn(encodedMethodCall); + FlutterMethodCallHandler handler = + ^(FlutterMethodCall* _Nonnull call, FlutterResult _Nonnull result) { + }; + [channel setMethodCallHandler:handler]; + OCMVerify([binaryMessenger setMessageHandlerOnChannel:channelName + binaryMessageHandler:[OCMArg isNotNil]]); +} + +- (void)testCallMethodHandler { + NSString* channelName = @"foo"; + MockBinaryMessenger* binaryMessenger = [[MockBinaryMessenger alloc] init]; + id codec = OCMProtocolMock(@protocol(FlutterMethodCodec)); + FlutterMethodChannel* channel = [[FlutterMethodChannel alloc] initWithName:channelName + binaryMessenger:binaryMessenger + codec:codec]; + XCTAssertNotNil(channel); + + NSData* encodedMethodCall = [@"encoded" dataUsingEncoding:NSUTF8StringEncoding]; + NSData* replyData = [@"reply" dataUsingEncoding:NSUTF8StringEncoding]; + NSData* replyEnvelopeData = [@"reply-envelope" dataUsingEncoding:NSUTF8StringEncoding]; + FlutterMethodCall* methodCall = [[FlutterMethodCall alloc] init]; + OCMStub([codec decodeMethodCall:encodedMethodCall]).andReturn(methodCall); + OCMStub([codec encodeSuccessEnvelope:replyData]).andReturn(replyEnvelopeData); + XCTestExpectation* didCallHandler = [self expectationWithDescription:@"didCallHandler"]; + XCTestExpectation* didCallReply = [self expectationWithDescription:@"didCallReply"]; + FlutterMethodCallHandler handler = + ^(FlutterMethodCall* _Nonnull call, FlutterResult _Nonnull result) { + XCTAssertEqual(methodCall, call); + [didCallHandler fulfill]; + result(replyData); + }; + [channel setMethodCallHandler:handler]; + binaryMessenger.handlers[channelName](encodedMethodCall, ^(NSData* reply) { + [didCallReply fulfill]; + XCTAssertEqual(replyEnvelopeData, reply); + }); + [self waitForExpectationsWithTimeout:1.0 handler:nil]; +} + +- (void)testResize { + NSString* channelName = @"flutter/test"; + id binaryMessenger = OCMStrictProtocolMock(@protocol(FlutterBinaryMessenger)); + id codec = OCMProtocolMock(@protocol(FlutterMethodCodec)); + FlutterBasicMessageChannel* channel = + [[FlutterBasicMessageChannel alloc] initWithName:channelName + binaryMessenger:binaryMessenger + codec:codec]; + XCTAssertNotNil(channel); + + // The expected content was created from the following Dart code: + // MethodCall call = MethodCall('resize', ['flutter/test',3]); + // StandardMethodCodec().encodeMethodCall(call).buffer.asUint8List(); + const unsigned char bytes[] = {7, 6, 114, 101, 115, 105, 122, 101, 12, 2, + 7, 12, 102, 108, 117, 116, 116, 101, 114, 47, + 116, 101, 115, 116, 3, 3, 0, 0, 0}; + NSData* expectedMessage = [NSData dataWithBytes:bytes length:sizeof(bytes)]; + + OCMExpect([binaryMessenger sendOnChannel:@"dev.flutter/channel-buffers" message:expectedMessage]); + [channel resizeChannelBuffer:3]; + OCMVerifyAll(binaryMessenger); + [binaryMessenger stopMocking]; +} + +- (void)testSetWarnsOnOverflow { + NSString* channelName = @"flutter/test"; + id binaryMessenger = OCMStrictProtocolMock(@protocol(FlutterBinaryMessenger)); + id codec = OCMProtocolMock(@protocol(FlutterMethodCodec)); + FlutterBasicMessageChannel* channel = + [[FlutterBasicMessageChannel alloc] initWithName:channelName + binaryMessenger:binaryMessenger + codec:codec]; + XCTAssertNotNil(channel); + + // The expected content was created from the following Dart code: + // MethodCall call = MethodCall('overflow',['flutter/test', true]); + // StandardMethodCodec().encodeMethodCall(call).buffer.asUint8List(); + const unsigned char bytes[] = {7, 8, 111, 118, 101, 114, 102, 108, 111, 119, 12, 2, 7, 12, + 102, 108, 117, 116, 116, 101, 114, 47, 116, 101, 115, 116, 1}; + NSData* expectedMessage = [NSData dataWithBytes:bytes length:sizeof(bytes)]; + + OCMExpect([binaryMessenger sendOnChannel:@"dev.flutter/channel-buffers" message:expectedMessage]); + [channel setWarnsOnOverflow:NO]; + OCMVerifyAll(binaryMessenger); + [binaryMessenger stopMocking]; +} + +- (void)testBasicMessageChannelCleanup { + NSString* channelName = @"foo"; + FlutterBinaryMessengerConnection connection = 123; + id binaryMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + id codec = OCMProtocolMock(@protocol(FlutterMethodCodec)); + FlutterBasicMessageChannel* channel = + [[FlutterBasicMessageChannel alloc] initWithName:channelName + binaryMessenger:binaryMessenger + codec:codec]; + FlutterMessageHandler handler = ^(id _Nullable message, FlutterReply callback) { + }; + OCMStub([binaryMessenger setMessageHandlerOnChannel:channelName + binaryMessageHandler:[OCMArg any]]) + .andReturn(connection); + [channel setMessageHandler:handler]; + OCMVerify([binaryMessenger setMessageHandlerOnChannel:channelName + binaryMessageHandler:[OCMArg isNotNil]]); + [channel setMessageHandler:nil]; + OCMVerify([binaryMessenger cleanUpConnection:connection]); +} + +- (void)testMethodChannelCleanup { + NSString* channelName = @"foo"; + FlutterBinaryMessengerConnection connection = 123; + id binaryMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + id codec = OCMProtocolMock(@protocol(FlutterMethodCodec)); + FlutterMethodChannel* channel = [[FlutterMethodChannel alloc] initWithName:channelName + binaryMessenger:binaryMessenger + codec:codec]; + XCTAssertNotNil(channel); + + OCMStub([binaryMessenger setMessageHandlerOnChannel:channelName + binaryMessageHandler:[OCMArg any]]) + .andReturn(connection); + + FlutterMethodCallHandler handler = + ^(FlutterMethodCall* _Nonnull call, FlutterResult _Nonnull result) { + }; + [channel setMethodCallHandler:handler]; + OCMVerify([binaryMessenger setMessageHandlerOnChannel:channelName + binaryMessageHandler:[OCMArg isNotNil]]); + [channel setMethodCallHandler:nil]; + OCMVerify([binaryMessenger cleanUpConnection:connection]); +} + +- (void)testBasicMessageChannelTaskQueue { + NSString* channelName = @"foo"; + FlutterBinaryMessengerConnection connection = 123; + id binaryMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + id codec = OCMProtocolMock(@protocol(FlutterMethodCodec)); + id taskQueue = OCMProtocolMock(@protocol(FlutterTaskQueueDispatch)); + FlutterBasicMessageChannel* channel = + [[FlutterBasicMessageChannel alloc] initWithName:channelName + binaryMessenger:binaryMessenger + codec:codec + taskQueue:taskQueue]; + FlutterMessageHandler handler = ^(id _Nullable message, FlutterReply callback) { + }; + OCMStub([binaryMessenger setMessageHandlerOnChannel:channelName + binaryMessageHandler:[OCMArg any] + taskQueue:taskQueue]) + .andReturn(connection); + [channel setMessageHandler:handler]; + OCMVerify([binaryMessenger setMessageHandlerOnChannel:channelName + binaryMessageHandler:[OCMArg isNotNil] + taskQueue:taskQueue]); + [channel setMessageHandler:nil]; + OCMVerify([binaryMessenger cleanUpConnection:connection]); +} + +- (void)testBasicMessageChannelInvokeHandlerAfterChannelReleased { + NSString* channelName = @"foo"; + __block NSString* handlerMessage; + __block FlutterBinaryMessageHandler messageHandler; + @autoreleasepool { + FlutterBinaryMessengerConnection connection = 123; + id binaryMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + id codec = OCMProtocolMock(@protocol(FlutterMessageCodec)); + id taskQueue = OCMProtocolMock(@protocol(FlutterTaskQueueDispatch)); + FlutterBasicMessageChannel* channel = + [[FlutterBasicMessageChannel alloc] initWithName:channelName + binaryMessenger:binaryMessenger + codec:codec + taskQueue:taskQueue]; + + FlutterMessageHandler handler = ^(id _Nullable message, FlutterReply callback) { + handlerMessage = message; + }; + OCMStub([binaryMessenger + setMessageHandlerOnChannel:channelName + binaryMessageHandler:[OCMArg checkWithBlock:^BOOL( + FlutterBinaryMessageHandler handler) { + messageHandler = handler; + return YES; + }] + taskQueue:taskQueue]) + .andReturn(connection); + OCMStub([codec decode:[OCMArg any]]).andReturn(@"decoded message"); + [channel setMessageHandler:handler]; + } + // Channel is released, messageHandler should still retain the codec. The codec + // internally makes a `decode` call and updates the `handlerMessage` to "decoded message". + messageHandler([NSData data], ^(NSData* data){ + }); + XCTAssertEqualObjects(handlerMessage, @"decoded message"); +} + +- (void)testMethodChannelInvokeHandlerAfterChannelReleased { + NSString* channelName = @"foo"; + FlutterBinaryMessengerConnection connection = 123; + __block FlutterMethodCall* decodedMethodCall; + __block FlutterBinaryMessageHandler messageHandler; + @autoreleasepool { + id binaryMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + id codec = OCMProtocolMock(@protocol(FlutterMethodCodec)); + id taskQueue = OCMProtocolMock(@protocol(FlutterTaskQueueDispatch)); + FlutterMethodChannel* channel = [[FlutterMethodChannel alloc] initWithName:channelName + binaryMessenger:binaryMessenger + codec:codec + taskQueue:taskQueue]; + FlutterMethodCallHandler handler = ^(FlutterMethodCall* call, FlutterResult result) { + decodedMethodCall = call; + }; + OCMStub([binaryMessenger + setMessageHandlerOnChannel:channelName + binaryMessageHandler:[OCMArg checkWithBlock:^BOOL( + FlutterBinaryMessageHandler handler) { + messageHandler = handler; + return YES; + }] + taskQueue:taskQueue]) + .andReturn(connection); + OCMStub([codec decodeMethodCall:[OCMArg any]]) + .andReturn([FlutterMethodCall methodCallWithMethodName:@"decoded method call" + arguments:nil]); + [channel setMethodCallHandler:handler]; + } + messageHandler([NSData data], ^(NSData* data){ + }); + XCTAssertEqualObjects(decodedMethodCall.method, @"decoded method call"); +} + +- (void)testMethodChannelTaskQueue { + NSString* channelName = @"foo"; + FlutterBinaryMessengerConnection connection = 123; + id binaryMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + id codec = OCMProtocolMock(@protocol(FlutterMethodCodec)); + id taskQueue = OCMProtocolMock(@protocol(FlutterTaskQueueDispatch)); + FlutterMethodChannel* channel = [[FlutterMethodChannel alloc] initWithName:channelName + binaryMessenger:binaryMessenger + codec:codec + taskQueue:taskQueue]; + XCTAssertNotNil(channel); + FlutterMethodCallHandler handler = ^(FlutterMethodCall* call, FlutterResult result) { + }; + OCMStub([binaryMessenger setMessageHandlerOnChannel:channelName + binaryMessageHandler:[OCMArg any] + taskQueue:taskQueue]) + .andReturn(connection); + [channel setMethodCallHandler:handler]; + OCMVerify([binaryMessenger setMessageHandlerOnChannel:channelName + binaryMessageHandler:[OCMArg isNotNil] + taskQueue:taskQueue]); + [channel setMethodCallHandler:nil]; + OCMVerify([binaryMessenger cleanUpConnection:connection]); +} + +- (void)testEventChannelTaskQueue { + NSString* channelName = @"foo"; + FlutterBinaryMessengerConnection connection = 123; + id binaryMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + id codec = OCMProtocolMock(@protocol(FlutterMethodCodec)); + id taskQueue = OCMProtocolMock(@protocol(FlutterTaskQueueDispatch)); + id handler = OCMProtocolMock(@protocol(FlutterStreamHandler)); + FlutterEventChannel* channel = [[FlutterEventChannel alloc] initWithName:channelName + binaryMessenger:binaryMessenger + codec:codec + taskQueue:taskQueue]; + XCTAssertNotNil(channel); + OCMStub([binaryMessenger setMessageHandlerOnChannel:channelName + binaryMessageHandler:[OCMArg any] + taskQueue:taskQueue]) + .andReturn(connection); + [channel setStreamHandler:handler]; + OCMVerify([binaryMessenger setMessageHandlerOnChannel:channelName + binaryMessageHandler:[OCMArg isNotNil] + taskQueue:taskQueue]); + [channel setStreamHandler:nil]; + OCMVerify([binaryMessenger cleanUpConnection:connection]); +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterCodecs.mm b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterCodecs.mm new file mode 100644 index 0000000000000000000000000000000000000000..a8653477e2c03868121714bcdb86513c56725171 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterCodecs.mm @@ -0,0 +1,172 @@ +// 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. + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h" + +#include + +FLUTTER_ASSERT_ARC + +@implementation FlutterBinaryCodec ++ (instancetype)sharedInstance { + static id _sharedInstance = nil; + if (!_sharedInstance) { + _sharedInstance = [[FlutterBinaryCodec alloc] init]; + } + return _sharedInstance; +} + +- (NSData*)encode:(id)message { + NSAssert(!message || [message isKindOfClass:[NSData class]], @""); + return message; +} + +- (NSData*)decode:(NSData*)message { + return message; +} +@end + +@implementation FlutterStringCodec ++ (instancetype)sharedInstance { + static id _sharedInstance = nil; + if (!_sharedInstance) { + _sharedInstance = [[FlutterStringCodec alloc] init]; + } + return _sharedInstance; +} + +- (NSData*)encode:(id)message { + if (message == nil) { + return nil; + } + NSAssert([message isKindOfClass:[NSString class]], @""); + NSString* stringMessage = message; + const char* utf8 = stringMessage.UTF8String; + return [NSData dataWithBytes:utf8 length:strlen(utf8)]; +} + +- (NSString*)decode:(NSData*)message { + if (message == nil) { + return nil; + } + return [[NSString alloc] initWithData:message encoding:NSUTF8StringEncoding]; +} +@end + +@implementation FlutterJSONMessageCodec ++ (instancetype)sharedInstance { + static id _sharedInstance = nil; + if (!_sharedInstance) { + _sharedInstance = [[FlutterJSONMessageCodec alloc] init]; + } + return _sharedInstance; +} + +- (NSData*)encode:(id)message { + if (message == nil) { + return nil; + } + NSData* encoding; + NSError* error; + if ([message isKindOfClass:[NSArray class]] || [message isKindOfClass:[NSDictionary class]]) { + encoding = [NSJSONSerialization dataWithJSONObject:message options:0 error:&error]; + } else { + // NSJSONSerialization does not support top-level simple values. + // We encode as singleton array, then extract the relevant bytes. + encoding = [NSJSONSerialization dataWithJSONObject:@[ message ] options:0 error:&error]; + if (encoding) { + encoding = [encoding subdataWithRange:NSMakeRange(1, encoding.length - 2)]; + } + } + NSAssert(encoding, @"Invalid JSON message, encoding failed: %@", error); + return encoding; +} + +- (id)decode:(NSData*)message { + if ([message length] == 0) { + return nil; + } + BOOL isSimpleValue = NO; + id decoded = nil; + NSError* error; + if (0 < message.length) { + UInt8 first; + [message getBytes:&first length:1]; + isSimpleValue = first != '{' && first != '['; + if (isSimpleValue) { + // NSJSONSerialization does not support top-level simple values. + // We expand encoding to singleton array, then decode that and extract + // the single entry. + UInt8 begin = '['; + UInt8 end = ']'; + NSMutableData* expandedMessage = [NSMutableData dataWithLength:message.length + 2]; + [expandedMessage replaceBytesInRange:NSMakeRange(0, 1) withBytes:&begin]; + [expandedMessage replaceBytesInRange:NSMakeRange(1, message.length) withBytes:message.bytes]; + [expandedMessage replaceBytesInRange:NSMakeRange(message.length + 1, 1) withBytes:&end]; + message = expandedMessage; + } + decoded = [NSJSONSerialization JSONObjectWithData:message options:0 error:&error]; + } + NSAssert(decoded, @"Invalid JSON message, decoding failed: %@", error); + return isSimpleValue ? ((NSArray*)decoded)[0] : decoded; +} +@end + +@implementation FlutterJSONMethodCodec ++ (instancetype)sharedInstance { + static id _sharedInstance = nil; + if (!_sharedInstance) { + _sharedInstance = [[FlutterJSONMethodCodec alloc] init]; + } + return _sharedInstance; +} + +- (NSData*)encodeMethodCall:(FlutterMethodCall*)call { + return [[FlutterJSONMessageCodec sharedInstance] encode:@{ + @"method" : call.method, + @"args" : [self wrapNil:call.arguments], + }]; +} + +- (NSData*)encodeSuccessEnvelope:(id)result { + return [[FlutterJSONMessageCodec sharedInstance] encode:@[ [self wrapNil:result] ]]; +} + +- (NSData*)encodeErrorEnvelope:(FlutterError*)error { + return [[FlutterJSONMessageCodec sharedInstance] encode:@[ + error.code, + [self wrapNil:error.message], + [self wrapNil:error.details], + ]]; +} + +- (FlutterMethodCall*)decodeMethodCall:(NSData*)message { + NSDictionary* dictionary = [[FlutterJSONMessageCodec sharedInstance] decode:message]; + id method = dictionary[@"method"]; + id arguments = [self unwrapNil:dictionary[@"args"]]; + NSAssert([method isKindOfClass:[NSString class]], @"Invalid JSON method call"); + return [FlutterMethodCall methodCallWithMethodName:method arguments:arguments]; +} + +- (id)decodeEnvelope:(NSData*)envelope { + NSArray* array = [[FlutterJSONMessageCodec sharedInstance] decode:envelope]; + if (array.count == 1) { + return [self unwrapNil:array[0]]; + } + NSAssert(array.count == 3, @"Invalid JSON envelope"); + id code = array[0]; + id message = [self unwrapNil:array[1]]; + id details = [self unwrapNil:array[2]]; + NSAssert([code isKindOfClass:[NSString class]], @"Invalid JSON envelope"); + NSAssert(message == nil || [message isKindOfClass:[NSString class]], @"Invalid JSON envelope"); + return [FlutterError errorWithCode:code message:message details:details]; +} + +- (id)wrapNil:(id)value { + return value == nil ? [NSNull null] : value; +} +- (id)unwrapNil:(id)value { + return value == [NSNull null] ? nil : value; +} +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterHourFormat.mm b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterHourFormat.mm new file mode 100644 index 0000000000000000000000000000000000000000..a3b80cf07362fc438c7cb10b862b922b9ed16303 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterHourFormat.mm @@ -0,0 +1,26 @@ +// 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. + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterHourFormat.h" + +@implementation FlutterHourFormat ++ (BOOL)isAlwaysUse24HourFormat { + // iOS does not report its "24-Hour Time" user setting in the API. Instead, it applies + // it automatically to NSDateFormatter when used with [NSLocale currentLocale]. It is + // essential that [NSLocale currentLocale] is used. Any custom locale, even the one + // that's the same as [NSLocale currentLocale] will ignore the 24-hour option (there + // must be some internal field that's not exposed to developers). + // + // Therefore this option behaves differently across Android and iOS. On Android this + // setting is exposed standalone, and can therefore be applied to all locales, whether + // the "current system locale" or a custom one. On iOS it only applies to the current + // system locale. Widget implementors must take this into account in order to provide + // platform-idiomatic behavior in their widgets. + NSString* dateFormat = [NSDateFormatter dateFormatFromTemplate:@"j" + options:0 + locale:[NSLocale currentLocale]]; + return [dateFormat rangeOfString:@"a"].location == NSNotFound; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterNSBundleUtils.h b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterNSBundleUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..e9b745cfdb145cb7844c788aa0e742ec92abcabe --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterNSBundleUtils.h @@ -0,0 +1,55 @@ +// 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_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_SOURCE_FLUTTERNSBUNDLEUTILS_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_SOURCE_FLUTTERNSBUNDLEUTILS_H_ + +#import + +NS_ASSUME_NONNULL_BEGIN + +extern NSString* const kDefaultAssetPath; + +// Finds a bundle with the named `flutterFrameworkBundleID` within `searchURL`. +// +// Returns `nil` if the bundle cannot be found or if errors are encountered. +NSBundle* FLTFrameworkBundleInternal(NSString* flutterFrameworkBundleID, NSURL* searchURL); + +// Finds a bundle with the named `flutterFrameworkBundleID`. +// +// `+[NSBundle bundleWithIdentifier:]` is slow, and can take in the order of +// tens of milliseconds in a minimal flutter app, and closer to 100 milliseconds +// in a medium sized Flutter app on an iPhone 13. It is likely that the slowness +// comes from having to traverse and load all bundles known to the process. +// Using `+[NSBundle allframeworks]` and filtering also suffers from the same +// problem. +// +// This implementation is an optimization to first limit the search space to +// `+[NSBundle privateFrameworksURL]` of the main bundle, which is usually where +// frameworks used by this file are placed. If the desired bundle cannot be +// found here, the implementation falls back to +// `+[NSBundle bundleWithIdentifier:]`. +NSBundle* FLTFrameworkBundleWithIdentifier(NSString* flutterFrameworkBundleID); + +// Finds the bundle of the application. +// +// Returns [NSBundle mainBundle] if the current running process is the application. +NSBundle* FLTGetApplicationBundle(); + +// Gets the flutter assets path directory from `bundle`. +// +// Returns `kDefaultAssetPath` if unable to find asset path from info.plist in `bundle`. +NSString* FLTAssetPath(NSBundle* bundle); + +// Finds the Flutter asset directory from `bundle`. +// +// The raw path can be set by the application via info.plist's `FLTAssetsPath` key. +// If the key is not set, `flutter_assets` is used as the raw path value. +// +// If no valid asset is found under the raw path, returns nil. +NSString* FLTAssetsPathFromBundle(NSBundle* bundle); + +NS_ASSUME_NONNULL_END + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_SOURCE_FLUTTERNSBUNDLEUTILS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterNSBundleUtils.mm b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterNSBundleUtils.mm new file mode 100644 index 0000000000000000000000000000000000000000..369e3ce263827996ffc8fbc68e4932fc9576e12f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterNSBundleUtils.mm @@ -0,0 +1,84 @@ +// 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. + +#import "flutter/shell/platform/darwin/common/framework/Source/FlutterNSBundleUtils.h" + +#include + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" + +FLUTTER_ASSERT_ARC + +NSString* const kDefaultAssetPath = @"Frameworks/App.framework/flutter_assets"; + +static NSString* GetFlutterAssetsPathFromBundle(NSBundle* bundle, NSString* relativeAssetsPath); + +NSBundle* FLTFrameworkBundleInternal(NSString* flutterFrameworkBundleID, NSURL* searchURL) { + NSDirectoryEnumerator* frameworkEnumerator = [NSFileManager.defaultManager + enumeratorAtURL:searchURL + includingPropertiesForKeys:nil + options:NSDirectoryEnumerationSkipsSubdirectoryDescendants | + NSDirectoryEnumerationSkipsHiddenFiles + // Skip directories where errors are encountered. + errorHandler:nil]; + + for (NSURL* candidate in frameworkEnumerator) { + NSBundle* flutterFrameworkBundle = [NSBundle bundleWithURL:candidate]; + if ([flutterFrameworkBundle.bundleIdentifier isEqualToString:flutterFrameworkBundleID]) { + return flutterFrameworkBundle; + } + } + return nil; +} + +NSBundle* FLTGetApplicationBundle() { + NSBundle* mainBundle = NSBundle.mainBundle; + // App extension bundle is in .app/PlugIns/Extension.appex. + if ([mainBundle.bundleURL.pathExtension isEqualToString:@"appex"]) { + // Up two levels. + return [NSBundle bundleWithURL:mainBundle.bundleURL.URLByDeletingLastPathComponent + .URLByDeletingLastPathComponent]; + } + return mainBundle; +} + +NSBundle* FLTFrameworkBundleWithIdentifier(NSString* flutterFrameworkBundleID) { + NSBundle* appBundle = FLTGetApplicationBundle(); + NSBundle* flutterFrameworkBundle = + FLTFrameworkBundleInternal(flutterFrameworkBundleID, appBundle.privateFrameworksURL); + if (flutterFrameworkBundle == nil) { + // Fallback to slow implementation. + flutterFrameworkBundle = [NSBundle bundleWithIdentifier:flutterFrameworkBundleID]; + } + if (flutterFrameworkBundle == nil) { + flutterFrameworkBundle = NSBundle.mainBundle; + } + return flutterFrameworkBundle; +} + +NSString* FLTAssetPath(NSBundle* bundle) { + return [bundle objectForInfoDictionaryKey:@"FLTAssetsPath"] ?: kDefaultAssetPath; +} + +NSString* FLTAssetsPathFromBundle(NSBundle* bundle) { + NSString* relativeAssetsPath = FLTAssetPath(bundle); + NSString* flutterAssetsPath = GetFlutterAssetsPathFromBundle(bundle, relativeAssetsPath); + if (flutterAssetsPath.length == 0) { + flutterAssetsPath = GetFlutterAssetsPathFromBundle(NSBundle.mainBundle, relativeAssetsPath); + } + return flutterAssetsPath; +} + +static NSString* GetFlutterAssetsPathFromBundle(NSBundle* bundle, NSString* relativeAssetsPath) { + // Use the raw path solution so that asset path can be returned from unloaded bundles. + // See https://github.com/flutter/engine/pull/46073 + NSString* assetsPath = [bundle pathForResource:relativeAssetsPath ofType:nil]; + if (assetsPath.length == 0) { + // In app extension, using full relative path (kDefaultAssetPath) + // returns nil when the app bundle is not loaded. Try to use + // the sub folder name, which can successfully return a valid path. + assetsPath = [bundle pathForResource:@"flutter_assets" ofType:nil]; + } + return assetsPath; +} diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterStandardCodec.mm b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterStandardCodec.mm new file mode 100644 index 0000000000000000000000000000000000000000..fc0fd0ca167073957df2d0a3b5787218ee76cfdf --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterStandardCodec.mm @@ -0,0 +1,444 @@ +// 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. + +#import "flutter/shell/platform/darwin/common/framework/Source/FlutterStandardCodecHelper.h" +#import "flutter/shell/platform/darwin/common/framework/Source/FlutterStandardCodec_Internal.h" + +FLUTTER_ASSERT_ARC + +#pragma mark - Codec for basic message channel + +@implementation FlutterStandardMessageCodec { + FlutterStandardReaderWriter* _readerWriter; +} ++ (instancetype)sharedInstance { + static id _sharedInstance = nil; + if (!_sharedInstance) { + FlutterStandardReaderWriter* readerWriter = [[FlutterStandardReaderWriter alloc] init]; + _sharedInstance = [[FlutterStandardMessageCodec alloc] initWithReaderWriter:readerWriter]; + } + return _sharedInstance; +} + ++ (instancetype)codecWithReaderWriter:(FlutterStandardReaderWriter*)readerWriter { + return [[FlutterStandardMessageCodec alloc] initWithReaderWriter:readerWriter]; +} + +- (instancetype)initWithReaderWriter:(FlutterStandardReaderWriter*)readerWriter { + self = [super init]; + NSAssert(self, @"Super init cannot be nil"); + _readerWriter = readerWriter; + return self; +} + +- (NSData*)encode:(id)message { + if (message == nil) { + return nil; + } + NSMutableData* data = [NSMutableData dataWithCapacity:32]; + FlutterStandardWriter* writer = [_readerWriter writerWithData:data]; + [writer writeValue:message]; + return data; +} + +- (id)decode:(NSData*)message { + if ([message length] == 0) { + return nil; + } + FlutterStandardReader* reader = [_readerWriter readerWithData:message]; + id value = [reader readValue]; + NSAssert(![reader hasMore], @"Corrupted standard message"); + return value; +} +@end + +#pragma mark - Codec for method channel + +@implementation FlutterStandardMethodCodec { + FlutterStandardReaderWriter* _readerWriter; +} ++ (instancetype)sharedInstance { + static id _sharedInstance = nil; + if (!_sharedInstance) { + FlutterStandardReaderWriter* readerWriter = [[FlutterStandardReaderWriter alloc] init]; + _sharedInstance = [[FlutterStandardMethodCodec alloc] initWithReaderWriter:readerWriter]; + } + return _sharedInstance; +} + ++ (instancetype)codecWithReaderWriter:(FlutterStandardReaderWriter*)readerWriter { + return [[FlutterStandardMethodCodec alloc] initWithReaderWriter:readerWriter]; +} + +- (instancetype)initWithReaderWriter:(FlutterStandardReaderWriter*)readerWriter { + self = [super init]; + NSAssert(self, @"Super init cannot be nil"); + _readerWriter = readerWriter; + return self; +} + +- (NSData*)encodeMethodCall:(FlutterMethodCall*)call { + NSMutableData* data = [NSMutableData dataWithCapacity:32]; + FlutterStandardWriter* writer = [_readerWriter writerWithData:data]; + [writer writeValue:call.method]; + [writer writeValue:call.arguments]; + return data; +} + +- (NSData*)encodeSuccessEnvelope:(id)result { + NSMutableData* data = [NSMutableData dataWithCapacity:32]; + FlutterStandardWriter* writer = [_readerWriter writerWithData:data]; + [writer writeByte:0]; + [writer writeValue:result]; + return data; +} + +- (NSData*)encodeErrorEnvelope:(FlutterError*)error { + NSMutableData* data = [NSMutableData dataWithCapacity:32]; + FlutterStandardWriter* writer = [_readerWriter writerWithData:data]; + [writer writeByte:1]; + [writer writeValue:error.code]; + [writer writeValue:error.message]; + [writer writeValue:error.details]; + return data; +} + +- (FlutterMethodCall*)decodeMethodCall:(NSData*)message { + FlutterStandardReader* reader = [_readerWriter readerWithData:message]; + id value1 = [reader readValue]; + id value2 = [reader readValue]; + NSAssert(![reader hasMore], @"Corrupted standard method call"); + NSAssert([value1 isKindOfClass:[NSString class]], @"Corrupted standard method call"); + return [FlutterMethodCall methodCallWithMethodName:value1 arguments:value2]; +} + +- (id)decodeEnvelope:(NSData*)envelope { + FlutterStandardReader* reader = [_readerWriter readerWithData:envelope]; + UInt8 flag = [reader readByte]; + NSAssert(flag <= 1, @"Corrupted standard envelope"); + id result; + switch (flag) { + case 0: { + result = [reader readValue]; + NSAssert(![reader hasMore], @"Corrupted standard envelope"); + } break; + case 1: { + id code = [reader readValue]; + id message = [reader readValue]; + id details = [reader readValue]; + NSAssert(![reader hasMore], @"Corrupted standard envelope"); + NSAssert([code isKindOfClass:[NSString class]], @"Invalid standard envelope"); + NSAssert(message == nil || [message isKindOfClass:[NSString class]], + @"Invalid standard envelope"); + result = [FlutterError errorWithCode:code message:message details:details]; + } break; + } + return result; +} +@end + +using namespace flutter; + +#pragma mark - Standard serializable types + +@implementation FlutterStandardTypedData ++ (instancetype)typedDataWithBytes:(NSData*)data { + return [FlutterStandardTypedData typedDataWithData:data type:FlutterStandardDataTypeUInt8]; +} + ++ (instancetype)typedDataWithInt32:(NSData*)data { + return [FlutterStandardTypedData typedDataWithData:data type:FlutterStandardDataTypeInt32]; +} + ++ (instancetype)typedDataWithInt64:(NSData*)data { + return [FlutterStandardTypedData typedDataWithData:data type:FlutterStandardDataTypeInt64]; +} + ++ (instancetype)typedDataWithFloat32:(NSData*)data { + return [FlutterStandardTypedData typedDataWithData:data type:FlutterStandardDataTypeFloat32]; +} + ++ (instancetype)typedDataWithFloat64:(NSData*)data { + return [FlutterStandardTypedData typedDataWithData:data type:FlutterStandardDataTypeFloat64]; +} + ++ (instancetype)typedDataWithData:(NSData*)data type:(FlutterStandardDataType)type { + return [[FlutterStandardTypedData alloc] initWithData:data type:type]; +} + +- (instancetype)initWithData:(NSData*)data type:(FlutterStandardDataType)type { + UInt8 elementSize = elementSizeForFlutterStandardDataType(type); + NSAssert(data, @"Data cannot be nil"); + NSAssert(data.length % elementSize == 0, @"Data must contain integral number of elements"); + self = [super init]; + NSAssert(self, @"Super init cannot be nil"); + _data = [data copy]; + _type = type; + _elementSize = elementSize; + _elementCount = data.length / elementSize; + return self; +} + +- (BOOL)isEqual:(id)object { + if (self == object) { + return YES; + } + if (![object isKindOfClass:[FlutterStandardTypedData class]]) { + return NO; + } + FlutterStandardTypedData* other = (FlutterStandardTypedData*)object; + return self.type == other.type && self.elementCount == other.elementCount && + [self.data isEqual:other.data]; +} + +- (NSUInteger)hash { + return [self.data hash] ^ self.type; +} +@end + +#pragma mark - Writer and reader of standard codec + +@implementation FlutterStandardWriter { + NSMutableData* _data; +} + +- (instancetype)initWithData:(NSMutableData*)data { + self = [super init]; + NSAssert(self, @"Super init cannot be nil"); + _data = data; + return self; +} + +- (void)writeByte:(UInt8)value { + FlutterStandardCodecHelperWriteByte((__bridge CFMutableDataRef)_data, value); +} + +- (void)writeBytes:(const void*)bytes length:(NSUInteger)length { + FlutterStandardCodecHelperWriteBytes((__bridge CFMutableDataRef)_data, bytes, length); +} + +- (void)writeData:(NSData*)data { + FlutterStandardCodecHelperWriteData((__bridge CFMutableDataRef)_data, (__bridge CFDataRef)data); +} + +- (void)writeSize:(UInt32)size { + FlutterStandardCodecHelperWriteSize((__bridge CFMutableDataRef)_data, size); +} + +- (void)writeAlignment:(UInt8)alignment { + FlutterStandardCodecHelperWriteAlignment((__bridge CFMutableDataRef)_data, alignment); +} + +- (void)writeUTF8:(NSString*)value { + FlutterStandardCodecHelperWriteUTF8((__bridge CFMutableDataRef)_data, + (__bridge CFStringRef)value); +} + +static FlutterStandardCodecObjcType GetWriteType(id value) { + if (value == nil || (__bridge CFNullRef)value == kCFNull) { + return FlutterStandardCodecObjcTypeNil; + } else if ([value isKindOfClass:[NSNumber class]]) { + return FlutterStandardCodecObjcTypeNSNumber; + } else if ([value isKindOfClass:[NSString class]]) { + return FlutterStandardCodecObjcTypeNSString; + } else if ([value isKindOfClass:[FlutterStandardTypedData class]]) { + return FlutterStandardCodecObjcTypeFlutterStandardTypedData; + } else if ([value isKindOfClass:[NSData class]]) { + return FlutterStandardCodecObjcTypeNSData; + } else if ([value isKindOfClass:[NSArray class]]) { + return FlutterStandardCodecObjcTypeNSArray; + } else if ([value isKindOfClass:[NSDictionary class]]) { + return FlutterStandardCodecObjcTypeNSDictionary; + } else { + return FlutterStandardCodecObjcTypeUnknown; + } +} + +struct WriteKeyValuesInfo { + CFTypeRef writer; + CFMutableDataRef data; +}; + +static void WriteKeyValues(CFTypeRef key, CFTypeRef value, void* context) { + WriteKeyValuesInfo* info = (WriteKeyValuesInfo*)context; + FastWriteValueOfType(info->writer, info->data, key); + FastWriteValueOfType(info->writer, info->data, value); +} + +// Recurses into WriteValueOfType directly if it is writing a known type, +// otherwise recurses with objc_msgSend. +static void FastWriteValueOfType(CFTypeRef writer, CFMutableDataRef data, CFTypeRef value) { + FlutterStandardCodecObjcType type = GetWriteType((__bridge id)value); + if (type != FlutterStandardCodecObjcTypeUnknown) { + WriteValueOfType(writer, data, type, value); + } else { + [(__bridge FlutterStandardWriter*)writer writeValue:(__bridge id)value]; + } +} + +static void WriteValueOfType(CFTypeRef writer, + CFMutableDataRef data, + FlutterStandardCodecObjcType type, + CFTypeRef value) { + switch (type) { + case FlutterStandardCodecObjcTypeNil: + FlutterStandardCodecHelperWriteByte(data, FlutterStandardFieldNil); + break; + case FlutterStandardCodecObjcTypeNSNumber: { + CFNumberRef number = (CFNumberRef)value; + BOOL success = FlutterStandardCodecHelperWriteNumber(data, number); + if (!success) { + NSLog(@"Unsupported value: %@ of number type %ld", value, CFNumberGetType(number)); + NSCAssert(NO, @"Unsupported value for standard codec"); + } + break; + } + case FlutterStandardCodecObjcTypeNSString: { + CFStringRef string = (CFStringRef)value; + FlutterStandardCodecHelperWriteByte(data, FlutterStandardFieldString); + FlutterStandardCodecHelperWriteUTF8(data, string); + break; + } + case FlutterStandardCodecObjcTypeFlutterStandardTypedData: { + FlutterStandardTypedData* typedData = (__bridge FlutterStandardTypedData*)value; + FlutterStandardCodecHelperWriteByte(data, FlutterStandardFieldForDataType(typedData.type)); + FlutterStandardCodecHelperWriteSize(data, typedData.elementCount); + FlutterStandardCodecHelperWriteAlignment(data, typedData.elementSize); + FlutterStandardCodecHelperWriteData(data, (__bridge CFDataRef)typedData.data); + break; + } + case FlutterStandardCodecObjcTypeNSData: + WriteValueOfType(writer, data, FlutterStandardCodecObjcTypeFlutterStandardTypedData, + (__bridge CFTypeRef) + [FlutterStandardTypedData typedDataWithBytes:(__bridge NSData*)value]); + break; + case FlutterStandardCodecObjcTypeNSArray: { + CFArrayRef array = (CFArrayRef)value; + FlutterStandardCodecHelperWriteByte(data, FlutterStandardFieldList); + CFIndex count = CFArrayGetCount(array); + FlutterStandardCodecHelperWriteSize(data, count); + for (CFIndex i = 0; i < count; ++i) { + FastWriteValueOfType(writer, data, CFArrayGetValueAtIndex(array, i)); + } + break; + } + case FlutterStandardCodecObjcTypeNSDictionary: { + CFDictionaryRef dict = (CFDictionaryRef)value; + FlutterStandardCodecHelperWriteByte(data, FlutterStandardFieldMap); + CFIndex count = CFDictionaryGetCount(dict); + FlutterStandardCodecHelperWriteSize(data, count); + WriteKeyValuesInfo info = { + .writer = writer, + .data = data, + }; + CFDictionaryApplyFunction(dict, WriteKeyValues, (void*)&info); + break; + } + case FlutterStandardCodecObjcTypeUnknown: { + id objc_value = (__bridge id)value; + NSLog(@"Unsupported value: %@ of type %@", objc_value, [objc_value class]); + NSCAssert(NO, @"Unsupported value for standard codec"); + break; + } + } +} + +- (void)writeValue:(id)value { + FlutterStandardCodecObjcType type = GetWriteType(value); + WriteValueOfType((__bridge CFTypeRef)self, (__bridge CFMutableDataRef)self->_data, type, + (__bridge CFTypeRef)value); +} +@end + +@implementation FlutterStandardReader { + NSData* _data; + NSRange _range; +} + +- (instancetype)initWithData:(NSData*)data { + self = [super init]; + NSAssert(self, @"Super init cannot be nil"); + _data = [data copy]; + _range = NSMakeRange(0, 0); + return self; +} + +- (BOOL)hasMore { + return _range.location < _data.length; +} + +- (void)readBytes:(void*)destination length:(NSUInteger)length { + FlutterStandardCodecHelperReadBytes(&_range.location, length, destination, + (__bridge CFDataRef)_data); +} + +- (UInt8)readByte { + return FlutterStandardCodecHelperReadByte(&_range.location, (__bridge CFDataRef)_data); +} + +- (UInt32)readSize { + return FlutterStandardCodecHelperReadSize(&_range.location, (__bridge CFDataRef)_data); +} + +- (NSData*)readData:(NSUInteger)length { + _range.length = length; + NSData* data = [_data subdataWithRange:_range]; + _range.location += _range.length; + return data; +} + +- (NSString*)readUTF8 { + return (__bridge NSString*)FlutterStandardCodecHelperReadUTF8(&_range.location, + (__bridge CFDataRef)_data); +} + +- (void)readAlignment:(UInt8)alignment { + FlutterStandardCodecHelperReadAlignment(&_range.location, alignment); +} + +- (nullable id)readValue { + return (__bridge id)ReadValue((__bridge CFTypeRef)self); +} + +static CFTypeRef ReadValue(CFTypeRef user_data) { + FlutterStandardReader* reader = (__bridge FlutterStandardReader*)user_data; + uint8_t type = FlutterStandardCodecHelperReadByte(&reader->_range.location, + (__bridge CFDataRef)reader->_data); + return (__bridge CFTypeRef)[reader readValueOfType:type]; +} + +static CFTypeRef ReadTypedDataOfType(FlutterStandardField field, CFTypeRef user_data) { + FlutterStandardReader* reader = (__bridge FlutterStandardReader*)user_data; + unsigned long* location = &reader->_range.location; + CFDataRef data = (__bridge CFDataRef)reader->_data; + FlutterStandardDataType type = FlutterStandardDataTypeForField(field); + + UInt64 elementCount = FlutterStandardCodecHelperReadSize(location, data); + UInt64 elementSize = elementSizeForFlutterStandardDataType(type); + FlutterStandardCodecHelperReadAlignment(location, elementSize); + UInt64 length = elementCount * elementSize; + NSRange range = NSMakeRange(*location, length); + // Note: subdataWithRange performs better than CFDataCreate and + // CFDataCreateBytesNoCopy crashes. + NSData* bytes = [(__bridge NSData*)data subdataWithRange:range]; + *location += length; + return (__bridge CFTypeRef)[FlutterStandardTypedData typedDataWithData:bytes type:type]; +} + +- (nullable id)readValueOfType:(UInt8)type { + return (__bridge id)FlutterStandardCodecHelperReadValueOfType( + &_range.location, (__bridge CFDataRef)_data, type, ReadValue, ReadTypedDataOfType, + (__bridge CFTypeRef)self); +} +@end + +@implementation FlutterStandardReaderWriter +- (FlutterStandardWriter*)writerWithData:(NSMutableData*)data { + return [[FlutterStandardWriter alloc] initWithData:data]; +} + +- (FlutterStandardReader*)readerWithData:(NSData*)data { + return [[FlutterStandardReader alloc] initWithData:data]; +} +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterStandardCodecHelper.cc b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterStandardCodecHelper.cc new file mode 100644 index 0000000000000000000000000000000000000000..1eb536d905724768bf022f5aadcb760b37b7e205 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterStandardCodecHelper.cc @@ -0,0 +1,273 @@ +// 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/shell/platform/darwin/common/framework/Source/FlutterStandardCodecHelper.h" +#include + +#include + +#include "flutter/fml/logging.h" + +// The google-runtime-int lint suggests uint64_t in place of unsigned long, +// however these functions are frequently used with NSUInteger, which is +// defined as an unsigned long. +// +// NOLINTBEGIN(google-runtime-int) + +void FlutterStandardCodecHelperReadAlignment(unsigned long* location, + uint8_t alignment) { + uint8_t mod = *location % alignment; + if (mod) { + *location += (alignment - mod); + } +} + +static uint8_t PeekByte(unsigned long location, CFDataRef data) { + uint8_t result; + CFRange range = CFRangeMake(location, 1); + CFDataGetBytes(data, range, &result); + return result; +} + +void FlutterStandardCodecHelperReadBytes(unsigned long* location, + unsigned long length, + void* destination, + CFDataRef data) { + CFRange range = CFRangeMake(*location, length); + CFDataGetBytes(data, range, static_cast(destination)); + *location += length; +} + +uint8_t FlutterStandardCodecHelperReadByte(unsigned long* location, + CFDataRef data) { + uint8_t value; + FlutterStandardCodecHelperReadBytes(location, 1, &value, data); + return value; +} + +uint32_t FlutterStandardCodecHelperReadSize(unsigned long* location, + CFDataRef data) { + uint8_t byte = FlutterStandardCodecHelperReadByte(location, data); + if (byte < 254) { + return static_cast(byte); + } else if (byte == 254) { + UInt16 value; + FlutterStandardCodecHelperReadBytes(location, 2, &value, data); + return value; + } else { + UInt32 value; + FlutterStandardCodecHelperReadBytes(location, 4, &value, data); + return value; + } +} + +static CFDataRef ReadDataNoCopy(unsigned long* location, + unsigned long length, + CFDataRef data) { + CFDataRef result = CFDataCreateWithBytesNoCopy( + kCFAllocatorDefault, CFDataGetBytePtr(data) + *location, length, + kCFAllocatorNull); + *location += length; + return static_cast(CFAutorelease(result)); +} + +CFStringRef FlutterStandardCodecHelperReadUTF8(unsigned long* location, + CFDataRef data) { + uint32_t size = FlutterStandardCodecHelperReadSize(location, data); + CFDataRef bytes = ReadDataNoCopy(location, size, data); + CFStringRef result = CFStringCreateFromExternalRepresentation( + kCFAllocatorDefault, bytes, kCFStringEncodingUTF8); + return static_cast(CFAutorelease(result)); +} + +// Peeks ahead to see if we are reading a standard type. If so, recurse +// directly to FlutterStandardCodecHelperReadValueOfType, otherwise recurse to +// objc. +static inline CFTypeRef FastReadValue( + unsigned long* location, + CFDataRef data, + CFTypeRef (*ReadValue)(CFTypeRef), + CFTypeRef (*ReadTypedDataOfType)(FlutterStandardField, CFTypeRef), + CFTypeRef user_data) { + uint8_t type = PeekByte(*location, data); + if (FlutterStandardFieldIsStandardType(type)) { + *location += 1; + return FlutterStandardCodecHelperReadValueOfType( + location, data, type, ReadValue, ReadTypedDataOfType, user_data); + } else { + return ReadValue(user_data); + } +} + +CFTypeRef FlutterStandardCodecHelperReadValueOfType( + unsigned long* location, + CFDataRef data, + uint8_t type, + CFTypeRef (*ReadValue)(CFTypeRef), + CFTypeRef (*ReadTypedDataOfType)(FlutterStandardField, CFTypeRef), + CFTypeRef user_data) { + FlutterStandardField field = static_cast(type); + switch (field) { + case FlutterStandardFieldNil: + return nil; + case FlutterStandardFieldTrue: + return kCFBooleanTrue; + case FlutterStandardFieldFalse: + return kCFBooleanFalse; + case FlutterStandardFieldInt32: { + int32_t value; + FlutterStandardCodecHelperReadBytes(location, 4, &value, data); + return CFAutorelease( + CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &value)); + } + case FlutterStandardFieldInt64: { + int64_t value; + FlutterStandardCodecHelperReadBytes(location, 8, &value, data); + return CFAutorelease( + CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &value)); + } + case FlutterStandardFieldFloat64: { + Float64 value; + FlutterStandardCodecHelperReadAlignment(location, 8); + FlutterStandardCodecHelperReadBytes(location, 8, &value, data); + return CFAutorelease( + CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &value)); + } + case FlutterStandardFieldIntHex: + case FlutterStandardFieldString: + return FlutterStandardCodecHelperReadUTF8(location, data); + case FlutterStandardFieldUInt8Data: + case FlutterStandardFieldInt32Data: + case FlutterStandardFieldInt64Data: + case FlutterStandardFieldFloat32Data: + case FlutterStandardFieldFloat64Data: + return ReadTypedDataOfType(field, user_data); + case FlutterStandardFieldList: { + UInt32 length = FlutterStandardCodecHelperReadSize(location, data); + CFMutableArrayRef array = CFArrayCreateMutable( + kCFAllocatorDefault, length, &kCFTypeArrayCallBacks); + for (UInt32 i = 0; i < length; i++) { + CFTypeRef value = FastReadValue(location, data, ReadValue, + ReadTypedDataOfType, user_data); + CFArrayAppendValue(array, (value == nil ? kCFNull : value)); + } + return CFAutorelease(array); + } + case FlutterStandardFieldMap: { + UInt32 size = FlutterStandardCodecHelperReadSize(location, data); + CFMutableDictionaryRef dict = CFDictionaryCreateMutable( + kCFAllocatorDefault, size, &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + for (UInt32 i = 0; i < size; i++) { + CFTypeRef key = FastReadValue(location, data, ReadValue, + ReadTypedDataOfType, user_data); + CFTypeRef val = FastReadValue(location, data, ReadValue, + ReadTypedDataOfType, user_data); + CFDictionaryAddValue(dict, (key == nil ? kCFNull : key), + (val == nil ? kCFNull : val)); + } + return CFAutorelease(dict); + } + default: + // Malformed message. + FML_DCHECK(false); + } +} + +void FlutterStandardCodecHelperWriteByte(CFMutableDataRef data, uint8_t value) { + CFDataAppendBytes(data, &value, 1); +} + +void FlutterStandardCodecHelperWriteBytes(CFMutableDataRef data, + const void* bytes, + unsigned long length) { + CFDataAppendBytes(data, static_cast(bytes), length); +} + +void FlutterStandardCodecHelperWriteSize(CFMutableDataRef data, uint32_t size) { + if (size < 254) { + FlutterStandardCodecHelperWriteByte(data, size); + } else if (size <= 0xffff) { + FlutterStandardCodecHelperWriteByte(data, 254); + UInt16 value = static_cast(size); + FlutterStandardCodecHelperWriteBytes(data, &value, 2); + } else { + FlutterStandardCodecHelperWriteByte(data, 255); + FlutterStandardCodecHelperWriteBytes(data, &size, 4); + } +} + +void FlutterStandardCodecHelperWriteAlignment(CFMutableDataRef data, + uint8_t alignment) { + uint8_t mod = CFDataGetLength(data) % alignment; + if (mod) { + for (int i = 0; i < (alignment - mod); i++) { + FlutterStandardCodecHelperWriteByte(data, 0); + } + } +} + +void FlutterStandardCodecHelperWriteUTF8(CFMutableDataRef data, + CFStringRef value) { + const char* utf8 = CFStringGetCStringPtr(value, kCFStringEncodingUTF8); + if (utf8) { + size_t length = strlen(utf8); + FlutterStandardCodecHelperWriteSize(data, length); + FlutterStandardCodecHelperWriteBytes(data, utf8, length); + } else { + CFIndex length = CFStringGetLength(value); + CFIndex used_length = 0; + // UTF16 length times 3 will fit all UTF8. + CFIndex buffer_length = length * 3; + std::vector buffer; + buffer.resize(buffer_length); + CFStringGetBytes(value, CFRangeMake(0, length), kCFStringEncodingUTF8, 0, + false, buffer.data(), buffer_length, &used_length); + FlutterStandardCodecHelperWriteSize(data, used_length); + FlutterStandardCodecHelperWriteBytes(data, buffer.data(), used_length); + } +} + +void FlutterStandardCodecHelperWriteData(CFMutableDataRef data, + CFDataRef value) { + const UInt8* bytes = CFDataGetBytePtr(value); + CFIndex length = CFDataGetLength(value); + FlutterStandardCodecHelperWriteBytes(data, bytes, length); +} + +bool FlutterStandardCodecHelperWriteNumber(CFMutableDataRef data, + CFNumberRef number) { + bool success = false; + if (CFGetTypeID(number) == CFBooleanGetTypeID()) { + bool b = CFBooleanGetValue(reinterpret_cast(number)); + FlutterStandardCodecHelperWriteByte( + data, (b ? FlutterStandardFieldTrue : FlutterStandardFieldFalse)); + success = true; + } else if (CFNumberIsFloatType(number)) { + Float64 f; + success = CFNumberGetValue(number, kCFNumberFloat64Type, &f); + if (success) { + FlutterStandardCodecHelperWriteByte(data, FlutterStandardFieldFloat64); + FlutterStandardCodecHelperWriteAlignment(data, 8); + FlutterStandardCodecHelperWriteBytes(data, &f, 8); + } + } else if (CFNumberGetByteSize(number) <= 4) { + SInt32 n; + success = CFNumberGetValue(number, kCFNumberSInt32Type, &n); + if (success) { + FlutterStandardCodecHelperWriteByte(data, FlutterStandardFieldInt32); + FlutterStandardCodecHelperWriteBytes(data, &n, 4); + } + } else if (CFNumberGetByteSize(number) <= 8) { + SInt64 n; + success = CFNumberGetValue(number, kCFNumberSInt64Type, &n); + if (success) { + FlutterStandardCodecHelperWriteByte(data, FlutterStandardFieldInt64); + FlutterStandardCodecHelperWriteBytes(data, &n, 8); + } + } + return success; +} + +// NOLINTEND(google-runtime-int) diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterStandardCodecHelper.h b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterStandardCodecHelper.h new file mode 100644 index 0000000000000000000000000000000000000000..aebe3689fb4517d13211741f2c9a6efc4ed3fc89 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterStandardCodecHelper.h @@ -0,0 +1,123 @@ +// 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_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_SOURCE_FLUTTERSTANDARDCODECHELPER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_SOURCE_FLUTTERSTANDARDCODECHELPER_H_ + +#include +#include +#include + +#if defined(__cplusplus) +extern "C" { +#endif + +// NOLINTBEGIN(google-runtime-int) + +// Note: Update FlutterStandardFieldIsStandardType if this changes. +typedef enum { + // NOLINTBEGIN(readability-identifier-naming) + FlutterStandardFieldNil, + FlutterStandardFieldTrue, + FlutterStandardFieldFalse, + FlutterStandardFieldInt32, + FlutterStandardFieldInt64, + FlutterStandardFieldIntHex, + FlutterStandardFieldFloat64, + FlutterStandardFieldString, + FlutterStandardFieldUInt8Data, + FlutterStandardFieldInt32Data, + FlutterStandardFieldInt64Data, + FlutterStandardFieldFloat64Data, + FlutterStandardFieldList, + FlutterStandardFieldMap, + FlutterStandardFieldFloat32Data, + // NOLINTEND(readability-identifier-naming) +} FlutterStandardField; + +static inline bool FlutterStandardFieldIsStandardType(uint8_t field) { + return field <= FlutterStandardFieldFloat32Data && + field >= FlutterStandardFieldNil; +} + +typedef enum { + // NOLINTBEGIN(readability-identifier-naming) + FlutterStandardCodecObjcTypeNil, + FlutterStandardCodecObjcTypeNSNumber, + FlutterStandardCodecObjcTypeNSString, + FlutterStandardCodecObjcTypeFlutterStandardTypedData, + FlutterStandardCodecObjcTypeNSData, + FlutterStandardCodecObjcTypeNSArray, + FlutterStandardCodecObjcTypeNSDictionary, + FlutterStandardCodecObjcTypeUnknown, + // NOLINTEND(readability-identifier-naming) +} FlutterStandardCodecObjcType; + +// NOLINTBEGIN(google-objc-function-naming) + +/////////////////////////////////////////////////////////////////////////////// +///\name Reader Helpers +///@{ + +void FlutterStandardCodecHelperReadAlignment(unsigned long* location, + uint8_t alignment); + +void FlutterStandardCodecHelperReadBytes(unsigned long* location, + unsigned long length, + void* destination, + CFDataRef data); + +uint8_t FlutterStandardCodecHelperReadByte(unsigned long* location, + CFDataRef data); + +uint32_t FlutterStandardCodecHelperReadSize(unsigned long* location, + CFDataRef data); + +CFStringRef FlutterStandardCodecHelperReadUTF8(unsigned long* location, + CFDataRef data); + +CFTypeRef FlutterStandardCodecHelperReadValueOfType( + unsigned long* location, + CFDataRef data, + uint8_t type, + CFTypeRef (*ReadValue)(CFTypeRef), + CFTypeRef (*ReadTypedDataOfType)(FlutterStandardField, CFTypeRef), + CFTypeRef user_data); + +///@} + +/////////////////////////////////////////////////////////////////////////////// +///\name Writer Helpers +///@{ + +void FlutterStandardCodecHelperWriteByte(CFMutableDataRef data, uint8_t value); + +void FlutterStandardCodecHelperWriteBytes(CFMutableDataRef data, + const void* bytes, + unsigned long length); + +void FlutterStandardCodecHelperWriteSize(CFMutableDataRef data, uint32_t size); + +void FlutterStandardCodecHelperWriteAlignment(CFMutableDataRef data, + uint8_t alignment); + +void FlutterStandardCodecHelperWriteUTF8(CFMutableDataRef data, + CFStringRef value); + +void FlutterStandardCodecHelperWriteData(CFMutableDataRef data, + CFDataRef value); + +bool FlutterStandardCodecHelperWriteNumber(CFMutableDataRef data, + CFNumberRef number); + +///@} + +// NOLINTEND(google-objc-function-naming) +// NOLINTEND(google-runtime-int) + +#if defined(__cplusplus) +} +#endif + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_SOURCE_FLUTTERSTANDARDCODECHELPER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterStandardCodec_Internal.h b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterStandardCodec_Internal.h new file mode 100644 index 0000000000000000000000000000000000000000..c0a4a217b17e14103f8445e437a52dcffd95b642 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterStandardCodec_Internal.h @@ -0,0 +1,61 @@ +// 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_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_SOURCE_FLUTTERSTANDARDCODEC_INTERNAL_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_SOURCE_FLUTTERSTANDARDCODEC_INTERNAL_H_ + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h" +#import "flutter/shell/platform/darwin/common/framework/Source/FlutterStandardCodecHelper.h" + +namespace flutter { +FlutterStandardField FlutterStandardFieldForDataType( + FlutterStandardDataType type) { + switch (type) { + case FlutterStandardDataTypeUInt8: + return FlutterStandardFieldUInt8Data; + case FlutterStandardDataTypeInt32: + return FlutterStandardFieldInt32Data; + case FlutterStandardDataTypeInt64: + return FlutterStandardFieldInt64Data; + case FlutterStandardDataTypeFloat32: + return FlutterStandardFieldFloat32Data; + case FlutterStandardDataTypeFloat64: + return FlutterStandardFieldFloat64Data; + } +} +FlutterStandardDataType FlutterStandardDataTypeForField( + FlutterStandardField field) { + switch (field) { + case FlutterStandardFieldUInt8Data: + return FlutterStandardDataTypeUInt8; + case FlutterStandardFieldInt32Data: + return FlutterStandardDataTypeInt32; + case FlutterStandardFieldInt64Data: + return FlutterStandardDataTypeInt64; + case FlutterStandardFieldFloat32Data: + return FlutterStandardDataTypeFloat32; + case FlutterStandardFieldFloat64Data: + return FlutterStandardDataTypeFloat64; + default: + return FlutterStandardDataTypeUInt8; + } +} + +UInt8 elementSizeForFlutterStandardDataType(FlutterStandardDataType type) { + switch (type) { + case FlutterStandardDataTypeUInt8: + return 1; + case FlutterStandardDataTypeInt32: + return 4; + case FlutterStandardDataTypeInt64: + return 8; + case FlutterStandardDataTypeFloat32: + return 4; + case FlutterStandardDataTypeFloat64: + return 8; + } +} +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_SOURCE_FLUTTERSTANDARDCODEC_INTERNAL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterTestUtils.h b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterTestUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..29e5bb2d7e5f41cf45288b370f30e93c270c8d82 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterTestUtils.h @@ -0,0 +1,13 @@ +// 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_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_SOURCE_FLUTTERTESTUTILS_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_SOURCE_FLUTTERTESTUTILS_H_ + +#import + +/// Returns YES if the block throws an exception. +BOOL FLTThrowsObjcException(dispatch_block_t block); + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_SOURCE_FLUTTERTESTUTILS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterTestUtils.mm b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterTestUtils.mm new file mode 100644 index 0000000000000000000000000000000000000000..3a562ccb6ce8a72d3e57fbe02da4e388cf0c6114 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/FlutterTestUtils.mm @@ -0,0 +1,18 @@ +// 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. + +#import "flutter/shell/platform/darwin/common/framework/Source/FlutterTestUtils.h" + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" + +FLUTTER_ASSERT_ARC + +BOOL FLTThrowsObjcException(dispatch_block_t block) { + @try { + block(); + } @catch (...) { + return YES; + } + return NO; +} diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/flutter_codecs_unittest.mm b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/flutter_codecs_unittest.mm new file mode 100644 index 0000000000000000000000000000000000000000..c9ab8fdaaac520f0da8d6728d727bf09619ad21f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/flutter_codecs_unittest.mm @@ -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. + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h" + +#include "gtest/gtest.h" + +FLUTTER_ASSERT_ARC + +TEST(FlutterStringCodec, CanEncodeAndDecodeNil) { + FlutterStringCodec* codec = [FlutterStringCodec sharedInstance]; + ASSERT_TRUE([codec encode:nil] == nil); + ASSERT_TRUE([codec decode:nil] == nil); +} + +TEST(FlutterStringCodec, CanEncodeAndDecodeEmptyString) { + FlutterStringCodec* codec = [FlutterStringCodec sharedInstance]; + ASSERT_TRUE([[codec encode:@""] isEqualTo:[NSData data]]); + ASSERT_TRUE([[codec decode:[NSData data]] isEqualTo:@""]); +} + +TEST(FlutterStringCodec, CanEncodeAndDecodeAsciiString) { + NSString* value = @"hello world"; + FlutterStringCodec* codec = [FlutterStringCodec sharedInstance]; + NSData* encoded = [codec encode:value]; + NSString* decoded = [codec decode:encoded]; + ASSERT_TRUE([value isEqualTo:decoded]); +} + +TEST(FlutterStringCodec, CanEncodeAndDecodeNonAsciiString) { + NSString* value = @"hello \u263A world"; + FlutterStringCodec* codec = [FlutterStringCodec sharedInstance]; + NSData* encoded = [codec encode:value]; + NSString* decoded = [codec decode:encoded]; + ASSERT_TRUE([value isEqualTo:decoded]); +} + +TEST(FlutterStringCodec, CanEncodeAndDecodeNonBMPString) { + NSString* value = @"hello \U0001F602 world"; + FlutterStringCodec* codec = [FlutterStringCodec sharedInstance]; + NSData* encoded = [codec encode:value]; + NSString* decoded = [codec decode:encoded]; + ASSERT_TRUE([value isEqualTo:decoded]); +} + +TEST(FlutterJSONCodec, ThrowsOnInvalidEncode) { + NSString* value = [[NSString alloc] initWithBytes:"\xdf\xff" + length:2 + encoding:NSUTF16StringEncoding]; + FlutterJSONMessageCodec* codec = [FlutterJSONMessageCodec sharedInstance]; + EXPECT_EXIT([codec encode:value], testing::KilledBySignal(SIGABRT), "failed to convert to UTF8"); +} + +TEST(FlutterJSONCodec, CanDecodeZeroLength) { + FlutterJSONMessageCodec* codec = [FlutterJSONMessageCodec sharedInstance]; + ASSERT_TRUE([codec decode:[NSData data]] == nil); +} + +TEST(FlutterJSONCodec, ThrowsOnInvalidDecode) { + NSString* value = @"{{{"; + FlutterJSONMessageCodec* codec = [FlutterJSONMessageCodec sharedInstance]; + EXPECT_EXIT([codec decode:[value dataUsingEncoding:value.fastestEncoding]], + testing::KilledBySignal(SIGABRT), "No string key for value in object around line 1"); +} + +TEST(FlutterJSONCodec, CanEncodeAndDecodeNil) { + FlutterJSONMessageCodec* codec = [FlutterJSONMessageCodec sharedInstance]; + ASSERT_TRUE([codec encode:nil] == nil); + ASSERT_TRUE([codec decode:nil] == nil); +} + +TEST(FlutterJSONCodec, CanEncodeAndDecodeArray) { + NSArray* value = @[ [NSNull null], @"hello", @3.14, @47, @{@"a" : @"nested"} ]; + FlutterJSONMessageCodec* codec = [FlutterJSONMessageCodec sharedInstance]; + NSData* encoded = [codec encode:value]; + NSArray* decoded = [codec decode:encoded]; + ASSERT_TRUE([value isEqualTo:decoded]); +} + +TEST(FlutterJSONCodec, CanEncodeAndDecodeDictionary) { + NSDictionary* value = @{@"a" : @3.14, @"b" : @47, @"c" : [NSNull null], @"d" : @[ @"nested" ]}; + FlutterJSONMessageCodec* codec = [FlutterJSONMessageCodec sharedInstance]; + NSData* encoded = [codec encode:value]; + NSDictionary* decoded = [codec decode:encoded]; + ASSERT_TRUE([value isEqualTo:decoded]); +} diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/flutter_standard_codec_unittest.mm b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/flutter_standard_codec_unittest.mm new file mode 100644 index 0000000000000000000000000000000000000000..3489cec7c0030fdf21b0e20bf5a9e2c5f9c294e5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/framework/Source/flutter_standard_codec_unittest.mm @@ -0,0 +1,361 @@ +// 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. + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h" + +#include + +#include "gtest/gtest.h" + +FLUTTER_ASSERT_ARC + +@interface Pair : NSObject +@property(atomic, readonly, strong, nullable) NSObject* left; +@property(atomic, readonly, strong, nullable) NSObject* right; +- (instancetype)initWithLeft:(NSObject*)first right:(NSObject*)right; +@end + +@implementation Pair +- (instancetype)initWithLeft:(NSObject*)left right:(NSObject*)right { + self = [super init]; + if (self) { + _left = left; + _right = right; + } + return self; +} +@end + +static const UInt8 kDATE = 128; +static const UInt8 kPAIR = 129; + +@interface ExtendedWriter : FlutterStandardWriter +- (void)writeValue:(id)value; +@end + +@implementation ExtendedWriter +- (void)writeValue:(id)value { + if ([value isKindOfClass:[NSDate class]]) { + [self writeByte:kDATE]; + NSDate* date = value; + NSTimeInterval time = date.timeIntervalSince1970; + SInt64 ms = (SInt64)(time * 1000.0); + [self writeBytes:&ms length:8]; + } else if ([value isKindOfClass:[Pair class]]) { + Pair* pair = value; + [self writeByte:kPAIR]; + [self writeValue:pair.left]; + [self writeValue:pair.right]; + } else { + [super writeValue:value]; + } +} +@end + +@interface ExtendedReader : FlutterStandardReader +- (id)readValueOfType:(UInt8)type; +@end + +@implementation ExtendedReader +- (id)readValueOfType:(UInt8)type { + switch (type) { + case kDATE: { + SInt64 value; + [self readBytes:&value length:8]; + NSTimeInterval time = [NSNumber numberWithLong:value].doubleValue / 1000.0; + return [NSDate dateWithTimeIntervalSince1970:time]; + } + case kPAIR: { + return [[Pair alloc] initWithLeft:[self readValue] right:[self readValue]]; + } + default: + return [super readValueOfType:type]; + } +} +@end + +@interface ExtendedReaderWriter : FlutterStandardReaderWriter +- (FlutterStandardWriter*)writerWithData:(NSMutableData*)data; +- (FlutterStandardReader*)readerWithData:(NSData*)data; +@end + +@implementation ExtendedReaderWriter +- (FlutterStandardWriter*)writerWithData:(NSMutableData*)data { + return [[ExtendedWriter alloc] initWithData:data]; +} +- (FlutterStandardReader*)readerWithData:(NSData*)data { + return [[ExtendedReader alloc] initWithData:data]; +} +@end + +static void CheckEncodeDecode(id value, NSData* expectedEncoding) { + FlutterStandardMessageCodec* codec = [FlutterStandardMessageCodec sharedInstance]; + NSData* encoded = [codec encode:value]; + if (expectedEncoding == nil) { + ASSERT_TRUE(encoded == nil); + } else { + ASSERT_TRUE([encoded isEqual:expectedEncoding]); + } + id decoded = [codec decode:encoded]; + if (value == nil || value == [NSNull null]) { + ASSERT_TRUE(decoded == nil); + } else { + ASSERT_TRUE([value isEqual:decoded]); + } +} + +static void CheckEncodeDecode(id value) { + FlutterStandardMessageCodec* codec = [FlutterStandardMessageCodec sharedInstance]; + NSData* encoded = [codec encode:value]; + id decoded = [codec decode:encoded]; + if (value == nil || value == [NSNull null]) { + ASSERT_TRUE(decoded == nil); + } else { + ASSERT_TRUE([value isEqual:decoded]); + } +} + +TEST(FlutterStandardCodec, CanDecodeZeroLength) { + FlutterStandardMessageCodec* codec = [FlutterStandardMessageCodec sharedInstance]; + id decoded = [codec decode:[NSData data]]; + ASSERT_TRUE(decoded == nil); +} + +TEST(FlutterStandardCodec, CanEncodeAndDecodeNil) { + CheckEncodeDecode(nil, nil); +} + +TEST(FlutterStandardCodec, CanEncodeAndDecodeNSNull) { + uint8_t bytes[1] = {0x00}; + CheckEncodeDecode([NSNull null], [NSData dataWithBytes:bytes length:1]); +} + +TEST(FlutterStandardCodec, CanEncodeAndDecodeYes) { + uint8_t bytes[1] = {0x01}; + CheckEncodeDecode(@YES, [NSData dataWithBytes:bytes length:1]); +} + +TEST(FlutterStandardCodec, CanEncodeAndDecodeNo) { + uint8_t bytes[1] = {0x02}; + CheckEncodeDecode(@NO, [NSData dataWithBytes:bytes length:1]); +} + +TEST(FlutterStandardCodec, CanEncodeAndDecodeUInt8) { + uint8_t bytes[5] = {0x03, 0xfe, 0x00, 0x00, 0x00}; + UInt8 value = 0xfe; + CheckEncodeDecode(@(value), [NSData dataWithBytes:bytes length:5]); +} + +TEST(FlutterStandardCodec, CanEncodeAndDecodeUInt16) { + uint8_t bytes[5] = {0x03, 0xdc, 0xfe, 0x00, 0x00}; + UInt16 value = 0xfedc; + CheckEncodeDecode(@(value), [NSData dataWithBytes:bytes length:5]); +} + +TEST(FlutterStandardCodec, CanEncodeAndDecodeUInt32) { + uint8_t bytes[9] = {0x04, 0x09, 0xba, 0xdc, 0xfe, 0x00, 0x00, 0x00, 0x00}; + UInt32 value = 0xfedcba09; + CheckEncodeDecode(@(value), [NSData dataWithBytes:bytes length:9]); +} + +TEST(FlutterStandardCodec, CanEncodeUInt64) { + FlutterStandardMessageCodec* codec = [FlutterStandardMessageCodec sharedInstance]; + UInt64 u64 = 0xfffffffffffffffa; + uint8_t bytes[9] = {0x04, 0xfa, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; + NSData* encoded = [codec encode:@(u64)]; + ASSERT_TRUE([encoded isEqual:[NSData dataWithBytes:bytes length:9]]); +} + +TEST(FlutterStandardCodec, CanEncodeAndDecodeSInt8) { + uint8_t bytes[5] = {0x03, 0xfe, 0xff, 0xff, 0xff}; + SInt8 value = 0xfe; + CheckEncodeDecode(@(value), [NSData dataWithBytes:bytes length:5]); +} + +TEST(FlutterStandardCodec, CanEncodeAndDecodeSInt16) { + uint8_t bytes[5] = {0x03, 0xdc, 0xfe, 0xff, 0xff}; + SInt16 value = 0xfedc; + CheckEncodeDecode(@(value), [NSData dataWithBytes:bytes length:5]); +} + +TEST(FlutterStandardCodec, CanEncodeAndDecodeSInt32) { + uint8_t bytes[5] = {0x03, 0x78, 0x56, 0x34, 0x12}; + CheckEncodeDecode(@(0x12345678), [NSData dataWithBytes:bytes length:5]); +} + +TEST(FlutterStandardCodec, CanEncodeAndDecodeSInt64) { + uint8_t bytes[9] = {0x04, 0xef, 0xcd, 0xab, 0x90, 0x78, 0x56, 0x34, 0x12}; + CheckEncodeDecode(@(0x1234567890abcdef), [NSData dataWithBytes:bytes length:9]); +} + +TEST(FlutterStandardCodec, CanEncodeAndDecodeFloat32) { + uint8_t bytes[16] = {0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x60, 0xfb, 0x21, 0x09, 0x40}; + CheckEncodeDecode(@3.1415927f, [NSData dataWithBytes:bytes length:16]); +} + +TEST(FlutterStandardCodec, CanEncodeAndDecodeFloat64) { + uint8_t bytes[16] = {0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x18, 0x2d, 0x44, 0x54, 0xfb, 0x21, 0x09, 0x40}; + CheckEncodeDecode(@3.14159265358979311599796346854, [NSData dataWithBytes:bytes length:16]); +} + +TEST(FlutterStandardCodec, CanEncodeAndDecodeString) { + uint8_t bytes[13] = {0x07, 0x0b, 0x68, 0x65, 0x6c, 0x6c, 0x6f, + 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64}; + CheckEncodeDecode(@"hello world", [NSData dataWithBytes:bytes length:13]); +} + +TEST(FlutterStandardCodec, CanEncodeAndDecodeStringWithNonAsciiCodePoint) { + uint8_t bytes[7] = {0x07, 0x05, 0x68, 0xe2, 0x98, 0xba, 0x77}; + CheckEncodeDecode(@"h\u263Aw", [NSData dataWithBytes:bytes length:7]); +} + +TEST(FlutterStandardCodec, CanEncodeAndDecodeStringWithNonBMPCodePoint) { + uint8_t bytes[8] = {0x07, 0x06, 0x68, 0xf0, 0x9f, 0x98, 0x82, 0x77}; + CheckEncodeDecode(@"h\U0001F602w", [NSData dataWithBytes:bytes length:8]); +} + +TEST(FlutterStandardCodec, CanEncodeAndDecodeIndirectString) { + // This test ensures that an indirect NSString, whose internal string buffer + // can't be simply returned by `CFStringGetCStringPtr`, can be encoded without + // violating the memory sanitizer. This test only works with `--asan` flag. + // See https://github.com/flutter/flutter/issues/142101 + uint8_t bytes[7] = {0x07, 0x05, 0x68, 0xe2, 0x98, 0xba, 0x77}; + NSString* target = @"h\u263Aw"; + // Ensures that this is an indirect string so that this test makes sense. + ASSERT_TRUE(CFStringGetCStringPtr((__bridge CFStringRef)target, kCFStringEncodingUTF8) == + nullptr); + CheckEncodeDecode(target, [NSData dataWithBytes:bytes length:7]); +} + +TEST(FlutterStandardCodec, CanEncodeAndDecodeArray) { + NSArray* value = @[ [NSNull null], @"hello", @3.14, @47, @{@42 : @"nested"} ]; + CheckEncodeDecode(value); +} + +TEST(FlutterStandardCodec, CanEncodeAndDecodeDictionary) { + NSDictionary* value = + @{@"a" : @3.14, + @"b" : @47, + [NSNull null] : [NSNull null], + @3.14 : @[ @"nested" ]}; + CheckEncodeDecode(value); +} + +TEST(FlutterStandardCodec, CanEncodeAndDecodeByteArray) { + uint8_t bytes[4] = {0xBA, 0x5E, 0xBA, 0x11}; + NSData* data = [NSData dataWithBytes:bytes length:4]; + FlutterStandardTypedData* value = [FlutterStandardTypedData typedDataWithBytes:data]; + CheckEncodeDecode(value); +} + +TEST(FlutterStandardCodec, CanEncodeAndDecodeNSData) { + FlutterStandardMessageCodec* codec = [FlutterStandardMessageCodec sharedInstance]; + uint8_t bytes[4] = {0xBA, 0x5E, 0xBA, 0x11}; + NSData* data = [NSData dataWithBytes:bytes length:4]; + FlutterStandardTypedData* standardData = [FlutterStandardTypedData typedDataWithBytes:data]; + + NSData* encoded = [codec encode:data]; + ASSERT_TRUE([encoded isEqual:[codec encode:standardData]]); +} + +TEST(FlutterStandardCodec, CanEncodeAndDecodeInt32Array) { + uint8_t bytes[8] = {0xBA, 0x5E, 0xBA, 0x11, 0xff, 0xff, 0xff, 0xff}; + NSData* data = [NSData dataWithBytes:bytes length:8]; + FlutterStandardTypedData* value = [FlutterStandardTypedData typedDataWithInt32:data]; + CheckEncodeDecode(value); +} + +TEST(FlutterStandardCodec, CanEncodeAndDecodeInt64Array) { + uint8_t bytes[8] = {0xBA, 0x5E, 0xBA, 0x11, 0xff, 0xff, 0xff, 0xff}; + NSData* data = [NSData dataWithBytes:bytes length:8]; + FlutterStandardTypedData* value = [FlutterStandardTypedData typedDataWithInt64:data]; + CheckEncodeDecode(value); +} + +TEST(FlutterStandardCodec, CanEncodeAndDecodeFloat32Array) { + uint8_t bytes[8] = {0xd8, 0x0f, 0x49, 0x40, 0x00, 0x00, 0x7a, 0x44}; + NSData* data = [NSData dataWithBytes:bytes length:8]; + FlutterStandardTypedData* value = [FlutterStandardTypedData typedDataWithFloat32:data]; + CheckEncodeDecode(value); +} + +TEST(FlutterStandardCodec, CanEncodeAndDecodeFloat64Array) { + uint8_t bytes[16] = {0xBA, 0x5E, 0xBA, 0x11, 0xff, 0xff, 0xff, 0xff, + 0xBA, 0x5E, 0xBA, 0x11, 0xff, 0xff, 0xff, 0xff}; + NSData* data = [NSData dataWithBytes:bytes length:16]; + FlutterStandardTypedData* value = [FlutterStandardTypedData typedDataWithFloat64:data]; + CheckEncodeDecode(value); +} + +TEST(FlutterStandardCodec, HandlesMethodCallsWithNilArguments) { + FlutterStandardMethodCodec* codec = [FlutterStandardMethodCodec sharedInstance]; + FlutterMethodCall* call = [FlutterMethodCall methodCallWithMethodName:@"hello" arguments:nil]; + NSData* encoded = [codec encodeMethodCall:call]; + FlutterMethodCall* decoded = [codec decodeMethodCall:encoded]; + ASSERT_TRUE([decoded isEqual:call]); +} + +TEST(FlutterStandardCodec, HandlesMethodCallsWithSingleArgument) { + FlutterStandardMethodCodec* codec = [FlutterStandardMethodCodec sharedInstance]; + FlutterMethodCall* call = [FlutterMethodCall methodCallWithMethodName:@"hello" arguments:@42]; + NSData* encoded = [codec encodeMethodCall:call]; + FlutterMethodCall* decoded = [codec decodeMethodCall:encoded]; + ASSERT_TRUE([decoded isEqual:call]); +} + +TEST(FlutterStandardCodec, HandlesMethodCallsWithArgumentList) { + FlutterStandardMethodCodec* codec = [FlutterStandardMethodCodec sharedInstance]; + NSArray* arguments = @[ @42, @"world" ]; + FlutterMethodCall* call = [FlutterMethodCall methodCallWithMethodName:@"hello" + arguments:arguments]; + NSData* encoded = [codec encodeMethodCall:call]; + FlutterMethodCall* decoded = [codec decodeMethodCall:encoded]; + ASSERT_TRUE([decoded isEqual:call]); +} + +TEST(FlutterStandardCodec, HandlesSuccessEnvelopesWithNilResult) { + FlutterStandardMethodCodec* codec = [FlutterStandardMethodCodec sharedInstance]; + NSData* encoded = [codec encodeSuccessEnvelope:nil]; + id decoded = [codec decodeEnvelope:encoded]; + ASSERT_TRUE(decoded == nil); +} + +TEST(FlutterStandardCodec, HandlesSuccessEnvelopesWithSingleResult) { + FlutterStandardMethodCodec* codec = [FlutterStandardMethodCodec sharedInstance]; + NSData* encoded = [codec encodeSuccessEnvelope:@42]; + id decoded = [codec decodeEnvelope:encoded]; + ASSERT_TRUE([decoded isEqual:@42]); +} + +TEST(FlutterStandardCodec, HandlesSuccessEnvelopesWithResultMap) { + FlutterStandardMethodCodec* codec = [FlutterStandardMethodCodec sharedInstance]; + NSDictionary* result = @{@"a" : @42, @42 : @"a"}; + NSData* encoded = [codec encodeSuccessEnvelope:result]; + id decoded = [codec decodeEnvelope:encoded]; + ASSERT_TRUE([decoded isEqual:result]); +} + +TEST(FlutterStandardCodec, HandlesErrorEnvelopes) { + FlutterStandardMethodCodec* codec = [FlutterStandardMethodCodec sharedInstance]; + NSDictionary* details = @{@"a" : @42, @42 : @"a"}; + FlutterError* error = [FlutterError errorWithCode:@"errorCode" + message:@"something failed" + details:details]; + NSData* encoded = [codec encodeErrorEnvelope:error]; + id decoded = [codec decodeEnvelope:encoded]; + ASSERT_TRUE([decoded isEqual:error]); +} + +TEST(FlutterStandardCodec, HandlesSubclasses) { + ExtendedReaderWriter* extendedReaderWriter = [[ExtendedReaderWriter alloc] init]; + FlutterStandardMessageCodec* codec = + [FlutterStandardMessageCodec codecWithReaderWriter:extendedReaderWriter]; + Pair* pair = [[Pair alloc] initWithLeft:@1 right:@2]; + NSData* encoded = [codec encode:pair]; + Pair* decoded = [codec decode:encoded]; + ASSERT_TRUE([pair.left isEqual:decoded.left]); + ASSERT_TRUE([pair.right isEqual:decoded.right]); +} diff --git a/flutter/engine/src/flutter/shell/platform/darwin/common/framework_common.gni b/flutter/engine/src/flutter/shell/platform/darwin/common/framework_common.gni new file mode 100644 index 0000000000000000000000000000000000000000..e2fa8eedad8d4991deb48f8d318f90e4a0ec7ab1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/common/framework_common.gni @@ -0,0 +1,15 @@ +# 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. + +framework_common_headers = + get_path_info([ + "framework/Headers/FlutterMacros.h", + "framework/Headers/FlutterBinaryMessenger.h", + "framework/Headers/FlutterChannels.h", + "framework/Headers/FlutterCodecs.h", + "framework/Headers/FlutterHourFormat.h", + "framework/Headers/FlutterTexture.h", + "framework/Headers/FlutterDartProject.h", + ], + "abspath") diff --git a/flutter/engine/src/flutter/shell/platform/darwin/graphics/BUILD.gn b/flutter/engine/src/flutter/shell/platform/darwin/graphics/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..54d8b17aa49dc03e345ca2e49dcb72ccc1350076 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/graphics/BUILD.gn @@ -0,0 +1,42 @@ +# 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. + +assert(is_ios || is_mac) + +import("//flutter/common/config.gni") +import("//flutter/impeller/tools/impeller.gni") + +source_set("graphics") { + cflags_objc = flutter_cflags_objc + cflags_objcc = flutter_cflags_objcc + + sources = [ + "FlutterDarwinContextMetalSkia.h", + "FlutterDarwinContextMetalSkia.mm", + "FlutterDarwinExternalTextureMetal.h", + "FlutterDarwinExternalTextureMetal.mm", + ] + + deps = [ + "//flutter/common/graphics", + "//flutter/display_list", + "//flutter/fml", + "//flutter/shell/common", + "//flutter/shell/platform/darwin/common:framework_common", + ] + + if (impeller_supports_rendering) { + sources += [ + "FlutterDarwinContextMetalImpeller.h", + "FlutterDarwinContextMetalImpeller.mm", + ] + deps += [ "//flutter/impeller" ] + } + + frameworks = [ "CoreVideo.framework" ] + + public_deps = [ "//flutter/skia" ] + + public_configs = [ "//flutter:config" ] +} diff --git a/flutter/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalImpeller.h b/flutter/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalImpeller.h new file mode 100644 index 0000000000000000000000000000000000000000..e004fc2abfe6389b5b94d254440d1d423dcc7415 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalImpeller.h @@ -0,0 +1,53 @@ +// 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_SHELL_PLATFORM_DARWIN_GRAPHICS_FLUTTERDARWINCONTEXTMETALIMPELLER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_GRAPHICS_FLUTTERDARWINCONTEXTMETALIMPELLER_H_ + +#import +#import +#import + +#include "flutter/fml/concurrent_message_loop.h" +#include "flutter/fml/platform/darwin/cf_utils.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterTexture.h" +#import "flutter/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.h" +#include "impeller/renderer/backend/metal/context_mtl.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * Provides skia GrContexts that are shared between iOS and macOS embeddings. + */ +@interface FlutterDarwinContextMetalImpeller : NSObject + +/** + * Initializes a FlutterDarwinContextMetalImpeller. + */ +- (instancetype)init:(const impeller::Flags&)flags + gpuDisabledSyncSwitch: + (const std::shared_ptr&)is_gpu_disabled_sync_switch; + +/** + * Creates an external texture with the specified ID and contents. + */ +- (FlutterDarwinExternalTextureMetal*) + createExternalTextureWithIdentifier:(int64_t)textureID + texture:(NSObject*)texture; + +/** + * Impeller context. + */ +@property(nonatomic, readonly) std::shared_ptr context; + +/* + * Texture cache for external textures. + */ +@property(nonatomic, readonly) fml::CFRef textureCache; + +@end + +NS_ASSUME_NONNULL_END + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_GRAPHICS_FLUTTERDARWINCONTEXTMETALIMPELLER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalImpeller.mm b/flutter/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalImpeller.mm new file mode 100644 index 0000000000000000000000000000000000000000..b893da311d8068c8fc50bcde540291929c5de367 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalImpeller.mm @@ -0,0 +1,68 @@ +// 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. + +#import "flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalImpeller.h" + +#include "flutter/common/graphics/persistent_cache.h" +#include "flutter/fml/logging.h" +#include "flutter/impeller/renderer/backend/metal/context_mtl.h" +#include "flutter/shell/common/context_options.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#include "impeller/entity/mtl/entity_shaders.h" +#include "impeller/entity/mtl/framebuffer_blend_shaders.h" +#include "impeller/entity/mtl/modern_shaders.h" + +FLUTTER_ASSERT_ARC + +static std::shared_ptr CreateImpellerContext( + const impeller::Flags& flags, + const std::shared_ptr& is_gpu_disabled_sync_switch) { + std::vector> shader_mappings = { + std::make_shared(impeller_entity_shaders_data, + impeller_entity_shaders_length), + std::make_shared(impeller_modern_shaders_data, + impeller_modern_shaders_length), + std::make_shared(impeller_framebuffer_blend_shaders_data, + impeller_framebuffer_blend_shaders_length), + }; + return impeller::ContextMTL::Create(flags, shader_mappings, is_gpu_disabled_sync_switch, + "Impeller Library"); +} + +@implementation FlutterDarwinContextMetalImpeller + +- (instancetype)init:(const impeller::Flags&)flags + gpuDisabledSyncSwitch: + (const std::shared_ptr&)is_gpu_disabled_sync_switch { + self = [super init]; + if (self != nil) { + _context = CreateImpellerContext(flags, is_gpu_disabled_sync_switch); + FML_CHECK(_context) << "Could not create Metal Impeller Context."; + id device = _context->GetMTLDevice(); + FML_CHECK(device) << "Could not acquire Metal device."; + + CVMetalTextureCacheRef textureCache; + CVReturn cvReturn = CVMetalTextureCacheCreate(kCFAllocatorDefault, // allocator + nil, // cache attributes (nil default) + device, // metal device + nil, // texture attributes (nil default) + &textureCache // [out] cache + ); + + FML_CHECK(cvReturn == kCVReturnSuccess) << "Could not acquire Metal device."; + _textureCache.Reset(textureCache); + } + return self; +} + +- (FlutterDarwinExternalTextureMetal*) + createExternalTextureWithIdentifier:(int64_t)textureID + texture:(NSObject*)texture { + return [[FlutterDarwinExternalTextureMetal alloc] initWithTextureCache:_textureCache + textureID:textureID + texture:texture + enableImpeller:YES]; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalSkia.h b/flutter/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalSkia.h new file mode 100644 index 0000000000000000000000000000000000000000..ebac28e07e4659b00bc14fddfed7926fe90e1e83 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalSkia.h @@ -0,0 +1,82 @@ +// 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_SHELL_PLATFORM_DARWIN_GRAPHICS_FLUTTERDARWINCONTEXTMETALSKIA_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_GRAPHICS_FLUTTERDARWINCONTEXTMETALSKIA_H_ + +#if !SLIMPELLER + +#import +#import +#import + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterTexture.h" +#import "flutter/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.h" +#include "third_party/skia/include/gpu/ganesh/GrDirectContext.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * Provides skia GrContexts that are shared between iOS and macOS embeddings. + */ +@interface FlutterDarwinContextMetalSkia : NSObject + +/** + * Initializes a FlutterDarwinContextMetalSkia with the system default MTLDevice and a new + * MTLCommandQueue. + */ +- (instancetype)initWithDefaultMTLDevice; + +/** + * Initializes a FlutterDarwinContextMetalSkia with provided MTLDevice and MTLCommandQueue. + */ +- (instancetype)initWithMTLDevice:(id)device + commandQueue:(id)commandQueue; + +/** + * Creates an external texture with the specified ID and contents. + */ +- (FlutterDarwinExternalTextureMetal*) + createExternalTextureWithIdentifier:(int64_t)textureID + texture:(NSObject*)texture; + +/** + * Creates a GrDirectContext with the provided `MTLDevice` and `MTLCommandQueue`. + */ ++ (sk_sp)createGrContext:(id)device + commandQueue:(id)commandQueue; + +/** + * MTLDevice that is backing this context.s + */ +@property(nonatomic, readonly) id device; + +/** + * MTLCommandQueue that is acquired from the `device`. This queue is used both for rendering and + * resource related commands. + */ +@property(nonatomic, readonly) id commandQueue; + +/** + * Skia GrContext that is used for rendering. + */ +@property(nonatomic, readonly) sk_sp mainContext; + +/** + * Skia GrContext that is used for resources (uploading textures etc). + */ +@property(nonatomic, readonly) sk_sp resourceContext; + +/* + * Texture cache for external textures. + */ +@property(nonatomic, readonly) CVMetalTextureCacheRef textureCache; + +@end + +NS_ASSUME_NONNULL_END + +#endif // !SLIMPELLER + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_GRAPHICS_FLUTTERDARWINCONTEXTMETALSKIA_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalSkia.mm b/flutter/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalSkia.mm new file mode 100644 index 0000000000000000000000000000000000000000..390328f1ed435961a215a5fc137c6c40c5a71c33 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalSkia.mm @@ -0,0 +1,119 @@ +// 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. + +#if !SLIMPELLER + +#import "flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalSkia.h" + +#include "flutter/common/graphics/persistent_cache.h" +#include "flutter/fml/logging.h" +#include "flutter/fml/platform/darwin/cf_utils.h" +#include "flutter/shell/common/context_options.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#include "third_party/skia/include/gpu/ganesh/GrDirectContext.h" +#include "third_party/skia/include/gpu/ganesh/mtl/GrMtlBackendContext.h" +#include "third_party/skia/include/gpu/ganesh/mtl/GrMtlDirectContext.h" + +FLUTTER_ASSERT_ARC + +@implementation FlutterDarwinContextMetalSkia { + fml::CFRef _textureCache; +} + +- (instancetype)initWithDefaultMTLDevice { + id device = MTLCreateSystemDefaultDevice(); + return [self initWithMTLDevice:device commandQueue:[device newCommandQueue]]; +} + +- (instancetype)initWithMTLDevice:(id)device + commandQueue:(id)commandQueue { + self = [super init]; + if (self != nil) { + _device = device; + + if (!_device) { + FML_DLOG(ERROR) << "Could not acquire Metal device."; + return nil; + } + + _commandQueue = commandQueue; + + if (!_commandQueue) { + FML_DLOG(ERROR) << "Could not create Metal command queue."; + return nil; + } + + [_commandQueue setLabel:@"Flutter Main Queue"]; + + { + CVMetalTextureCacheRef cache = nullptr; + CVReturn cvReturn = CVMetalTextureCacheCreate(kCFAllocatorDefault, // allocator + nil, // cache attributes (nil default) + _device, // metal device + nil, // texture attributes (nil default) + &cache // [out] cache + ); + _textureCache.Reset(cache); + if (cvReturn != kCVReturnSuccess) { + FML_DLOG(ERROR) << "Could not create Metal texture cache."; + return nil; + } + } + + // The devices are in the same "sharegroup" because they share the same device and command + // queues for now. When the resource context gets its own transfer queue, this will have to be + // refactored. + _mainContext = [self createGrContext]; + _resourceContext = [self createGrContext]; + + if (!_mainContext || !_resourceContext) { + FML_DLOG(ERROR) << "Could not create Skia Metal contexts."; + return nil; + } + + // Only log this message on iOS where the default is Impeller. On macOS + // desktop, Skia is still the default and this log is unecessary. +#if defined(FML_OS_IOS) || defined(FML_OS_IOS_SIM) + FML_LOG(IMPORTANT) << "Using the Skia rendering backend (Metal)."; +#endif // defined(FML_OS_IOS) || defined(FML_OS_IOS_SIM) + + _resourceContext->setResourceCacheLimit(0u); + } + return self; +} + +- (sk_sp)createGrContext { + id device = _device; + id commandQueue = _commandQueue; + return [FlutterDarwinContextMetalSkia createGrContext:device commandQueue:commandQueue]; +} + ++ (sk_sp)createGrContext:(id)device + commandQueue:(id)commandQueue { + const auto contextOptions = + flutter::MakeDefaultContextOptions(flutter::ContextType::kRender, GrBackendApi::kMetal); + GrMtlBackendContext backendContext = {}; + // Skia expect arguments to `MakeMetal` transfer ownership of the reference in for release later + // when the GrDirectContext is collected. + backendContext.fDevice.retain((__bridge void*)device); + backendContext.fQueue.retain((__bridge void*)commandQueue); + return GrDirectContexts::MakeMetal(backendContext, contextOptions); +} + +- (FlutterDarwinExternalTextureMetal*) + createExternalTextureWithIdentifier:(int64_t)textureID + texture:(NSObject*)texture { + return [[FlutterDarwinExternalTextureMetal alloc] initWithTextureCache:_textureCache + textureID:textureID + texture:texture + enableImpeller:NO]; +} + +- (CVMetalTextureCacheRef)textureCache { + return _textureCache; +} + +@end + +#endif // !SLIMPELLER diff --git a/flutter/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.h b/flutter/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.h new file mode 100644 index 0000000000000000000000000000000000000000..4cedf2c872487c1c240d154018b04089207f57de --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.h @@ -0,0 +1,70 @@ +// 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_SHELL_PLATFORM_DARWIN_GRAPHICS_FLUTTERDARWINEXTERNALTEXTUREMETAL_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_GRAPHICS_FLUTTERDARWINEXTERNALTEXTUREMETAL_H_ + +#import +#import + +#include "flutter/common/graphics/texture.h" +#include "flutter/display_list/image/dl_image.h" +#include "flutter/impeller/display_list/aiks_context.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterTexture.h" +#include "third_party/skia/include/core/SkCanvas.h" +#include "third_party/skia/include/core/SkImage.h" + +@interface FlutterDarwinExternalTextureSkImageWrapper : NSObject + ++ (sk_sp)wrapYUVATexture:(nonnull id)yTex + UVTex:(nonnull id)uvTex + YUVColorSpace:(SkYUVColorSpace)colorSpace + grContext:(nonnull GrDirectContext*)grContext + width:(size_t)width + height:(size_t)height; + ++ (sk_sp)wrapRGBATexture:(nonnull id)rgbaTex + grContext:(nonnull GrDirectContext*)grContext + width:(size_t)width + height:(size_t)height; + +@end + +@interface FlutterDarwinExternalTextureImpellerImageWrapper : NSObject + ++ (sk_sp)wrapYUVATexture:(nonnull id)yTex + UVTex:(nonnull id)uvTex + YUVColorSpace:(impeller::YUVColorSpace)colorSpace + aiksContext:(nonnull impeller::AiksContext*)aiksContext; + ++ (sk_sp)wrapRGBATexture:(nonnull id)rgbaTex + aiksContext:(nonnull impeller::AiksContext*)aiks_context; + +@end + +@interface FlutterDarwinExternalTextureMetal : NSObject + +- (nullable instancetype)initWithTextureCache:(nonnull CVMetalTextureCacheRef)textureCache + textureID:(int64_t)textureID + texture:(nonnull NSObject*)texture + enableImpeller:(BOOL)enableImpeller; + +- (void)paintContext:(flutter::Texture::PaintContext&)context + bounds:(const SkRect&)bounds + freeze:(BOOL)freeze + sampling:(const flutter::DlImageSampling)sampling; + +- (void)onGrContextCreated; + +- (void)onGrContextDestroyed; + +- (void)markNewFrameAvailable; + +- (void)onTextureUnregistered; + +@property(nonatomic, readonly) int64_t textureID; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_GRAPHICS_FLUTTERDARWINEXTERNALTEXTUREMETAL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.mm b/flutter/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.mm new file mode 100644 index 0000000000000000000000000000000000000000..b5a937f07ca5e7903ab43219a3b29fefd90bef9e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.mm @@ -0,0 +1,363 @@ +// 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. + +#import "flutter/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.h" + +#include "flutter/display_list/image/dl_image.h" +#include "flutter/fml/platform/darwin/cf_utils.h" +#include "impeller/base/validation.h" +#include "impeller/display_list/aiks_context.h" +#include "impeller/display_list/dl_image_impeller.h" +#include "impeller/renderer/backend/metal/texture_mtl.h" +#include "third_party/skia/include/core/SkColorSpace.h" +#include "third_party/skia/include/core/SkImage.h" +#include "third_party/skia/include/core/SkYUVAInfo.h" +#include "third_party/skia/include/gpu/GpuTypes.h" +#include "third_party/skia/include/gpu/ganesh/GrBackendSurface.h" +#include "third_party/skia/include/gpu/ganesh/GrDirectContext.h" +#include "third_party/skia/include/gpu/ganesh/GrYUVABackendTextures.h" +#include "third_party/skia/include/gpu/ganesh/SkImageGanesh.h" +#include "third_party/skia/include/gpu/ganesh/mtl/GrMtlBackendSurface.h" +#include "third_party/skia/include/gpu/ganesh/mtl/GrMtlTypes.h" +#include "third_party/skia/include/ports/SkCFObject.h" + +FLUTTER_ASSERT_ARC + +@implementation FlutterDarwinExternalTextureMetal { + fml::CFRef _textureCache; + NSObject* _externalTexture; + BOOL _textureFrameAvailable; + sk_sp _externalImage; + CVPixelBufferRef _lastPixelBuffer; + OSType _pixelFormat; + BOOL _enableImpeller; +} + +- (instancetype)initWithTextureCache:(nonnull CVMetalTextureCacheRef)textureCache + textureID:(int64_t)textureID + texture:(NSObject*)texture + enableImpeller:(BOOL)enableImpeller { + if (self = [super init]) { + _textureCache.Retain(textureCache); + _textureID = textureID; + _externalTexture = texture; + _enableImpeller = enableImpeller; + return self; + } + return nil; +} + +- (void)dealloc { + CVPixelBufferRelease(_lastPixelBuffer); + if (_textureCache) { + CVMetalTextureCacheFlush(_textureCache, /* options (must be zero) */ 0); + } +} + +- (void)paintContext:(flutter::Texture::PaintContext&)context + bounds:(const SkRect&)bounds + freeze:(BOOL)freeze + sampling:(const flutter::DlImageSampling)sampling { + const bool needsUpdatedTexture = (!freeze && _textureFrameAvailable) || !_externalImage; + + if (needsUpdatedTexture) { + [self onNeedsUpdatedTexture:context]; + } + + if (_externalImage) { + context.canvas->DrawImageRect( + _externalImage, // image + flutter::DlRect::Make(_externalImage->GetBounds()), // source rect + flutter::ToDlRect(bounds), // destination rect + sampling, // sampling + context.paint, // paint + flutter::DlSrcRectConstraint::kStrict // enforce edges + ); + } +} + +- (void)onNeedsUpdatedTexture:(flutter::Texture::PaintContext&)context { + CVPixelBufferRef pixelBuffer = [_externalTexture copyPixelBuffer]; + if (pixelBuffer) { + CVPixelBufferRelease(_lastPixelBuffer); + _lastPixelBuffer = pixelBuffer; + _pixelFormat = CVPixelBufferGetPixelFormatType(_lastPixelBuffer); + } + + // If the application told us there was a texture frame available but did not provide one when + // asked for it, reuse the previous texture but make sure to ask again the next time around. + sk_sp image = [self wrapExternalPixelBuffer:_lastPixelBuffer context:context]; + if (image) { + _externalImage = image; + _textureFrameAvailable = false; + } +} + +- (void)onGrContextCreated { + // External images in this backend have no thread affinity and are not tied to the context in any + // way. Instead, they are tied to the Metal device which is associated with the cache already and + // is consistent throughout the shell run. +} + +- (void)onGrContextDestroyed { + // The image must be reset because it is tied to the onscreen context. But the pixel buffer that + // created the image is still around. In case of context reacquisition, that last pixel + // buffer will be used to materialize the image in case the application fails to provide a new + // one. + _externalImage.reset(); + if (_textureCache) { + CVMetalTextureCacheFlush(_textureCache, /* options (must be zero) */ 0); + } +} + +- (void)markNewFrameAvailable { + _textureFrameAvailable = YES; +} + +- (void)onTextureUnregistered { + if ([_externalTexture respondsToSelector:@selector(onTextureUnregistered:)]) { + [_externalTexture onTextureUnregistered:_externalTexture]; + } +} + +#pragma mark - External texture skia wrapper methods. + +- (sk_sp)wrapExternalPixelBuffer:(CVPixelBufferRef)pixelBuffer + context:(flutter::Texture::PaintContext&)context { + if (!pixelBuffer) { + return nullptr; + } + + sk_sp image = nullptr; + if (_pixelFormat == kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange || + _pixelFormat == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) { + image = [self wrapNV12ExternalPixelBuffer:pixelBuffer context:context]; + } else if (_pixelFormat == kCVPixelFormatType_32BGRA) { + image = [self wrapBGRAExternalPixelBuffer:pixelBuffer context:context]; + } else { + FML_LOG(ERROR) << "Unsupported pixel format: " << _pixelFormat; + return nullptr; + } + + if (!image) { + FML_DLOG(ERROR) << "Could not wrap Metal texture as a display list image."; + } + + return image; +} + +- (sk_sp)wrapNV12ExternalPixelBuffer:(CVPixelBufferRef)pixelBuffer + context:(flutter::Texture::PaintContext&)context { + SkISize textureSize = + SkISize::Make(CVPixelBufferGetWidth(pixelBuffer), CVPixelBufferGetHeight(pixelBuffer)); + CVMetalTextureRef yMetalTexture = nullptr; + { + CVReturn cvReturn = + CVMetalTextureCacheCreateTextureFromImage(/*allocator=*/kCFAllocatorDefault, + /*textureCache=*/_textureCache, + /*sourceImage=*/pixelBuffer, + /*textureAttributes=*/nullptr, + /*pixelFormat=*/MTLPixelFormatR8Unorm, + /*width=*/textureSize.width(), + /*height=*/textureSize.height(), + /*planeIndex=*/0u, + /*texture=*/&yMetalTexture); + + if (cvReturn != kCVReturnSuccess) { + FML_DLOG(ERROR) << "Could not create Metal texture from pixel buffer: CVReturn " << cvReturn; + return nullptr; + } + } + + CVMetalTextureRef uvMetalTexture = nullptr; + { + CVReturn cvReturn = + CVMetalTextureCacheCreateTextureFromImage(/*allocator=*/kCFAllocatorDefault, + /*textureCache=*/_textureCache, + /*sourceImage=*/pixelBuffer, + /*textureAttributes=*/nullptr, + /*pixelFormat=*/MTLPixelFormatRG8Unorm, + /*width=*/textureSize.width() / 2, + /*height=*/textureSize.height() / 2, + /*planeIndex=*/1u, + /*texture=*/&uvMetalTexture); + + if (cvReturn != kCVReturnSuccess) { + FML_DLOG(ERROR) << "Could not create Metal texture from pixel buffer: CVReturn " << cvReturn; + return nullptr; + } + } + + id yTex = CVMetalTextureGetTexture(yMetalTexture); + CVBufferRelease(yMetalTexture); + + id uvTex = CVMetalTextureGetTexture(uvMetalTexture); + CVBufferRelease(uvMetalTexture); + + if (_enableImpeller) { + impeller::YUVColorSpace yuvColorSpace = + _pixelFormat == kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange + ? impeller::YUVColorSpace::kBT601LimitedRange + : impeller::YUVColorSpace::kBT601FullRange; + return [FlutterDarwinExternalTextureImpellerImageWrapper wrapYUVATexture:yTex + UVTex:uvTex + YUVColorSpace:yuvColorSpace + aiksContext:context.aiks_context]; + } + + SkYUVColorSpace colorSpace = _pixelFormat == kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange + ? kRec601_Limited_SkYUVColorSpace + : kJPEG_Full_SkYUVColorSpace; + auto skImage = [FlutterDarwinExternalTextureSkImageWrapper wrapYUVATexture:yTex + UVTex:uvTex + YUVColorSpace:colorSpace + grContext:context.gr_context + width:textureSize.width() + height:textureSize.height()]; + if (!skImage) { + return nullptr; + } + + // This image should not escape local use by this flutter::Texture implementation + return flutter::DlImage::Make(skImage); +} + +- (sk_sp)wrapBGRAExternalPixelBuffer:(CVPixelBufferRef)pixelBuffer + context:(flutter::Texture::PaintContext&)context { + SkISize textureSize = + SkISize::Make(CVPixelBufferGetWidth(pixelBuffer), CVPixelBufferGetHeight(pixelBuffer)); + CVMetalTextureRef metalTexture = nullptr; + CVReturn cvReturn = + CVMetalTextureCacheCreateTextureFromImage(/*allocator=*/kCFAllocatorDefault, + /*textureCache=*/_textureCache, + /*sourceImage=*/pixelBuffer, + /*textureAttributes=*/nullptr, + /*pixelFormat=*/MTLPixelFormatBGRA8Unorm, + /*width=*/textureSize.width(), + /*height=*/textureSize.height(), + /*planeIndex=*/0u, + /*texture=*/&metalTexture); + + if (cvReturn != kCVReturnSuccess) { + FML_DLOG(ERROR) << "Could not create Metal texture from pixel buffer: CVReturn " << cvReturn; + return nullptr; + } + + id rgbaTex = CVMetalTextureGetTexture(metalTexture); + CVBufferRelease(metalTexture); + + if (_enableImpeller) { + return [FlutterDarwinExternalTextureImpellerImageWrapper wrapRGBATexture:rgbaTex + aiksContext:context.aiks_context]; + } + + auto skImage = [FlutterDarwinExternalTextureSkImageWrapper wrapRGBATexture:rgbaTex + grContext:context.gr_context + width:textureSize.width() + height:textureSize.height()]; + if (!skImage) { + return nullptr; + } + + // This image should not escape local use by this flutter::Texture implementation + return flutter::DlImage::Make(skImage); +} + +@end + +@implementation FlutterDarwinExternalTextureSkImageWrapper + ++ (sk_sp)wrapYUVATexture:(id)yTex + UVTex:(id)uvTex + YUVColorSpace:(SkYUVColorSpace)colorSpace + grContext:(nonnull GrDirectContext*)grContext + width:(size_t)width + height:(size_t)height { +#if SLIMPELLER + return nullptr; +#else // SLIMPELLER + GrMtlTextureInfo ySkiaTextureInfo; + ySkiaTextureInfo.fTexture.retain((__bridge GrMTLHandle)yTex); + + GrBackendTexture skiaBackendTextures[2]; + skiaBackendTextures[0] = + GrBackendTextures::MakeMtl(width, height, skgpu::Mipmapped::kNo, ySkiaTextureInfo); + + GrMtlTextureInfo uvSkiaTextureInfo; + uvSkiaTextureInfo.fTexture.retain((__bridge GrMTLHandle)uvTex); + + skiaBackendTextures[1] = + GrBackendTextures::MakeMtl(width, height, skgpu::Mipmapped::kNo, uvSkiaTextureInfo); + SkYUVAInfo yuvaInfo(skiaBackendTextures[0].dimensions(), SkYUVAInfo::PlaneConfig::kY_UV, + SkYUVAInfo::Subsampling::k444, colorSpace); + GrYUVABackendTextures yuvaBackendTextures(yuvaInfo, skiaBackendTextures, + kTopLeft_GrSurfaceOrigin); + + return SkImages::TextureFromYUVATextures(grContext, yuvaBackendTextures, + /*imageColorSpace=*/nullptr, + /*releaseProc*/ nullptr, /*releaseContext*/ nullptr); +#endif // SLIMPELLER +} + ++ (sk_sp)wrapRGBATexture:(id)rgbaTex + grContext:(nonnull GrDirectContext*)grContext + width:(size_t)width + height:(size_t)height { +#if SLIMPELLER + return nullptr; +#else // SLIMPELLER + + GrMtlTextureInfo skiaTextureInfo; + skiaTextureInfo.fTexture.retain((__bridge GrMTLHandle)rgbaTex); + + GrBackendTexture skiaBackendTexture = + GrBackendTextures::MakeMtl(width, height, skgpu::Mipmapped ::kNo, skiaTextureInfo); + + return SkImages::BorrowTextureFrom(grContext, skiaBackendTexture, kTopLeft_GrSurfaceOrigin, + kBGRA_8888_SkColorType, kPremul_SkAlphaType, + /*colorSpace=*/nullptr, /*releaseProc*/ nullptr, + /*releaseContext*/ nullptr); +#endif // SLIMPELLER +} +@end + +@implementation FlutterDarwinExternalTextureImpellerImageWrapper + ++ (sk_sp)wrapYUVATexture:(id)yTex + UVTex:(id)uvTex + YUVColorSpace:(impeller::YUVColorSpace)colorSpace + aiksContext:(nonnull impeller::AiksContext*)aiks_context { + impeller::TextureDescriptor yDesc; + yDesc.storage_mode = impeller::StorageMode::kDevicePrivate; + yDesc.format = impeller::PixelFormat::kR8UNormInt; + yDesc.size = impeller::ISize(yTex.width, yTex.height); + yDesc.mip_count = 1; + auto yTexture = impeller::TextureMTL::Wrapper(yDesc, yTex); + yTexture->SetCoordinateSystem(impeller::TextureCoordinateSystem::kUploadFromHost); + + impeller::TextureDescriptor uvDesc; + uvDesc.storage_mode = impeller::StorageMode::kDevicePrivate; + uvDesc.format = impeller::PixelFormat::kR8G8UNormInt; + uvDesc.size = impeller::ISize(uvTex.width, uvTex.height); + uvDesc.mip_count = 1; + auto uvTexture = impeller::TextureMTL::Wrapper(uvDesc, uvTex); + uvTexture->SetCoordinateSystem(impeller::TextureCoordinateSystem::kUploadFromHost); + ; + + return impeller::DlImageImpeller::MakeFromYUVTextures(aiks_context, yTexture, uvTexture, + colorSpace); +} + ++ (sk_sp)wrapRGBATexture:(id)rgbaTex + aiksContext:(nonnull impeller::AiksContext*)aiks_context { + impeller::TextureDescriptor desc; + desc.storage_mode = impeller::StorageMode::kDevicePrivate; + desc.format = impeller::PixelFormat::kB8G8R8A8UNormInt; + desc.size = impeller::ISize(rgbaTex.width, rgbaTex.height); + desc.mip_count = 1; + auto texture = impeller::TextureMTL::Wrapper(desc, rgbaTex); + texture->SetCoordinateSystem(impeller::TextureCoordinateSystem::kUploadFromHost); + return impeller::DlImageImpeller::Make(texture); +} +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/BUILD.gn b/flutter/engine/src/flutter/shell/platform/darwin/ios/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..900fc461b92be2ca7df494b245f33e43de842234 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/BUILD.gn @@ -0,0 +1,421 @@ +# 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. + +assert(is_ios) + +import("//build/config/ios/ios_sdk.gni") +import("//build/toolchain/clang.gni") +import("//build/toolchain/toolchain.gni") +import("//flutter/common/config.gni") +import("//flutter/shell/config.gni") +import("//flutter/shell/gpu/gpu.gni") +import("//flutter/shell/platform/darwin/common/framework_common.gni") +import("//flutter/testing/testing.gni") + +_flutter_framework_dir = "$root_out_dir/Flutter.framework" + +shell_gpu_configuration("ios_gpu_configuration") { + enable_software = true + enable_gl = false + enable_vulkan = false + enable_metal = true +} + +# The headers that will be copied to the Flutter.framework and be accessed +# from outside the Flutter engine source root. +_flutter_framework_headers = [ + "framework/Headers/Flutter.h", + "framework/Headers/FlutterAppDelegate.h", + "framework/Headers/FlutterCallbackCache.h", + "framework/Headers/FlutterEngine.h", + "framework/Headers/FlutterEngineGroup.h", + "framework/Headers/FlutterHeadlessDartRunner.h", + "framework/Headers/FlutterPlatformViews.h", + "framework/Headers/FlutterPlugin.h", + "framework/Headers/FlutterPluginAppLifeCycleDelegate.h", + "framework/Headers/FlutterViewController.h", +] + +_flutter_framework_headers_copy_dir = "$_flutter_framework_dir/Headers" + +source_set("flutter_framework_source") { + visibility = [ ":*" ] + cflags_objc = flutter_cflags_objc + cflags_objcc = flutter_cflags_objcc + + defines = [ "FLUTTER_FRAMEWORK=1" ] + public_configs = [ + ":ios_gpu_configuration_config", + "//flutter:config", + ] + + configs += [ "//build/config/ios:ios_application_extension" ] + + sources = [ + "framework/Source/FlutterAppDelegate.mm", + "framework/Source/FlutterCallbackCache.mm", + "framework/Source/FlutterCallbackCache_Internal.h", + "framework/Source/FlutterChannelKeyResponder.h", + "framework/Source/FlutterChannelKeyResponder.mm", + "framework/Source/FlutterDartProject.mm", + "framework/Source/FlutterDartProject_Internal.h", + "framework/Source/FlutterDartVMServicePublisher.h", + "framework/Source/FlutterDartVMServicePublisher.mm", + "framework/Source/FlutterEmbedderKeyResponder.h", + "framework/Source/FlutterEmbedderKeyResponder.mm", + "framework/Source/FlutterEngine.mm", + "framework/Source/FlutterEngineGroup.mm", + "framework/Source/FlutterEngine_Internal.h", + "framework/Source/FlutterHeadlessDartRunner.mm", + "framework/Source/FlutterKeyPrimaryResponder.h", + "framework/Source/FlutterKeySecondaryResponder.h", + "framework/Source/FlutterKeyboardManager.h", + "framework/Source/FlutterKeyboardManager.mm", + "framework/Source/FlutterMetalLayer.h", + "framework/Source/FlutterMetalLayer.mm", + "framework/Source/FlutterOverlayView.h", + "framework/Source/FlutterOverlayView.mm", + "framework/Source/FlutterPlatformPlugin.h", + "framework/Source/FlutterPlatformPlugin.mm", + "framework/Source/FlutterPlatformViews.mm", + "framework/Source/FlutterPlatformViewsController.h", + "framework/Source/FlutterPlatformViewsController.mm", + "framework/Source/FlutterPlatformViews_Internal.h", + "framework/Source/FlutterPluginAppLifeCycleDelegate.mm", + "framework/Source/FlutterRestorationPlugin.h", + "framework/Source/FlutterRestorationPlugin.mm", + "framework/Source/FlutterSemanticsScrollView.h", + "framework/Source/FlutterSemanticsScrollView.mm", + "framework/Source/FlutterSharedApplication.h", + "framework/Source/FlutterSharedApplication.mm", + "framework/Source/FlutterSpellCheckPlugin.h", + "framework/Source/FlutterSpellCheckPlugin.mm", + "framework/Source/FlutterTextInputDelegate.h", + "framework/Source/FlutterTextInputPlugin.h", + "framework/Source/FlutterTextInputPlugin.mm", + "framework/Source/FlutterTextureRegistryRelay.h", + "framework/Source/FlutterTextureRegistryRelay.mm", + "framework/Source/FlutterUIPressProxy.h", + "framework/Source/FlutterUIPressProxy.mm", + "framework/Source/FlutterUndoManagerDelegate.h", + "framework/Source/FlutterUndoManagerPlugin.h", + "framework/Source/FlutterUndoManagerPlugin.mm", + "framework/Source/FlutterView.h", + "framework/Source/FlutterView.mm", + "framework/Source/FlutterViewController.mm", + "framework/Source/FlutterViewController_Internal.h", + "framework/Source/FlutterViewResponder.h", + "framework/Source/KeyCodeMap.g.mm", + "framework/Source/KeyCodeMap_Internal.h", + "framework/Source/SemanticsObject+UIFocusSystem.mm", + "framework/Source/SemanticsObject.h", + "framework/Source/SemanticsObject.mm", + "framework/Source/TextInputSemanticsObject.h", + "framework/Source/TextInputSemanticsObject.mm", + "framework/Source/UIViewController+FlutterScreenAndSceneIfLoaded.h", + "framework/Source/UIViewController+FlutterScreenAndSceneIfLoaded.mm", + "framework/Source/accessibility_bridge.h", + "framework/Source/accessibility_bridge.mm", + "framework/Source/connection_collection.h", + "framework/Source/connection_collection.mm", + "framework/Source/overlay_layer_pool.h", + "framework/Source/overlay_layer_pool.mm", + "framework/Source/platform_message_response_darwin.h", + "framework/Source/platform_message_response_darwin.mm", + "framework/Source/profiler_metrics_ios.h", + "framework/Source/profiler_metrics_ios.mm", + "framework/Source/vsync_waiter_ios.h", + "framework/Source/vsync_waiter_ios.mm", + "ios_context.h", + "ios_context.mm", + "ios_context_metal_impeller.h", + "ios_context_metal_impeller.mm", + "ios_context_noop.h", + "ios_context_noop.mm", + "ios_external_texture_metal.h", + "ios_external_texture_metal.mm", + "ios_external_view_embedder.h", + "ios_external_view_embedder.mm", + "ios_surface.h", + "ios_surface.mm", + "ios_surface_metal_impeller.h", + "ios_surface_metal_impeller.mm", + "ios_surface_noop.h", + "ios_surface_noop.mm", + "platform_message_handler_ios.h", + "platform_message_handler_ios.mm", + "platform_view_ios.h", + "platform_view_ios.mm", + "rendering_api_selection.h", + "rendering_api_selection.mm", + ] + sources += _flutter_framework_headers + + frameworks = [ + "AudioToolbox.framework", + "CoreMedia.framework", + "CoreVideo.framework", + "IOSurface.framework", + "QuartzCore.framework", + "WebKit.framework", + "UIKit.framework", + ] + if (flutter_runtime_mode == "profile" || flutter_runtime_mode == "debug") { + # This is required by the profiler_metrics_ios.mm to get GPU statistics. + # Usage in release builds will cause rejection from the App Store. + frameworks += [ "IOKit.framework" ] + } + + deps = [ + ":ios_gpu_configuration", + "//flutter/common:common", + "//flutter/common/graphics", + "//flutter/fml", + "//flutter/lib/ui", + "//flutter/runtime", + "//flutter/shell/common", + "//flutter/shell/platform/common:common_cpp_input", + "//flutter/shell/platform/darwin/common", + "//flutter/shell/platform/darwin/common:framework_common", + "//flutter/shell/platform/darwin/graphics", + "//flutter/shell/platform/embedder:embedder_as_internal_library", + "//flutter/shell/profiling:profiling", + "//flutter/third_party/icu", + "//flutter/third_party/spring_animation", + ] +} + +platform_frameworks_path = + rebase_path("$ios_sdk_path/../../Library/Frameworks/") + +shared_library("ios_test_flutter") { + testonly = true + visibility = [ "*" ] + + cflags_objc = flutter_cflags_objc + cflags_objcc = flutter_cflags_objcc + cflags = [ + "-fvisibility=default", + "-F$platform_frameworks_path", + "-mios-simulator-version-min=$ios_testing_deployment_target", + ] + + ldflags = [ + "-F$platform_frameworks_path", + "-Wl,-install_name,@rpath/Frameworks/libios_test_flutter.dylib", + ] + frameworks = [ "XCTest.framework" ] + configs -= [ + "//build/config/gcc:symbol_visibility_hidden", + "//build/config:symbol_visibility_hidden", + ] + sources = [ + "framework/Source/FlutterAppDelegateTest.mm", + "framework/Source/FlutterChannelKeyResponderTest.mm", + "framework/Source/FlutterDartProjectTest.mm", + "framework/Source/FlutterEmbedderKeyResponderTest.mm", + "framework/Source/FlutterEngineGroupTest.mm", + "framework/Source/FlutterEnginePlatformViewTest.mm", + "framework/Source/FlutterEngineTest.mm", + "framework/Source/FlutterFakeKeyEvents.h", + "framework/Source/FlutterFakeKeyEvents.mm", + "framework/Source/FlutterKeyboardManagerTest.mm", + "framework/Source/FlutterMetalLayerTest.mm", + "framework/Source/FlutterPlatformPluginTest.mm", + "framework/Source/FlutterPlatformViewsTest.mm", + "framework/Source/FlutterPluginAppLifeCycleDelegateTest.mm", + "framework/Source/FlutterRestorationPluginTest.mm", + "framework/Source/FlutterSharedApplicationTest.mm", + "framework/Source/FlutterSpellCheckPluginTest.mm", + "framework/Source/FlutterTextInputPluginTest.mm", + "framework/Source/FlutterTextureRegistryRelayTest.mm", + "framework/Source/FlutterTouchInterceptingView_Test.h", + "framework/Source/FlutterUndoManagerPluginTest.mm", + "framework/Source/FlutterViewControllerTest.mm", + "framework/Source/FlutterViewTest.mm", + "framework/Source/SemanticsObjectTest.mm", + "framework/Source/SemanticsObjectTestMocks.h", + "framework/Source/UIViewController_FlutterScreenAndSceneIfLoadedTest.mm", + "framework/Source/VsyncWaiterIosTest.mm", + "framework/Source/accessibility_bridge_test.mm", + "framework/Source/availability_version_check_test.mm", + "framework/Source/connection_collection_test.mm", + "ios_context_noop_unittests.mm", + "ios_surface_noop_unittests.mm", + "platform_message_handler_ios_test.mm", + ] + deps = [ + ":flutter_framework", + ":flutter_framework_source", + ":ios_gpu_configuration", + "//flutter/common:common", + "//flutter/lib/ui:ui", + "//flutter/shell/platform/darwin/common:framework_common", + "//flutter/shell/platform/embedder:embedder_as_internal_library", + "//flutter/shell/platform/embedder:embedder_test_utils", + "//flutter/third_party/ocmock:ocmock_shared", + "//flutter/third_party/rapidjson", + "//flutter/third_party/spring_animation", + "//flutter/third_party/tonic", + "//flutter/txt", + ] + public_configs = [ + ":ios_gpu_configuration_config", + "//flutter:config", + ] +} + +shared_library("create_flutter_framework_dylib") { + visibility = [ ":*" ] + + output_name = "Flutter" + + ldflags = [ "-Wl,-install_name,@rpath/Flutter.framework/Flutter" ] + + public = _flutter_framework_headers + + deps = [ ":flutter_framework_source" ] + + public_configs = [ "//flutter:config" ] + configs += [ "//build/config/ios:ios_application_extension" ] +} + +copy("copy_dylib") { + visibility = [ ":*" ] + + sources = [ "$root_out_dir/libFlutter.dylib" ] + outputs = [ "$_flutter_framework_dir/Flutter" ] + + deps = [ ":create_flutter_framework_dylib" ] +} + +copy("copy_asan_runtime_dylib") { + visibility = [ ":*" ] + + _libclang_base_path = + "$buildtools_path/mac-x64/clang/lib/clang/13.0.0/lib/darwin/" + + if (defined(use_ios_simulator) && use_ios_simulator) { + _dylib_name = "libclang_rt.asan_iossim_dynamic.dylib" + } else { + _dylib_name = "libclang_rt.asan_ios_dynamic.dylib" + } + + sources = [ "$_libclang_base_path/$_dylib_name" ] + outputs = [ "$root_out_dir/$_dylib_name" ] + + deps = [ ":create_flutter_framework_dylib" ] +} + +action("copy_framework_info_plist") { + script = "//flutter/build/copy_info_plist.py" + visibility = [ ":*" ] + sources = [ "framework/Info.plist" ] + outputs = [ "$_flutter_framework_dir/Info.plist" ] + args = [ + "--source", + rebase_path(sources[0]), + "--destination", + rebase_path(outputs[0]), + "--minversion", + ios_deployment_target, + ] +} + +copy("copy_framework_module_map") { + visibility = [ ":*" ] + sources = [ "framework/module.modulemap" ] + outputs = [ "$_flutter_framework_dir/Modules/module.modulemap" ] +} + +# Copy privacy manifest. This file is required by Apple for third-party SDKs, +# and documents engine and third_party usage of timestamps and boot time APIs. +# See https://developer.apple.com/documentation/bundleresources/privacy_manifest_files +copy("copy_framework_privacy_manifest") { + visibility = [ ":*" ] + sources = [ "framework/PrivacyInfo.xcprivacy" ] + outputs = [ "$_flutter_framework_dir/PrivacyInfo.xcprivacy" ] +} + +action("copy_framework_headers") { + script = "//flutter/sky/tools/install_framework_headers.py" + visibility = [ ":*" ] + sources = get_path_info(_flutter_framework_headers, "abspath") + + framework_common_headers + outputs = [] + foreach(header, sources) { + header_basename = get_path_info(header, "file") + outputs += [ "$_flutter_framework_headers_copy_dir/$header_basename" ] + } + args = [ + "--location", + rebase_path("$_flutter_framework_headers_copy_dir"), + "--headers", + ] + rebase_path(sources, "", "//") +} + +copy("copy_framework_icu") { + visibility = [ ":*" ] + sources = [ "//flutter/third_party/icu/flutter/icudtl.dat" ] + outputs = [ "$_flutter_framework_dir/{{source_file_part}}" ] +} + +copy("copy_license") { + visibility = [ ":*" ] + sources = [ "//LICENSE" ] + outputs = [ "$root_out_dir/LICENSE" ] +} + +shared_library("copy_and_verify_framework_module") { + framework_search_path = rebase_path("$root_out_dir") + visibility = [ ":*" ] + cflags_objc = [ "-F$framework_search_path" ] + ldflags = [ + "-F$framework_search_path", + "-Xlinker", + "-fatal_warnings", + ] + + sources = [ "framework/Source/FlutterUmbrellaImport.m" ] + deps = [ + ":copy_framework_headers", + ":copy_framework_info_plist", + ":copy_framework_module_map", + ":copy_framework_privacy_manifest", + ] + + configs += [ "//build/config/ios:ios_application_extension" ] +} + +group("universal_flutter_framework") { + visibility = [ ":*" ] + deps = [ + ":copy_and_verify_framework_module", + ":copy_dylib", + ":copy_framework_icu", + ":copy_framework_info_plist", + ":copy_framework_module_map", + ":copy_framework_privacy_manifest", + ":copy_license", + ] + + if (is_asan) { + deps += [ ":copy_asan_runtime_dylib" ] + } +} + +action("flutter_framework") { + script = "//flutter/sky/tools/create_xcframework.py" + outputs = [ "$root_out_dir/Flutter.xcframework" ] + args = [ + "--frameworks", + rebase_path("$_flutter_framework_dir"), + "--name", + "Flutter", + "--location", + rebase_path("$root_out_dir"), + ] + + deps = [ ":universal_flutter_framework" ] +} diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/flutter_task_queue_dispatch.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/flutter_task_queue_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..18e476469879501ce61a8abcd96e35153d440f05 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/flutter_task_queue_dispatch.h @@ -0,0 +1,20 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FLUTTER_TASK_QUEUE_DISPATCH_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FLUTTER_TASK_QUEUE_DISPATCH_H_ + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h" + +/// The private implementation of `FlutterTaskQueue` that has method +/// declarations. +/// +/// `FlutterTaskQueue` doesn't have any methods publicly since it is supposed to +/// be an opaque data structure. For Swift integration though `FlutterTaskQueue` +/// is visible publicly with no methods. +@protocol FlutterTaskQueueDispatch +- (void)dispatch:(dispatch_block_t)block; +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FLUTTER_TASK_QUEUE_DISPATCH_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/Flutter.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/Flutter.h new file mode 100644 index 0000000000000000000000000000000000000000..705dfcb028d2afe17b404c3d63d57c4e52ae3217 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/Flutter.h @@ -0,0 +1,24 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTER_H_ + +#import "FlutterAppDelegate.h" +#import "FlutterBinaryMessenger.h" +#import "FlutterCallbackCache.h" +#import "FlutterChannels.h" +#import "FlutterCodecs.h" +#import "FlutterDartProject.h" +#import "FlutterEngine.h" +#import "FlutterEngineGroup.h" +#import "FlutterHeadlessDartRunner.h" +#import "FlutterMacros.h" +#import "FlutterPlatformViews.h" +#import "FlutterPlugin.h" +#import "FlutterPluginAppLifeCycleDelegate.h" +#import "FlutterTexture.h" +#import "FlutterViewController.h" + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterAppDelegate.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterAppDelegate.h new file mode 100644 index 0000000000000000000000000000000000000000..0c427c247d437d8097c11c2440e151fe12a20686 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterAppDelegate.h @@ -0,0 +1,34 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERAPPDELEGATE_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERAPPDELEGATE_H_ + +#import + +#import "FlutterMacros.h" +#import "FlutterPlugin.h" + +/** + * `UIApplicationDelegate` subclass for simple apps that want default behavior. + * + * This class implements the following behaviors: + * * Status bar touches are forwarded to the key window's root view + * `FlutterViewController`, in order to trigger scroll to top. + * * Keeps the Flutter connection open in debug mode when the phone screen + * locks. + * + * App delegates for Flutter applications are *not* required to inherit from + * this class. Developers of custom app delegate classes should copy and paste + * code as necessary from FlutterAppDelegate.mm. + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterAppDelegate + : UIResponder + +@property(strong, nonatomic) UIWindow* window; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERAPPDELEGATE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterCallbackCache.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterCallbackCache.h new file mode 100644 index 0000000000000000000000000000000000000000..b6e331d445b6a629ccefeb2ccc1923a3df9c12ab --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterCallbackCache.h @@ -0,0 +1,54 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERCALLBACKCACHE_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERCALLBACKCACHE_H_ + +#import + +#import "FlutterMacros.h" + +/** + * An object containing the result of `FlutterCallbackCache`'s `lookupCallbackInformation` + * method. + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterCallbackInformation : NSObject +/** + * The name of the callback. + */ +@property(copy) NSString* callbackName; +/** + * The class name of the callback. + */ +@property(copy) NSString* callbackClassName; +/** + * The library path of the callback. + */ +@property(copy) NSString* callbackLibraryPath; +@end + +/** + * The cache containing callback information for spawning a + * `FlutterHeadlessDartRunner`. + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterCallbackCache : NSObject +/** + * Returns the callback information for the given callback handle. + * This callback information can be used when spawning a + * `FlutterHeadlessDartRunner`. + * + * @param handle The handle for a callback, provided by the + * Dart method `PluginUtilities.getCallbackHandle`. + * @return A `FlutterCallbackInformation` object which contains the name of the + * callback, the name of the class in which the callback is defined, and the + * path of the library which contains the callback. If the provided handle is + * invalid, nil is returned. + */ ++ (FlutterCallbackInformation*)lookupCallbackInformation:(int64_t)handle; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERCALLBACKCACHE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterEngine.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterEngine.h new file mode 100644 index 0000000000000000000000000000000000000000..931c8de7b09d90c63840c1d89bc919405e6e581e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterEngine.h @@ -0,0 +1,462 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERENGINE_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERENGINE_H_ + +#import +#import + +#import "FlutterBinaryMessenger.h" +#import "FlutterDartProject.h" +#import "FlutterMacros.h" +#import "FlutterPlugin.h" +#import "FlutterTexture.h" + +@class FlutterViewController; + +NS_ASSUME_NONNULL_BEGIN + +/** + * The dart entrypoint that is associated with `main()`. This is to be used as an argument to the + * `runWithEntrypoint*` methods. + */ +// NOLINTNEXTLINE(readability-identifier-naming) +extern NSString* const FlutterDefaultDartEntrypoint; + +/** + * The default Flutter initial route ("/"). + */ +// NOLINTNEXTLINE(readability-identifier-naming) +extern NSString* const FlutterDefaultInitialRoute; + +/** + * The FlutterEngine class coordinates a single instance of execution for a + * `FlutterDartProject`. It may have zero or one `FlutterViewController` at a + * time, which can be specified via `-setViewController:`. + * `FlutterViewController`'s `initWithEngine` initializer will automatically call + * `-setViewController:` for itself. + * + * A FlutterEngine can be created independently of a `FlutterViewController` for + * headless execution. It can also persist across the lifespan of multiple + * `FlutterViewController` instances to maintain state and/or asynchronous tasks + * (such as downloading a large file). + * + * A FlutterEngine can also be used to prewarm the Dart execution environment and reduce the + * latency of showing the Flutter screen when a `FlutterViewController` is created and presented. + * See http://flutter.dev/docs/development/add-to-app/performance for more details on loading + * performance. + * + * Alternatively, you can simply create a new `FlutterViewController` with only a + * `FlutterDartProject`. That `FlutterViewController` will internally manage its + * own instance of a FlutterEngine, but will not guarantee survival of the engine + * beyond the life of the ViewController. + * + * A newly initialized FlutterEngine will not actually run a Dart Isolate until + * either `-runWithEntrypoint:` or `-runWithEntrypoint:libraryURI` is invoked. + * One of these methods must be invoked before calling `-setViewController:`. + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterEngine : NSObject + +/** + * Default initializer for a FlutterEngine. + * + * Threads created by this FlutterEngine will appear as "FlutterEngine #" in + * Instruments. The prefix can be customized using `initWithName`. + * + * The engine will execute the project located in the bundle with the identifier + * "io.flutter.flutter.app" (the default for Flutter projects). + * + * A newly initialized engine will not run until either `-runWithEntrypoint:` or + * `-runWithEntrypoint:libraryURI:` is called. + * + * FlutterEngine created with this method will have allowHeadlessExecution set to `YES`. + * This means that the engine will continue to run regardless of whether a `FlutterViewController` + * is attached to it or not, until `-destroyContext:` is called or the process finishes. + */ +- (instancetype)init; + +/** + * Initialize this FlutterEngine. + * + * The engine will execute the project located in the bundle with the identifier + * "io.flutter.flutter.app" (the default for Flutter projects). + * + * A newly initialized engine will not run until either `-runWithEntrypoint:` or + * `-runWithEntrypoint:libraryURI:` is called. + * + * FlutterEngine created with this method will have allowHeadlessExecution set to `YES`. + * This means that the engine will continue to run regardless of whether a `FlutterViewController` + * is attached to it or not, until `-destroyContext:` is called or the process finishes. + * + * @param labelPrefix The label prefix used to identify threads for this instance. Should + * be unique across FlutterEngine instances, and is used in instrumentation to label + * the threads used by this FlutterEngine. + */ +- (instancetype)initWithName:(NSString*)labelPrefix; + +/** + * Initialize this FlutterEngine with a `FlutterDartProject`. + * + * If the FlutterDartProject is not specified, the FlutterEngine will attempt to locate + * the project in a default location (the flutter_assets folder in the iOS application + * bundle). + * + * A newly initialized engine will not run the `FlutterDartProject` until either + * `-runWithEntrypoint:` or `-runWithEntrypoint:libraryURI:` is called. + * + * FlutterEngine created with this method will have allowHeadlessExecution set to `YES`. + * This means that the engine will continue to run regardless of whether a `FlutterViewController` + * is attached to it or not, until `-destroyContext:` is called or the process finishes. + * + * @param labelPrefix The label prefix used to identify threads for this instance. Should + * be unique across FlutterEngine instances, and is used in instrumentation to label + * the threads used by this FlutterEngine. + * @param project The `FlutterDartProject` to run. + */ +- (instancetype)initWithName:(NSString*)labelPrefix project:(nullable FlutterDartProject*)project; + +/** + * Initialize this FlutterEngine with a `FlutterDartProject`. + * + * If the FlutterDartProject is not specified, the FlutterEngine will attempt to locate + * the project in a default location (the flutter_assets folder in the iOS application + * bundle). + * + * A newly initialized engine will not run the `FlutterDartProject` until either + * `-runWithEntrypoint:` or `-runWithEntrypoint:libraryURI:` is called. + * + * @param labelPrefix The label prefix used to identify threads for this instance. Should + * be unique across FlutterEngine instances, and is used in instrumentation to label + * the threads used by this FlutterEngine. + * @param project The `FlutterDartProject` to run. + * @param allowHeadlessExecution Whether or not to allow this instance to continue + * running after passing a nil `FlutterViewController` to `-setViewController:`. + */ +- (instancetype)initWithName:(NSString*)labelPrefix + project:(nullable FlutterDartProject*)project + allowHeadlessExecution:(BOOL)allowHeadlessExecution; + +/** + * Initialize this FlutterEngine with a `FlutterDartProject`. + * + * If the FlutterDartProject is not specified, the FlutterEngine will attempt to locate + * the project in a default location (the flutter_assets folder in the iOS application + * bundle). + * + * A newly initialized engine will not run the `FlutterDartProject` until either + * `-runWithEntrypoint:` or `-runWithEntrypoint:libraryURI:` is called. + * + * @param labelPrefix The label prefix used to identify threads for this instance. Should + * be unique across FlutterEngine instances, and is used in instrumentation to label + * the threads used by this FlutterEngine. + * @param project The `FlutterDartProject` to run. + * @param allowHeadlessExecution Whether or not to allow this instance to continue + * running after passing a nil `FlutterViewController` to `-setViewController:`. + * @param restorationEnabled Whether state restoration is enabled. When true, the framework will + * wait for the attached view controller to provide restoration data. + */ +- (instancetype)initWithName:(NSString*)labelPrefix + project:(nullable FlutterDartProject*)project + allowHeadlessExecution:(BOOL)allowHeadlessExecution + restorationEnabled:(BOOL)restorationEnabled NS_DESIGNATED_INITIALIZER; + +/** + * Runs a Dart program on an Isolate from the main Dart library (i.e. the library that + * contains `main()`), using `main()` as the entrypoint (the default for Flutter projects), + * and using "/" (the default route) as the initial route. + * + * The first call to this method will create a new Isolate. Subsequent calls will return + * immediately and have no effect. + * + * @return YES if the call succeeds in creating and running a Flutter Engine instance; NO otherwise. + */ +- (BOOL)run; + +/** + * Runs a Dart program on an Isolate from the main Dart library (i.e. the library that + * contains `main()`), using "/" (the default route) as the initial route. + * + * The first call to this method will create a new Isolate. Subsequent calls will return + * immediately and have no effect. + * + * @param entrypoint The name of a top-level function from the same Dart + * library that contains the app's main() function. If this is FlutterDefaultDartEntrypoint (or + * nil) it will default to `main()`. If it is not the app's main() function, that function must + * be decorated with `@pragma(vm:entry-point)` to ensure the method is not tree-shaken by the Dart + * compiler. + * @return YES if the call succeeds in creating and running a Flutter Engine instance; NO otherwise. + */ +- (BOOL)runWithEntrypoint:(nullable NSString*)entrypoint; + +/** + * Runs a Dart program on an Isolate from the main Dart library (i.e. the library that + * contains `main()`). + * + * The first call to this method will create a new Isolate. Subsequent calls will return + * immediately and have no effect. + * + * @param entrypoint The name of a top-level function from the same Dart + * library that contains the app's main() function. If this is FlutterDefaultDartEntrypoint (or + * nil), it will default to `main()`. If it is not the app's main() function, that function must + * be decorated with `@pragma(vm:entry-point)` to ensure the method is not tree-shaken by the Dart + * compiler. + * @param initialRoute The name of the initial Flutter `Navigator` `Route` to load. If this is + * FlutterDefaultInitialRoute (or nil), it will default to the "/" route. + * @return YES if the call succeeds in creating and running a Flutter Engine instance; NO otherwise. + */ +- (BOOL)runWithEntrypoint:(nullable NSString*)entrypoint + initialRoute:(nullable NSString*)initialRoute; + +/** + * Runs a Dart program on an Isolate using the specified entrypoint and Dart library, + * which may not be the same as the library containing the Dart program's `main()` function. + * + * The first call to this method will create a new Isolate. Subsequent calls will return + * immediately and have no effect. + * + * @param entrypoint The name of a top-level function from a Dart library. If this is + * FlutterDefaultDartEntrypoint (or nil); this will default to `main()`. If it is not the app's + * main() function, that function must be decorated with `@pragma(vm:entry-point)` to ensure the + * method is not tree-shaken by the Dart compiler. + * @param uri The URI of the Dart library which contains the entrypoint method + * (example "package:foo_package/main.dart"). If nil, this will default to + * the same library as the `main()` function in the Dart program. + * @return YES if the call succeeds in creating and running a Flutter Engine instance; NO otherwise. + */ +- (BOOL)runWithEntrypoint:(nullable NSString*)entrypoint libraryURI:(nullable NSString*)uri; + +/** + * Runs a Dart program on an Isolate using the specified entrypoint and Dart library, + * which may not be the same as the library containing the Dart program's `main()` function. + * + * The first call to this method will create a new Isolate. Subsequent calls will return + * immediately and have no effect. + * + * @param entrypoint The name of a top-level function from a Dart library. If this is + * FlutterDefaultDartEntrypoint (or nil); this will default to `main()`. If it is not the app's + * main() function, that function must be decorated with `@pragma(vm:entry-point)` to ensure the + * method is not tree-shaken by the Dart compiler. + * @param libraryURI The URI of the Dart library which contains the entrypoint + * method (example "package:foo_package/main.dart"). If nil, this will + * default to the same library as the `main()` function in the Dart program. + * @param initialRoute The name of the initial Flutter `Navigator` `Route` to load. If this is + * FlutterDefaultInitialRoute (or nil), it will default to the "/" route. + * @return YES if the call succeeds in creating and running a Flutter Engine instance; NO otherwise. + */ +- (BOOL)runWithEntrypoint:(nullable NSString*)entrypoint + libraryURI:(nullable NSString*)libraryURI + initialRoute:(nullable NSString*)initialRoute; + +/** + * Runs a Dart program on an Isolate using the specified entrypoint and Dart library, + * which may not be the same as the library containing the Dart program's `main()` function. + * + * The first call to this method will create a new Isolate. Subsequent calls will return + * immediately and have no effect. + * + * @param entrypoint The name of a top-level function from a Dart library. If this is + * FlutterDefaultDartEntrypoint (or nil); this will default to `main()`. If it is not the app's + * main() function, that function must be decorated with `@pragma(vm:entry-point)` to ensure the + * method is not tree-shaken by the Dart compiler. + * @param libraryURI The URI of the Dart library which contains the entrypoint + * method (example "package:foo_package/main.dart"). If nil, this will + * default to the same library as the `main()` function in the Dart program. + * @param initialRoute The name of the initial Flutter `Navigator` `Route` to load. If this is + * FlutterDefaultInitialRoute (or nil), it will default to the "/" route. + * @param entrypointArgs Arguments passed as a list of string to Dart's entrypoint function. + * @return YES if the call succeeds in creating and running a Flutter Engine instance; NO otherwise. + */ +- (BOOL)runWithEntrypoint:(nullable NSString*)entrypoint + libraryURI:(nullable NSString*)libraryURI + initialRoute:(nullable NSString*)initialRoute + entrypointArgs:(nullable NSArray*)entrypointArgs; + +/** + * Destroy running context for an engine. + * + * This method can be used to force the FlutterEngine object to release all resources. + * After sending this message, the object will be in an unusable state until it is deallocated. + * Accessing properties or sending messages to it will result in undefined behavior or runtime + * errors. + */ +- (void)destroyContext; + +/** + * Ensures that Flutter will generate a semantics tree. + * + * This is enabled by default if certain accessibility services are turned on by + * the user, or when using a Simulator. This method allows a user to turn + * semantics on when they would not ordinarily be generated and the performance + * overhead is not a concern, e.g. for UI testing. Note that semantics should + * never be programmatically turned off, as it would potentially disable + * accessibility services an end user has requested. + * + * This method must only be called after launching the engine via + * `-runWithEntrypoint:` or `-runWithEntryPoint:libraryURI`. + * + * Although this method returns synchronously, it does not guarantee that a + * semantics tree is actually available when the method returns. It + * synchronously ensures that the next frame the Flutter framework creates will + * have a semantics tree. + * + * You can subscribe to semantics updates via `NSNotificationCenter` by adding + * an observer for the name `FlutterSemanticsUpdateNotification`. The `object` + * parameter will be the `FlutterViewController` associated with the semantics + * update. This will asynchronously fire after a semantics tree has actually + * built (which may be some time after the frame has been rendered). + */ +- (void)ensureSemanticsEnabled; + +/** + * Sets the `FlutterViewController` for this instance. The FlutterEngine must be + * running (e.g. a successful call to `-runWithEntrypoint:` or `-runWithEntrypoint:libraryURI`) + * before calling this method. Callers may pass nil to remove the viewController + * and have the engine run headless in the current process. + * + * A FlutterEngine can only have one `FlutterViewController` at a time. If there is + * already a `FlutterViewController` associated with this instance, this method will replace + * the engine's current viewController with the newly specified one. + * + * Setting the viewController will signal the engine to start animations and drawing, and unsetting + * it will signal the engine to stop animations and drawing. However, neither will impact the state + * of the Dart program's execution. + */ +@property(nonatomic, weak) FlutterViewController* viewController; + +/** + * The `FlutterMethodChannel` used for localization related platform messages, such as + * setting the locale. + * + * Can be nil after `destroyContext` is called. + */ +@property(nonatomic, readonly, nullable) FlutterMethodChannel* localizationChannel; +/** + * The `FlutterMethodChannel` used for navigation related platform messages. + * + * Can be nil after `destroyContext` is called. + * + * @see [Navigation + * Channel](https://api.flutter.dev/flutter/services/SystemChannels/navigation-constant.html) + * @see [Navigator Widget](https://api.flutter.dev/flutter/widgets/Navigator-class.html) + */ +@property(nonatomic, readonly) FlutterMethodChannel* navigationChannel; + +/** + * The `FlutterMethodChannel` used for restoration related platform messages. + * + * Can be nil after `destroyContext` is called. + * + * @see [Restoration + * Channel](https://api.flutter.dev/flutter/services/SystemChannels/restoration-constant.html) + */ +@property(nonatomic, readonly) FlutterMethodChannel* restorationChannel; + +/** + * The `FlutterMethodChannel` used for core platform messages, such as + * information about the screen orientation. + * + * Can be nil after `destroyContext` is called. + */ +@property(nonatomic, readonly) FlutterMethodChannel* platformChannel; + +/** + * The `FlutterMethodChannel` used to communicate text input events to the + * Dart Isolate. + * + * Can be nil after `destroyContext` is called. + * + * @see [Text Input + * Channel](https://api.flutter.dev/flutter/services/SystemChannels/textInput-constant.html) + */ +@property(nonatomic, readonly) FlutterMethodChannel* textInputChannel; + +/** + * The `FlutterBasicMessageChannel` used to communicate app lifecycle events + * to the Dart Isolate. + * + * Can be nil after `destroyContext` is called. + * + * @see [Lifecycle + * Channel](https://api.flutter.dev/flutter/services/SystemChannels/lifecycle-constant.html) + */ +@property(nonatomic, readonly) FlutterBasicMessageChannel* lifecycleChannel; + +/** + * The `FlutterBasicMessageChannel` used for communicating system events, such as + * memory pressure events. + * + * Can be nil after `destroyContext` is called. + * + * @see [System + * Channel](https://api.flutter.dev/flutter/services/SystemChannels/system-constant.html) + */ +@property(nonatomic, readonly) FlutterBasicMessageChannel* systemChannel; + +/** + * The `FlutterBasicMessageChannel` used for communicating user settings such as + * clock format and text scale. + * + * Can be nil after `destroyContext` is called. + */ +@property(nonatomic, readonly) FlutterBasicMessageChannel* settingsChannel; + +/** + * The `FlutterBasicMessageChannel` used for communicating key events + * from physical keyboards + * + * Can be nil after `destroyContext` is called. + */ +@property(nonatomic, readonly) FlutterBasicMessageChannel* keyEventChannel; + +/** + * The depcreated `NSURL` of the Dart VM Service for the service isolate. + * + * This is only set in debug and profile runtime modes, and only after the + * Dart VM Service is ready. In release mode or before the Dart VM Service has + * started, it returns `nil`. + */ +@property(nonatomic, readonly, nullable) + NSURL* observatoryUrl FLUTTER_DEPRECATED("Use vmServiceUrl instead"); + +/** + * The `NSURL` of the Dart VM Service for the service isolate. + * + * This is only set in debug and profile runtime modes, and only after the + * Dart VM Service is ready. In release mode or before the Dart VM Service has + * started, it returns `nil`. + */ +@property(nonatomic, readonly, nullable) NSURL* vmServiceUrl; + +/** + * The `FlutterBinaryMessenger` associated with this FlutterEngine (used for communicating with + * channels). + */ +@property(nonatomic, readonly) NSObject* binaryMessenger; + +/** + * The `FlutterTextureRegistry` associated with this FlutterEngine (used to register textures). + */ +@property(nonatomic, readonly) NSObject* textureRegistry; + +/** + * The UI Isolate ID of the engine. + * + * This property will be nil if the engine is not running. + */ +@property(nonatomic, readonly, copy, nullable) NSString* isolateId; + +/** + * Whether or not GPU calls are allowed. + * + * Typically this is set when the app is backgrounded and foregrounded. + */ +@property(nonatomic, assign) BOOL isGpuDisabled; + +@end + +NS_ASSUME_NONNULL_END + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERENGINE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterEngineGroup.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterEngineGroup.h new file mode 100644 index 0000000000000000000000000000000000000000..47cdc07537fe7c19f0b136df2fc07e1c21a5d5c3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterEngineGroup.h @@ -0,0 +1,115 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERENGINEGROUP_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERENGINEGROUP_H_ + +#import + +#import "FlutterEngine.h" + +NS_ASSUME_NONNULL_BEGIN + +/** Options that control how a FlutterEngine should be created. */ +FLUTTER_DARWIN_EXPORT +@interface FlutterEngineGroupOptions : NSObject + +/** + * The name of a top-level function from a Dart library. If this is FlutterDefaultDartEntrypoint + * (or nil); this will default to `main()`. If it is not the app's main() function, that function + * must be decorated with `@pragma(vm:entry-point)` to ensure themethod is not tree-shaken by the + * Dart compiler. + */ +@property(nonatomic, copy, nullable) NSString* entrypoint; + +/** + * The URI of the Dart library which contains the entrypoint method. If nil, this will default to + * the same library as the `main()` function in the Dart program. + */ +@property(nonatomic, copy, nullable) NSString* libraryURI; + +/** + * The name of the initial Flutter `Navigator` `Route` to load. If this is + * FlutterDefaultInitialRoute (or nil), it will default to the "/" route. + */ +@property(nonatomic, copy, nullable) NSString* initialRoute; + +/** + * Arguments passed as a list of string to Dart's entrypoint function. + */ +@property(nonatomic, copy, nullable) NSArray* entrypointArgs; +@end + +/** + * Represents a collection of FlutterEngines who share resources which allows + * them to be created with less time const and occupy less memory than just + * creating multiple FlutterEngines. + * + * Deleting a FlutterEngineGroup doesn't invalidate existing FlutterEngines, but + * it eliminates the possibility to create more FlutterEngines in that group. + * + * @warning This class is a work-in-progress and may change. + * @see https://github.com/flutter/flutter/issues/72009 + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterEngineGroup : NSObject +- (instancetype)init NS_UNAVAILABLE; + +/** + * Initialize a new FlutterEngineGroup. + * + * @param name The name that will present in the threads shared across the + * engines in this group. + * @param project The `FlutterDartProject` that all FlutterEngines in this group + * will be executing. + */ +- (instancetype)initWithName:(NSString*)name + project:(nullable FlutterDartProject*)project NS_DESIGNATED_INITIALIZER; + +/** + * Creates a running `FlutterEngine` that shares components with this group. + * + * @param entrypoint The name of a top-level function from a Dart library. If this is + * FlutterDefaultDartEntrypoint (or nil); this will default to `main()`. If it is not the app's + * main() function, that function must be decorated with `@pragma(vm:entry-point)` to ensure the + * method is not tree-shaken by the Dart compiler. + * @param libraryURI The URI of the Dart library which contains the entrypoint method. IF nil, + * this will default to the same library as the `main()` function in the Dart program. + * + * @see FlutterEngineGroup + */ +- (FlutterEngine*)makeEngineWithEntrypoint:(nullable NSString*)entrypoint + libraryURI:(nullable NSString*)libraryURI; + +/** + * Creates a running `FlutterEngine` that shares components with this group. + * + * @param entrypoint The name of a top-level function from a Dart library. If this is + * FlutterDefaultDartEntrypoint (or nil); this will default to `main()`. If it is not the app's + * main() function, that function must be decorated with `@pragma(vm:entry-point)` to ensure the + * method is not tree-shaken by the Dart compiler. + * @param libraryURI The URI of the Dart library which contains the entrypoint method. IF nil, + * this will default to the same library as the `main()` function in the Dart program. + * @param initialRoute The name of the initial Flutter `Navigator` `Route` to load. If this is + * FlutterDefaultInitialRoute (or nil), it will default to the "/" route. + * + * @see FlutterEngineGroup + */ +- (FlutterEngine*)makeEngineWithEntrypoint:(nullable NSString*)entrypoint + libraryURI:(nullable NSString*)libraryURI + initialRoute:(nullable NSString*)initialRoute; + +/** + * Creates a running `FlutterEngine` that shares components with this group. + * + * @param options Options that control how a FlutterEngine should be created. + * + * @see FlutterEngineGroupOptions + */ +- (FlutterEngine*)makeEngineWithOptions:(nullable FlutterEngineGroupOptions*)options; +@end + +NS_ASSUME_NONNULL_END + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERENGINEGROUP_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterHeadlessDartRunner.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterHeadlessDartRunner.h new file mode 100644 index 0000000000000000000000000000000000000000..08069ab5b86088d2d3ab42afcd761c44960fa3d9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterHeadlessDartRunner.h @@ -0,0 +1,97 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERHEADLESSDARTRUNNER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERHEADLESSDARTRUNNER_H_ + +#import + +#import "FlutterBinaryMessenger.h" +#import "FlutterDartProject.h" +#import "FlutterEngine.h" +#import "FlutterMacros.h" + +/** + * A callback for when FlutterHeadlessDartRunner has attempted to start a Dart + * Isolate in the background. + * + * @param success YES if the Isolate was started and run successfully, NO + * otherwise. + */ +typedef void (^FlutterHeadlessDartRunnerCallback)(BOOL success); + +/** + * The deprecated FlutterHeadlessDartRunner runs Flutter Dart code with a null rasterizer, + * and no native drawing surface. It is appropriate for use in running Dart + * code e.g. in the background from a plugin. + * + * Most callers should prefer using `FlutterEngine` directly; this interface exists + * for legacy support. + */ +FLUTTER_DARWIN_EXPORT +FLUTTER_DEPRECATED("FlutterEngine should be used rather than FlutterHeadlessDartRunner") +@interface FlutterHeadlessDartRunner : FlutterEngine + +/** + * Initialize this FlutterHeadlessDartRunner with a `FlutterDartProject`. + * + * If the FlutterDartProject is not specified, the FlutterHeadlessDartRunner will attempt to locate + * the project in a default location. + * + * A newly initialized engine will not run the `FlutterDartProject` until either + * `-runWithEntrypoint:` or `-runWithEntrypoint:libraryURI` is called. + * + * @param labelPrefix The label prefix used to identify threads for this instance. Should + * be unique across FlutterEngine instances + * @param projectOrNil The `FlutterDartProject` to run. + */ +- (instancetype)initWithName:(NSString*)labelPrefix project:(FlutterDartProject*)projectOrNil; + +/** + * Initialize this FlutterHeadlessDartRunner with a `FlutterDartProject`. + * + * If the FlutterDartProject is not specified, the FlutterHeadlessDartRunner will attempt to locate + * the project in a default location. + * + * A newly initialized engine will not run the `FlutterDartProject` until either + * `-runWithEntrypoint:` or `-runWithEntrypoint:libraryURI` is called. + * + * @param labelPrefix The label prefix used to identify threads for this instance. Should + * be unique across FlutterEngine instances + * @param projectOrNil The `FlutterDartProject` to run. + * @param allowHeadlessExecution Must be set to `YES`. + */ +- (instancetype)initWithName:(NSString*)labelPrefix + project:(FlutterDartProject*)projectOrNil + allowHeadlessExecution:(BOOL)allowHeadlessExecution; + +/** + * Initialize this FlutterHeadlessDartRunner with a `FlutterDartProject`. + * + * If the FlutterDartProject is not specified, the FlutterHeadlessDartRunner will attempt to locate + * the project in a default location. + * + * A newly initialized engine will not run the `FlutterDartProject` until either + * `-runWithEntrypoint:` or `-runWithEntrypoint:libraryURI` is called. + * + * @param labelPrefix The label prefix used to identify threads for this instance. Should + * be unique across FlutterEngine instances + * @param projectOrNil The `FlutterDartProject` to run. + * @param allowHeadlessExecution Must be set to `YES`. + * @param restorationEnabled Must be set to `NO`. + */ +- (instancetype)initWithName:(NSString*)labelPrefix + project:(FlutterDartProject*)projectOrNil + allowHeadlessExecution:(BOOL)allowHeadlessExecution + restorationEnabled:(BOOL)restorationEnabled NS_DESIGNATED_INITIALIZER; + +/** + * Not recommended for use - will initialize with a default label ("io.flutter.headless") + * and the default FlutterDartProject. + */ +- (instancetype)init; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERHEADLESSDARTRUNNER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterPlatformViews.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterPlatformViews.h new file mode 100644 index 0000000000000000000000000000000000000000..59ba4af616c1c9646645b63944e089f6e89f1e8e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterPlatformViews.h @@ -0,0 +1,56 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERPLATFORMVIEWS_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERPLATFORMVIEWS_H_ + +#import + +#import "FlutterCodecs.h" +#import "FlutterMacros.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * Wraps a `UIView` for embedding in the Flutter hierarchy + */ +@protocol FlutterPlatformView +/** + * Returns a reference to the `UIView` that is wrapped by this `FlutterPlatformView`. + */ +- (UIView*)view; +@end + +FLUTTER_DARWIN_EXPORT +@protocol FlutterPlatformViewFactory +/** + * Create a `FlutterPlatformView`. + * + * Implemented by iOS code that expose a `UIView` for embedding in a Flutter app. + * + * The implementation of this method should create a new `UIView` and return it. + * + * @param frame The rectangle for the newly created `UIView` measured in points. + * @param viewId A unique identifier for this `UIView`. + * @param args Parameters for creating the `UIView` sent from the Dart side of the Flutter app. + * If `createArgsCodec` is not implemented, or if no creation arguments were sent from the Dart + * code, this will be null. Otherwise this will be the value sent from the Dart code as decoded by + * `createArgsCodec`. + */ +- (NSObject*)createWithFrame:(CGRect)frame + viewIdentifier:(int64_t)viewId + arguments:(id _Nullable)args; + +/** + * Returns the `FlutterMessageCodec` for decoding the args parameter of `createWithFrame`. + * + * Only needs to be implemented if `createWithFrame` needs an arguments parameter. + */ +@optional +- (NSObject*)createArgsCodec; +@end + +NS_ASSUME_NONNULL_END + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERPLATFORMVIEWS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterPlugin.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterPlugin.h new file mode 100644 index 0000000000000000000000000000000000000000..8ab46cfe80ac9d30337c72a7f6426e7cd4934da4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterPlugin.h @@ -0,0 +1,448 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERPLUGIN_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERPLUGIN_H_ + +#import +#import + +#import "FlutterBinaryMessenger.h" +#import "FlutterChannels.h" +#import "FlutterCodecs.h" +#import "FlutterPlatformViews.h" +#import "FlutterTexture.h" + +NS_ASSUME_NONNULL_BEGIN +@protocol FlutterPluginRegistrar; +@protocol FlutterPluginRegistry; + +#pragma mark - +/** + * Protocol for listener of events from the UIApplication, typically a FlutterPlugin. + */ +@protocol FlutterApplicationLifeCycleDelegate + +@optional +/** + * Called if this has been registered for `UIApplicationDelegate` callbacks. + * + * @return `NO` if this vetos application launch. + */ +- (BOOL)application:(UIApplication*)application + didFinishLaunchingWithOptions:(NSDictionary*)launchOptions; + +/** + * Called if this has been registered for `UIApplicationDelegate` callbacks. + * + * @return `NO` if this vetos application launch. + */ +- (BOOL)application:(UIApplication*)application + willFinishLaunchingWithOptions:(NSDictionary*)launchOptions; + +/** + * Called if this has been registered for `UIApplicationDelegate` callbacks. + */ +- (void)applicationDidBecomeActive:(UIApplication*)application; + +/** + * Called if this has been registered for `UIApplicationDelegate` callbacks. + */ +- (void)applicationWillResignActive:(UIApplication*)application; + +/** + * Called if this has been registered for `UIApplicationDelegate` callbacks. + */ +- (void)applicationDidEnterBackground:(UIApplication*)application; + +/** + * Called if this has been registered for `UIApplicationDelegate` callbacks. + */ +- (void)applicationWillEnterForeground:(UIApplication*)application; + +/** + Called if this has been registered for `UIApplicationDelegate` callbacks. + */ +- (void)applicationWillTerminate:(UIApplication*)application; + +/** + * Called if this has been registered for `UIApplicationDelegate` callbacks. + */ +- (void)application:(UIApplication*)application + didRegisterUserNotificationSettings:(UIUserNotificationSettings*)notificationSettings + API_DEPRECATED( + "See -[UIApplicationDelegate application:didRegisterUserNotificationSettings:] deprecation", + ios(8.0, 10.0)); + +/** + * Called if this has been registered for `UIApplicationDelegate` callbacks. + */ +- (void)application:(UIApplication*)application + didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken; + +/** + * Called if this has been registered for `UIApplicationDelegate` callbacks. + */ +- (void)application:(UIApplication*)application + didFailToRegisterForRemoteNotificationsWithError:(NSError*)error; + +/** + * Called if this has been registered for `UIApplicationDelegate` callbacks. + * + * @return `YES` if this handles the request. + */ +- (BOOL)application:(UIApplication*)application + didReceiveRemoteNotification:(NSDictionary*)userInfo + fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler; + +/** + * Calls all plugins registered for `UIApplicationDelegate` callbacks. + */ +- (void)application:(UIApplication*)application + didReceiveLocalNotification:(UILocalNotification*)notification + API_DEPRECATED( + "See -[UIApplicationDelegate application:didReceiveLocalNotification:] deprecation", + ios(4.0, 10.0)); + +/** + * Called if this has been registered for `UIApplicationDelegate` callbacks. + * + * @return `YES` if this handles the request. + */ +- (BOOL)application:(UIApplication*)application + openURL:(NSURL*)url + options:(NSDictionary*)options; + +/** + * Called if this has been registered for `UIApplicationDelegate` callbacks. + * + * @return `YES` if this handles the request. + */ +- (BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)url; + +/** + * Called if this has been registered for `UIApplicationDelegate` callbacks. + * + * @return `YES` if this handles the request. + */ +- (BOOL)application:(UIApplication*)application + openURL:(NSURL*)url + sourceApplication:(NSString*)sourceApplication + annotation:(id)annotation; + +/** + * Called if this has been registered for `UIApplicationDelegate` callbacks. + * + * @return `YES` if this handles the request. + */ +- (BOOL)application:(UIApplication*)application + performActionForShortcutItem:(UIApplicationShortcutItem*)shortcutItem + completionHandler:(void (^)(BOOL succeeded))completionHandler + API_AVAILABLE(ios(9.0)); + +/** + * Called if this has been registered for `UIApplicationDelegate` callbacks. + * + * @return `YES` if this handles the request. + */ +- (BOOL)application:(UIApplication*)application + handleEventsForBackgroundURLSession:(nonnull NSString*)identifier + completionHandler:(nonnull void (^)(void))completionHandler; + +/** + * Called if this has been registered for `UIApplicationDelegate` callbacks. + * + * @return `YES` if this handles the request. + */ +- (BOOL)application:(UIApplication*)application + performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler; + +/** + * Called if this has been registered for `UIApplicationDelegate` callbacks. + * + * @return `YES` if this handles the request. + */ +- (BOOL)application:(UIApplication*)application + continueUserActivity:(NSUserActivity*)userActivity + restorationHandler:(void (^)(NSArray*))restorationHandler; +@end + +#pragma mark - +/** + * A plugin registration callback. + * + * Used for registering plugins with additional instances of + * `FlutterPluginRegistry`. + * + * @param registry The registry to register plugins with. + */ +typedef void (*FlutterPluginRegistrantCallback)(NSObject* registry); + +#pragma mark - +/** + * Implemented by the iOS part of a Flutter plugin. + * + * Defines a set of optional callback methods and a method to set up the plugin + * and register it to be called by other application components. + */ +@protocol FlutterPlugin +@required +/** + * Registers this plugin using the context information and callback registration + * methods exposed by the given registrar. + * + * The registrar is obtained from a `FlutterPluginRegistry` which keeps track of + * the identity of registered plugins and provides basic support for cross-plugin + * coordination. + * + * The caller of this method, a plugin registrant, is usually autogenerated by + * Flutter tooling based on declared plugin dependencies. The generated registrant + * asks the registry for a registrar for each plugin, and calls this method to + * allow the plugin to initialize itself and register callbacks with application + * objects available through the registrar protocol. + * + * @param registrar A helper providing application context and methods for + * registering callbacks. + */ ++ (void)registerWithRegistrar:(NSObject*)registrar; +@optional +/** + * Set a callback for registering plugins to an additional `FlutterPluginRegistry`, + * including headless `FlutterEngine` instances. + * + * This method is typically called from within an application's `AppDelegate` at + * startup to allow for plugins which create additional `FlutterEngine` instances + * to register the application's plugins. + * + * @param callback A callback for registering some set of plugins with a + * `FlutterPluginRegistry`. + */ ++ (void)setPluginRegistrantCallback:(FlutterPluginRegistrantCallback)callback; +@optional +/** + * Called if this plugin has been registered to receive `FlutterMethodCall`s. + * + * @param call The method call command object. + * @param result A callback for submitting the result of the call. + */ +- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result; +@optional +/** + * Called when a plugin is being removed from a `FlutterEngine`, which is + * usually the result of the `FlutterEngine` being deallocated. This method + * provides the opportunity to do necessary cleanup. + * + * You will only receive this method if you registered your plugin instance with + * the `FlutterEngine` via `-[FlutterPluginRegistry publish:]`. + * + * @param registrar The registrar that was used to publish the plugin. + * + */ +- (void)detachFromEngineForRegistrar:(NSObject*)registrar; +@end + +#pragma mark - +/** + * How the UIGestureRecognizers of a platform view are blocked. + * + * UIGestureRecognizers of platform views can be blocked based on decisions made by the + * Flutter Framework (e.g. When an interact-able widget is covering the platform view). + */ +typedef enum { + // NOLINTBEGIN(readability-identifier-naming) + /** + * Flutter blocks all the UIGestureRecognizers on the platform view as soon as it + * decides they should be blocked. + * + * With this policy, only the `touchesBegan` method for all the UIGestureRecognizers is guaranteed + * to be called. + */ + FlutterPlatformViewGestureRecognizersBlockingPolicyEager, + /** + * Flutter blocks the platform view's UIGestureRecognizers from recognizing only after + * touchesEnded was invoked. + * + * This results in the platform view's UIGestureRecognizers seeing the entire touch sequence, + * but never recognizing the gesture (and never invoking actions). + */ + FlutterPlatformViewGestureRecognizersBlockingPolicyWaitUntilTouchesEnded, + // NOLINTEND(readability-identifier-naming) +} FlutterPlatformViewGestureRecognizersBlockingPolicy; + +#pragma mark - +/** + * Registration context for a single `FlutterPlugin`, providing a one stop shop + * for the plugin to access contextual information and register callbacks for + * various application events. + * + * Registrars are obtained from a `FlutterPluginRegistry` which keeps track of + * the identity of registered plugins and provides basic support for cross-plugin + * coordination. + */ +@protocol FlutterPluginRegistrar +/** + * Returns a `FlutterBinaryMessenger` for creating Dart/iOS communication + * channels to be used by the plugin. + * + * @return The messenger. + */ +- (NSObject*)messenger; + +/** + * Returns a `FlutterTextureRegistry` for registering textures + * provided by the plugin. + * + * @return The texture registry. + */ +- (NSObject*)textures; + +/** + * Registers a `FlutterPlatformViewFactory` for creation of platform views. + * + * Plugins expose `UIView` for embedding in Flutter apps by registering a view factory. + * + * @param factory The view factory that will be registered. + * @param factoryId A unique identifier for the factory, the Dart code of the Flutter app can use + * this identifier to request creation of a `UIView` by the registered factory. + */ +- (void)registerViewFactory:(NSObject*)factory + withId:(NSString*)factoryId; + +/** + * Registers a `FlutterPlatformViewFactory` for creation of platform views. + * + * Plugins can expose a `UIView` for embedding in Flutter apps by registering a view factory. + * + * @param factory The view factory that will be registered. + * @param factoryId A unique identifier for the factory, the Dart code of the Flutter app can use + * this identifier to request creation of a `UIView` by the registered factory. + * @param gestureRecognizersBlockingPolicy How UIGestureRecognizers on the platform views are + * blocked. + * + */ +- (void)registerViewFactory:(NSObject*)factory + withId:(NSString*)factoryId + gestureRecognizersBlockingPolicy: + (FlutterPlatformViewGestureRecognizersBlockingPolicy)gestureRecognizersBlockingPolicy; + +/** + * Publishes a value for external use of the plugin. + * + * Plugins may publish a single value, such as an instance of the + * plugin's main class, for situations where external control or + * interaction is needed. + * + * The published value will be available from the `FlutterPluginRegistry`. + * Repeated calls overwrite any previous publication. + * + * @param value The value to be published. + */ +- (void)publish:(NSObject*)value; + +/** + * Registers the plugin as a receiver of incoming method calls from the Dart side + * on the specified `FlutterMethodChannel`. + * + * @param delegate The receiving object, such as the plugin's main class. + * @param channel The channel + */ +- (void)addMethodCallDelegate:(NSObject*)delegate + channel:(FlutterMethodChannel*)channel; + +/** + * Registers the plugin as a receiver of `UIApplicationDelegate` calls. + * + * @param delegate The receiving object, such as the plugin's main class. + */ +- (void)addApplicationDelegate:(NSObject*)delegate + NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in plugins used in app extensions"); + +/** + * Returns the file name for the given asset. + * The returned file name can be used to access the asset in the application's main bundle. + * + * @param asset The name of the asset. The name can be hierarchical. + * @return the file name to be used for lookup in the main bundle. + */ +- (NSString*)lookupKeyForAsset:(NSString*)asset; + +/** + * Returns the file name for the given asset which originates from the specified package. + * The returned file name can be used to access the asset in the application's main bundle. + * + * + * @param asset The name of the asset. The name can be hierarchical. + * @param package The name of the package from which the asset originates. + * @return the file name to be used for lookup in the main bundle. + */ +- (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package; +@end + +#pragma mark - +/** + * A registry of Flutter iOS plugins. + * + * Plugins are identified by unique string keys, typically the name of the + * plugin's main class. The registry tracks plugins by this key, mapping it to + * a value published by the plugin during registration, if any. This provides a + * very basic means of cross-plugin coordination with loose coupling between + * unrelated plugins. + * + * Plugins typically need contextual information and the ability to register + * callbacks for various application events. To keep the API of the registry + * focused, these facilities are not provided directly by the registry, but by + * a `FlutterPluginRegistrar`, created by the registry in exchange for the unique + * key of the plugin. + * + * There is no implied connection between the registry and the registrar. + * Specifically, callbacks registered by the plugin via the registrar may be + * relayed directly to the underlying iOS application objects. + */ +@protocol FlutterPluginRegistry +/** + * Returns a registrar for registering a plugin. + * + * @param pluginKey The unique key identifying the plugin. + */ +- (nullable NSObject*)registrarForPlugin:(NSString*)pluginKey; +/** + * Returns whether the specified plugin has been registered. + * + * @param pluginKey The unique key identifying the plugin. + * @return `YES` if `registrarForPlugin` has been called with `pluginKey`. + */ +- (BOOL)hasPlugin:(NSString*)pluginKey; + +/** + * Returns a value published by the specified plugin. + * + * @param pluginKey The unique key identifying the plugin. + * @return An object published by the plugin, if any. Will be `NSNull` if + * nothing has been published. Will be `nil` if the plugin has not been + * registered. + */ +- (nullable NSObject*)valuePublishedByPlugin:(NSString*)pluginKey; +@end + +#pragma mark - +/** + * Implement this in the `UIAppDelegate` of your app to enable Flutter plugins to register + * themselves to the application life cycle events. + * + * For plugins to receive events from `UNUserNotificationCenter`, register this as the + * `UNUserNotificationCenterDelegate`. + */ +@protocol FlutterAppLifeCycleProvider + +/** + * Called when registering a new `FlutterApplicaitonLifeCycleDelegate`. + * + * See also: `-[FlutterAppDelegate addApplicationLifeCycleDelegate:]` + */ +- (void)addApplicationLifeCycleDelegate:(NSObject*)delegate; +@end + +NS_ASSUME_NONNULL_END + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERPLUGIN_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterPluginAppLifeCycleDelegate.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterPluginAppLifeCycleDelegate.h new file mode 100644 index 0000000000000000000000000000000000000000..95d1e611e495019aaf08c8a1f0126a1560b7f695 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterPluginAppLifeCycleDelegate.h @@ -0,0 +1,148 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERPLUGINAPPLIFECYCLEDELEGATE_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERPLUGINAPPLIFECYCLEDELEGATE_H_ + +#import "FlutterPlugin.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * Propagates `UIAppDelegate` callbacks to registered plugins. + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterPluginAppLifeCycleDelegate : NSObject + +/** + * Registers `delegate` to receive life cycle callbacks via this FlutterPluginAppLifeCycleDelegate + * as long as it is alive. + * + * `delegate` will only be referenced weakly. + */ +- (void)addDelegate:(NSObject*)delegate; + +/** + * Calls all plugins registered for `UIApplicationDelegate` callbacks. + * + * @return `NO` if any plugin vetos application launch. + */ +- (BOOL)application:(UIApplication*)application + didFinishLaunchingWithOptions:(NSDictionary*)launchOptions; + +/** + * Calls all plugins registered for `UIApplicationDelegate` callbacks. + * + * @return `NO` if any plugin vetos application launch. + */ +- (BOOL)application:(UIApplication*)application + willFinishLaunchingWithOptions:(NSDictionary*)launchOptions; + +/** + * Called if this plugin has been registered for `UIApplicationDelegate` callbacks. + */ +- (void)application:(UIApplication*)application + didRegisterUserNotificationSettings:(UIUserNotificationSettings*)notificationSettings + API_DEPRECATED( + "See -[UIApplicationDelegate application:didRegisterUserNotificationSettings:] deprecation", + ios(8.0, 10.0)); + +/** + * Calls all plugins registered for `UIApplicationDelegate` callbacks. + */ +- (void)application:(UIApplication*)application + didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken; + +/** + * Calls all plugins registered for `UIApplicationDelegate` callbacks. + */ +- (void)application:(UIApplication*)application + didFailToRegisterForRemoteNotificationsWithError:(NSError*)error; + +/** + * Calls all plugins registered for `UIApplicationDelegate` callbacks. + */ +- (void)application:(UIApplication*)application + didReceiveRemoteNotification:(NSDictionary*)userInfo + fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler; + +/** + * Calls all plugins registered for `UIApplicationDelegate` callbacks. + */ +- (void)application:(UIApplication*)application + didReceiveLocalNotification:(UILocalNotification*)notification + API_DEPRECATED( + "See -[UIApplicationDelegate application:didReceiveLocalNotification:] deprecation", + ios(4.0, 10.0)); + +/** + * Calls all plugins registered for `UIApplicationDelegate` callbacks in order of registration until + * some plugin handles the request. + * + * @return `YES` if any plugin handles the request. + */ +- (BOOL)application:(UIApplication*)application + openURL:(NSURL*)url + options:(NSDictionary*)options; + +/** + * Calls all plugins registered for `UIApplicationDelegate` callbacks in order of registration until + * some plugin handles the request. + * + * @return `YES` if any plugin handles the request. + */ +- (BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)url; + +/** + * Calls all plugins registered for `UIApplicationDelegate` callbacks in order of registration until + * some plugin handles the request. + * + * @return `YES` if any plugin handles the request. + */ +- (BOOL)application:(UIApplication*)application + openURL:(NSURL*)url + sourceApplication:(NSString*)sourceApplication + annotation:(id)annotation; + +/** + * Calls all plugins registered for `UIApplicationDelegate` callbacks. + */ +- (void)application:(UIApplication*)application + performActionForShortcutItem:(UIApplicationShortcutItem*)shortcutItem + completionHandler:(void (^)(BOOL succeeded))completionHandler + API_AVAILABLE(ios(9.0)); + +/** + * Calls all plugins registered for `UIApplicationDelegate` callbacks in order of registration until + * some plugin handles the request. + * + * @return `YES` if any plugin handles the request. + */ +- (BOOL)application:(UIApplication*)application + handleEventsForBackgroundURLSession:(nonnull NSString*)identifier + completionHandler:(nonnull void (^)(void))completionHandler; + +/** + * Calls all plugins registered for `UIApplicationDelegate` callbacks in order of registration until + * some plugin handles the request. + * + * @returns `YES` if any plugin handles the request. + */ +- (BOOL)application:(UIApplication*)application + performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler; + +/** + * Calls all plugins registered for `UIApplicationDelegate` callbacks in order of registration until + * some plugin handles the request. + * + * @return `YES` if any plugin handles the request. + */ +- (BOOL)application:(UIApplication*)application + continueUserActivity:(NSUserActivity*)userActivity + restorationHandler:(void (^)(NSArray*))restorationHandler; +@end + +NS_ASSUME_NONNULL_END + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERPLUGINAPPLIFECYCLEDELEGATE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h new file mode 100644 index 0000000000000000000000000000000000000000..e41565c3b1fc2c68f4425aadc1a63987da047438 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h @@ -0,0 +1,261 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERVIEWCONTROLLER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERVIEWCONTROLLER_H_ + +#import +#include + +#import "FlutterBinaryMessenger.h" +#import "FlutterDartProject.h" +#import "FlutterEngine.h" +#import "FlutterHourFormat.h" +#import "FlutterMacros.h" +#import "FlutterPlugin.h" +#import "FlutterTexture.h" + +NS_ASSUME_NONNULL_BEGIN + +@class FlutterEngine; + +/** + * The name used for semantic update notifications via `NSNotificationCenter`. + * + * The object passed as the sender is the `FlutterViewController` associated + * with the update. + */ +FLUTTER_DARWIN_EXPORT +// NOLINTNEXTLINE(readability-identifier-naming) +extern NSNotificationName const FlutterSemanticsUpdateNotification; + +/** + * A `UIViewController` implementation for Flutter views. + * + * Dart execution, channel communication, texture registration, and plugin registration are all + * handled by `FlutterEngine`. Calls on this class to those members all proxy through to the + * `FlutterEngine` attached FlutterViewController. + * + * A FlutterViewController can be initialized either with an already-running `FlutterEngine` via the + * `initWithEngine:` initializer, or it can be initialized with a `FlutterDartProject` that will be + * used to implicitly spin up a new `FlutterEngine`. Creating a `FlutterEngine` before showing a + * FlutterViewController can be used to pre-initialize the Dart VM and to prepare the isolate in + * order to reduce the latency to the first rendered frame. See + * https://flutter.dev/docs/development/add-to-app/performance for more details on loading + * latency. + * + * Holding a `FlutterEngine` independently of FlutterViewControllers can also be used to not to lose + * Dart-related state and asynchronous tasks when navigating back and forth between a + * FlutterViewController and other `UIViewController`s. + */ +FLUTTER_DARWIN_EXPORT +#ifdef __IPHONE_13_4 +@interface FlutterViewController + : UIViewController +#else +@interface FlutterViewController : UIViewController +#endif + +/** + * Initializes this FlutterViewController with the specified `FlutterEngine`. + * + * The initialized viewcontroller will attach itself to the engine as part of this process. + * + * @param engine The `FlutterEngine` instance to attach to. Cannot be nil. + * @param nibName The NIB name to initialize this UIViewController with. + * @param nibBundle The NIB bundle. + */ +- (instancetype)initWithEngine:(FlutterEngine*)engine + nibName:(nullable NSString*)nibName + bundle:(nullable NSBundle*)nibBundle NS_DESIGNATED_INITIALIZER; + +/** + * Initializes a new FlutterViewController and `FlutterEngine` with the specified + * `FlutterDartProject`. + * + * This will implicitly create a new `FlutterEngine` which is retrievable via the `engine` property + * after initialization. + * + * @param project The `FlutterDartProject` to initialize the `FlutterEngine` with. + * @param nibName The NIB name to initialize this UIViewController with. + * @param nibBundle The NIB bundle. + */ +- (instancetype)initWithProject:(nullable FlutterDartProject*)project + nibName:(nullable NSString*)nibName + bundle:(nullable NSBundle*)nibBundle NS_DESIGNATED_INITIALIZER; + +/** + * Initializes a new FlutterViewController and `FlutterEngine` with the specified + * `FlutterDartProject` and `initialRoute`. + * + * This will implicitly create a new `FlutterEngine` which is retrievable via the `engine` property + * after initialization. + * + * @param project The `FlutterDartProject` to initialize the `FlutterEngine` with. + * @param initialRoute The initial `Navigator` route to load. + * @param nibName The NIB name to initialize this UIViewController with. + * @param nibBundle The NIB bundle. + */ +- (instancetype)initWithProject:(nullable FlutterDartProject*)project + initialRoute:(nullable NSString*)initialRoute + nibName:(nullable NSString*)nibName + bundle:(nullable NSBundle*)nibBundle NS_DESIGNATED_INITIALIZER; + +/** + * Initializer that is called from loading a FlutterViewController from a XIB. + * + * See also: + * https://developer.apple.com/documentation/foundation/nscoding/1416145-initwithcoder?language=objc + */ +- (instancetype)initWithCoder:(NSCoder*)aDecoder NS_DESIGNATED_INITIALIZER; + +/** + * Registers a callback that will be invoked when the Flutter view has been rendered. + * The callback will be fired only once. + * + * Replaces an existing callback. Use a `nil` callback to unregister the existing one. + */ +- (void)setFlutterViewDidRenderCallback:(void (^)(void))callback; + +/** + * Returns the file name for the given asset. + * The returned file name can be used to access the asset in the application's + * main bundle. + * + * @param asset The name of the asset. The name can be hierarchical. + * @return The file name to be used for lookup in the main bundle. + */ +- (NSString*)lookupKeyForAsset:(NSString*)asset; + +/** + * Returns the file name for the given asset which originates from the specified + * package. + * The returned file name can be used to access the asset in the application's + * main bundle. + * + * @param asset The name of the asset. The name can be hierarchical. + * @param package The name of the package from which the asset originates. + * @return The file name to be used for lookup in the main bundle. + */ +- (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package; + +/** + * Deprecated API to set initial route. + * + * Attempts to set the first route that the Flutter app shows if the Flutter + * runtime hasn't yet started. The default is "/". + * + * This method must be called immediately after `initWithProject` and has no + * effect when using `initWithEngine` if the `FlutterEngine` has already been + * run. + * + * Setting this after the Flutter started running has no effect. See `pushRoute` + * and `popRoute` to change the route after Flutter started running. + * + * This is deprecated because it needs to be called at the time of initialization + * and thus should just be in the `initWithProject` initializer. If using + * `initWithEngine`, the initial route should be set on the engine's + * initializer. + * + * @param route The name of the first route to show. + */ +- (void)setInitialRoute:(NSString*)route + FLUTTER_DEPRECATED("Use FlutterViewController initializer to specify initial route"); + +/** + * Instructs the Flutter Navigator (if any) to go back. + */ +- (void)popRoute; + +/** + * Instructs the Flutter Navigator (if any) to push a route on to the navigation + * stack. + * + * @param route The name of the route to push to the navigation stack. + */ +- (void)pushRoute:(NSString*)route; + +/** + * The `FlutterPluginRegistry` used by this FlutterViewController. + */ +- (id)pluginRegistry; + +/** + * A wrapper around UIAccessibilityIsVoiceOverRunning(). + * + * As a C function, UIAccessibilityIsVoiceOverRunning() cannot be mocked in testing. Mock + * this class method to testing features depends on UIAccessibilityIsVoiceOverRunning(). + */ ++ (BOOL)isUIAccessibilityIsVoiceOverRunning; + +/** + * True if at least one frame has rendered and the ViewController has appeared. + * + * This property is reset to false when the ViewController disappears. It is + * guaranteed to only alternate between true and false for observers. + */ +@property(nonatomic, readonly, getter=isDisplayingFlutterUI) BOOL displayingFlutterUI; + +/** + * Specifies the view to use as a splash screen. Flutter's rendering is asynchronous, so the first + * frame rendered by the Flutter application might not immediately appear when the Flutter view is + * initially placed in the view hierarchy. The splash screen view will be used as + * a replacement until the first frame is rendered. + * + * The view used should be appropriate for multiple sizes; an autoresizing mask to + * have a flexible width and height will be applied automatically. + * + * Set to nil to remove the splash screen view. + */ +@property(strong, nonatomic, nullable) UIView* splashScreenView; + +/** + * Attempts to set the `splashScreenView` property from the `UILaunchStoryboardName` from the + * main bundle's `Info.plist` file. This method will not change the value of `splashScreenView` + * if it cannot find a default one from a storyboard or nib. + * + * @return `YES` if successful, `NO` otherwise. + */ +- (BOOL)loadDefaultSplashScreenView; + +/** + * Controls whether the created view will be opaque or not. + * + * Default is `YES`. Note that setting this to `NO` may negatively impact performance + * when using hardware acceleration, and toggling this will trigger a re-layout of the + * view. + */ +@property(nonatomic, getter=isViewOpaque) BOOL viewOpaque; + +/** + * The `FlutterEngine` instance for this view controller. This could be the engine this + * `FlutterViewController` is initialized with or a new `FlutterEngine` implicitly created if + * no engine was supplied during initialization. + */ +@property(nonatomic, readonly) FlutterEngine* engine; + +/** + * The `FlutterBinaryMessenger` associated with this FlutterViewController (used for communicating + * with channels). + * + * This is just a convenient way to get the |FlutterEngine|'s binary messenger. + */ +@property(nonatomic, readonly) NSObject* binaryMessenger; + +/** + * If the `FlutterViewController` creates a `FlutterEngine`, this property + * determines if that `FlutterEngine` has `allowHeadlessExecution` set. + * + * The intention is that this is used with the XIB. Otherwise, a + * `FlutterEngine` can just be sent to the init methods. + * + * See also: `-[FlutterEngine initWithName:project:allowHeadlessExecution:]` + */ +@property(nonatomic, readonly) BOOL engineAllowHeadlessExecution; + +@end + +NS_ASSUME_NONNULL_END + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERVIEWCONTROLLER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Info.plist b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Info.plist new file mode 100644 index 0000000000000000000000000000000000000000..ceca7a90b8178fd5b323bfdfa8049c445e11e6f4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Info.plist @@ -0,0 +1,30 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + Flutter + CFBundleIdentifier + io.flutter.flutter + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + Flutter + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + MinimumOSVersion + {min_version} + FlutterEngine + {revision} + ClangVersion + {clang_version} + + diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/PrivacyInfo.xcprivacy b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/PrivacyInfo.xcprivacy new file mode 100644 index 0000000000000000000000000000000000000000..d4bc7fc2eda844cd89eb1b4aaf04611e511912ed --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/PrivacyInfo.xcprivacy @@ -0,0 +1,32 @@ + + + + + NSPrivacyTracking + + NSPrivacyTrackingDomains + + NSPrivacyCollectedDataTypes + + NSPrivacyAccessedAPITypes + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryFileTimestamp + NSPrivacyAccessedAPITypeReasons + + 0A2A.1 + C617.1 + + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategorySystemBootTime + NSPrivacyAccessedAPITypeReasons + + 35F9.1 + + + + + diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterAppDelegate.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterAppDelegate.mm new file mode 100644 index 0000000000000000000000000000000000000000..74e6902c1898aafa87f1e2ed8915d29de7e71330 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterAppDelegate.mm @@ -0,0 +1,344 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterAppDelegate.h" + +#import "flutter/fml/logging.h" +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterPluginAppLifeCycleDelegate.h" +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterAppDelegate_Test.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegate_internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterSharedApplication.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h" + +FLUTTER_ASSERT_ARC + +static NSString* const kUIBackgroundMode = @"UIBackgroundModes"; +static NSString* const kRemoteNotificationCapabitiliy = @"remote-notification"; +static NSString* const kBackgroundFetchCapatibility = @"fetch"; +static NSString* const kRestorationStateAppModificationKey = @"mod-date"; + +@interface FlutterAppDelegate () +@property(nonatomic, copy) FlutterViewController* (^rootFlutterViewControllerGetter)(void); +@property(nonatomic, strong) FlutterPluginAppLifeCycleDelegate* lifeCycleDelegate; +@end + +@implementation FlutterAppDelegate + +- (instancetype)init { + if (self = [super init]) { + _lifeCycleDelegate = [[FlutterPluginAppLifeCycleDelegate alloc] init]; + } + return self; +} + +- (BOOL)application:(UIApplication*)application + willFinishLaunchingWithOptions:(NSDictionary*)launchOptions { + return [self.lifeCycleDelegate application:application + willFinishLaunchingWithOptions:launchOptions]; +} + +- (BOOL)application:(UIApplication*)application + didFinishLaunchingWithOptions:(NSDictionary*)launchOptions { + return [self.lifeCycleDelegate application:application + didFinishLaunchingWithOptions:launchOptions]; +} + +// Returns the key window's rootViewController, if it's a FlutterViewController. +// Otherwise, returns nil. +- (FlutterViewController*)rootFlutterViewController { + if (_rootFlutterViewControllerGetter != nil) { + return _rootFlutterViewControllerGetter(); + } + UIViewController* rootViewController = _window.rootViewController; + if ([rootViewController isKindOfClass:[FlutterViewController class]]) { + return (FlutterViewController*)rootViewController; + } + return nil; +} + +// Do not remove, some clients may be calling these via `super`. +- (void)applicationDidEnterBackground:(UIApplication*)application { +} + +// Do not remove, some clients may be calling these via `super`. +- (void)applicationWillEnterForeground:(UIApplication*)application { +} + +// Do not remove, some clients may be calling these via `super`. +- (void)applicationWillResignActive:(UIApplication*)application { +} + +// Do not remove, some clients may be calling these via `super`. +- (void)applicationDidBecomeActive:(UIApplication*)application { +} + +// Do not remove, some clients may be calling these via `super`. +- (void)applicationWillTerminate:(UIApplication*)application { +} + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +- (void)application:(UIApplication*)application + didRegisterUserNotificationSettings:(UIUserNotificationSettings*)notificationSettings { + [self.lifeCycleDelegate application:application + didRegisterUserNotificationSettings:notificationSettings]; +} +#pragma GCC diagnostic pop + +- (void)application:(UIApplication*)application + didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken { + [self.lifeCycleDelegate application:application + didRegisterForRemoteNotificationsWithDeviceToken:deviceToken]; +} + +- (void)application:(UIApplication*)application + didFailToRegisterForRemoteNotificationsWithError:(NSError*)error { + [self.lifeCycleDelegate application:application + didFailToRegisterForRemoteNotificationsWithError:error]; +} + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +- (void)application:(UIApplication*)application + didReceiveLocalNotification:(UILocalNotification*)notification { + [self.lifeCycleDelegate application:application didReceiveLocalNotification:notification]; +} +#pragma GCC diagnostic pop + +- (void)userNotificationCenter:(UNUserNotificationCenter*)center + willPresentNotification:(UNNotification*)notification + withCompletionHandler: + (void (^)(UNNotificationPresentationOptions options))completionHandler { + if ([self.lifeCycleDelegate respondsToSelector:_cmd]) { + [self.lifeCycleDelegate userNotificationCenter:center + willPresentNotification:notification + withCompletionHandler:completionHandler]; + } +} + +/** + * Calls all plugins registered for `UNUserNotificationCenterDelegate` callbacks. + */ +- (void)userNotificationCenter:(UNUserNotificationCenter*)center + didReceiveNotificationResponse:(UNNotificationResponse*)response + withCompletionHandler:(void (^)(void))completionHandler { + if ([self.lifeCycleDelegate respondsToSelector:_cmd]) { + [self.lifeCycleDelegate userNotificationCenter:center + didReceiveNotificationResponse:response + withCompletionHandler:completionHandler]; + } +} + +- (BOOL)isFlutterDeepLinkingEnabled { + NSNumber* isDeepLinkingEnabled = + [[NSBundle mainBundle] objectForInfoDictionaryKey:@"FlutterDeepLinkingEnabled"]; + // if not set, return YES + return isDeepLinkingEnabled ? [isDeepLinkingEnabled boolValue] : YES; +} + +// This method is called when opening an URL with custom schemes. +- (BOOL)application:(UIApplication*)application + openURL:(NSURL*)url + options:(NSDictionary*)options { + if ([self.lifeCycleDelegate application:application openURL:url options:options]) { + return YES; + } + + // Relaying to the system here will case an infinite loop, so we don't do it here. + return [self handleOpenURL:url options:options relayToSystemIfUnhandled:NO]; +} + +// Helper function for opening an URL, either with a custom scheme or a http/https scheme. +- (BOOL)handleOpenURL:(NSURL*)url + options:(NSDictionary*)options + relayToSystemIfUnhandled:(BOOL)throwBack { + UIApplication* flutterApplication = FlutterSharedApplication.application; + if (flutterApplication == nil) { + return NO; + } + if (![self isFlutterDeepLinkingEnabled]) { + return NO; + } + + FlutterViewController* flutterViewController = [self rootFlutterViewController]; + if (flutterViewController) { + [flutterViewController sendDeepLinkToFramework:url + completionHandler:^(BOOL success) { + if (!success && throwBack) { + // throw it back to iOS + [flutterApplication openURL:url + options:@{} + completionHandler:nil]; + } + }]; + } else { + FML_LOG(ERROR) << "Attempting to open an URL without a Flutter RootViewController."; + return NO; + } + return YES; +} + +- (BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)url { + return [self.lifeCycleDelegate application:application handleOpenURL:url]; +} + +- (BOOL)application:(UIApplication*)application + openURL:(NSURL*)url + sourceApplication:(NSString*)sourceApplication + annotation:(id)annotation { + return [self.lifeCycleDelegate application:application + openURL:url + sourceApplication:sourceApplication + annotation:annotation]; +} + +- (void)application:(UIApplication*)application + performActionForShortcutItem:(UIApplicationShortcutItem*)shortcutItem + completionHandler:(void (^)(BOOL succeeded))completionHandler { + [self.lifeCycleDelegate application:application + performActionForShortcutItem:shortcutItem + completionHandler:completionHandler]; +} + +- (void)application:(UIApplication*)application + handleEventsForBackgroundURLSession:(nonnull NSString*)identifier + completionHandler:(nonnull void (^)())completionHandler { + [self.lifeCycleDelegate application:application + handleEventsForBackgroundURLSession:identifier + completionHandler:completionHandler]; +} + +// This method is called when opening an URL with a http/https scheme. +- (BOOL)application:(UIApplication*)application + continueUserActivity:(NSUserActivity*)userActivity + restorationHandler: + (void (^)(NSArray>* __nullable restorableObjects)) + restorationHandler { + if ([self.lifeCycleDelegate application:application + continueUserActivity:userActivity + restorationHandler:restorationHandler]) { + return YES; + } + + return [self handleOpenURL:userActivity.webpageURL options:@{} relayToSystemIfUnhandled:YES]; +} + +#pragma mark - FlutterPluginRegistry methods. All delegating to the rootViewController + +- (NSObject*)registrarForPlugin:(NSString*)pluginKey { + FlutterViewController* flutterRootViewController = [self rootFlutterViewController]; + if (flutterRootViewController) { + return [[flutterRootViewController pluginRegistry] registrarForPlugin:pluginKey]; + } + return nil; +} + +- (BOOL)hasPlugin:(NSString*)pluginKey { + FlutterViewController* flutterRootViewController = [self rootFlutterViewController]; + if (flutterRootViewController) { + return [[flutterRootViewController pluginRegistry] hasPlugin:pluginKey]; + } + return false; +} + +- (NSObject*)valuePublishedByPlugin:(NSString*)pluginKey { + FlutterViewController* flutterRootViewController = [self rootFlutterViewController]; + if (flutterRootViewController) { + return [[flutterRootViewController pluginRegistry] valuePublishedByPlugin:pluginKey]; + } + return nil; +} + +#pragma mark - Selectors handling + +- (void)addApplicationLifeCycleDelegate:(NSObject*)delegate { + [self.lifeCycleDelegate addDelegate:delegate]; +} + +#pragma mark - UIApplicationDelegate method dynamic implementation + +- (BOOL)respondsToSelector:(SEL)selector { + if ([self.lifeCycleDelegate isSelectorAddedDynamically:selector]) { + return [self delegateRespondsSelectorToPlugins:selector]; + } + return [super respondsToSelector:selector]; +} + +- (BOOL)delegateRespondsSelectorToPlugins:(SEL)selector { + if ([self.lifeCycleDelegate hasPluginThatRespondsToSelector:selector]) { + return [self.lifeCycleDelegate respondsToSelector:selector]; + } else { + return NO; + } +} + +- (id)forwardingTargetForSelector:(SEL)aSelector { + if ([self.lifeCycleDelegate isSelectorAddedDynamically:aSelector]) { + [self logCapabilityConfigurationWarningIfNeeded:aSelector]; + return self.lifeCycleDelegate; + } + return [super forwardingTargetForSelector:aSelector]; +} + +// Mimic the logging from Apple when the capability is not set for the selectors. +// However the difference is that Apple logs these message when the app launches, we only +// log it when the method is invoked. We can possibly also log it when the app launches, but +// it will cause an additional scan over all the plugins. +- (void)logCapabilityConfigurationWarningIfNeeded:(SEL)selector { + NSArray* backgroundModesArray = + [[NSBundle mainBundle] objectForInfoDictionaryKey:kUIBackgroundMode]; + NSSet* backgroundModesSet = [[NSSet alloc] initWithArray:backgroundModesArray]; + if (selector == @selector(application:didReceiveRemoteNotification:fetchCompletionHandler:)) { + if (![backgroundModesSet containsObject:kRemoteNotificationCapabitiliy]) { + NSLog( + @"You've implemented -[ " + @"application:didReceiveRemoteNotification:fetchCompletionHandler:], but you still need " + @"to add \"remote-notification\" to the list of your supported UIBackgroundModes in your " + @"Info.plist."); + } + } else if (selector == @selector(application:performFetchWithCompletionHandler:)) { + if (![backgroundModesSet containsObject:kBackgroundFetchCapatibility]) { + NSLog(@"You've implemented -[ " + @"application:performFetchWithCompletionHandler:], but you still need to add \"fetch\" " + @"to the list of your supported UIBackgroundModes in your Info.plist."); + } + } +} + +#pragma mark - State Restoration + +- (BOOL)application:(UIApplication*)application shouldSaveApplicationState:(NSCoder*)coder { + [coder encodeInt64:self.lastAppModificationTime forKey:kRestorationStateAppModificationKey]; + return YES; +} + +- (BOOL)application:(UIApplication*)application shouldRestoreApplicationState:(NSCoder*)coder { + int64_t stateDate = [coder decodeInt64ForKey:kRestorationStateAppModificationKey]; + return self.lastAppModificationTime == stateDate; +} + +- (BOOL)application:(UIApplication*)application shouldSaveSecureApplicationState:(NSCoder*)coder { + [coder encodeInt64:self.lastAppModificationTime forKey:kRestorationStateAppModificationKey]; + return YES; +} + +- (BOOL)application:(UIApplication*)application + shouldRestoreSecureApplicationState:(NSCoder*)coder { + int64_t stateDate = [coder decodeInt64ForKey:kRestorationStateAppModificationKey]; + return self.lastAppModificationTime == stateDate; +} + +- (int64_t)lastAppModificationTime { + NSDate* fileDate; + NSError* error = nil; + [[[NSBundle mainBundle] executableURL] getResourceValue:&fileDate + forKey:NSURLContentModificationDateKey + error:&error]; + NSAssert(error == nil, @"Cannot obtain modification date of main bundle: %@", error); + return [fileDate timeIntervalSince1970]; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterAppDelegateTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterAppDelegateTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..df9e7c9b43a18c3dae569efcd93874abcec8a9b2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterAppDelegateTest.mm @@ -0,0 +1,201 @@ +// 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. + +#import +#import + +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterAppDelegate.h" +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterEngine.h" +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterAppDelegate_Test.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Test.h" + +FLUTTER_ASSERT_ARC + +@interface FlutterAppDelegateTest : XCTestCase +@property(strong) FlutterAppDelegate* appDelegate; +@property(strong) FlutterViewController* viewController; +@property(strong) id mockMainBundle; +@property(strong) id mockNavigationChannel; + +// Retain callback until the tests are done. +// https://github.com/flutter/flutter/issues/74267 +@property(strong) id mockEngineFirstFrameCallback; +@end + +@implementation FlutterAppDelegateTest + +- (void)setUp { + [super setUp]; + + id mockMainBundle = OCMClassMock([NSBundle class]); + OCMStub([mockMainBundle mainBundle]).andReturn(mockMainBundle); + self.mockMainBundle = mockMainBundle; + + FlutterAppDelegate* appDelegate = [[FlutterAppDelegate alloc] init]; + self.appDelegate = appDelegate; + + FlutterViewController* viewController = OCMClassMock([FlutterViewController class]); + self.viewController = viewController; + + FlutterMethodChannel* navigationChannel = OCMClassMock([FlutterMethodChannel class]); + self.mockNavigationChannel = navigationChannel; + + FlutterEngine* engine = OCMClassMock([FlutterEngine class]); + OCMStub([engine navigationChannel]).andReturn(navigationChannel); + OCMStub([viewController engine]).andReturn(engine); + + id mockEngineFirstFrameCallback = [OCMArg invokeBlockWithArgs:@NO, nil]; + self.mockEngineFirstFrameCallback = mockEngineFirstFrameCallback; + OCMStub([engine waitForFirstFrame:3.0 callback:mockEngineFirstFrameCallback]); + appDelegate.rootFlutterViewControllerGetter = ^{ + return viewController; + }; +} + +- (void)tearDown { + // Explicitly stop mocking the NSBundle class property. + [self.mockMainBundle stopMocking]; + [super tearDown]; +} + +- (void)testLaunchUrl { + OCMStub([self.mockMainBundle objectForInfoDictionaryKey:@"FlutterDeepLinkingEnabled"]) + .andReturn(@YES); + + OCMStub([self.mockNavigationChannel + invokeMethod:@"pushRouteInformation" + arguments:@{@"location" : @"http://myApp/custom/route?query=test"}]) + .andReturn(@YES); + + BOOL result = + [self.appDelegate application:[UIApplication sharedApplication] + openURL:[NSURL URLWithString:@"http://myApp/custom/route?query=test"] + options:@{}]; + + XCTAssertTrue(result); + OCMVerifyAll(self.mockNavigationChannel); +} + +- (void)testLaunchUrlWithDeepLinkingNotSet { + OCMStub([self.mockMainBundle objectForInfoDictionaryKey:@"FlutterDeepLinkingEnabled"]) + .andReturn(nil); + + OCMStub([self.mockNavigationChannel + invokeMethod:@"pushRouteInformation" + arguments:@{@"location" : @"http://myApp/custom/route?query=test"}]) + .andReturn(@YES); + + BOOL result = + [self.appDelegate application:[UIApplication sharedApplication] + openURL:[NSURL URLWithString:@"http://myApp/custom/route?query=test"] + options:@{}]; + + XCTAssertTrue(result); + OCMVerifyAll(self.mockNavigationChannel); +} + +- (void)testLaunchUrlWithDeepLinkingDisabled { + OCMStub([self.mockMainBundle objectForInfoDictionaryKey:@"FlutterDeepLinkingEnabled"]) + .andReturn(@NO); + + BOOL result = + [self.appDelegate application:[UIApplication sharedApplication] + openURL:[NSURL URLWithString:@"http://myApp/custom/route?query=test"] + options:@{}]; + XCTAssertFalse(result); + OCMReject([self.mockNavigationChannel invokeMethod:OCMOCK_ANY arguments:OCMOCK_ANY]); +} + +- (void)testLaunchUrlWithQueryParameterAndFragment { + OCMStub([self.mockMainBundle objectForInfoDictionaryKey:@"FlutterDeepLinkingEnabled"]) + .andReturn(@YES); + OCMStub([self.mockNavigationChannel + invokeMethod:@"pushRouteInformation" + arguments:@{@"location" : @"http://myApp/custom/route?query=test#fragment"}]) + .andReturn(@YES); + BOOL result = [self.appDelegate + application:[UIApplication sharedApplication] + openURL:[NSURL URLWithString:@"http://myApp/custom/route?query=test#fragment"] + options:@{}]; + XCTAssertTrue(result); + OCMVerifyAll(self.mockNavigationChannel); +} + +- (void)testLaunchUrlWithFragmentNoQueryParameter { + OCMStub([self.mockMainBundle objectForInfoDictionaryKey:@"FlutterDeepLinkingEnabled"]) + .andReturn(@YES); + OCMStub([self.mockNavigationChannel + invokeMethod:@"pushRouteInformation" + arguments:@{@"location" : @"http://myApp/custom/route#fragment"}]) + .andReturn(@YES); + BOOL result = + [self.appDelegate application:[UIApplication sharedApplication] + openURL:[NSURL URLWithString:@"http://myApp/custom/route#fragment"] + options:@{}]; + XCTAssertTrue(result); + OCMVerifyAll(self.mockNavigationChannel); +} + +- (void)testReleasesWindowOnDealloc { + __weak UIWindow* weakWindow; + @autoreleasepool { + id mockWindow = OCMClassMock([UIWindow class]); + FlutterAppDelegate* appDelegate = [[FlutterAppDelegate alloc] init]; + appDelegate.window = mockWindow; + weakWindow = mockWindow; + XCTAssertNotNil(weakWindow); + [mockWindow stopMocking]; + mockWindow = nil; + appDelegate = nil; + } + // App delegate has released the window. + XCTAssertNil(weakWindow); +} + +#pragma mark - Deep linking + +- (void)testUniversalLinkPushRouteInformation { + OCMStub([self.mockMainBundle objectForInfoDictionaryKey:@"FlutterDeepLinkingEnabled"]) + .andReturn(@YES); + OCMStub([self.mockNavigationChannel + invokeMethod:@"pushRouteInformation" + arguments:@{@"location" : @"http://myApp/custom/route?query=test"}]) + .andReturn(@YES); + NSUserActivity* userActivity = [[NSUserActivity alloc] initWithActivityType:@"com.example.test"]; + userActivity.webpageURL = [NSURL URLWithString:@"http://myApp/custom/route?query=test"]; + BOOL result = [self.appDelegate + application:[UIApplication sharedApplication] + continueUserActivity:userActivity + restorationHandler:^(NSArray>* __nullable restorableObjects){ + }]; + XCTAssertTrue(result); + OCMVerifyAll(self.mockNavigationChannel); +} + +- (void)testUseNonDeprecatedOpenURLAPI { + OCMStub([self.mockMainBundle objectForInfoDictionaryKey:@"FlutterDeepLinkingEnabled"]) + .andReturn(@YES); + NSUserActivity* userActivity = [[NSUserActivity alloc] initWithActivityType:@"com.example.test"]; + userActivity.webpageURL = [NSURL URLWithString:@"http://myApp/custom/route?query=nonexist"]; + OCMStub([self.viewController sendDeepLinkToFramework:[OCMArg any] completionHandler:[OCMArg any]]) + .andDo(^(NSInvocation* invocation) { + void (^handler)(BOOL success); + [invocation getArgument:&handler atIndex:3]; + handler(NO); + }); + id mockApplication = OCMClassMock([UIApplication class]); + OCMStub([mockApplication sharedApplication]).andReturn(mockApplication); + BOOL result = [self.appDelegate + application:[UIApplication sharedApplication] + continueUserActivity:userActivity + restorationHandler:^(NSArray>* __nullable restorableObjects){ + }]; + XCTAssertTrue(result); + OCMVerify([mockApplication openURL:[OCMArg any] + options:[OCMArg any] + completionHandler:[OCMArg any]]); +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterAppDelegate_Test.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterAppDelegate_Test.h new file mode 100644 index 0000000000000000000000000000000000000000..405fb0279ef6e930ed5c7d957bbdf587002f9216 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterAppDelegate_Test.h @@ -0,0 +1,15 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERAPPDELEGATE_TEST_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERAPPDELEGATE_TEST_H_ + +@class FlutterViewController; + +@interface FlutterAppDelegate (Test) +@property(nonatomic, copy) FlutterViewController* (^rootFlutterViewControllerGetter)(void); + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERAPPDELEGATE_TEST_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterCallbackCache.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterCallbackCache.mm new file mode 100644 index 0000000000000000000000000000000000000000..1d752ebcccb4e19a65e8aabe22506c6b4cdcdd6e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterCallbackCache.mm @@ -0,0 +1,49 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterCallbackCache_Internal.h" + +#include "flutter/fml/logging.h" +#include "flutter/lib/ui/plugins/callback_cache.h" + +FLUTTER_ASSERT_ARC + +@implementation FlutterCallbackInformation +@end + +@implementation FlutterCallbackCache + ++ (FlutterCallbackInformation*)lookupCallbackInformation:(int64_t)handle { + auto info = flutter::DartCallbackCache::GetCallbackInformation(handle); + if (info == nullptr) { + return nil; + } + FlutterCallbackInformation* new_info = [[FlutterCallbackInformation alloc] init]; + new_info.callbackName = [NSString stringWithUTF8String:info->name.c_str()]; + new_info.callbackClassName = [NSString stringWithUTF8String:info->class_name.c_str()]; + new_info.callbackLibraryPath = [NSString stringWithUTF8String:info->library_path.c_str()]; + return new_info; +} + ++ (void)setCachePath:(NSString*)path { + FML_DCHECK(path != nil); + flutter::DartCallbackCache::SetCachePath([path UTF8String]); + NSString* cache_path = + [NSString stringWithUTF8String:flutter::DartCallbackCache::GetCachePath().c_str()]; + // Set the "Do Not Backup" flag to ensure that the cache isn't moved off disk in + // low-memory situations. + if (![[NSFileManager defaultManager] fileExistsAtPath:cache_path]) { + [[NSFileManager defaultManager] createFileAtPath:cache_path contents:nil attributes:nil]; + NSError* error = nil; + NSURL* URL = [NSURL fileURLWithPath:cache_path]; + BOOL success = [URL setResourceValue:[NSNumber numberWithBool:YES] + forKey:NSURLIsExcludedFromBackupKey + error:&error]; + if (!success) { + NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error); + } + } +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterCallbackCache_Internal.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterCallbackCache_Internal.h new file mode 100644 index 0000000000000000000000000000000000000000..1d05c7bb2305168b05f0ed0b17b7bbbb643f185b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterCallbackCache_Internal.h @@ -0,0 +1,16 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERCALLBACKCACHE_INTERNAL_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERCALLBACKCACHE_INTERNAL_H_ + +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterCallbackCache.h" + +@interface FlutterCallbackCache () + ++ (void)setCachePath:(NSString*)path; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERCALLBACKCACHE_INTERNAL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponder.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponder.h new file mode 100644 index 0000000000000000000000000000000000000000..514d1c6b3e9b2d3be067194562f1892db8b70772 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponder.h @@ -0,0 +1,29 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERCHANNELKEYRESPONDER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERCHANNELKEYRESPONDER_H_ + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyPrimaryResponder.h" + +#import + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" + +/** + * A primary responder of |FlutterKeyboardManager| that handles events by + * sending the raw information through a method channel. + * + * This class corresponds to the RawKeyboard API in the framework. + */ +@interface FlutterChannelKeyResponder : NSObject + +/** + * Create an instance by specifying the method channel to use. + */ +- (nonnull instancetype)initWithChannel:(nonnull FlutterBasicMessageChannel*)channel; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERCHANNELKEYRESPONDER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponder.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponder.mm new file mode 100644 index 0000000000000000000000000000000000000000..433b1c574cf6f48aa4b38b15c716d57c61bfd355 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponder.mm @@ -0,0 +1,248 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponder.h" + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/KeyCodeMap_Internal.h" + +FLUTTER_ASSERT_ARC + +namespace { +// An enumeration of the modifier values that the framework expects. These are +// largely the same values as the OS (UIKeyModifierShift, etc.), but because the +// framework code expects certain values, and has additional values (like the +// sided modifier values below), we translate the iOS values to the framework +// values, and add a mask for all the possible values. +typedef NS_OPTIONS(NSInteger, kKeyboardModifier) { + kKeyboardModifierAlphaShift = 0x10000, + kKeyboardModifierShift = 0x20000, + kKeyboardModifierLeftShift = 0x02, + kKeyboardModifierRightShift = 0x04, + kKeyboardModifierControl = 0x40000, + kKeyboardModifierLeftControl = 0x01, + kKeyboardModifierRightControl = 0x2000, + kKeyboardModifierOption = 0x80000, + kKeyboardModifierLeftOption = 0x20, + kKeyboardModifierRightOption = 0x40, + kKeyboardModifierCommand = 0x100000, + kKeyboardModifierLeftCommand = 0x08, + kKeyboardModifierRightCommand = 0x10, + kKeyboardModifierNumericPad = 0x200000, + kKeyboardModifierMask = kKeyboardModifierAlphaShift | // + kKeyboardModifierShift | // + kKeyboardModifierLeftShift | // + kKeyboardModifierRightShift | // + kKeyboardModifierControl | // + kKeyboardModifierLeftControl | // + kKeyboardModifierRightControl | // + kKeyboardModifierOption | // + kKeyboardModifierLeftOption | // + kKeyboardModifierRightOption | // + kKeyboardModifierCommand | // + kKeyboardModifierLeftCommand | // + kKeyboardModifierRightCommand | // + kKeyboardModifierNumericPad, +}; + +/** + * Filters out some special cases in the characters field on UIKey. + */ +static NSString* getEventCharacters(NSString* characters, UIKeyboardHIDUsage keyCode) + API_AVAILABLE(ios(13.4)) { + if (characters == nil) { + return nil; + } + if ([characters length] == 0) { + return nil; + } + if (@available(iOS 13.4, *)) { + // On iOS, function keys return the UTF8 string "\^P" (with a literal '/', + // '^' and a 'P', not escaped ctrl-P) as their "characters" field. This + // isn't a valid (single) UTF8 character. Looking at the only UTF16 + // character for a function key yields a value of "16", which is a Unicode + // "SHIFT IN" character, which is just odd. UTF8 conversion of that string + // is what generates the three characters "\^P". + // + // Anyhow, we strip them all out and replace them with empty strings, since + // function keys shouldn't be printable. + if (functionKeyCodes.find(keyCode) != functionKeyCodes.end()) { + return nil; + } + } + return characters; +} + +} // namespace +@interface FlutterChannelKeyResponder () + +/** + * The channel used to communicate with Flutter. + */ +@property(nonatomic) FlutterBasicMessageChannel* channel; + +- (NSInteger)adjustModifiers:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)); +- (void)updatePressedModifiers:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)); + +@property(nonatomic) kKeyboardModifier pressedModifiers; +@end + +@implementation FlutterChannelKeyResponder + +- (nonnull instancetype)initWithChannel:(nonnull FlutterBasicMessageChannel*)channel { + self = [super init]; + if (self != nil) { + _channel = channel; + _pressedModifiers = 0; + } + return self; +} + +- (void)handlePress:(nonnull FlutterUIPressProxy*)press + callback:(nonnull FlutterAsyncKeyCallback)callback API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + // no-op + } else { + return; + } + NSString* type; + switch (press.phase) { + case UIPressPhaseBegan: + type = @"keydown"; + break; + case UIPressPhaseCancelled: + // This event doesn't appear to happen on iOS, at least when switching + // apps. Maybe on tvOS? In any case, it's probably best to send a keyup if + // we do receive one, since if the event was canceled, it's likely that a + // keyup will never be received otherwise. + case UIPressPhaseEnded: + type = @"keyup"; + break; + case UIPressPhaseChanged: + // This only happens for analog devices like joysticks. + return; + case UIPressPhaseStationary: + // The entire volume of documentation of this phase on the Apple site, and + // indeed the Internet, is: + // "A button was pressed but hasn’t moved since the previous event." + // It's unclear what this is actually used for, and we've yet to see it in + // the wild. + return; + } + + NSString* characters = getEventCharacters(press.key.characters, press.key.keyCode); + NSString* charactersIgnoringModifiers = + getEventCharacters(press.key.charactersIgnoringModifiers, press.key.keyCode); + NSDictionary* keyMessage = @{ + @"keymap" : @"ios", + @"type" : type, + @"keyCode" : @(press.key.keyCode), + @"modifiers" : @([self adjustModifiers:press]), + @"characters" : characters == nil ? @"" : characters, + @"charactersIgnoringModifiers" : charactersIgnoringModifiers == nil + ? @"" + : charactersIgnoringModifiers, + }; + [self.channel sendMessage:keyMessage + reply:^(id reply) { + bool handled = reply ? [[reply valueForKey:@"handled"] boolValue] : true; + callback(handled); + }]; +} + +#pragma mark - Private + +- (void)updatePressedModifiers:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + // no-op + } else { + return; + } + + bool isKeyDown = false; + switch (press.phase) { + case UIPressPhaseStationary: + case UIPressPhaseChanged: + // These kinds of events shouldn't get this far. + NSAssert(false, @"Unexpected key event type received in updatePressedModifiers."); + return; + case UIPressPhaseBegan: + isKeyDown = true; + break; + case UIPressPhaseCancelled: + case UIPressPhaseEnded: + isKeyDown = false; + break; + } + + void (^update)(kKeyboardModifier, bool) = ^(kKeyboardModifier mod, bool isOn) { + if (isOn) { + _pressedModifiers |= mod; + } else { + _pressedModifiers &= ~mod; + } + }; + switch (press.key.keyCode) { + case UIKeyboardHIDUsageKeyboardCapsLock: + update(kKeyboardModifierAlphaShift, isKeyDown); + break; + case UIKeyboardHIDUsageKeypadNumLock: + update(kKeyboardModifierNumericPad, isKeyDown); + break; + case UIKeyboardHIDUsageKeyboardLeftShift: + update(kKeyboardModifierLeftShift, isKeyDown); + break; + case UIKeyboardHIDUsageKeyboardRightShift: + update(kKeyboardModifierRightShift, isKeyDown); + break; + case UIKeyboardHIDUsageKeyboardLeftControl: + update(kKeyboardModifierLeftControl, isKeyDown); + break; + case UIKeyboardHIDUsageKeyboardRightControl: + update(kKeyboardModifierRightControl, isKeyDown); + break; + case UIKeyboardHIDUsageKeyboardLeftAlt: + update(kKeyboardModifierLeftOption, isKeyDown); + break; + case UIKeyboardHIDUsageKeyboardRightAlt: + update(kKeyboardModifierRightOption, isKeyDown); + break; + case UIKeyboardHIDUsageKeyboardLeftGUI: + update(kKeyboardModifierLeftCommand, isKeyDown); + break; + case UIKeyboardHIDUsageKeyboardRightGUI: + update(kKeyboardModifierRightCommand, isKeyDown); + break; + default: + // If we didn't update any of the modifiers above, we're done. + return; + } + // Update the non-sided modifier flags to match the content of the sided ones. + update(kKeyboardModifierShift, + _pressedModifiers & (kKeyboardModifierRightShift | kKeyboardModifierLeftShift)); + update(kKeyboardModifierControl, + _pressedModifiers & (kKeyboardModifierRightControl | kKeyboardModifierLeftControl)); + update(kKeyboardModifierOption, + _pressedModifiers & (kKeyboardModifierRightOption | kKeyboardModifierLeftOption)); + update(kKeyboardModifierCommand, + _pressedModifiers & (kKeyboardModifierRightCommand | kKeyboardModifierLeftCommand)); +} + +// Because iOS differs from macOS in that the modifier flags still contain the +// flag for the key that is being released on the keyup event, we adjust the +// modifiers when the key being released is the matching modifier key itself. +- (NSInteger)adjustModifiers:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + // no-op + } else { + return press.key.modifierFlags; + } + + [self updatePressedModifiers:press]; + // Replace the supplied modifier flags with our computed ones. + return _pressedModifiers | (press.key.modifierFlags & ~kKeyboardModifierMask); +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponderTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponderTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..16b26ceabd6013c8e53852f086cc117443452118 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponderTest.mm @@ -0,0 +1,143 @@ +// 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. + +#import +#import +#import + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponder.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.h" + +FLUTTER_ASSERT_ARC; + +#define XCTAssertStrEqual(value, expected) \ + XCTAssertTrue([value isEqualToString:expected], \ + @"String \"%@\" not equal to the expected value of \"%@\"", value, expected) + +using namespace flutter::testing; + +API_AVAILABLE(ios(13.4)) +@interface FlutterChannelKeyResponderTest : XCTestCase +@property(copy, nonatomic) FlutterUIPressProxy* testKeyDownEvent API_AVAILABLE(ios(13.4)); +@property(copy, nonatomic) FlutterUIPressProxy* testKeyUpEvent API_AVAILABLE(ios(13.4)); +@end + +@implementation FlutterChannelKeyResponderTest + +- (void)setUp { + // All of these tests were designed to run on iOS 13.4 or later. + if (@available(iOS 13.4, *)) { + } else { + XCTSkip(@"Required API not present for test."); + } + _testKeyDownEvent = keyDownEvent(UIKeyboardHIDUsageKeyboardA, 0x0, 0.0f, "a", "a"); + _testKeyUpEvent = keyUpEvent(UIKeyboardHIDUsageKeyboardA, 0x0, 0.0f); +} + +- (void)tearDown API_AVAILABLE(ios(13.4)) { + _testKeyDownEvent = nil; + _testKeyUpEvent = nil; +} + +- (void)testBasicKeyEvent API_AVAILABLE(ios(13.4)) { + __block NSMutableArray* messages = [[NSMutableArray alloc] init]; + __block BOOL next_response = TRUE; + __block NSMutableArray* responses = [[NSMutableArray alloc] init]; + + id mockKeyEventChannel = OCMStrictClassMock([FlutterBasicMessageChannel class]); + OCMStub([mockKeyEventChannel sendMessage:[OCMArg any] reply:[OCMArg any]]) + .andDo((^(NSInvocation* invocation) { + [invocation retainArguments]; + NSDictionary* message; + [invocation getArgument:&message atIndex:2]; + [messages addObject:message]; + + FlutterReply callback; + [invocation getArgument:&callback atIndex:3]; + NSDictionary* keyMessage = @{ + @"handled" : @(next_response), + }; + callback(keyMessage); + })); + + // Key down + FlutterChannelKeyResponder* responder = + [[FlutterChannelKeyResponder alloc] initWithChannel:mockKeyEventChannel]; + [responder handlePress:_testKeyDownEvent + callback:^(BOOL handled) { + [responses addObject:@(handled)]; + }]; + + XCTAssertEqual([messages count], 1u); + XCTAssertStrEqual([messages lastObject][@"keymap"], @"ios"); + XCTAssertStrEqual([messages lastObject][@"type"], @"keydown"); + XCTAssertEqual([[messages lastObject][@"keyCode"] intValue], UIKeyboardHIDUsageKeyboardA); + XCTAssertEqual([[messages lastObject][@"modifiers"] intValue], 0x0); + XCTAssertStrEqual([messages lastObject][@"characters"], @"a"); + XCTAssertStrEqual([messages lastObject][@"charactersIgnoringModifiers"], @"a"); + + XCTAssertEqual([responses count], 1u); + XCTAssertEqual([[responses lastObject] boolValue], TRUE); + + [messages removeAllObjects]; + [responses removeAllObjects]; + + // Key up + next_response = FALSE; + [responder handlePress:_testKeyUpEvent + callback:^(BOOL handled) { + [responses addObject:@(handled)]; + }]; + + XCTAssertEqual([messages count], 1u); + XCTAssertStrEqual([messages lastObject][@"keymap"], @"ios"); + XCTAssertStrEqual([messages lastObject][@"type"], @"keyup"); + XCTAssertEqual([[messages lastObject][@"keyCode"] intValue], UIKeyboardHIDUsageKeyboardA); + XCTAssertEqual([[messages lastObject][@"modifiers"] intValue], 0x0); + + XCTAssertEqual([responses count], 1u); + XCTAssertEqual([[responses lastObject] boolValue], FALSE); + + [messages removeAllObjects]; + [responses removeAllObjects]; +} + +- (void)testEmptyResponseIsTakenAsHandled API_AVAILABLE(ios(13.4)) { + __block NSMutableArray* messages = [[NSMutableArray alloc] init]; + __block NSMutableArray* responses = [[NSMutableArray alloc] init]; + + id mockKeyEventChannel = OCMStrictClassMock([FlutterBasicMessageChannel class]); + OCMStub([mockKeyEventChannel sendMessage:[OCMArg any] reply:[OCMArg any]]) + .andDo((^(NSInvocation* invocation) { + [invocation retainArguments]; + NSDictionary* message; + [invocation getArgument:&message atIndex:2]; + [messages addObject:message]; + + FlutterReply callback; + [invocation getArgument:&callback atIndex:3]; + callback(nullptr); + })); + + FlutterChannelKeyResponder* responder = + [[FlutterChannelKeyResponder alloc] initWithChannel:mockKeyEventChannel]; + [responder handlePress:_testKeyDownEvent + callback:^(BOOL handled) { + [responses addObject:@(handled)]; + }]; + + XCTAssertEqual([messages count], 1u); + XCTAssertStrEqual([messages lastObject][@"keymap"], @"ios"); + XCTAssertStrEqual([messages lastObject][@"type"], @"keydown"); + XCTAssertEqual([[messages lastObject][@"keyCode"] intValue], UIKeyboardHIDUsageKeyboardA); + XCTAssertEqual([[messages lastObject][@"modifiers"] intValue], 0x0); + XCTAssertStrEqual([messages lastObject][@"characters"], @"a"); + XCTAssertStrEqual([messages lastObject][@"charactersIgnoringModifiers"], @"a"); + + XCTAssertEqual([responses count], 1u); + XCTAssertEqual([[responses lastObject] boolValue], TRUE); +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject.mm new file mode 100644 index 0000000000000000000000000000000000000000..132c581bc10e746b8fd4dc88c4090b4175cf158d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject.mm @@ -0,0 +1,409 @@ +// 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. + +#define FML_USED_ON_EMBEDDER + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h" + +#import +#import + +#include + +#include "flutter/common/constants.h" +#include "flutter/fml/build_config.h" +#include "flutter/shell/common/switches.h" +#include "flutter/shell/platform/darwin/common/command_line.h" + +FLUTTER_ASSERT_ARC + +extern "C" { +#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG +// Used for debugging dart:* sources. +extern const uint8_t kPlatformStrongDill[]; +extern const intptr_t kPlatformStrongDillSize; +#endif +} + +static const char* kApplicationKernelSnapshotFileName = "kernel_blob.bin"; + +static BOOL DoesHardwareSupportWideGamut() { + static BOOL result = NO; + static dispatch_once_t once_token = 0; + dispatch_once(&once_token, ^{ + id device = MTLCreateSystemDefaultDevice(); + if (@available(iOS 13.0, *)) { + // MTLGPUFamilyApple2 = A9/A10 + result = [device supportsFamily:MTLGPUFamilyApple2]; + } else { + // A9/A10 on iOS 10+ + result = [device supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily3_v2]; + } + }); + return result; +} + +flutter::Settings FLTDefaultSettingsForBundle(NSBundle* bundle, NSProcessInfo* processInfoOrNil) { + auto command_line = flutter::CommandLineFromNSProcessInfo(processInfoOrNil); + + // Precedence: + // 1. Settings from the specified NSBundle. + // 2. Settings passed explicitly via command-line arguments. + // 3. Settings from the NSBundle with the default bundle ID. + // 4. Settings from the main NSBundle and default values. + + NSBundle* mainBundle = FLTGetApplicationBundle(); + NSBundle* engineBundle = [NSBundle bundleForClass:[FlutterDartProject class]]; + + bool hasExplicitBundle = bundle != nil; + if (bundle == nil) { + bundle = FLTFrameworkBundleWithIdentifier([FlutterDartProject defaultBundleIdentifier]); + } + + auto settings = flutter::SettingsFromCommandLine(command_line); + + settings.task_observer_add = [](intptr_t key, const fml::closure& callback) { + fml::MessageLoop::GetCurrent().AddTaskObserver(key, callback); + }; + + settings.task_observer_remove = [](intptr_t key) { + fml::MessageLoop::GetCurrent().RemoveTaskObserver(key); + }; + + settings.log_message_callback = [](const std::string& tag, const std::string& message) { + // TODO(cbracken): replace this with os_log-based approach. + // https://github.com/flutter/flutter/issues/44030 + std::stringstream stream; + if (!tag.empty()) { + stream << tag << ": "; + } + stream << message; + std::string log = stream.str(); + syslog(LOG_ALERT, "%.*s", (int)log.size(), log.c_str()); + }; + + settings.enable_platform_isolates = true; + + // The command line arguments may not always be complete. If they aren't, attempt to fill in + // defaults. + + // Flutter ships the ICU data file in the bundle of the engine. Look for it there. + if (settings.icu_data_path.empty()) { + NSString* icuDataPath = [engineBundle pathForResource:@"icudtl" ofType:@"dat"]; + if (icuDataPath.length > 0) { + settings.icu_data_path = icuDataPath.UTF8String; + } + } + + if (flutter::DartVM::IsRunningPrecompiledCode()) { + if (hasExplicitBundle) { + NSString* executablePath = bundle.executablePath; + if ([[NSFileManager defaultManager] fileExistsAtPath:executablePath]) { + settings.application_library_path.push_back(executablePath.UTF8String); + } + } + + // No application bundle specified. Try a known location from the main bundle's Info.plist. + if (settings.application_library_path.empty()) { + NSString* libraryName = [mainBundle objectForInfoDictionaryKey:@"FLTLibraryPath"]; + NSString* libraryPath = [mainBundle pathForResource:libraryName ofType:@""]; + if (libraryPath.length > 0) { + NSString* executablePath = [NSBundle bundleWithPath:libraryPath].executablePath; + if (executablePath.length > 0) { + settings.application_library_path.push_back(executablePath.UTF8String); + } + } + } + + // In case the application bundle is still not specified, look for the App.framework in the + // Frameworks directory. + if (settings.application_library_path.empty()) { + NSString* applicationFrameworkPath = [mainBundle pathForResource:@"Frameworks/App.framework" + ofType:@""]; + if (applicationFrameworkPath.length > 0) { + NSString* executablePath = + [NSBundle bundleWithPath:applicationFrameworkPath].executablePath; + if (executablePath.length > 0) { + settings.application_library_path.push_back(executablePath.UTF8String); + } + } + } + } + + // Checks to see if the flutter assets directory is already present. + if (settings.assets_path.empty()) { + NSString* assetsPath = FLTAssetsPathFromBundle(bundle); + + if (assetsPath.length == 0) { + NSLog(@"Failed to find assets path for \"%@\"", bundle); + } else { + settings.assets_path = assetsPath.UTF8String; + + // Check if there is an application kernel snapshot in the assets directory we could + // potentially use. Looking for the snapshot makes sense only if we have a VM that can use + // it. + if (!flutter::DartVM::IsRunningPrecompiledCode()) { + NSURL* applicationKernelSnapshotURL = + [NSURL URLWithString:@(kApplicationKernelSnapshotFileName) + relativeToURL:[NSURL fileURLWithPath:assetsPath]]; + NSError* error; + if ([applicationKernelSnapshotURL checkResourceIsReachableAndReturnError:&error]) { + settings.application_kernel_asset = applicationKernelSnapshotURL.path.UTF8String; + } else { + NSLog(@"Failed to find snapshot at %@: %@", applicationKernelSnapshotURL.path, error); + } + } + } + } + + // Domain network configuration + // Disabled in https://github.com/flutter/flutter/issues/72723. + // Re-enable in https://github.com/flutter/flutter/issues/54448. + settings.may_insecurely_connect_to_all_domains = true; + settings.domain_network_policy = ""; + + // Whether to enable wide gamut colors. +#if TARGET_OS_SIMULATOR + // As of Xcode 14.1, the wide gamut surface pixel formats are not supported by + // the simulator. + settings.enable_wide_gamut = false; + // Removes unused function warning. + (void)DoesHardwareSupportWideGamut; +#else + NSNumber* nsEnableWideGamut = [mainBundle objectForInfoDictionaryKey:@"FLTEnableWideGamut"]; + BOOL enableWideGamut = + (nsEnableWideGamut ? nsEnableWideGamut.boolValue : YES) && DoesHardwareSupportWideGamut(); + settings.enable_wide_gamut = enableWideGamut; +#endif + + NSNumber* nsAntialiasLines = [mainBundle objectForInfoDictionaryKey:@"FLTAntialiasLines"]; + settings.impeller_antialiased_lines = (nsAntialiasLines ? nsAntialiasLines.boolValue : NO); + + settings.warn_on_impeller_opt_out = true; + + NSNumber* enableTraceSystrace = [mainBundle objectForInfoDictionaryKey:@"FLTTraceSystrace"]; + // Change the default only if the option is present. + if (enableTraceSystrace != nil) { + settings.trace_systrace = enableTraceSystrace.boolValue; + } + + NSNumber* enableDartAsserts = [mainBundle objectForInfoDictionaryKey:@"FLTEnableDartAsserts"]; + if (enableDartAsserts != nil) { + settings.dart_flags.push_back("--enable-asserts"); + } + + NSNumber* enableDartProfiling = [mainBundle objectForInfoDictionaryKey:@"FLTEnableDartProfiling"]; + // Change the default only if the option is present. + if (enableDartProfiling != nil) { + settings.enable_dart_profiling = enableDartProfiling.boolValue; + } + + // Leak Dart VM settings, set whether leave or clean up the VM after the last shell shuts down. + NSNumber* leakDartVM = [mainBundle objectForInfoDictionaryKey:@"FLTLeakDartVM"]; + // It will change the default leak_vm value in settings only if the key exists. + if (leakDartVM != nil) { + settings.leak_vm = leakDartVM.boolValue; + } + + NSNumber* enableMergedPlatformUIThread = + [mainBundle objectForInfoDictionaryKey:@"FLTEnableMergedPlatformUIThread"]; + if (enableMergedPlatformUIThread != nil) { + settings.merged_platform_ui_thread = enableMergedPlatformUIThread.boolValue; + } + +#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG + // There are no ownership concerns here as all mappings are owned by the + // embedder and not the engine. + auto make_mapping_callback = [](const uint8_t* mapping, size_t size) { + return [mapping, size]() { return std::make_unique(mapping, size); }; + }; + + settings.dart_library_sources_kernel = + make_mapping_callback(kPlatformStrongDill, kPlatformStrongDillSize); +#endif // FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG + + // If we even support setting this e.g. from the command line or the plist, + // we should let the user override it. + // Otherwise, we want to set this to a value that will avoid having the OS + // kill us. On most iOS devices, that happens somewhere near half + // the available memory. + // The VM expects this value to be in megabytes. + if (settings.old_gen_heap_size <= 0) { + settings.old_gen_heap_size = std::round([NSProcessInfo processInfo].physicalMemory * .48 / + flutter::kMegaByteSizeInBytes); + } + + // This is the formula Android uses. + // https://android.googlesource.com/platform/frameworks/base/+/39ae5bac216757bc201490f4c7b8c0f63006c6cd/libs/hwui/renderthread/CacheManager.cpp#45 + CGFloat scale = [UIScreen mainScreen].scale; + CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width * scale; + CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height * scale; + settings.resource_cache_max_bytes_threshold = screenWidth * screenHeight * 12 * 4; + + // Whether to enable ios embedder api. + NSNumber* enable_embedder_api = + [mainBundle objectForInfoDictionaryKey:@"FLTEnableIOSEmbedderAPI"]; + // Change the default only if the option is present. + if (enable_embedder_api) { + settings.enable_embedder_api = enable_embedder_api.boolValue; + } + + return settings; +} + +@implementation FlutterDartProject { + flutter::Settings _settings; +} + +// This property is marked unavailable on iOS in the common header. +// That doesn't seem to be enough to prevent this property from being synthesized. +// Mark dynamic to avoid warnings. +@dynamic dartEntrypointArguments; + +#pragma mark - Override base class designated initializers + +- (instancetype)init { + return [self initWithPrecompiledDartBundle:nil]; +} + +#pragma mark - Designated initializers + +- (instancetype)initWithPrecompiledDartBundle:(nullable NSBundle*)bundle { + self = [super init]; + + if (self) { + _settings = FLTDefaultSettingsForBundle(bundle); + } + + return self; +} + +- (instancetype)initWithSettings:(const flutter::Settings&)settings { + self = [self initWithPrecompiledDartBundle:nil]; + + if (self) { + _settings = settings; + } + + return self; +} + +#pragma mark - PlatformData accessors + +- (const flutter::PlatformData)defaultPlatformData { + flutter::PlatformData PlatformData; + PlatformData.lifecycle_state = std::string("AppLifecycleState.detached"); + return PlatformData; +} + +#pragma mark - Settings accessors + +- (const flutter::Settings&)settings { + return _settings; +} + +- (flutter::RunConfiguration)runConfiguration { + return [self runConfigurationForEntrypoint:nil]; +} + +- (flutter::RunConfiguration)runConfigurationForEntrypoint:(nullable NSString*)entrypointOrNil { + return [self runConfigurationForEntrypoint:entrypointOrNil libraryOrNil:nil]; +} + +- (flutter::RunConfiguration)runConfigurationForEntrypoint:(nullable NSString*)entrypointOrNil + libraryOrNil:(nullable NSString*)dartLibraryOrNil { + return [self runConfigurationForEntrypoint:entrypointOrNil + libraryOrNil:dartLibraryOrNil + entrypointArgs:nil]; +} + +- (flutter::RunConfiguration)runConfigurationForEntrypoint:(nullable NSString*)entrypointOrNil + libraryOrNil:(nullable NSString*)dartLibraryOrNil + entrypointArgs: + (nullable NSArray*)entrypointArgs { + auto config = flutter::RunConfiguration::InferFromSettings(_settings); + if (dartLibraryOrNil && entrypointOrNil) { + config.SetEntrypointAndLibrary(std::string([entrypointOrNil UTF8String]), + std::string([dartLibraryOrNil UTF8String])); + + } else if (entrypointOrNil) { + config.SetEntrypoint(std::string([entrypointOrNil UTF8String])); + } + + if (entrypointArgs.count) { + std::vector cppEntrypointArgs; + for (NSString* arg in entrypointArgs) { + cppEntrypointArgs.push_back(std::string([arg UTF8String])); + } + config.SetEntrypointArgs(std::move(cppEntrypointArgs)); + } + + return config; +} + +#pragma mark - Assets-related utilities + ++ (NSString*)flutterAssetsName:(NSBundle*)bundle { + if (bundle == nil) { + bundle = FLTFrameworkBundleWithIdentifier([FlutterDartProject defaultBundleIdentifier]); + } + return FLTAssetPath(bundle); +} + ++ (NSString*)domainNetworkPolicy:(NSDictionary*)appTransportSecurity { + // https://developer.apple.com/documentation/bundleresources/information_property_list/nsapptransportsecurity/nsexceptiondomains + NSDictionary* exceptionDomains = appTransportSecurity[@"NSExceptionDomains"]; + if (exceptionDomains == nil) { + return @""; + } + NSMutableArray* networkConfigArray = [[NSMutableArray alloc] init]; + for (NSString* domain in exceptionDomains) { + NSDictionary* domainConfiguration = exceptionDomains[domain]; + // Default value is false. + bool includesSubDomains = [domainConfiguration[@"NSIncludesSubdomains"] boolValue]; + bool allowsCleartextCommunication = + [domainConfiguration[@"NSExceptionAllowsInsecureHTTPLoads"] boolValue]; + [networkConfigArray addObject:@[ + domain, includesSubDomains ? @YES : @NO, allowsCleartextCommunication ? @YES : @NO + ]]; + } + NSData* jsonData = [NSJSONSerialization dataWithJSONObject:networkConfigArray + options:0 + error:NULL]; + return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; +} + ++ (bool)allowsArbitraryLoads:(NSDictionary*)appTransportSecurity { + return [appTransportSecurity[@"NSAllowsArbitraryLoads"] boolValue]; +} + ++ (NSString*)lookupKeyForAsset:(NSString*)asset { + return [self lookupKeyForAsset:asset fromBundle:nil]; +} + ++ (NSString*)lookupKeyForAsset:(NSString*)asset fromBundle:(nullable NSBundle*)bundle { + NSString* flutterAssetsName = [FlutterDartProject flutterAssetsName:bundle]; + return [NSString stringWithFormat:@"%@/%@", flutterAssetsName, asset]; +} + ++ (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package { + return [self lookupKeyForAsset:asset fromPackage:package fromBundle:nil]; +} + ++ (NSString*)lookupKeyForAsset:(NSString*)asset + fromPackage:(NSString*)package + fromBundle:(nullable NSBundle*)bundle { + return [self lookupKeyForAsset:[NSString stringWithFormat:@"packages/%@/%@", package, asset] + fromBundle:bundle]; +} + ++ (NSString*)defaultBundleIdentifier { + return @"io.flutter.flutter.app"; +} + +- (BOOL)isWideGamutEnabled { + return _settings.enable_wide_gamut; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProjectTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProjectTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..414761f9ad8e796b9dc32aa247e1dcf1463848d1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProjectTest.mm @@ -0,0 +1,314 @@ +// 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. + +#import +#import + +#include "flutter/common/constants.h" +#include "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h" + +FLUTTER_ASSERT_ARC + +@interface FlutterDartProjectTest : XCTestCase +@end + +@implementation FlutterDartProjectTest + +- (void)setUp { +} + +- (void)tearDown { +} + +- (void)testOldGenHeapSizeSetting { + FlutterDartProject* project = [[FlutterDartProject alloc] init]; + int64_t old_gen_heap_size = + std::round([NSProcessInfo processInfo].physicalMemory * .48 / flutter::kMegaByteSizeInBytes); + XCTAssertEqual(project.settings.old_gen_heap_size, old_gen_heap_size); +} + +- (void)testResourceCacheMaxBytesThresholdSetting { + FlutterDartProject* project = [[FlutterDartProject alloc] init]; + CGFloat scale = [UIScreen mainScreen].scale; + CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width * scale; + CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height * scale; + size_t resource_cache_max_bytes_threshold = screenWidth * screenHeight * 12 * 4; + XCTAssertEqual(project.settings.resource_cache_max_bytes_threshold, + resource_cache_max_bytes_threshold); +} + +- (void)testMainBundleSettingsAreCorrectlyParsed { + NSBundle* mainBundle = [NSBundle mainBundle]; + NSDictionary* appTransportSecurity = + [mainBundle objectForInfoDictionaryKey:@"NSAppTransportSecurity"]; + XCTAssertTrue([FlutterDartProject allowsArbitraryLoads:appTransportSecurity]); + XCTAssertEqualObjects( + @"[[\"invalid-site.com\",true,false],[\"sub.invalid-site.com\",false,false]]", + [FlutterDartProject domainNetworkPolicy:appTransportSecurity]); +} + +- (void)testLeakDartVMSettingsAreCorrectlyParsed { + // The FLTLeakDartVM's value is defined in Info.plist + NSBundle* mainBundle = [NSBundle mainBundle]; + NSNumber* leakDartVM = [mainBundle objectForInfoDictionaryKey:@"FLTLeakDartVM"]; + XCTAssertEqual(leakDartVM.boolValue, NO); + + auto settings = FLTDefaultSettingsForBundle(); + // Check settings.leak_vm value is same as the value defined in Info.plist. + XCTAssertEqual(settings.leak_vm, NO); +} + +- (void)testFLTFrameworkBundleInternalWhenBundleIsNotPresent { + NSBundle* found = + FLTFrameworkBundleInternal(@"doesNotExist", NSBundle.mainBundle.privateFrameworksURL); + XCTAssertNil(found); +} + +- (void)testFLTFrameworkBundleInternalWhenBundleIsPresent { + NSString* presentBundleID = @"io.flutter.flutter"; + NSBundle* found = + FLTFrameworkBundleInternal(presentBundleID, NSBundle.mainBundle.privateFrameworksURL); + XCTAssertNotNil(found); +} + +- (void)testFLTGetApplicationBundleWhenCurrentTargetIsNotExtension { + NSBundle* bundle = FLTGetApplicationBundle(); + XCTAssertEqual(bundle, [NSBundle mainBundle]); +} + +- (void)testFLTGetApplicationBundleWhenCurrentTargetIsExtension { + id mockMainBundle = OCMPartialMock([NSBundle mainBundle]); + NSURL* url = [[NSBundle mainBundle].bundleURL URLByAppendingPathComponent:@"foo/ext.appex"]; + OCMStub([mockMainBundle bundleURL]).andReturn(url); + NSBundle* bundle = FLTGetApplicationBundle(); + [mockMainBundle stopMocking]; + XCTAssertEqualObjects(bundle.bundleURL, [NSBundle mainBundle].bundleURL); +} + +- (void)testFLTAssetsURLFromBundle { + { + // Found asset path in info.plist + id mockBundle = OCMClassMock([NSBundle class]); + OCMStub([mockBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(@"foo/assets"); + NSString* resultAssetsPath = @"path/to/foo/assets"; + OCMStub([mockBundle pathForResource:@"foo/assets" ofType:nil]).andReturn(resultAssetsPath); + NSString* path = FLTAssetsPathFromBundle(mockBundle); + XCTAssertEqualObjects(path, @"path/to/foo/assets"); + } + { + // Found asset path in info.plist, is not overriden by main bundle + id mockBundle = OCMClassMock([NSBundle class]); + id mockMainBundle = OCMPartialMock(NSBundle.mainBundle); + OCMStub([mockBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(@"foo/assets"); + OCMStub([mockMainBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(nil); + NSString* resultAssetsPath = @"path/to/foo/assets"; + OCMStub([mockBundle pathForResource:@"foo/assets" ofType:nil]).andReturn(resultAssetsPath); + NSString* path = FLTAssetsPathFromBundle(mockBundle); + XCTAssertEqualObjects(path, @"path/to/foo/assets"); + [mockMainBundle stopMocking]; + } + { + // No asset path in info.plist, defaults to main bundle + id mockBundle = OCMClassMock([NSBundle class]); + id mockMainBundle = OCMPartialMock([NSBundle mainBundle]); + NSString* resultAssetsPath = @"path/to/foo/assets"; + OCMStub([mockBundle pathForResource:@"Frameworks/App.framework/flutter_assets" ofType:nil]) + .andReturn(nil); + OCMStub([mockMainBundle pathForResource:@"Frameworks/App.framework/flutter_assets" ofType:nil]) + .andReturn(resultAssetsPath); + NSString* path = FLTAssetsPathFromBundle(mockBundle); + XCTAssertEqualObjects(path, @"path/to/foo/assets"); + [mockMainBundle stopMocking]; + } +} + +- (void)testFLTAssetPathReturnsTheCorrectValue { + { + // Found assets path in info.plist + id mockBundle = OCMClassMock([NSBundle class]); + OCMStub([mockBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(@"foo/assets"); + XCTAssertEqualObjects(FLTAssetPath(mockBundle), @"foo/assets"); + } + { + // No assets path in info.plist, use default value + id mockBundle = OCMClassMock([NSBundle class]); + OCMStub([mockBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(nil); + XCTAssertEqualObjects(FLTAssetPath(mockBundle), kDefaultAssetPath); + } +} + +- (void)testLookUpForAssets { + { + id mockBundle = OCMPartialMock([NSBundle mainBundle]); + // Found assets path in info.plist + OCMStub([mockBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(@"foo/assets"); + NSString* assetsPath = [FlutterDartProject lookupKeyForAsset:@"bar"]; + // This is testing public API, changing this assert is likely to break plugins. + XCTAssertEqualObjects(assetsPath, @"foo/assets/bar"); + [mockBundle stopMocking]; + } + { + id mockBundle = OCMPartialMock([NSBundle mainBundle]); + // No assets path in info.plist, use default value + OCMStub([mockBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(nil); + NSString* assetsPath = [FlutterDartProject lookupKeyForAsset:@"bar"]; + // This is testing public API, changing this assert is likely to break plugins. + XCTAssertEqualObjects(assetsPath, @"Frameworks/App.framework/flutter_assets/bar"); + [mockBundle stopMocking]; + } +} + +- (void)testLookUpForAssetsFromBundle { + { + id mockBundle = OCMClassMock([NSBundle class]); + // Found assets path in info.plist + OCMStub([mockBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(@"foo/assets"); + NSString* assetsPath = [FlutterDartProject lookupKeyForAsset:@"bar" fromBundle:mockBundle]; + // This is testing public API, changing this assert is likely to break plugins. + XCTAssertEqualObjects(assetsPath, @"foo/assets/bar"); + } + { + // No assets path in info.plist, use default value + id mockBundle = OCMClassMock([NSBundle class]); + OCMStub([mockBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(nil); + NSString* assetsPath = [FlutterDartProject lookupKeyForAsset:@"bar" fromBundle:mockBundle]; + // This is testing public API, changing this assert is likely to break plugins. + XCTAssertEqualObjects(assetsPath, @"Frameworks/App.framework/flutter_assets/bar"); + } +} + +- (void)testLookUpForAssetsFromPackage { + { + id mockBundle = OCMPartialMock([NSBundle mainBundle]); + // Found assets path in info.plist + OCMStub([mockBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(@"foo/assets"); + NSString* assetsPath = [FlutterDartProject lookupKeyForAsset:@"bar" fromPackage:@"bar_package"]; + // This is testing public API, changing this assert is likely to break plugins. + XCTAssertEqualObjects(assetsPath, @"foo/assets/packages/bar_package/bar"); + [mockBundle stopMocking]; + } + { + id mockBundle = OCMPartialMock([NSBundle mainBundle]); + // No assets path in info.plist, use default value + OCMStub([mockBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(nil); + NSString* assetsPath = [FlutterDartProject lookupKeyForAsset:@"bar" fromPackage:@"bar_package"]; + // This is testing public API, changing this assert is likely to break plugins. + XCTAssertEqualObjects(assetsPath, + @"Frameworks/App.framework/flutter_assets/packages/bar_package/bar"); + [mockBundle stopMocking]; + } +} + +- (void)testLookUpForAssetsFromPackageFromBundle { + { + id mockBundle = OCMClassMock([NSBundle class]); + // Found assets path in info.plist + OCMStub([mockBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(@"foo/assets"); + NSString* assetsPath = [FlutterDartProject lookupKeyForAsset:@"bar" + fromPackage:@"bar_package" + fromBundle:mockBundle]; + // This is testing public API, changing this assert is likely to break plugins. + XCTAssertEqualObjects(assetsPath, @"foo/assets/packages/bar_package/bar"); + } + { + id mockBundle = OCMClassMock([NSBundle class]); + // No assets path in info.plist, use default value + OCMStub([mockBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]).andReturn(nil); + NSString* assetsPath = [FlutterDartProject lookupKeyForAsset:@"bar" + fromPackage:@"bar_package" + fromBundle:mockBundle]; + // This is testing public API, changing this assert is likely to break plugins. + XCTAssertEqualObjects(assetsPath, + @"Frameworks/App.framework/flutter_assets/packages/bar_package/bar"); + } +} + +- (void)testEnableDartAssertsCommandLineArgument { + id mockMainBundle = OCMPartialMock([NSBundle mainBundle]); + OCMStub([mockMainBundle objectForInfoDictionaryKey:@"FLTEnableDartAsserts"]).andReturn(@"YES"); + id mockProcessInfo = OCMPartialMock([NSProcessInfo processInfo]); + NSArray* arguments = @[ @"process_name" ]; + OCMStub([mockProcessInfo arguments]).andReturn(arguments); + + auto settings = FLTDefaultSettingsForBundle(nil, mockProcessInfo); + + XCTAssertEqual(settings.dart_flags.size(), 1u); + XCTAssertEqual(settings.dart_flags[0], "--enable-asserts"); + [mockMainBundle stopMocking]; +} + +- (void)testEnableTraceSystraceSettingIsCorrectlyParsed { + NSBundle* mainBundle = [NSBundle mainBundle]; + NSNumber* enableTraceSystrace = [mainBundle objectForInfoDictionaryKey:@"FLTTraceSystrace"]; + XCTAssertNotNil(enableTraceSystrace); + XCTAssertEqual(enableTraceSystrace.boolValue, NO); + auto settings = FLTDefaultSettingsForBundle(); + XCTAssertEqual(settings.trace_systrace, NO); +} + +- (void)testEnableDartProflingSettingIsCorrectlyParsed { + NSBundle* mainBundle = [NSBundle mainBundle]; + NSNumber* enableTraceSystrace = [mainBundle objectForInfoDictionaryKey:@"FLTEnableDartProfiling"]; + XCTAssertNotNil(enableTraceSystrace); + XCTAssertEqual(enableTraceSystrace.boolValue, NO); + auto settings = FLTDefaultSettingsForBundle(); + XCTAssertEqual(settings.trace_systrace, NO); +} + +- (void)testEmptySettingsAreCorrect { + XCTAssertFalse([FlutterDartProject allowsArbitraryLoads:[[NSDictionary alloc] init]]); + XCTAssertEqualObjects(@"", [FlutterDartProject domainNetworkPolicy:[[NSDictionary alloc] init]]); +} + +- (void)testAllowsArbitraryLoads { + XCTAssertFalse([FlutterDartProject allowsArbitraryLoads:@{@"NSAllowsArbitraryLoads" : @false}]); + XCTAssertTrue([FlutterDartProject allowsArbitraryLoads:@{@"NSAllowsArbitraryLoads" : @true}]); +} + +- (void)testProperlyFormedExceptionDomains { + NSDictionary* domainInfoOne = @{ + @"NSIncludesSubdomains" : @false, + @"NSExceptionAllowsInsecureHTTPLoads" : @true, + @"NSExceptionMinimumTLSVersion" : @"4.0" + }; + NSDictionary* domainInfoTwo = @{ + @"NSIncludesSubdomains" : @true, + @"NSExceptionAllowsInsecureHTTPLoads" : @false, + @"NSExceptionMinimumTLSVersion" : @"4.0" + }; + NSDictionary* domainInfoThree = @{ + @"NSIncludesSubdomains" : @false, + @"NSExceptionAllowsInsecureHTTPLoads" : @true, + @"NSExceptionMinimumTLSVersion" : @"4.0" + }; + NSDictionary* exceptionDomains = @{ + @"domain.name" : domainInfoOne, + @"sub.domain.name" : domainInfoTwo, + @"sub.two.domain.name" : domainInfoThree + }; + NSDictionary* appTransportSecurity = @{@"NSExceptionDomains" : exceptionDomains}; + XCTAssertEqualObjects(@"[[\"domain.name\",false,true],[\"sub.domain.name\",true,false]," + @"[\"sub.two.domain.name\",false,true]]", + [FlutterDartProject domainNetworkPolicy:appTransportSecurity]); +} + +- (void)testExceptionDomainsWithMissingInfo { + NSDictionary* domainInfoOne = @{@"NSExceptionMinimumTLSVersion" : @"4.0"}; + NSDictionary* domainInfoTwo = @{ + @"NSIncludesSubdomains" : @true, + }; + NSDictionary* domainInfoThree = @{}; + NSDictionary* exceptionDomains = @{ + @"domain.name" : domainInfoOne, + @"sub.domain.name" : domainInfoTwo, + @"sub.two.domain.name" : domainInfoThree + }; + NSDictionary* appTransportSecurity = @{@"NSExceptionDomains" : exceptionDomains}; + XCTAssertEqualObjects(@"[[\"domain.name\",false,false],[\"sub.domain.name\",true,false]," + @"[\"sub.two.domain.name\",false,false]]", + [FlutterDartProject domainNetworkPolicy:appTransportSecurity]); +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h new file mode 100644 index 0000000000000000000000000000000000000000..7d3a3d8e5fd92ead6a2742462e2d0d6d06d180af --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h @@ -0,0 +1,47 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERDARTPROJECT_INTERNAL_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERDARTPROJECT_INTERNAL_H_ + +#include "flutter/common/settings.h" +#include "flutter/runtime/platform_data.h" +#include "flutter/shell/common/engine.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterDartProject.h" +#import "flutter/shell/platform/darwin/common/framework/Source/FlutterNSBundleUtils.h" + +NS_ASSUME_NONNULL_BEGIN + +flutter::Settings FLTDefaultSettingsForBundle(NSBundle* _Nullable bundle = nil, + NSProcessInfo* _Nullable processInfoOrNil = nil); + +@interface FlutterDartProject () + +@property(nonatomic, readonly) BOOL isWideGamutEnabled; + +/** + * This is currently used for *only for tests* to override settings. + */ +- (instancetype)initWithSettings:(const flutter::Settings&)settings; +- (const flutter::Settings&)settings; +- (const flutter::PlatformData)defaultPlatformData; + +- (flutter::RunConfiguration)runConfiguration; +- (flutter::RunConfiguration)runConfigurationForEntrypoint:(nullable NSString*)entrypointOrNil; +- (flutter::RunConfiguration)runConfigurationForEntrypoint:(nullable NSString*)entrypointOrNil + libraryOrNil:(nullable NSString*)dartLibraryOrNil; +- (flutter::RunConfiguration)runConfigurationForEntrypoint:(nullable NSString*)entrypointOrNil + libraryOrNil:(nullable NSString*)dartLibraryOrNil + entrypointArgs: + (nullable NSArray*)entrypointArgs; + ++ (NSString*)flutterAssetsName:(NSBundle*)bundle; ++ (NSString*)domainNetworkPolicy:(NSDictionary*)appTransportSecurity; ++ (bool)allowsArbitraryLoads:(NSDictionary*)appTransportSecurity; + +@end + +NS_ASSUME_NONNULL_END + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERDARTPROJECT_INTERNAL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartVMServicePublisher.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartVMServicePublisher.h new file mode 100644 index 0000000000000000000000000000000000000000..7870ef80791874a990e50779f69f38d7dc9e2cc5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartVMServicePublisher.h @@ -0,0 +1,21 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERDARTVMSERVICEPUBLISHER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERDARTVMSERVICEPUBLISHER_H_ + +#import + +@interface FlutterDartVMServicePublisher : NSObject + +- (instancetype)initWithEnableVMServicePublication:(BOOL)enableVMServicePublication + NS_DESIGNATED_INITIALIZER; +- (instancetype)init NS_UNAVAILABLE; ++ (instancetype)new NS_UNAVAILABLE; + +@property(nonatomic, readonly) NSURL* url; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERDARTVMSERVICEPUBLISHER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartVMServicePublisher.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartVMServicePublisher.mm new file mode 100644 index 0000000000000000000000000000000000000000..690d8c1936a7fd4d1168d22d0784d4f397a590fd --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartVMServicePublisher.mm @@ -0,0 +1,199 @@ +// 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. + +#define FML_USED_ON_EMBEDDER + +#import "FlutterDartVMServicePublisher.h" + +#if FLUTTER_RELEASE + +@implementation FlutterDartVMServicePublisher +- (instancetype)initWithEnableVMServicePublication:(BOOL)enableVMServicePublication { + return [super init]; +} +@end + +#else // FLUTTER_RELEASE + +#import +// NSNetService works fine on physical devices before iOS 13.2. +// However, it doesn't expose the services to regular mDNS +// queries on the Simulator or on iOS 13.2+ devices. +// +// When debugging issues with this implementation, the following is helpful: +// +// 1) Running `dns-sd -Z _dartVmService`. This is a built-in macOS tool that +// can find advertized observatories using this method. If dns-sd can't find +// it, then the VM service is not getting advertised over any network +// interface that the host machine has access to. +// 2) The Python zeroconf package. The dns-sd tool can sometimes see things +// that aren't advertizing over a network interface - for example, simulators +// using NSNetService has been observed using dns-sd, but doesn't show up in +// the Python package (which is a high quality socket based implementation). +// If that happens, this code should be tweaked such that it shows up in both +// dns-sd's output and Python zeroconf's detection. +// 3) The Dart multicast_dns package, which is what Flutter uses to find the +// port and auth code. If the advertizement shows up in dns-sd and Python +// zeroconf but not multicast_dns, then it is a bug in multicast_dns. +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/message_loop.h" +#include "flutter/runtime/dart_service_isolate.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" + +FLUTTER_ASSERT_ARC + +@protocol FlutterDartVMServicePublisherDelegate +- (void)publishServiceProtocolPort:(NSURL*)uri; +- (void)stopService; +@end + +@interface FlutterDartVMServicePublisher () ++ (NSData*)createTxtData:(NSURL*)url; + +@property(readonly, class) NSString* serviceName; +@property(readonly) NSObject* delegate; +@property(nonatomic, readwrite) NSURL* url; +@property(readonly) BOOL enableVMServicePublication; + +@end + +@interface DartVMServiceDNSServiceDelegate : NSObject +@end + +@implementation DartVMServiceDNSServiceDelegate { + DNSServiceRef _dnsServiceRef; +} + +- (void)stopService { + if (_dnsServiceRef) { + DNSServiceRefDeallocate(_dnsServiceRef); + _dnsServiceRef = NULL; + } +} + +- (void)publishServiceProtocolPort:(NSURL*)url { + // TODO(vashworth): Remove once done debugging https://github.com/flutter/flutter/issues/129836 + FML_LOG(INFO) << "Publish Service Protocol Port"; + DNSServiceFlags flags = kDNSServiceFlagsDefault; +#if TARGET_IPHONE_SIMULATOR + // Simulator needs to use local loopback explicitly to work. + uint32_t interfaceIndex = if_nametoindex("lo0"); +#else // TARGET_IPHONE_SIMULATOR + // Physical devices need to request all interfaces. + uint32_t interfaceIndex = 0; +#endif // TARGET_IPHONE_SIMULATOR + const char* registrationType = "_dartVmService._tcp"; + + const char* domain = "local."; // default domain + uint16_t port = [[url port] unsignedShortValue]; + + NSData* txtData = [FlutterDartVMServicePublisher createTxtData:url]; + int err = DNSServiceRegister(&_dnsServiceRef, flags, interfaceIndex, + FlutterDartVMServicePublisher.serviceName.UTF8String, + registrationType, domain, NULL, htons(port), txtData.length, + txtData.bytes, RegistrationCallback, NULL); + + if (err == 0) { + DNSServiceSetDispatchQueue(_dnsServiceRef, dispatch_get_main_queue()); + return; + } + + FML_LOG(ERROR) << "Failed to register Dart VM Service port with mDNS with error " << err << "."; + if (@available(iOS 14.0, *)) { + FML_LOG(ERROR) << "On iOS 14+, local network broadcast in apps need to be declared in " + << "the app's Info.plist. Debug and profile Flutter apps and modules host " + << "VM services on the local network to support debugging features such " + << "as hot reload and DevTools. To make your Flutter app or module " + << "attachable and debuggable, add a '" << registrationType << "' value " + << "to the 'NSBonjourServices' key in your Info.plist for the Debug/" + << "Profile configurations. " << "For more information, see " + << "https://flutter.dev/docs/development/add-to-app/ios/" + "project-setup#local-network-privacy-permissions"; + } +} + +static void DNSSD_API RegistrationCallback(DNSServiceRef sdRef, + DNSServiceFlags flags, + DNSServiceErrorType errorCode, + const char* name, + const char* regType, + const char* domain, + void* context) { + if (errorCode == kDNSServiceErr_NoError) { + FML_DLOG(INFO) << "FlutterDartVMServicePublisher is ready!"; + } else if (errorCode == kDNSServiceErr_PolicyDenied) { + FML_LOG(ERROR) + << "Could not register as server for FlutterDartVMServicePublisher, permission " + << "denied. Check your 'Local Network' permissions for this app in the Privacy section of " + << "the system Settings."; + } else { + FML_LOG(ERROR) << "Could not register as server for FlutterDartVMServicePublisher. Check your " + "network settings and relaunch the application."; + } +} + +@end + +@implementation FlutterDartVMServicePublisher { + flutter::DartServiceIsolate::CallbackHandle _callbackHandle; +} + +- (instancetype)initWithEnableVMServicePublication:(BOOL)enableVMServicePublication { + self = [super init]; + NSAssert(self, @"Super must not return null on init."); + + _delegate = [[DartVMServiceDNSServiceDelegate alloc] init]; + _enableVMServicePublication = enableVMServicePublication; + __weak __typeof(self) weakSelf = self; + + fml::MessageLoop::EnsureInitializedForCurrentThread(); + + _callbackHandle = flutter::DartServiceIsolate::AddServerStatusCallback( + [weakSelf, runner = fml::MessageLoop::GetCurrent().GetTaskRunner()](const std::string& uri) { + if (!uri.empty()) { + runner->PostTask([weakSelf, uri]() { + FlutterDartVMServicePublisher* strongSelf = weakSelf; + // uri comes in as something like 'http://127.0.0.1:XXXXX/' where XXXXX is the port + // number. + if (strongSelf) { + NSURL* url = + [[NSURL alloc] initWithString:[NSString stringWithUTF8String:uri.c_str()]]; + strongSelf.url = url; + if (strongSelf.enableVMServicePublication) { + [[strongSelf delegate] publishServiceProtocolPort:url]; + } + } + }); + } + }); + + return self; +} + ++ (NSString*)serviceName { + return NSBundle.mainBundle.bundleIdentifier; +} + ++ (NSData*)createTxtData:(NSURL*)url { + // Check to see if there's an authentication code. If there is, we'll provide + // it as a txt record so flutter tools can establish a connection. + NSString* path = [[url path] substringFromIndex:MIN(1, [[url path] length])]; + NSData* pathData = [path dataUsingEncoding:NSUTF8StringEncoding]; + NSDictionary* txtDict = @{ + @"authCode" : pathData, + }; + return [NSNetService dataFromTXTRecordDictionary:txtDict]; +} + +- (void)dealloc { + [_delegate stopService]; + + flutter::DartServiceIsolate::RemoveServerStatusCallback(_callbackHandle); +} +@end + +#endif // FLUTTER_RELEASE diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.h new file mode 100644 index 0000000000000000000000000000000000000000..4acc5572cf133a5f387ca7123516d29d704c58e9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.h @@ -0,0 +1,34 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTEREMBEDDERKEYRESPONDER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTEREMBEDDERKEYRESPONDER_H_ + +#import + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyPrimaryResponder.h" +#import "flutter/shell/platform/embedder/embedder.h" + +typedef void (^FlutterSendKeyEvent)(const FlutterKeyEvent& /* event */, + _Nullable FlutterKeyEventCallback /* callback */, + void* _Nullable /* user_data */); + +/** + * A primary responder of |FlutterKeyboardManager| that handles events by + * sending the converted events through a Dart hook to the framework. + * + * This class interfaces with the HardwareKeyboard API in the framework. + */ +@interface FlutterEmbedderKeyResponder : NSObject + +/** + * Create an instance by specifying the function to send converted events to. + * + * The |sendEvent| is typically |FlutterEngine|'s |sendKeyEvent|. + */ +- (nonnull instancetype)initWithSendEvent:(nonnull FlutterSendKeyEvent)sendEvent; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTEREMBEDDERKEYRESPONDER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.mm new file mode 100644 index 0000000000000000000000000000000000000000..7b057be4529ce489da4051b499410a93388cc2dd --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.mm @@ -0,0 +1,880 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.h" +#include + +#import +#include +#include "fml/memory/weak_ptr.h" + +#import "KeyCodeMap_Internal.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" + +FLUTTER_ASSERT_ARC + +namespace { + +/** + * Isolate the least significant 1-bit. + * + * For example, + * + * * lowestSetBit(0x1010) returns 0x10. + * * lowestSetBit(0) returns 0. + */ +static NSUInteger lowestSetBit(NSUInteger bitmask) { + // This utilizes property of two's complement (negation), which propagates a + // carry bit from LSB to the lowest set bit. + return bitmask & -bitmask; +} + +/** + * Whether a string represents a control character. + */ +static bool IsControlCharacter(NSUInteger length, NSString* label) { + if (length > 1) { + return false; + } + unichar codeUnit = [label characterAtIndex:0]; + return (codeUnit <= 0x1f && codeUnit >= 0x00) || (codeUnit >= 0x7f && codeUnit <= 0x9f); +} + +/** + * Whether a string represents an unprintable key. + */ +static bool IsUnprintableKey(NSUInteger length, NSString* label) { + if (length > 1) { + return false; + } + unichar codeUnit = [label characterAtIndex:0]; + return codeUnit >= 0xF700 && codeUnit <= 0xF8FF; +} + +/** + * Returns a key code composed with a base key and a plane. + * + * Examples of unprintable keys are "NSUpArrowFunctionKey = 0xF700" or + * "NSHomeFunctionKey = 0xF729". + * + * See + * https://developer.apple.com/documentation/appkit/1535851-function-key_unicodes?language=objc + * for more information. + */ +static uint64_t KeyOfPlane(uint64_t baseKey, uint64_t plane) { + return plane | (baseKey & kValueMask); +} + +/** + * Returns the physical key for a key code. + */ +static uint64_t GetPhysicalKeyForKeyCode(UInt32 keyCode) { + auto physicalKey = keyCodeToPhysicalKey.find(keyCode); + if (physicalKey == keyCodeToPhysicalKey.end()) { + return KeyOfPlane(keyCode, kIosPlane); + } + return physicalKey->second; +} + +/** + * Returns the logical key for a modifier physical key. + */ +static uint64_t GetLogicalKeyForModifier(UInt32 keyCode, uint64_t hidCode) { + auto fromKeyCode = keyCodeToLogicalKey.find(keyCode); + if (fromKeyCode != keyCodeToLogicalKey.end()) { + return fromKeyCode->second; + } + return KeyOfPlane(hidCode, kIosPlane); +} + +/** + * Converts upper letters to lower letters in ASCII and extended ASCII, and + * returns as-is otherwise. + * + * Independent of locale. + */ +static uint64_t toLower(uint64_t n) { + constexpr uint64_t lower_a = 0x61; + constexpr uint64_t upper_a = 0x41; + constexpr uint64_t upper_z = 0x5a; + + constexpr uint64_t lower_a_grave = 0xe0; + constexpr uint64_t upper_a_grave = 0xc0; + constexpr uint64_t upper_thorn = 0xde; + constexpr uint64_t division = 0xf7; + + // ASCII range. + if (n >= upper_a && n <= upper_z) { + return n - upper_a + lower_a; + } + + // EASCII range. + if (n >= upper_a_grave && n <= upper_thorn && n != division) { + return n - upper_a_grave + lower_a_grave; + } + + return n; +} + +/** + * Filters out some special cases in the characters field on UIKey. + */ +static const char* getEventCharacters(NSString* characters, UIKeyboardHIDUsage keyCode) + API_AVAILABLE(ios(13.4)) { + if (characters == nil) { + return nullptr; + } + if ([characters length] == 0) { + return nullptr; + } + if (@available(iOS 13.4, *)) { + // On iOS, function keys return the UTF8 string "\^P" (with a literal '/', + // '^' and a 'P', not escaped ctrl-P) as their "characters" field. This + // isn't a valid (single) UTF8 character. Looking at the only UTF16 + // character for a function key yields a value of "16", which is a Unicode + // "SHIFT IN" character, which is just odd. UTF8 conversion of that string + // is what generates the three characters "\^P". + // + // Anyhow, we strip them all out and replace them with empty strings, since + // function keys shouldn't be printable. + if (functionKeyCodes.find(keyCode) != functionKeyCodes.end()) { + return nullptr; + } + } + return [characters UTF8String]; +} + +/** + * Returns the logical key of a KeyUp or KeyDown event. + * + * The `maybeSpecialKey` is a nullable integer, and if not nil, indicates + * that the event key is a special key as defined by `specialKeyMapping`, + * and is the corresponding logical key. + * + * For modifier keys, use GetLogicalKeyForModifier. + */ +static uint64_t GetLogicalKeyForEvent(FlutterUIPressProxy* press, NSNumber* maybeSpecialKey) + API_AVAILABLE(ios(13.4)) { + if (maybeSpecialKey != nil) { + return [maybeSpecialKey unsignedLongLongValue]; + } + // Look to see if the keyCode can be mapped from keycode. + auto fromKeyCode = keyCodeToLogicalKey.find(press.key.keyCode); + if (fromKeyCode != keyCodeToLogicalKey.end()) { + return fromKeyCode->second; + } + const char* characters = + getEventCharacters(press.key.charactersIgnoringModifiers, press.key.keyCode); + NSString* keyLabel = + characters == nullptr ? nil : [[NSString alloc] initWithUTF8String:characters]; + NSUInteger keyLabelLength = [keyLabel length]; + // If this key is printable, generate the logical key from its Unicode + // value. Control keys such as ESC, CTRL, and SHIFT are not printable. HOME, + // DEL, arrow keys, and function keys are considered modifier function keys, + // which generate invalid Unicode scalar values. + if (keyLabelLength != 0 && !IsControlCharacter(keyLabelLength, keyLabel) && + !IsUnprintableKey(keyLabelLength, keyLabel)) { + // Given that charactersIgnoringModifiers can contain a string of arbitrary + // length, limit to a maximum of two Unicode scalar values. It is unlikely + // that a keyboard would produce a code point bigger than 32 bits, but it is + // still worth defending against this case. + NSCAssert((keyLabelLength < 2), @"Unexpected long key label: |%@|.", keyLabel); + + uint64_t codeUnit = (uint64_t)[keyLabel characterAtIndex:0]; + if (keyLabelLength == 2) { + uint64_t secondCode = (uint64_t)[keyLabel characterAtIndex:1]; + codeUnit = (codeUnit << 16) | secondCode; + } + return KeyOfPlane(toLower(codeUnit), kUnicodePlane); + } + + // This is a non-printable key that is unrecognized, so a new code is minted + // with the autogenerated bit set. + return KeyOfPlane(press.key.keyCode, kIosPlane); +} + +/** + * Converts NSEvent.timestamp to the timestamp for Flutter. + */ +static double GetFlutterTimestampFrom(NSTimeInterval timestamp) { + // Timestamp in microseconds. The event.timestamp is in seconds with sub-ms precision. + return timestamp * 1000000.0; +} + +/** + * Compute |modifierFlagOfInterestMask| out of |keyCodeToModifierFlag|. + * + * This is equal to the bitwise-or of all values of |keyCodeToModifierFlag|. + */ +static NSUInteger computeModifierFlagOfInterestMask() { + NSUInteger modifierFlagOfInterestMask = kModifierFlagCapsLock | kModifierFlagShiftAny | + kModifierFlagControlAny | kModifierFlagAltAny | + kModifierFlagMetaAny; + for (std::pair entry : keyCodeToModifierFlag) { + modifierFlagOfInterestMask = modifierFlagOfInterestMask | entry.second; + } + return modifierFlagOfInterestMask; +} + +static bool isKeyDown(FlutterUIPressProxy* press) API_AVAILABLE(ios(13.4)) { + switch (press.phase) { + case UIPressPhaseStationary: + case UIPressPhaseChanged: + // Not sure if this is the right thing to do for these two, but true seems + // more correct than false. + return true; + case UIPressPhaseBegan: + return true; + case UIPressPhaseCancelled: + case UIPressPhaseEnded: + return false; + } + return false; +} + +/** + * The C-function sent to the engine's |sendKeyEvent|, wrapping + * |FlutterEmbedderKeyResponder.handleResponse|. + * + * For the reason of this wrap, see |FlutterKeyPendingResponse|. + */ +void HandleResponse(bool handled, void* user_data); +} // namespace + +/** + * The invocation context for |HandleResponse|, wrapping + * |FlutterEmbedderKeyResponder.handleResponse|. + * + * The key responder's functions only accept C-functions as callbacks, as well + * as arbitrary user_data. In order to send an instance method of + * |FlutterEmbedderKeyResponder.handleResponse| to the engine's |SendKeyEvent|, + * we wrap the invocation into a C-function |HandleResponse| and invocation + * context |FlutterKeyPendingResponse|. + */ +@interface FlutterKeyPendingResponse : NSObject + +@property(readonly, weak) FlutterEmbedderKeyResponder* responder; + +@property(nonatomic) uint64_t responseId; + +- (nonnull instancetype)initWithHandler:(nonnull FlutterEmbedderKeyResponder*)responder + responseId:(uint64_t)responseId; + +@end + +@implementation FlutterKeyPendingResponse +- (instancetype)initWithHandler:(FlutterEmbedderKeyResponder*)responder + responseId:(uint64_t)responseId { + self = [super init]; + if (self != nil) { + _responder = responder; + _responseId = responseId; + } + return self; +} +@end + +/** + * Guards a |FlutterAsyncKeyCallback| to make sure it's handled exactly once + * throughout the process of handling an event in |FlutterEmbedderKeyResponder|. + * + * A callback can either be handled with |pendTo:withId:|, or with |resolveTo:|. + * Either way, the callback cannot be handled again, or an assertion will be + * thrown. + */ +@interface FlutterKeyCallbackGuard : NSObject +- (nonnull instancetype)initWithCallback:(FlutterAsyncKeyCallback)callback; + +/** + * Handle the callback by storing it to pending responses. + */ +- (void)pendTo:(nonnull NSMutableDictionary*)pendingResponses + withId:(uint64_t)responseId; + +/** + * Handle the callback by calling it with a result. + */ +- (void)resolveTo:(BOOL)handled; + +@property(nonatomic) BOOL handled; +/** + * A string indicating how the callback is handled. + * + * Only set in debug mode. Nil in release mode, or if the callback has not been + * handled. + */ +@property(readonly, copy) NSString* debugHandleSource; +@end + +@implementation FlutterKeyCallbackGuard { + // The callback is declared in the implementation block to avoid being + // accessed directly. + FlutterAsyncKeyCallback _callback; +} +- (nonnull instancetype)initWithCallback:(FlutterAsyncKeyCallback)callback { + self = [super init]; + if (self != nil) { + _callback = [callback copy]; + _handled = FALSE; + } + return self; +} + +- (void)pendTo:(nonnull NSMutableDictionary*)pendingResponses + withId:(uint64_t)responseId { + NSAssert(!_handled, @"This callback has been handled by %@.", _debugHandleSource); + if (_handled) { + return; + } + pendingResponses[@(responseId)] = _callback; + _handled = TRUE; + NSAssert( + ((_debugHandleSource = [NSString stringWithFormat:@"pending event %llu", responseId]), TRUE), + @""); +} + +- (void)resolveTo:(BOOL)handled { + NSAssert(!_handled, @"This callback has been handled by %@.", _debugHandleSource); + if (_handled) { + return; + } + _callback(handled); + _handled = TRUE; + NSAssert(((_debugHandleSource = [NSString stringWithFormat:@"resolved with %d", _handled]), TRUE), + @""); +} +@end + +@interface FlutterEmbedderKeyResponder () + +/** + * The function to send converted events to. + * + * Set by the initializer. + */ +@property(nonatomic, copy, readonly) FlutterSendKeyEvent sendEvent; + +/** + * A map of pressed keys. + * + * The keys of the dictionary are physical keys, while the values are the logical keys + * of the key down event. + */ +@property(nonatomic, copy, readonly) NSMutableDictionary* pressingRecords; + +/** + * A constant mask for NSEvent.modifierFlags that Flutter synchronizes with. + * + * Flutter keeps track of the last |modifierFlags| and compares it with the + * incoming one. Any bit within |modifierFlagOfInterestMask| that is different + * (except for the one that corresponds to the event key) indicates that an + * event for this modifier was missed, and Flutter synthesizes an event to make + * up for the state difference. + * + * It is computed by computeModifierFlagOfInterestMask. + */ +@property(nonatomic) NSUInteger modifierFlagOfInterestMask; + +/** + * The modifier flags of the last received key event, excluding uninterested + * bits. + * + * This should be kept synchronized with the last |NSEvent.modifierFlags| + * after masking with |modifierFlagOfInterestMask|. This should also be kept + * synchronized with the corresponding keys of |pressingRecords|. + * + * This is used by |synchronizeModifiers| to quickly find out modifier keys that + * are desynchronized. + */ +@property(nonatomic) NSUInteger lastModifierFlagsOfInterest; + +/** + * A self-incrementing ID used to label key events sent to the framework. + */ +@property(nonatomic) uint64_t responseId; + +/** + * A map of unresponded key events sent to the framework. + * + * Its values are |responseId|s, and keys are the callback that was received + * along with the event. + */ +@property(nonatomic, copy, readonly) + NSMutableDictionary* pendingResponses; + +/** + * Compare the last modifier flags and the current, and dispatch synthesized + * key events for each different modifier flag bit. + * + * The flags compared are all flags after masking with + * |modifierFlagOfInterestMask| and excluding |ignoringFlags|. + */ +- (void)synchronizeModifiers:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)); + +/** + * Update the pressing state. + * + * If `logicalKey` is not 0, `physicalKey` is pressed as `logicalKey`. + * Otherwise, `physicalKey` is released. + */ +- (void)updateKey:(uint64_t)physicalKey asPressed:(uint64_t)logicalKey; + +/** + * Synthesize a CapsLock down event, then a CapsLock up event. + */ +- (void)synthesizeCapsLockTapWithTimestamp:(NSTimeInterval)timestamp; + +/** + * Send an event to the framework, expecting its response. + */ +- (void)sendPrimaryFlutterEvent:(const FlutterKeyEvent&)event + callback:(nonnull FlutterKeyCallbackGuard*)callback; + +/** + * Send an empty key event. + * + * The event is never synthesized, and never expects an event result. An empty + * event is sent when no other events should be sent, such as upon back-to-back + * keydown events of the same key. + */ +- (void)sendEmptyEvent; + +/** + * Send a key event for a modifier key. + */ +- (void)synthesizeModifierEventOfType:(BOOL)isDownEvent + timestamp:(NSTimeInterval)timestamp + keyCode:(UInt32)keyCode; + +/** + * Processes a down event from the system. + */ +- (void)handlePressBegin:(nonnull FlutterUIPressProxy*)press + callback:(nonnull FlutterKeyCallbackGuard*)callback API_AVAILABLE(ios(13.4)); + +/** + * Processes an up event from the system. + */ +- (void)handlePressEnd:(nonnull FlutterUIPressProxy*)press + callback:(nonnull FlutterKeyCallbackGuard*)callback API_AVAILABLE(ios(13.4)); + +/** + * Processes the response from the framework. + */ +- (void)handleResponse:(BOOL)handled forId:(uint64_t)responseId; + +/** + * Fix up the modifiers for a particular type of modifier key. + */ +- (UInt32)fixSidedFlags:(ModifierFlag)anyFlag + withLeftFlag:(ModifierFlag)leftSide + withRightFlag:(ModifierFlag)rightSide + withLeftKey:(UInt16)leftKeyCode + withRightKey:(UInt16)rightKeyCode + withKeyCode:(UInt16)keyCode + keyDown:(BOOL)isKeyDown + forFlags:(UInt32)modifiersPressed API_AVAILABLE(ios(13.4)); + +/** + * Because iOS differs from other platforms in that the modifier flags still + * contain the flag for the key that is being released on the keyup event, we + * adjust the modifiers when the released key is a matching modifier key. + */ +- (UInt32)adjustModifiers:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)); +@end + +@implementation FlutterEmbedderKeyResponder + +- (nonnull instancetype)initWithSendEvent:(FlutterSendKeyEvent)sendEvent { + self = [super init]; + if (self != nil) { + _sendEvent = [sendEvent copy]; + _pressingRecords = [[NSMutableDictionary alloc] init]; + _pendingResponses = [[NSMutableDictionary alloc] init]; + _responseId = 1; + _lastModifierFlagsOfInterest = 0; + _modifierFlagOfInterestMask = computeModifierFlagOfInterestMask(); + } + return self; +} + +- (void)handlePress:(nonnull FlutterUIPressProxy*)press + callback:(FlutterAsyncKeyCallback)callback API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + } else { + return; + } + // The conversion algorithm relies on a non-nil callback to properly compute + // `synthesized`. + NSAssert(callback != nil, @"The callback must not be nil."); + + FlutterKeyCallbackGuard* guardedCallback = nil; + switch (press.phase) { + case UIPressPhaseBegan: + guardedCallback = [[FlutterKeyCallbackGuard alloc] initWithCallback:callback]; + [self handlePressBegin:press callback:guardedCallback]; + break; + case UIPressPhaseEnded: + guardedCallback = [[FlutterKeyCallbackGuard alloc] initWithCallback:callback]; + [self handlePressEnd:press callback:guardedCallback]; + break; + case UIPressPhaseChanged: + case UIPressPhaseCancelled: + // TODO(gspencergoog): Handle cancelled events as synthesized up events. + case UIPressPhaseStationary: + NSAssert(false, @"Unexpected press phase receieved in handlePress"); + return; + } + NSAssert(guardedCallback.handled, @"The callback returned without being handled."); + NSAssert( + (_lastModifierFlagsOfInterest & ~kModifierFlagCapsLock) == + ([self adjustModifiers:press] & (_modifierFlagOfInterestMask & ~kModifierFlagCapsLock)), + @"The modifier flags are not properly updated: recorded 0x%lx, event with mask 0x%lx", + static_cast(_lastModifierFlagsOfInterest & ~kModifierFlagCapsLock), + static_cast([self adjustModifiers:press] & + (_modifierFlagOfInterestMask & ~kModifierFlagCapsLock))); +} + +#pragma mark - Private + +- (void)synchronizeModifiers:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + } else { + return; + } + + const UInt32 lastFlagsOfInterest = _lastModifierFlagsOfInterest & _modifierFlagOfInterestMask; + const UInt32 pressedModifiers = [self adjustModifiers:press]; + const UInt32 currentFlagsOfInterest = pressedModifiers & _modifierFlagOfInterestMask; + UInt32 flagDifference = currentFlagsOfInterest ^ lastFlagsOfInterest; + if (flagDifference & kModifierFlagCapsLock) { + // If the caps lock changed, and we didn't expect that, then send a + // synthesized down and an up to simulate a toggle of the state. + if (press.key.keyCode != UIKeyboardHIDUsageKeyboardCapsLock) { + [self synthesizeCapsLockTapWithTimestamp:press.timestamp]; + } + flagDifference &= ~kModifierFlagCapsLock; + } + while (true) { + const UInt32 currentFlag = lowestSetBit(flagDifference); + if (currentFlag == 0) { + break; + } + flagDifference &= ~currentFlag; + if (currentFlag & kModifierFlagAnyMask) { + // Skip synthesizing keys for the "any" flags, since their synthesis will + // be handled when we do the sided flags. We still want them in the flags + // of interest, though, so we can keep their state. + continue; + } + auto keyCode = modifierFlagToKeyCode.find(static_cast(currentFlag)); + NSAssert(keyCode != modifierFlagToKeyCode.end(), @"Invalid modifier flag of interest 0x%lx", + static_cast(currentFlag)); + if (keyCode == modifierFlagToKeyCode.end()) { + continue; + } + // If this press matches the modifier key in question, then don't synthesize + // it, because it's already a "real" keypress. + if (keyCode->second == static_cast(press.key.keyCode)) { + continue; + } + BOOL isDownEvent = currentFlagsOfInterest & currentFlag; + [self synthesizeModifierEventOfType:isDownEvent + timestamp:press.timestamp + keyCode:keyCode->second]; + } + _lastModifierFlagsOfInterest = + (_lastModifierFlagsOfInterest & ~_modifierFlagOfInterestMask) | currentFlagsOfInterest; +} + +- (void)synthesizeCapsLockTapWithTimestamp:(NSTimeInterval)timestamp { + // The assumption when the app starts is that caps lock is off, but if that + // turns out to be untrue (according to the modifier flags), then this is used + // to simulate a key down and a key up of the caps lock key, to simulate + // toggling of that state in the framework. + FlutterKeyEvent flutterEvent = { + .struct_size = sizeof(FlutterKeyEvent), + .timestamp = GetFlutterTimestampFrom(timestamp), + .type = kFlutterKeyEventTypeDown, + .physical = kCapsLockPhysicalKey, + .logical = kCapsLockLogicalKey, + .character = nil, + .synthesized = true, + .device_type = kFlutterKeyEventDeviceTypeKeyboard, + }; + _sendEvent(flutterEvent, nullptr, nullptr); + + flutterEvent.type = kFlutterKeyEventTypeUp; + _sendEvent(flutterEvent, nullptr, nullptr); +} + +- (void)updateKey:(uint64_t)physicalKey asPressed:(uint64_t)logicalKey { + if (logicalKey == 0) { + [_pressingRecords removeObjectForKey:@(physicalKey)]; + } else { + _pressingRecords[@(physicalKey)] = @(logicalKey); + } +} + +- (void)sendPrimaryFlutterEvent:(const FlutterKeyEvent&)event + callback:(FlutterKeyCallbackGuard*)callback { + _responseId += 1; + uint64_t responseId = _responseId; + FlutterKeyPendingResponse* pending = + [[FlutterKeyPendingResponse alloc] initWithHandler:self responseId:responseId]; + [callback pendTo:_pendingResponses withId:responseId]; + _sendEvent(event, HandleResponse, (__bridge_retained void* _Nullable)pending); +} + +- (void)sendEmptyEvent { + FlutterKeyEvent event = { + .struct_size = sizeof(FlutterKeyEvent), + .timestamp = 0, + .type = kFlutterKeyEventTypeDown, + .physical = 0, + .logical = 0, + .character = nil, + .synthesized = false, + .device_type = kFlutterKeyEventDeviceTypeKeyboard, + }; + _sendEvent(event, nil, nil); +} + +- (void)synthesizeModifierEventOfType:(BOOL)isDownEvent + timestamp:(NSTimeInterval)timestamp + keyCode:(UInt32)keyCode { + uint64_t physicalKey = GetPhysicalKeyForKeyCode(keyCode); + uint64_t logicalKey = GetLogicalKeyForModifier(keyCode, physicalKey); + if (physicalKey == 0 || logicalKey == 0) { + return; + } + FlutterKeyEvent flutterEvent = { + .struct_size = sizeof(FlutterKeyEvent), + .timestamp = GetFlutterTimestampFrom(timestamp), + .type = isDownEvent ? kFlutterKeyEventTypeDown : kFlutterKeyEventTypeUp, + .physical = physicalKey, + .logical = logicalKey, + .character = nil, + .synthesized = true, + .device_type = kFlutterKeyEventDeviceTypeKeyboard, + }; + [self updateKey:physicalKey asPressed:isDownEvent ? logicalKey : 0]; + _sendEvent(flutterEvent, nullptr, nullptr); +} + +- (void)handlePressBegin:(nonnull FlutterUIPressProxy*)press + callback:(nonnull FlutterKeyCallbackGuard*)callback API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + } else { + return; + } + uint64_t physicalKey = GetPhysicalKeyForKeyCode(press.key.keyCode); + // Some unprintable keys on iOS have literal names on their key label, such as + // @"UIKeyInputEscape". They are called the "special keys" and have predefined + // logical keys and empty characters. + NSNumber* specialKey = [specialKeyMapping objectForKey:press.key.charactersIgnoringModifiers]; + uint64_t logicalKey = GetLogicalKeyForEvent(press, specialKey); + [self synchronizeModifiers:press]; + + NSNumber* pressedLogicalKey = nil; + if ([_pressingRecords count] > 0) { + pressedLogicalKey = _pressingRecords[@(physicalKey)]; + if (pressedLogicalKey != nil) { + // Normally the key up events won't be missed since iOS always sends the + // key up event to the view where the corresponding key down occurred. + // However this might happen in add-to-app scenarios if the focus is changed + // from the native view to the Flutter view amid the key tap. + [callback resolveTo:TRUE]; + [self sendEmptyEvent]; + return; + } + } + + if (pressedLogicalKey == nil) { + [self updateKey:physicalKey asPressed:logicalKey]; + } + + FlutterKeyEvent flutterEvent = { + .struct_size = sizeof(FlutterKeyEvent), + .timestamp = GetFlutterTimestampFrom(press.timestamp), + .type = kFlutterKeyEventTypeDown, + .physical = physicalKey, + .logical = pressedLogicalKey == nil ? logicalKey : [pressedLogicalKey unsignedLongLongValue], + .character = + specialKey != nil ? nil : getEventCharacters(press.key.characters, press.key.keyCode), + .synthesized = false, + .device_type = kFlutterKeyEventDeviceTypeKeyboard, + }; + [self sendPrimaryFlutterEvent:flutterEvent callback:callback]; +} + +- (void)handlePressEnd:(nonnull FlutterUIPressProxy*)press + callback:(nonnull FlutterKeyCallbackGuard*)callback API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + } else { + return; + } + [self synchronizeModifiers:press]; + + uint64_t physicalKey = GetPhysicalKeyForKeyCode(press.key.keyCode); + NSNumber* pressedLogicalKey = _pressingRecords[@(physicalKey)]; + if (pressedLogicalKey == nil) { + // Normally the key up events won't be missed since iOS always sends the + // key up event to the view where the corresponding key down occurred. + // However this might happen in add-to-app scenarios if the focus is changed + // from the native view to the Flutter view amid the key tap. + [callback resolveTo:TRUE]; + [self sendEmptyEvent]; + return; + } + [self updateKey:physicalKey asPressed:0]; + + FlutterKeyEvent flutterEvent = { + .struct_size = sizeof(FlutterKeyEvent), + .timestamp = GetFlutterTimestampFrom(press.timestamp), + .type = kFlutterKeyEventTypeUp, + .physical = physicalKey, + .logical = [pressedLogicalKey unsignedLongLongValue], + .character = nil, + .synthesized = false, + .device_type = kFlutterKeyEventDeviceTypeKeyboard, + }; + [self sendPrimaryFlutterEvent:flutterEvent callback:callback]; +} + +- (void)handleResponse:(BOOL)handled forId:(uint64_t)responseId { + FlutterAsyncKeyCallback callback = _pendingResponses[@(responseId)]; + callback(handled); + [_pendingResponses removeObjectForKey:@(responseId)]; +} + +- (UInt32)fixSidedFlags:(ModifierFlag)anyFlag + withLeftFlag:(ModifierFlag)leftSide + withRightFlag:(ModifierFlag)rightSide + withLeftKey:(UInt16)leftKeyCode + withRightKey:(UInt16)rightKeyCode + withKeyCode:(UInt16)keyCode + keyDown:(BOOL)isKeyDown + forFlags:(UInt32)modifiersPressed API_AVAILABLE(ios(13.4)) { + UInt32 newModifiers = modifiersPressed; + if (isKeyDown) { + // Add in the modifier flags that correspond to this key code, if any. + if (keyCode == leftKeyCode) { + newModifiers |= leftSide | anyFlag; + } else if (keyCode == rightKeyCode) { + newModifiers |= rightSide | anyFlag; + } + } else { + // If this is a key up, then remove any modifier that matches the keycode in + // the event from the flags, and the anyFlag if the other side isn't also + // pressed. + if (keyCode == leftKeyCode) { + newModifiers &= ~leftSide; + if (!(newModifiers & rightSide)) { + newModifiers &= ~anyFlag; + } + } else if (keyCode == rightKeyCode) { + newModifiers &= ~rightSide; + if (!(newModifiers & leftSide)) { + newModifiers &= ~anyFlag; + } + } + } + + if (!(newModifiers & anyFlag)) { + // Turn off any sided flags, since the "any" flag is gone. + newModifiers &= ~(leftSide | rightSide); + } + + return newModifiers; +} + +// This fixes a few cases where iOS provides modifier flags differently from how +// the framework would like to receive them. +// +// 1) iOS turns off the flag associated with a modifier key AFTER the modifier +// key up event, so when the key up event arrives, the flags must be modified +// before synchronizing so they do not include the modifier that arrived in +// the key up event. +// 2) Modifier flags can be set even when that modifier is not being pressed. +// One example of this is when a special character is produced with the Alt +// (Option) key, and the Alt key is released before the letter key: the +// letter key's key up event still contains the Alt key flag. +// 3) iOS doesn't provide information about which side modifier was pressed, +// except through the keycode of the pressed key, so we look at the pressed +// key code to decide which side to indicate in the flags. If we can't know +// (in the case of a non-modifier key event having an "any" modifier set, but +// we don't know already that the modifier is down), then we just pick the +// left one arbitrarily. +- (UInt32)adjustModifiers:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + // no-op + } else { + return press.key.modifierFlags; + } + + bool keyDown = isKeyDown(press); + + // Start with the current modifier flags, along with any sided flags that we + // already know are down. + UInt32 pressedModifiers = + press.key.modifierFlags | (_lastModifierFlagsOfInterest & kModifierFlagSidedMask); + + pressedModifiers = [self fixSidedFlags:kModifierFlagShiftAny + withLeftFlag:kModifierFlagShiftLeft + withRightFlag:kModifierFlagShiftRight + withLeftKey:UIKeyboardHIDUsageKeyboardLeftShift + withRightKey:UIKeyboardHIDUsageKeyboardRightShift + withKeyCode:press.key.keyCode + keyDown:keyDown + forFlags:pressedModifiers]; + pressedModifiers = [self fixSidedFlags:kModifierFlagControlAny + withLeftFlag:kModifierFlagControlLeft + withRightFlag:kModifierFlagControlRight + withLeftKey:UIKeyboardHIDUsageKeyboardLeftControl + withRightKey:UIKeyboardHIDUsageKeyboardRightControl + withKeyCode:press.key.keyCode + keyDown:keyDown + forFlags:pressedModifiers]; + pressedModifiers = [self fixSidedFlags:kModifierFlagAltAny + withLeftFlag:kModifierFlagAltLeft + withRightFlag:kModifierFlagAltRight + withLeftKey:UIKeyboardHIDUsageKeyboardLeftAlt + withRightKey:UIKeyboardHIDUsageKeyboardRightAlt + withKeyCode:press.key.keyCode + keyDown:keyDown + forFlags:pressedModifiers]; + pressedModifiers = [self fixSidedFlags:kModifierFlagMetaAny + withLeftFlag:kModifierFlagMetaLeft + withRightFlag:kModifierFlagMetaRight + withLeftKey:UIKeyboardHIDUsageKeyboardLeftGUI + withRightKey:UIKeyboardHIDUsageKeyboardRightGUI + withKeyCode:press.key.keyCode + keyDown:keyDown + forFlags:pressedModifiers]; + + if (press.key.keyCode == UIKeyboardHIDUsageKeyboardCapsLock) { + // The caps lock modifier needs to be unset only if it was already on + // and this is a key up. This is because it indicates the lock state, and + // not the key press state. The caps lock state should be on between the + // first down, and the second up (i.e. while the lock in effect), and + // this code turns it off at the second up event. The OS leaves it on still + // because of iOS's weird late processing of modifier states. Synthesis of + // the appropriate synthesized key events happens in synchronizeModifiers. + if (!keyDown && _lastModifierFlagsOfInterest & kModifierFlagCapsLock) { + pressedModifiers &= ~kModifierFlagCapsLock; + } + } + return pressedModifiers; +} + +@end + +namespace { +void HandleResponse(bool handled, void* user_data) { + FlutterKeyPendingResponse* pending = (__bridge_transfer FlutterKeyPendingResponse*)user_data; + [pending.responder handleResponse:handled forId:pending.responseId]; +} +} // namespace diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponderTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponderTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..929e96a9a3d5fc7f8dcac9b89bdec799c0e9360b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponderTest.mm @@ -0,0 +1,1092 @@ +// 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. + +#import +#import +#import +#include <_types/_uint64_t.h> + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/KeyCodeMap_Internal.h" +#include "flutter/shell/platform/embedder/embedder.h" +#include "flutter/shell/platform/embedder/test_utils/key_codes.g.h" + +using namespace flutter::testing::keycodes; +using namespace flutter::testing; + +FLUTTER_ASSERT_ARC; + +#define XCTAssertStrEqual(value, expected) \ + XCTAssertTrue(strcmp(value, expected) == 0, \ + @"String \"%s\" not equal to the expected value of \"%s\"", value, expected) + +// A wrap to convert FlutterKeyEvent to a ObjC class. +@interface TestKeyEvent : NSObject +@property(nonatomic) FlutterKeyEvent* data; +@property(nonatomic) FlutterKeyEventCallback callback; +@property(nonatomic, nullable) void* userData; +@end + +@implementation TestKeyEvent +- (instancetype)initWithEvent:(const FlutterKeyEvent*)event + callback:(nullable FlutterKeyEventCallback)callback + userData:(nullable void*)userData { + self = [super init]; + _data = new FlutterKeyEvent(*event); + if (event->character != nullptr) { + size_t len = strlen(event->character); + char* character = new char[len + 1]; + strlcpy(character, event->character, len + 1); + _data->character = character; + } + _callback = callback; + _userData = userData; + return self; +} + +- (BOOL)hasCallback { + return _callback != nil; +} + +- (void)respond:(BOOL)handled { + NSAssert( + _callback != nil, + @"Improper call to `respond` that does not have a callback."); // Caller's responsibility + _callback(handled, _userData); +} + +- (void)dealloc { + if (_data->character != nullptr) { + delete[] _data->character; + } + delete _data; +} +@end + +namespace { +API_AVAILABLE(ios(13.4)) +constexpr UIKeyboardHIDUsage kKeyCodeUndefined = (UIKeyboardHIDUsage)0x03; +API_AVAILABLE(ios(13.4)) +constexpr UIKeyboardHIDUsage kKeyCodeKeyA = (UIKeyboardHIDUsage)0x04; +API_AVAILABLE(ios(13.4)) +constexpr UIKeyboardHIDUsage kKeyCodePeriod = (UIKeyboardHIDUsage)0x37; +API_AVAILABLE(ios(13.4)) +constexpr UIKeyboardHIDUsage kKeyCodeKeyW = (UIKeyboardHIDUsage)0x1a; +API_AVAILABLE(ios(13.4)) +constexpr UIKeyboardHIDUsage kKeyCodeShiftLeft = (UIKeyboardHIDUsage)0xe1; +API_AVAILABLE(ios(13.4)) +constexpr UIKeyboardHIDUsage kKeyCodeShiftRight = (UIKeyboardHIDUsage)0xe5; +API_AVAILABLE(ios(13.4)) +constexpr UIKeyboardHIDUsage kKeyCodeNumpad1 = (UIKeyboardHIDUsage)0x59; +API_AVAILABLE(ios(13.4)) +constexpr UIKeyboardHIDUsage kKeyCodeCapsLock = (UIKeyboardHIDUsage)0x39; +API_AVAILABLE(ios(13.4)) +constexpr UIKeyboardHIDUsage kKeyCodeF1 = (UIKeyboardHIDUsage)0x3a; +API_AVAILABLE(ios(13.4)) +constexpr UIKeyboardHIDUsage kKeyCodeCommandLeft = (UIKeyboardHIDUsage)0xe3; +API_AVAILABLE(ios(13.4)) +constexpr UIKeyboardHIDUsage kKeyCodeAltRight = (UIKeyboardHIDUsage)0xe6; +API_AVAILABLE(ios(13.4)) +constexpr UIKeyboardHIDUsage kKeyCodeEject = (UIKeyboardHIDUsage)0xb8; + +constexpr uint64_t kPhysicalKeyUndefined = 0x00070003; + +constexpr uint64_t kLogicalKeyUndefined = 0x1300000003; + +constexpr uint64_t kModifierFlagNone = 0x0; + +typedef void (^ResponseCallback)(bool handled); +} // namespace + +@interface FlutterEmbedderKeyResponderTest : XCTestCase +@end + +@implementation FlutterEmbedderKeyResponderTest + +- (void)setUp { + // All of these tests were designed to run on iOS 13.4 or later. + if (@available(iOS 13.4, *)) { + } else { + XCTSkip(@"Required API not present for test."); + } +} + +- (void)tearDown { +} + +// Test the most basic key events. +// +// Press, hold, and release key A on an US keyboard. +- (void)testBasicKeyEvent API_AVAILABLE(ios(13.4)) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + __block BOOL last_handled = TRUE; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + void* _Nullable user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + last_handled = FALSE; + [responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f, "a", "a") + callback:^(BOOL handled) { + last_handled = handled; + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->timestamp, 123000000.0f); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertStrEqual(event->character, "a"); + XCTAssertEqual(event->synthesized, false); + + XCTAssertEqual(last_handled, FALSE); + XCTAssert([[events lastObject] hasCallback]); + [[events lastObject] respond:TRUE]; + XCTAssertEqual(last_handled, TRUE); + + [events removeAllObjects]; + + last_handled = TRUE; + [responder handlePress:keyUpEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f) + callback:^(BOOL handled) { + last_handled = handled; + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->timestamp, 123000000.0f); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + + XCTAssertEqual(last_handled, TRUE); + XCTAssert([[events lastObject] hasCallback]); + [[events lastObject] respond:FALSE]; // Check if responding FALSE works + XCTAssertEqual(last_handled, FALSE); + + [events removeAllObjects]; +} + +- (void)testIosKeyPlane API_AVAILABLE(ios(13.4)) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + __block BOOL last_handled = TRUE; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + void* _Nullable user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + last_handled = FALSE; + // Verify that the eject key (keycode 0xb8, which is not present in the keymap) + // should be translated to the right logical and physical keys. + [responder handlePress:keyDownEvent(kKeyCodeEject, kModifierFlagNone, 123.0f) + callback:^(BOOL handled) { + last_handled = handled; + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kKeyCodeEject | kIosPlane); + XCTAssertEqual(event->logical, kKeyCodeEject | kIosPlane); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + + XCTAssertEqual(last_handled, FALSE); + XCTAssert([[events lastObject] hasCallback]); + [[events lastObject] respond:TRUE]; + XCTAssertEqual(last_handled, TRUE); + + [events removeAllObjects]; + + last_handled = TRUE; + [responder handlePress:keyUpEvent(kKeyCodeEject, kModifierFlagNone, 123.0f) + callback:^(BOOL handled) { + last_handled = handled; + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kKeyCodeEject | kIosPlane); + XCTAssertEqual(event->logical, kKeyCodeEject | kIosPlane); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + + XCTAssertEqual(last_handled, TRUE); + XCTAssert([[events lastObject] hasCallback]); + [[events lastObject] respond:FALSE]; // Check if responding FALSE works + XCTAssertEqual(last_handled, FALSE); + + [events removeAllObjects]; +} + +- (void)testOutOfOrderModifiers API_AVAILABLE(ios(13.4)) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + void* _Nullable user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + // This tests that we synthesize the correct modifier keys when we release the + // modifier key that created the letter before we release the letter. + [responder handlePress:keyDownEvent(kKeyCodeAltRight, kModifierFlagAltAny, 123.0f) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalAltRight); + XCTAssertEqual(event->logical, kLogicalAltRight); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + + [events removeAllObjects]; + + // Test non-ASCII characters being produced. + [responder handlePress:keyDownEvent(kKeyCodeKeyW, kModifierFlagAltAny, 123.0f, "∑", "w") + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalKeyW); + XCTAssertEqual(event->logical, kLogicalKeyW); + XCTAssertStrEqual(event->character, "∑"); + XCTAssertEqual(event->synthesized, false); + + [events removeAllObjects]; + + // Releasing the modifier key before the letter should send the key up to the + // framework. + [responder handlePress:keyUpEvent(kKeyCodeAltRight, kModifierFlagAltAny, 123.0f) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalAltRight); + XCTAssertEqual(event->logical, kLogicalAltRight); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + + [events removeAllObjects]; + + // Yes, iOS sends a modifier flag for the Alt key being down on this event, + // even though the Alt (Option) key has already been released. This means that + // for the framework to be in the correct state, we must synthesize a key down + // event for the modifier key here, and another key up before the next key + // event. + [responder handlePress:keyUpEvent(kKeyCodeKeyW, kModifierFlagAltAny, 123.0f) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalKeyW); + XCTAssertEqual(event->logical, kLogicalKeyW); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + + [events removeAllObjects]; + + // Here we should simulate a key up for the Alt key, since it is no longer + // shown as down in the modifier flags. + [responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f, "å", "a") + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertStrEqual(event->character, "å"); + XCTAssertEqual(event->synthesized, false); +} + +- (void)testIgnoreDuplicateDownEvent API_AVAILABLE(ios(13.4)) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + __block BOOL last_handled = TRUE; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + void* _Nullable user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + last_handled = FALSE; + [responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f, "a", "a") + callback:^(BOOL handled) { + last_handled = handled; + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertStrEqual(event->character, "a"); + XCTAssertEqual(event->synthesized, false); + XCTAssertEqual(last_handled, FALSE); + [[events lastObject] respond:TRUE]; + XCTAssertEqual(last_handled, TRUE); + + [events removeAllObjects]; + + last_handled = FALSE; + [responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f, "a", "a") + callback:^(BOOL handled) { + last_handled = handled; + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->physical, 0ull); + XCTAssertEqual(event->logical, 0ull); + XCTAssertEqual(event->synthesized, false); + XCTAssertFalse([[events lastObject] hasCallback]); + XCTAssertEqual(last_handled, TRUE); + + [events removeAllObjects]; + + last_handled = FALSE; + [responder handlePress:keyUpEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f) + callback:^(BOOL handled) { + last_handled = handled; + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + XCTAssertEqual(last_handled, FALSE); + [[events lastObject] respond:TRUE]; + XCTAssertEqual(last_handled, TRUE); + + [events removeAllObjects]; +} + +- (void)testIgnoreAbruptUpEvent API_AVAILABLE(ios(13.4)) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + __block BOOL last_handled = TRUE; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + void* _Nullable user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + last_handled = FALSE; + [responder handlePress:keyUpEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f) + callback:^(BOOL handled) { + last_handled = handled; + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->physical, 0ull); + XCTAssertEqual(event->logical, 0ull); + XCTAssertEqual(event->synthesized, false); + XCTAssertFalse([[events lastObject] hasCallback]); + XCTAssertEqual(last_handled, TRUE); + + [events removeAllObjects]; +} + +// Press R-Shift, A, then release R-Shift then A, on a US keyboard. +// +// This is special because the characters for the A key will change in this +// process. +- (void)testToggleModifiersDuringKeyTap API_AVAILABLE(ios(13.4)) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + void* _Nullable user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + [responder handlePress:keyDownEvent(kKeyCodeShiftRight, kModifierFlagShiftAny, 123.0f) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->timestamp, 123000000.0f); + XCTAssertEqual(event->physical, kPhysicalShiftRight); + XCTAssertEqual(event->logical, kLogicalShiftRight); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + [responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagShiftAny, 123.0f, "A", "A") + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertStrEqual(event->character, "A"); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + [responder handlePress:keyUpEvent(kKeyCodeShiftRight, kModifierFlagNone, 123.0f) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalShiftRight); + XCTAssertEqual(event->logical, kLogicalShiftRight); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + [responder handlePress:keyUpEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; +} + +// Special modifier flags. +// +// Some keys in modifierFlags are not to indicate modifier state, but to mark +// the key area that the key belongs to, such as numpad keys or function keys. +// Ensure these flags do not obstruct other keys. +- (void)testSpecialModiferFlags API_AVAILABLE(ios(13.4)) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + FlutterKeyEvent* event; + __block BOOL last_handled = TRUE; + id keyEventCallback = ^(BOOL handled) { + last_handled = handled; + }; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + void* _Nullable user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + // Keydown: Numpad1, Fn (undefined), F1, KeyA, ShiftLeft + // Then KeyUp: Numpad1, Fn (undefined), F1, KeyA, ShiftLeft + + // Numpad 1 + // OS provides: char: "1", code: 0x59, modifiers: 0x200000 + [responder handlePress:keyDownEvent(kKeyCodeNumpad1, kModifierFlagNumPadKey, 123.0, "1", "1") + callback:keyEventCallback]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalNumpad1); + XCTAssertEqual(event->logical, kLogicalNumpad1); + XCTAssertStrEqual(event->character, "1"); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + // Fn Key (sends HID undefined) + // OS provides: char: nil, keycode: 0x3, modifiers: 0x0 + [responder handlePress:keyDownEvent(kKeyCodeUndefined, kModifierFlagNone, 123.0) + callback:keyEventCallback]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalKeyUndefined); + XCTAssertEqual(event->logical, kLogicalKeyUndefined); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + // F1 Down + // OS provides: char: UIKeyInputF1, code: 0x3a, modifiers: 0x0 + [responder handlePress:keyDownEvent(kKeyCodeF1, kModifierFlagNone, 123.0f, "\\^P", "\\^P") + callback:keyEventCallback]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalF1); + XCTAssertEqual(event->logical, kLogicalF1); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + // KeyA Down + // OS provides: char: "q", code: 0x4, modifiers: 0x0 + [responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f, "a", "a") + callback:keyEventCallback]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertStrEqual(event->character, "a"); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + // ShiftLeft Down + // OS Provides: char: nil, code: 0xe1, modifiers: 0x20000 + [responder handlePress:keyDownEvent(kKeyCodeShiftLeft, kModifierFlagShiftAny, 123.0f) + callback:keyEventCallback]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalShiftLeft); + XCTAssertEqual(event->logical, kLogicalShiftLeft); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + + [events removeAllObjects]; + + // Numpad 1 Up + // OS provides: char: "1", code: 0x59, modifiers: 0x200000 + [responder handlePress:keyUpEvent(kKeyCodeNumpad1, kModifierFlagNumPadKey, 123.0f) + callback:keyEventCallback]; + + XCTAssertEqual([events count], 2u); + + // Because the OS no longer provides the 0x20000 (kModifierFlagShiftAny), we + // have to simulate a keyup. + event = [events firstObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalShiftLeft); + XCTAssertEqual(event->logical, kLogicalShiftLeft); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, true); + + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalNumpad1); + XCTAssertEqual(event->logical, kLogicalNumpad1); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + // F1 Up + // OS provides: char: UIKeyInputF1, code: 0x3a, modifiers: 0x0 + [responder handlePress:keyUpEvent(kKeyCodeF1, kModifierFlagNone, 123.0f) + callback:keyEventCallback]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalF1); + XCTAssertEqual(event->logical, kLogicalF1); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + // Fn Key (sends HID undefined) + // OS provides: char: nil, code: 0x3, modifiers: 0x0 + [responder handlePress:keyUpEvent(kKeyCodeUndefined, kModifierFlagNone, 123.0) + callback:keyEventCallback]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalKeyUndefined); + XCTAssertEqual(event->logical, kLogicalKeyUndefined); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + // KeyA Up + // OS provides: char: "a", code: 0x4, modifiers: 0x0 + [responder handlePress:keyUpEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f) + callback:keyEventCallback]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + // ShiftLeft Up + // OS provides: char: nil, code: 0xe1, modifiers: 0x20000 + [responder handlePress:keyUpEvent(kKeyCodeShiftLeft, kModifierFlagShiftAny, 123.0f) + callback:keyEventCallback]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->physical, 0ull); + XCTAssertEqual(event->logical, 0ull); + XCTAssertEqual(event->synthesized, false); + XCTAssertFalse([[events lastObject] hasCallback]); + XCTAssertEqual(last_handled, TRUE); + + [events removeAllObjects]; +} + +- (void)testIdentifyLeftAndRightModifiers API_AVAILABLE(ios(13.4)) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + void* _Nullable user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + [responder handlePress:keyDownEvent(kKeyCodeShiftLeft, kModifierFlagShiftAny, 123.0f) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalShiftLeft); + XCTAssertEqual(event->logical, kLogicalShiftLeft); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + [responder handlePress:keyDownEvent(kKeyCodeShiftRight, kModifierFlagShiftAny, 123.0f) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalShiftRight); + XCTAssertEqual(event->logical, kLogicalShiftRight); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + [responder handlePress:keyUpEvent(kKeyCodeShiftLeft, kModifierFlagShiftAny, 123.0f) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalShiftLeft); + XCTAssertEqual(event->logical, kLogicalShiftLeft); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + [responder handlePress:keyUpEvent(kKeyCodeShiftRight, kModifierFlagShiftAny, 123.0f) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalShiftRight); + XCTAssertEqual(event->logical, kLogicalShiftRight); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; +} + +// Press the CapsLock key when CapsLock state is desynchronized +- (void)testSynchronizeCapsLockStateOnCapsLock API_AVAILABLE(ios(13.4)) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + __block BOOL last_handled = TRUE; + id keyEventCallback = ^(BOOL handled) { + last_handled = handled; + }; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + void* _Nullable user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + last_handled = FALSE; + [responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagCapsLock, 123.0f, "A", "A") + callback:keyEventCallback]; + + XCTAssertEqual([events count], 3u); + + event = events[0].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalCapsLock); + XCTAssertEqual(event->logical, kLogicalCapsLock); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, true); + XCTAssertFalse([events[0] hasCallback]); + + event = events[1].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalCapsLock); + XCTAssertEqual(event->logical, kLogicalCapsLock); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, true); + XCTAssertFalse([events[1] hasCallback]); + + event = events[2].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertStrEqual(event->character, "A"); + XCTAssertEqual(event->synthesized, false); + XCTAssert([events[2] hasCallback]); + + XCTAssertEqual(last_handled, FALSE); + [[events lastObject] respond:TRUE]; + XCTAssertEqual(last_handled, TRUE); + + [events removeAllObjects]; + + // Release the "A" key. + [responder handlePress:keyUpEvent(kKeyCodeKeyA, kModifierFlagCapsLock, 123.0f) + callback:keyEventCallback]; + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertEqual(event->synthesized, false); + + [events removeAllObjects]; + + // In: CapsLock down + // Out: CapsLock down + last_handled = FALSE; + [responder handlePress:keyDownEvent(kKeyCodeCapsLock, kModifierFlagCapsLock, 123.0f) + callback:keyEventCallback]; + + XCTAssertEqual([events count], 1u); + event = [events firstObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalCapsLock); + XCTAssertEqual(event->logical, kLogicalCapsLock); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + XCTAssert([[events firstObject] hasCallback]); + + [events removeAllObjects]; + + // In: CapsLock up + // Out: CapsLock up + // This turns off the caps lock, triggering a synthesized up/down to tell the + // framework that. + last_handled = FALSE; + [responder handlePress:keyUpEvent(kKeyCodeCapsLock, kModifierFlagCapsLock, 123.0f) + callback:keyEventCallback]; + + XCTAssertEqual([events count], 1u); + event = [events firstObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalCapsLock); + XCTAssertEqual(event->logical, kLogicalCapsLock); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + XCTAssert([[events firstObject] hasCallback]); + + [events removeAllObjects]; + + last_handled = FALSE; + [responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f, "a", "a") + callback:keyEventCallback]; + + // Just to make sure that we aren't simulating events now, since the state is + // consistent, and should be off. + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertNotEqual(event, nullptr); + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertStrEqual(event->character, "a"); + XCTAssertEqual(event->synthesized, false); + XCTAssert([[events firstObject] hasCallback]); +} + +// Press the CapsLock key when CapsLock state is desynchronized +- (void)testSynchronizeCapsLockStateOnNormalKey API_AVAILABLE(ios(13.4)) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + __block BOOL last_handled = TRUE; + id keyEventCallback = ^(BOOL handled) { + last_handled = handled; + }; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + void* _Nullable user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + last_handled = FALSE; + [responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagCapsLock, 123.0f, "A", "a") + callback:keyEventCallback]; + + XCTAssertEqual([events count], 3u); + + event = events[0].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalCapsLock); + XCTAssertEqual(event->logical, kLogicalCapsLock); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, true); + XCTAssertFalse([events[0] hasCallback]); + + event = events[1].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalCapsLock); + XCTAssertEqual(event->logical, kLogicalCapsLock); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, true); + XCTAssertFalse([events[1] hasCallback]); + + event = events[2].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertStrEqual(event->character, "A"); + XCTAssertEqual(event->synthesized, false); + XCTAssert([events[2] hasCallback]); + + XCTAssertEqual(last_handled, FALSE); + [[events lastObject] respond:TRUE]; + XCTAssertEqual(last_handled, TRUE); + + [events removeAllObjects]; +} + +// Press Cmd-. should correctly result in an Escape event. +- (void)testCommandPeriodKey API_AVAILABLE(ios(13.4)) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + id keyEventCallback = ^(BOOL handled) { + }; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + void* _Nullable user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event callback:nil userData:nil]]; + callback(true, user_data); + }]; + + // MetaLeft down. + [responder handlePress:keyDownEvent(kKeyCodeCommandLeft, kModifierFlagMetaAny, 123.0f, "", "") + callback:keyEventCallback]; + XCTAssertEqual([events count], 1u); + event = events[0].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalMetaLeft); + XCTAssertEqual(event->logical, kLogicalMetaLeft); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [events removeAllObjects]; + + // Period down, which is logically Escape. + [responder handlePress:keyDownEvent(kKeyCodePeriod, kModifierFlagMetaAny, 123.0f, + "UIKeyInputEscape", "UIKeyInputEscape") + callback:keyEventCallback]; + XCTAssertEqual([events count], 1u); + event = events[0].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalPeriod); + XCTAssertEqual(event->logical, kLogicalEscape); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [events removeAllObjects]; + + // Period up, which unconventionally has characters. + [responder handlePress:keyUpEvent(kKeyCodePeriod, kModifierFlagMetaAny, 123.0f, + "UIKeyInputEscape", "UIKeyInputEscape") + callback:keyEventCallback]; + XCTAssertEqual([events count], 1u); + event = events[0].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalPeriod); + XCTAssertEqual(event->logical, kLogicalEscape); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [events removeAllObjects]; + + // MetaLeft up. + [responder handlePress:keyUpEvent(kKeyCodeCommandLeft, kModifierFlagMetaAny, 123.0f, "", "") + callback:keyEventCallback]; + XCTAssertEqual([events count], 1u); + event = events[0].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->device_type, kFlutterKeyEventDeviceTypeKeyboard); + XCTAssertEqual(event->physical, kPhysicalMetaLeft); + XCTAssertEqual(event->logical, kLogicalMetaLeft); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [events removeAllObjects]; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine.mm new file mode 100644 index 0000000000000000000000000000000000000000..daae40eb5e70e33d5fdd458172634882053188fe --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine.mm @@ -0,0 +1,1567 @@ +// 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 "common/settings.h" +#define FML_USED_ON_EMBEDDER + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h" + +#include + +#include "flutter/common/constants.h" +#include "flutter/fml/message_loop.h" +#include "flutter/fml/platform/darwin/platform_version.h" +#include "flutter/fml/trace_event.h" +#include "flutter/runtime/ptrace_check.h" +#include "flutter/shell/common/engine.h" +#include "flutter/shell/common/platform_view.h" +#include "flutter/shell/common/shell.h" +#include "flutter/shell/common/switches.h" +#include "flutter/shell/common/thread_host.h" +#include "flutter/shell/common/variable_refresh_rate_display.h" +#import "flutter/shell/platform/darwin/common/command_line.h" +#import "flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartVMServicePublisher.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterIndirectScribbleDelegate.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPlugin.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterSharedApplication.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterSpellCheckPlugin.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextureRegistryRelay.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerDelegate.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerPlugin.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/UIViewController+FlutterScreenAndSceneIfLoaded.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/connection_collection.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/platform_message_response_darwin.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/profiler_metrics_ios.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.h" +#import "flutter/shell/platform/darwin/ios/platform_view_ios.h" +#import "flutter/shell/platform/darwin/ios/rendering_api_selection.h" +#include "flutter/shell/profiling/sampling_profiler.h" + +FLUTTER_ASSERT_ARC + +/// Inheriting ThreadConfigurer and use iOS platform thread API to configure the thread priorities +/// Using iOS platform thread API to configure thread priority +static void IOSPlatformThreadConfigSetter(const fml::Thread::ThreadConfig& config) { + // set thread name + fml::Thread::SetCurrentThreadName(config); + + // set thread priority + switch (config.priority) { + case fml::Thread::ThreadPriority::kBackground: { + pthread_set_qos_class_self_np(QOS_CLASS_BACKGROUND, 0); + [[NSThread currentThread] setThreadPriority:0]; + break; + } + case fml::Thread::ThreadPriority::kNormal: { + pthread_set_qos_class_self_np(QOS_CLASS_DEFAULT, 0); + [[NSThread currentThread] setThreadPriority:0.5]; + break; + } + case fml::Thread::ThreadPriority::kRaster: + case fml::Thread::ThreadPriority::kDisplay: { + pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0); + [[NSThread currentThread] setThreadPriority:1.0]; + sched_param param; + int policy; + pthread_t thread = pthread_self(); + if (!pthread_getschedparam(thread, &policy, ¶m)) { + param.sched_priority = 50; + pthread_setschedparam(thread, policy, ¶m); + } + break; + } + } +} + +#pragma mark - Public exported constants + +NSString* const FlutterDefaultDartEntrypoint = nil; +NSString* const FlutterDefaultInitialRoute = nil; + +#pragma mark - Internal constants + +NSString* const kFlutterKeyDataChannel = @"flutter/keydata"; +static constexpr int kNumProfilerSamplesPerSec = 5; + +@interface FlutterEngineRegistrar : NSObject +@property(nonatomic, weak) FlutterEngine* flutterEngine; +- (instancetype)initWithPlugin:(NSString*)pluginKey flutterEngine:(FlutterEngine*)flutterEngine; +@end + +@interface FlutterEngine () + +#pragma mark - Properties + +@property(nonatomic, readonly) FlutterDartProject* dartProject; +@property(nonatomic, readonly, copy) NSString* labelPrefix; +@property(nonatomic, readonly, assign) BOOL allowHeadlessExecution; +@property(nonatomic, readonly, assign) BOOL restorationEnabled; + +@property(nonatomic, strong) FlutterPlatformViewsController* platformViewsController; + +// Maintains a dictionary of plugin names that have registered with the engine. Used by +// FlutterEngineRegistrar to implement a FlutterPluginRegistrar. +@property(nonatomic, readonly) NSMutableDictionary* pluginPublications; +@property(nonatomic, readonly) NSMutableDictionary* registrars; + +@property(nonatomic, readwrite, copy) NSString* isolateId; +@property(nonatomic, copy) NSString* initialRoute; +@property(nonatomic, strong) id flutterViewControllerWillDeallocObserver; +@property(nonatomic, strong) FlutterDartVMServicePublisher* publisher; +@property(nonatomic, assign) int64_t nextTextureId; + +#pragma mark - Channel properties + +@property(nonatomic, strong) FlutterPlatformPlugin* platformPlugin; +@property(nonatomic, strong) FlutterTextInputPlugin* textInputPlugin; +@property(nonatomic, strong) FlutterUndoManagerPlugin* undoManagerPlugin; +@property(nonatomic, strong) FlutterSpellCheckPlugin* spellCheckPlugin; +@property(nonatomic, strong) FlutterRestorationPlugin* restorationPlugin; +@property(nonatomic, strong) FlutterMethodChannel* localizationChannel; +@property(nonatomic, strong) FlutterMethodChannel* navigationChannel; +@property(nonatomic, strong) FlutterMethodChannel* restorationChannel; +@property(nonatomic, strong) FlutterMethodChannel* platformChannel; +@property(nonatomic, strong) FlutterMethodChannel* platformViewsChannel; +@property(nonatomic, strong) FlutterMethodChannel* textInputChannel; +@property(nonatomic, strong) FlutterMethodChannel* undoManagerChannel; +@property(nonatomic, strong) FlutterMethodChannel* scribbleChannel; +@property(nonatomic, strong) FlutterMethodChannel* spellCheckChannel; +@property(nonatomic, strong) FlutterBasicMessageChannel* lifecycleChannel; +@property(nonatomic, strong) FlutterBasicMessageChannel* systemChannel; +@property(nonatomic, strong) FlutterBasicMessageChannel* settingsChannel; +@property(nonatomic, strong) FlutterBasicMessageChannel* keyEventChannel; +@property(nonatomic, strong) FlutterMethodChannel* screenshotChannel; + +#pragma mark - Embedder API properties + +@property(nonatomic, assign) BOOL enableEmbedderAPI; +// Function pointers for interacting with the embedder.h API. +@property(nonatomic) FlutterEngineProcTable& embedderAPI; + +@end + +@implementation FlutterEngine { + std::shared_ptr _threadHost; + std::unique_ptr _shell; + + flutter::IOSRenderingAPI _renderingApi; + std::shared_ptr _profiler; + + FlutterBinaryMessengerRelay* _binaryMessenger; + FlutterTextureRegistryRelay* _textureRegistry; + std::unique_ptr _connections; +} + +- (int64_t)engineIdentifier { + return reinterpret_cast((__bridge void*)self); +} + +- (instancetype)init { + return [self initWithName:@"FlutterEngine" project:nil allowHeadlessExecution:YES]; +} + +- (instancetype)initWithName:(NSString*)labelPrefix { + return [self initWithName:labelPrefix project:nil allowHeadlessExecution:YES]; +} + +- (instancetype)initWithName:(NSString*)labelPrefix project:(FlutterDartProject*)project { + return [self initWithName:labelPrefix project:project allowHeadlessExecution:YES]; +} + +- (instancetype)initWithName:(NSString*)labelPrefix + project:(FlutterDartProject*)project + allowHeadlessExecution:(BOOL)allowHeadlessExecution { + return [self initWithName:labelPrefix + project:project + allowHeadlessExecution:allowHeadlessExecution + restorationEnabled:NO]; +} + +- (instancetype)initWithName:(NSString*)labelPrefix + project:(FlutterDartProject*)project + allowHeadlessExecution:(BOOL)allowHeadlessExecution + restorationEnabled:(BOOL)restorationEnabled { + self = [super init]; + NSAssert(self, @"Super init cannot be nil"); + NSAssert(labelPrefix, @"labelPrefix is required"); + + _restorationEnabled = restorationEnabled; + _allowHeadlessExecution = allowHeadlessExecution; + _labelPrefix = [labelPrefix copy]; + _dartProject = project ?: [[FlutterDartProject alloc] init]; + + _enableEmbedderAPI = _dartProject.settings.enable_embedder_api; + if (_enableEmbedderAPI) { + NSLog(@"============== iOS: enable_embedder_api is on =============="); + _embedderAPI.struct_size = sizeof(FlutterEngineProcTable); + FlutterEngineGetProcAddresses(&_embedderAPI); + } + + if (!EnableTracingIfNecessary(_dartProject.settings)) { + NSLog( + @"Cannot create a FlutterEngine instance in debug mode without Flutter tooling or " + @"Xcode.\n\nTo launch in debug mode in iOS 14+, run flutter run from Flutter tools, run " + @"from an IDE with a Flutter IDE plugin or run the iOS project from Xcode.\nAlternatively " + @"profile and release mode apps can be launched from the home screen."); + return nil; + } + + _pluginPublications = [[NSMutableDictionary alloc] init]; + _registrars = [[NSMutableDictionary alloc] init]; + [self recreatePlatformViewsController]; + _binaryMessenger = [[FlutterBinaryMessengerRelay alloc] initWithParent:self]; + _textureRegistry = [[FlutterTextureRegistryRelay alloc] initWithParent:self]; + _connections.reset(new flutter::ConnectionCollection()); + + NSNotificationCenter* center = [NSNotificationCenter defaultCenter]; + [center addObserver:self + selector:@selector(onMemoryWarning:) + name:UIApplicationDidReceiveMemoryWarningNotification + object:nil]; + + [self setUpLifecycleNotifications:center]; + + [center addObserver:self + selector:@selector(onLocaleUpdated:) + name:NSCurrentLocaleDidChangeNotification + object:nil]; + + return self; +} + ++ (FlutterEngine*)engineForIdentifier:(int64_t)identifier { + NSAssert([[NSThread currentThread] isMainThread], @"Must be called on the main thread."); + return (__bridge FlutterEngine*)reinterpret_cast(identifier); +} + +- (void)setUpLifecycleNotifications:(NSNotificationCenter*)center { + // If the application is not available, use the scene for lifecycle notifications if available. + if (!FlutterSharedApplication.isAvailable) { + if (@available(iOS 13.0, *)) { + [center addObserver:self + selector:@selector(sceneWillEnterForeground:) + name:UISceneWillEnterForegroundNotification + object:nil]; + [center addObserver:self + selector:@selector(sceneDidEnterBackground:) + name:UISceneDidEnterBackgroundNotification + object:nil]; + return; + } + } + [center addObserver:self + selector:@selector(applicationWillEnterForeground:) + name:UIApplicationWillEnterForegroundNotification + object:nil]; + [center addObserver:self + selector:@selector(applicationDidEnterBackground:) + name:UIApplicationDidEnterBackgroundNotification + object:nil]; +} + +- (void)recreatePlatformViewsController { + _renderingApi = flutter::GetRenderingAPIForProcess(/*force_software=*/false); + _platformViewsController = [[FlutterPlatformViewsController alloc] init]; +} + +- (flutter::IOSRenderingAPI)platformViewsRenderingAPI { + return _renderingApi; +} + +- (void)dealloc { + /// Notify plugins of dealloc. This should happen first in dealloc since the + /// plugins may be talking to things like the binaryMessenger. + [_pluginPublications enumerateKeysAndObjectsUsingBlock:^(id key, id object, BOOL* stop) { + if ([object respondsToSelector:@selector(detachFromEngineForRegistrar:)]) { + NSObject* registrar = self.registrars[key]; + [object detachFromEngineForRegistrar:registrar]; + } + }]; + + // nil out weak references. + // TODO(cbracken): https://github.com/flutter/flutter/issues/156222 + // Ensure that FlutterEngineRegistrar is using weak pointers, then eliminate this code. + [_registrars + enumerateKeysAndObjectsUsingBlock:^(id key, FlutterEngineRegistrar* registrar, BOOL* stop) { + registrar.flutterEngine = nil; + }]; + + _binaryMessenger.parent = nil; + _textureRegistry.parent = nil; + + NSNotificationCenter* center = [NSNotificationCenter defaultCenter]; + if (_flutterViewControllerWillDeallocObserver) { + [center removeObserver:_flutterViewControllerWillDeallocObserver]; + } + [center removeObserver:self]; +} + +- (flutter::Shell&)shell { + FML_DCHECK(_shell); + return *_shell; +} + +- (void)updateViewportMetrics:(flutter::ViewportMetrics)viewportMetrics { + if (!self.platformView) { + return; + } + self.platformView->SetViewportMetrics(flutter::kFlutterImplicitViewId, viewportMetrics); +} + +- (void)dispatchPointerDataPacket:(std::unique_ptr)packet { + if (!self.platformView) { + return; + } + self.platformView->DispatchPointerDataPacket(std::move(packet)); +} + +- (void)installFirstFrameCallback:(void (^)(void))block { + if (!self.platformView) { + return; + } + + __weak FlutterEngine* weakSelf = self; + self.platformView->SetNextFrameCallback([weakSelf, block] { + FlutterEngine* strongSelf = weakSelf; + if (!strongSelf) { + return; + } + FML_DCHECK(strongSelf.platformTaskRunner); + FML_DCHECK(strongSelf.rasterTaskRunner); + FML_DCHECK(strongSelf.rasterTaskRunner->RunsTasksOnCurrentThread()); + // Get callback on raster thread and jump back to platform thread. + strongSelf.platformTaskRunner->PostTask([block]() { block(); }); + }); +} + +- (void)enableSemantics:(BOOL)enabled withFlags:(int64_t)flags { + if (!self.platformView) { + return; + } + self.platformView->SetSemanticsEnabled(enabled); + self.platformView->SetAccessibilityFeatures(flags); +} + +- (void)notifyViewCreated { + if (!self.platformView) { + return; + } + self.platformView->NotifyCreated(); +} + +- (void)notifyViewDestroyed { + if (!self.platformView) { + return; + } + self.platformView->NotifyDestroyed(); +} + +- (flutter::PlatformViewIOS*)platformView { + if (!_shell) { + return nullptr; + } + return static_cast(_shell->GetPlatformView().get()); +} + +- (fml::RefPtr)platformTaskRunner { + if (!_shell) { + return {}; + } + return _shell->GetTaskRunners().GetPlatformTaskRunner(); +} + +- (fml::RefPtr)uiTaskRunner { + if (!_shell) { + return {}; + } + return _shell->GetTaskRunners().GetUITaskRunner(); +} + +- (fml::RefPtr)rasterTaskRunner { + if (!_shell) { + return {}; + } + return _shell->GetTaskRunners().GetRasterTaskRunner(); +} + +- (void)sendKeyEvent:(const FlutterKeyEvent&)event + callback:(FlutterKeyEventCallback)callback + userData:(void*)userData API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + } else { + return; + } + if (!self.platformView) { + return; + } + const char* character = event.character; + + flutter::KeyData key_data; + key_data.Clear(); + key_data.timestamp = (uint64_t)event.timestamp; + switch (event.type) { + case kFlutterKeyEventTypeUp: + key_data.type = flutter::KeyEventType::kUp; + break; + case kFlutterKeyEventTypeDown: + key_data.type = flutter::KeyEventType::kDown; + break; + case kFlutterKeyEventTypeRepeat: + key_data.type = flutter::KeyEventType::kRepeat; + break; + } + key_data.physical = event.physical; + key_data.logical = event.logical; + key_data.synthesized = event.synthesized; + + auto packet = std::make_unique(key_data, character); + NSData* message = [NSData dataWithBytes:packet->data().data() length:packet->data().size()]; + + auto response = ^(NSData* reply) { + if (callback == nullptr) { + return; + } + BOOL handled = FALSE; + if (reply.length == 1 && *reinterpret_cast(reply.bytes) == 1) { + handled = TRUE; + } + callback(handled, userData); + }; + + [self sendOnChannel:kFlutterKeyDataChannel message:message binaryReply:response]; +} + +- (void)ensureSemanticsEnabled { + if (!self.platformView) { + return; + } + self.platformView->SetSemanticsEnabled(true); +} + +- (void)setViewController:(FlutterViewController*)viewController { + FML_DCHECK(self.platformView); + _viewController = viewController; + self.platformView->SetOwnerViewController(_viewController); + [self maybeSetupPlatformViewChannels]; + [self updateDisplays]; + self.textInputPlugin.viewController = viewController; + + if (viewController) { + __weak __block FlutterEngine* weakSelf = self; + self.flutterViewControllerWillDeallocObserver = + [[NSNotificationCenter defaultCenter] addObserverForName:FlutterViewControllerWillDealloc + object:viewController + queue:[NSOperationQueue mainQueue] + usingBlock:^(NSNotification* note) { + [weakSelf notifyViewControllerDeallocated]; + }]; + } else { + self.flutterViewControllerWillDeallocObserver = nil; + [self notifyLowMemory]; + } +} + +- (void)attachView { + FML_DCHECK(self.platformView); + self.platformView->attachView(); +} + +- (void)setFlutterViewControllerWillDeallocObserver:(id)observer { + if (observer != _flutterViewControllerWillDeallocObserver) { + if (_flutterViewControllerWillDeallocObserver) { + [[NSNotificationCenter defaultCenter] + removeObserver:_flutterViewControllerWillDeallocObserver]; + } + _flutterViewControllerWillDeallocObserver = observer; + } +} + +- (void)notifyViewControllerDeallocated { + [self.lifecycleChannel sendMessage:@"AppLifecycleState.detached"]; + self.textInputPlugin.viewController = nil; + if (!self.allowHeadlessExecution) { + [self destroyContext]; + } else if (self.platformView) { + self.platformView->SetOwnerViewController({}); + } + [self.textInputPlugin resetViewResponder]; + _viewController = nil; +} + +- (void)destroyContext { + [self resetChannels]; + self.isolateId = nil; + _shell.reset(); + _profiler.reset(); + _threadHost.reset(); + _platformViewsController = nil; +} + +- (NSURL*)observatoryUrl { + return self.publisher.url; +} + +- (NSURL*)vmServiceUrl { + return self.publisher.url; +} + +- (void)resetChannels { + self.localizationChannel = nil; + self.navigationChannel = nil; + self.restorationChannel = nil; + self.platformChannel = nil; + self.platformViewsChannel = nil; + self.textInputChannel = nil; + self.undoManagerChannel = nil; + self.scribbleChannel = nil; + self.lifecycleChannel = nil; + self.systemChannel = nil; + self.settingsChannel = nil; + self.keyEventChannel = nil; + self.spellCheckChannel = nil; +} + +- (void)startProfiler { + FML_DCHECK(!_threadHost->name_prefix.empty()); + _profiler = std::make_shared( + _threadHost->name_prefix.c_str(), _threadHost->profiler_thread->GetTaskRunner(), + []() { + flutter::ProfilerMetricsIOS profiler_metrics; + return profiler_metrics.GenerateSample(); + }, + kNumProfilerSamplesPerSec); + _profiler->Start(); +} + +// If you add a channel, be sure to also update `resetChannels`. +// Channels get a reference to the engine, and therefore need manual +// cleanup for proper collection. +- (void)setUpChannels { + // This will be invoked once the shell is done setting up and the isolate ID + // for the UI isolate is available. + __weak FlutterEngine* weakSelf = self; + [_binaryMessenger setMessageHandlerOnChannel:@"flutter/isolate" + binaryMessageHandler:^(NSData* message, FlutterBinaryReply reply) { + if (weakSelf) { + weakSelf.isolateId = + [[FlutterStringCodec sharedInstance] decode:message]; + } + }]; + + self.localizationChannel = + [[FlutterMethodChannel alloc] initWithName:@"flutter/localization" + binaryMessenger:self.binaryMessenger + codec:[FlutterJSONMethodCodec sharedInstance]]; + + self.navigationChannel = + [[FlutterMethodChannel alloc] initWithName:@"flutter/navigation" + binaryMessenger:self.binaryMessenger + codec:[FlutterJSONMethodCodec sharedInstance]]; + + if ([_initialRoute length] > 0) { + // Flutter isn't ready to receive this method call yet but the channel buffer will cache this. + [self.navigationChannel invokeMethod:@"setInitialRoute" arguments:_initialRoute]; + _initialRoute = nil; + } + + self.restorationChannel = + [[FlutterMethodChannel alloc] initWithName:@"flutter/restoration" + binaryMessenger:self.binaryMessenger + codec:[FlutterStandardMethodCodec sharedInstance]]; + + self.platformChannel = + [[FlutterMethodChannel alloc] initWithName:@"flutter/platform" + binaryMessenger:self.binaryMessenger + codec:[FlutterJSONMethodCodec sharedInstance]]; + + self.platformViewsChannel = + [[FlutterMethodChannel alloc] initWithName:@"flutter/platform_views" + binaryMessenger:self.binaryMessenger + codec:[FlutterStandardMethodCodec sharedInstance]]; + + self.textInputChannel = + [[FlutterMethodChannel alloc] initWithName:@"flutter/textinput" + binaryMessenger:self.binaryMessenger + codec:[FlutterJSONMethodCodec sharedInstance]]; + + self.undoManagerChannel = + [[FlutterMethodChannel alloc] initWithName:@"flutter/undomanager" + binaryMessenger:self.binaryMessenger + codec:[FlutterJSONMethodCodec sharedInstance]]; + + self.scribbleChannel = + [[FlutterMethodChannel alloc] initWithName:@"flutter/scribble" + binaryMessenger:self.binaryMessenger + codec:[FlutterJSONMethodCodec sharedInstance]]; + + self.spellCheckChannel = + [[FlutterMethodChannel alloc] initWithName:@"flutter/spellcheck" + binaryMessenger:self.binaryMessenger + codec:[FlutterStandardMethodCodec sharedInstance]]; + + self.lifecycleChannel = + [[FlutterBasicMessageChannel alloc] initWithName:@"flutter/lifecycle" + binaryMessenger:self.binaryMessenger + codec:[FlutterStringCodec sharedInstance]]; + + self.systemChannel = + [[FlutterBasicMessageChannel alloc] initWithName:@"flutter/system" + binaryMessenger:self.binaryMessenger + codec:[FlutterJSONMessageCodec sharedInstance]]; + + self.settingsChannel = + [[FlutterBasicMessageChannel alloc] initWithName:@"flutter/settings" + binaryMessenger:self.binaryMessenger + codec:[FlutterJSONMessageCodec sharedInstance]]; + + self.keyEventChannel = + [[FlutterBasicMessageChannel alloc] initWithName:@"flutter/keyevent" + binaryMessenger:self.binaryMessenger + codec:[FlutterJSONMessageCodec sharedInstance]]; + + self.textInputPlugin = [[FlutterTextInputPlugin alloc] initWithDelegate:self]; + self.textInputPlugin.indirectScribbleDelegate = self; + [self.textInputPlugin setUpIndirectScribbleInteraction:self.viewController]; + + self.undoManagerPlugin = [[FlutterUndoManagerPlugin alloc] initWithDelegate:self]; + self.platformPlugin = [[FlutterPlatformPlugin alloc] initWithEngine:self]; + + self.restorationPlugin = + [[FlutterRestorationPlugin alloc] initWithChannel:self.restorationChannel + restorationEnabled:self.restorationEnabled]; + self.spellCheckPlugin = [[FlutterSpellCheckPlugin alloc] init]; + + self.screenshotChannel = + [[FlutterMethodChannel alloc] initWithName:@"flutter/screenshot" + binaryMessenger:self.binaryMessenger + codec:[FlutterStandardMethodCodec sharedInstance]]; + + [self.screenshotChannel setMethodCallHandler:^(FlutterMethodCall* _Nonnull call, + FlutterResult _Nonnull result) { + FlutterEngine* strongSelf = weakSelf; + if (!(strongSelf && strongSelf->_shell && strongSelf->_shell->IsSetup())) { + return result([FlutterError + errorWithCode:@"invalid_state" + message:@"Requesting screenshot while engine is not running." + details:nil]); + } + flutter::Rasterizer::Screenshot screenshot = + [strongSelf screenshot:flutter::Rasterizer::ScreenshotType::SurfaceData base64Encode:NO]; + if (!screenshot.data) { + return result([FlutterError errorWithCode:@"failure" + message:@"Unable to get screenshot." + details:nil]); + } + // TODO(gaaclarke): Find way to eliminate this data copy. + NSData* data = [NSData dataWithBytes:screenshot.data->writable_data() + length:screenshot.data->size()]; + NSString* format = [NSString stringWithUTF8String:screenshot.format.c_str()]; + NSNumber* width = @(screenshot.frame_size.fWidth); + NSNumber* height = @(screenshot.frame_size.fHeight); + return result(@[ width, height, format ?: [NSNull null], data ]); + }]; +} + +- (void)maybeSetupPlatformViewChannels { + if (_shell && self.shell.IsSetup()) { + __weak FlutterEngine* weakSelf = self; + + [self.platformChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { + [weakSelf.platformPlugin handleMethodCall:call result:result]; + }]; + + [self.platformViewsChannel + setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { + if (weakSelf) { + [weakSelf.platformViewsController onMethodCall:call result:result]; + } + }]; + + [self.textInputChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { + [weakSelf.textInputPlugin handleMethodCall:call result:result]; + }]; + + [self.undoManagerChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { + [weakSelf.undoManagerPlugin handleMethodCall:call result:result]; + }]; + + [self.spellCheckChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { + [weakSelf.spellCheckPlugin handleMethodCall:call result:result]; + }]; + } +} + +- (flutter::Rasterizer::Screenshot)screenshot:(flutter::Rasterizer::ScreenshotType)type + base64Encode:(bool)base64Encode { + return self.shell.Screenshot(type, base64Encode); +} + +- (void)launchEngine:(NSString*)entrypoint + libraryURI:(NSString*)libraryOrNil + entrypointArgs:(NSArray*)entrypointArgs { + // Launch the Dart application with the inferred run configuration. + flutter::RunConfiguration configuration = + [self.dartProject runConfigurationForEntrypoint:entrypoint + libraryOrNil:libraryOrNil + entrypointArgs:entrypointArgs]; + + configuration.SetEngineId(self.engineIdentifier); + self.shell.RunEngine(std::move(configuration)); +} + +- (void)setUpShell:(std::unique_ptr)shell + withVMServicePublication:(BOOL)doesVMServicePublication { + _shell = std::move(shell); + [self setUpChannels]; + [self onLocaleUpdated:nil]; + [self updateDisplays]; + self.publisher = [[FlutterDartVMServicePublisher alloc] + initWithEnableVMServicePublication:doesVMServicePublication]; + [self maybeSetupPlatformViewChannels]; + _shell->SetGpuAvailability(_isGpuDisabled ? flutter::GpuAvailability::kUnavailable + : flutter::GpuAvailability::kAvailable); +} + ++ (BOOL)isProfilerEnabled { + bool profilerEnabled = false; +#if (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG) || \ + (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_PROFILE) + profilerEnabled = true; +#endif + return profilerEnabled; +} + ++ (NSString*)generateThreadLabel:(NSString*)labelPrefix { + static size_t s_shellCount = 0; + return [NSString stringWithFormat:@"%@.%zu", labelPrefix, ++s_shellCount]; +} + +static flutter::ThreadHost MakeThreadHost(NSString* thread_label, + const flutter::Settings& settings) { + // The current thread will be used as the platform thread. Ensure that the message loop is + // initialized. + fml::MessageLoop::EnsureInitializedForCurrentThread(); + + uint32_t threadHostType = flutter::ThreadHost::Type::kRaster | flutter::ThreadHost::Type::kIo; + if (!settings.merged_platform_ui_thread) { + threadHostType |= flutter::ThreadHost::Type::kUi; + } + + if ([FlutterEngine isProfilerEnabled]) { + threadHostType = threadHostType | flutter::ThreadHost::Type::kProfiler; + } + + flutter::ThreadHost::ThreadHostConfig host_config(thread_label.UTF8String, threadHostType, + IOSPlatformThreadConfigSetter); + + host_config.ui_config = + fml::Thread::ThreadConfig(flutter::ThreadHost::ThreadHostConfig::MakeThreadName( + flutter::ThreadHost::Type::kUi, thread_label.UTF8String), + fml::Thread::ThreadPriority::kDisplay); + host_config.raster_config = + fml::Thread::ThreadConfig(flutter::ThreadHost::ThreadHostConfig::MakeThreadName( + flutter::ThreadHost::Type::kRaster, thread_label.UTF8String), + fml::Thread::ThreadPriority::kRaster); + + host_config.io_config = + fml::Thread::ThreadConfig(flutter::ThreadHost::ThreadHostConfig::MakeThreadName( + flutter::ThreadHost::Type::kIo, thread_label.UTF8String), + fml::Thread::ThreadPriority::kNormal); + + return (flutter::ThreadHost){host_config}; +} + +static void SetEntryPoint(flutter::Settings* settings, NSString* entrypoint, NSString* libraryURI) { + if (libraryURI) { + FML_DCHECK(entrypoint) << "Must specify entrypoint if specifying library"; + settings->advisory_script_entrypoint = entrypoint.UTF8String; + settings->advisory_script_uri = libraryURI.UTF8String; + } else if (entrypoint) { + settings->advisory_script_entrypoint = entrypoint.UTF8String; + settings->advisory_script_uri = std::string("main.dart"); + } else { + settings->advisory_script_entrypoint = std::string("main"); + settings->advisory_script_uri = std::string("main.dart"); + } +} + +- (BOOL)createShell:(NSString*)entrypoint + libraryURI:(NSString*)libraryURI + initialRoute:(NSString*)initialRoute { + if (_shell != nullptr) { + FML_LOG(WARNING) << "This FlutterEngine was already invoked."; + return NO; + } + + self.initialRoute = initialRoute; + + auto settings = [self.dartProject settings]; + if (initialRoute != nil) { + self.initialRoute = initialRoute; + } else if (settings.route.empty() == false) { + self.initialRoute = [NSString stringWithUTF8String:settings.route.c_str()]; + } + + auto platformData = [self.dartProject defaultPlatformData]; + + SetEntryPoint(&settings, entrypoint, libraryURI); + + NSString* threadLabel = [FlutterEngine generateThreadLabel:self.labelPrefix]; + _threadHost = std::make_shared(); + *_threadHost = MakeThreadHost(threadLabel, settings); + + __weak FlutterEngine* weakSelf = self; + flutter::Shell::CreateCallback on_create_platform_view = + [weakSelf](flutter::Shell& shell) { + FlutterEngine* strongSelf = weakSelf; + if (!strongSelf) { + return std::unique_ptr(); + } + [strongSelf recreatePlatformViewsController]; + strongSelf.platformViewsController.taskRunner = + shell.GetTaskRunners().GetPlatformTaskRunner(); + return std::make_unique( + shell, strongSelf->_renderingApi, strongSelf.platformViewsController, + shell.GetTaskRunners(), shell.GetConcurrentWorkerTaskRunner(), + shell.GetIsGpuDisabledSyncSwitch()); + }; + + flutter::Shell::CreateCallback on_create_rasterizer = + [](flutter::Shell& shell) { return std::make_unique(shell); }; + + fml::RefPtr ui_runner; + if (settings.enable_impeller && settings.merged_platform_ui_thread) { + ui_runner = fml::MessageLoop::GetCurrent().GetTaskRunner(); + } else { + ui_runner = _threadHost->ui_thread->GetTaskRunner(); + } + flutter::TaskRunners task_runners(threadLabel.UTF8String, // label + fml::MessageLoop::GetCurrent().GetTaskRunner(), // platform + _threadHost->raster_thread->GetTaskRunner(), // raster + ui_runner, // ui + _threadHost->io_thread->GetTaskRunner() // io + ); + + // Disable GPU if the app or scene is running in the background. + self.isGpuDisabled = self.viewController + ? self.viewController.stateIsBackground + : FlutterSharedApplication.application && + FlutterSharedApplication.application.applicationState == + UIApplicationStateBackground; + + // Create the shell. This is a blocking operation. + std::unique_ptr shell = flutter::Shell::Create( + /*platform_data=*/platformData, + /*task_runners=*/task_runners, + /*settings=*/settings, + /*on_create_platform_view=*/on_create_platform_view, + /*on_create_rasterizer=*/on_create_rasterizer, + /*is_gpu_disabled=*/_isGpuDisabled); + + if (shell == nullptr) { + FML_LOG(ERROR) << "Could not start a shell FlutterEngine with entrypoint: " + << entrypoint.UTF8String; + } else { + // TODO(vashworth): Remove once done debugging https://github.com/flutter/flutter/issues/129836 + FML_LOG(INFO) << "Enabled VM Service Publication: " << settings.enable_vm_service_publication; + [self setUpShell:std::move(shell) + withVMServicePublication:settings.enable_vm_service_publication]; + if ([FlutterEngine isProfilerEnabled]) { + [self startProfiler]; + } + } + + return _shell != nullptr; +} + +- (void)updateDisplays { + if (!_shell) { + // Tests may do this. + return; + } + auto vsync_waiter = _shell->GetVsyncWaiter().lock(); + auto vsync_waiter_ios = std::static_pointer_cast(vsync_waiter); + std::vector> displays; + auto screen_size = UIScreen.mainScreen.nativeBounds.size; + auto scale = UIScreen.mainScreen.scale; + displays.push_back(std::make_unique( + 0, vsync_waiter_ios, screen_size.width, screen_size.height, scale)); + _shell->OnDisplayUpdates(std::move(displays)); +} + +- (BOOL)run { + return [self runWithEntrypoint:FlutterDefaultDartEntrypoint + libraryURI:nil + initialRoute:FlutterDefaultInitialRoute]; +} + +- (BOOL)runWithEntrypoint:(NSString*)entrypoint libraryURI:(NSString*)libraryURI { + return [self runWithEntrypoint:entrypoint + libraryURI:libraryURI + initialRoute:FlutterDefaultInitialRoute]; +} + +- (BOOL)runWithEntrypoint:(NSString*)entrypoint { + return [self runWithEntrypoint:entrypoint libraryURI:nil initialRoute:FlutterDefaultInitialRoute]; +} + +- (BOOL)runWithEntrypoint:(NSString*)entrypoint initialRoute:(NSString*)initialRoute { + return [self runWithEntrypoint:entrypoint libraryURI:nil initialRoute:initialRoute]; +} + +- (BOOL)runWithEntrypoint:(NSString*)entrypoint + libraryURI:(NSString*)libraryURI + initialRoute:(NSString*)initialRoute { + return [self runWithEntrypoint:entrypoint + libraryURI:libraryURI + initialRoute:initialRoute + entrypointArgs:nil]; +} + +- (BOOL)runWithEntrypoint:(NSString*)entrypoint + libraryURI:(NSString*)libraryURI + initialRoute:(NSString*)initialRoute + entrypointArgs:(NSArray*)entrypointArgs { + if ([self createShell:entrypoint libraryURI:libraryURI initialRoute:initialRoute]) { + [self launchEngine:entrypoint libraryURI:libraryURI entrypointArgs:entrypointArgs]; + } + + return _shell != nullptr; +} + +- (void)notifyLowMemory { + if (_shell) { + _shell->NotifyLowMemoryWarning(); + } + [self.systemChannel sendMessage:@{@"type" : @"memoryPressure"}]; +} + +#pragma mark - Text input delegate + +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + updateEditingClient:(int)client + withState:(NSDictionary*)state { + [self.textInputChannel invokeMethod:@"TextInputClient.updateEditingState" + arguments:@[ @(client), state ]]; +} + +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + updateEditingClient:(int)client + withState:(NSDictionary*)state + withTag:(NSString*)tag { + [self.textInputChannel invokeMethod:@"TextInputClient.updateEditingStateWithTag" + arguments:@[ @(client), @{tag : state} ]]; +} + +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + updateEditingClient:(int)client + withDelta:(NSDictionary*)delta { + [self.textInputChannel invokeMethod:@"TextInputClient.updateEditingStateWithDeltas" + arguments:@[ @(client), delta ]]; +} + +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + updateFloatingCursor:(FlutterFloatingCursorDragState)state + withClient:(int)client + withPosition:(NSDictionary*)position { + NSString* stateString; + switch (state) { + case FlutterFloatingCursorDragStateStart: + stateString = @"FloatingCursorDragState.start"; + break; + case FlutterFloatingCursorDragStateUpdate: + stateString = @"FloatingCursorDragState.update"; + break; + case FlutterFloatingCursorDragStateEnd: + stateString = @"FloatingCursorDragState.end"; + break; + } + [self.textInputChannel invokeMethod:@"TextInputClient.updateFloatingCursor" + arguments:@[ @(client), stateString, position ]]; +} + +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + performAction:(FlutterTextInputAction)action + withClient:(int)client { + NSString* actionString; + switch (action) { + case FlutterTextInputActionUnspecified: + // Where did the term "unspecified" come from? iOS has a "default" and Android + // has "unspecified." These 2 terms seem to mean the same thing but we need + // to pick just one. "unspecified" was chosen because "default" is often a + // reserved word in languages with switch statements (dart, java, etc). + actionString = @"TextInputAction.unspecified"; + break; + case FlutterTextInputActionDone: + actionString = @"TextInputAction.done"; + break; + case FlutterTextInputActionGo: + actionString = @"TextInputAction.go"; + break; + case FlutterTextInputActionSend: + actionString = @"TextInputAction.send"; + break; + case FlutterTextInputActionSearch: + actionString = @"TextInputAction.search"; + break; + case FlutterTextInputActionNext: + actionString = @"TextInputAction.next"; + break; + case FlutterTextInputActionContinue: + actionString = @"TextInputAction.continueAction"; + break; + case FlutterTextInputActionJoin: + actionString = @"TextInputAction.join"; + break; + case FlutterTextInputActionRoute: + actionString = @"TextInputAction.route"; + break; + case FlutterTextInputActionEmergencyCall: + actionString = @"TextInputAction.emergencyCall"; + break; + case FlutterTextInputActionNewline: + actionString = @"TextInputAction.newline"; + break; + } + [self.textInputChannel invokeMethod:@"TextInputClient.performAction" + arguments:@[ @(client), actionString ]]; +} + +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + showAutocorrectionPromptRectForStart:(NSUInteger)start + end:(NSUInteger)end + withClient:(int)client { + [self.textInputChannel invokeMethod:@"TextInputClient.showAutocorrectionPromptRect" + arguments:@[ @(client), @(start), @(end) ]]; +} + +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + willDismissEditMenuWithTextInputClient:(int)client { + [self.platformChannel invokeMethod:@"ContextMenu.onDismissSystemContextMenu" + arguments:@[ @(client) ]]; +} + +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + shareSelectedText:(NSString*)selectedText { + [self.platformPlugin showShareViewController:selectedText]; +} + +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + searchWebWithSelectedText:(NSString*)selectedText { + [self.platformPlugin searchWeb:selectedText]; +} + +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + lookUpSelectedText:(NSString*)selectedText { + [self.platformPlugin showLookUpViewController:selectedText]; +} + +#pragma mark - FlutterViewEngineDelegate + +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView showToolbar:(int)client { + // TODO(justinmc): Switch from the TextInputClient to Scribble channel when + // the framework has finished transitioning to the Scribble channel. + // https://github.com/flutter/flutter/pull/115296 + [self.textInputChannel invokeMethod:@"TextInputClient.showToolbar" arguments:@[ @(client) ]]; +} + +- (void)flutterTextInputPlugin:(FlutterTextInputPlugin*)textInputPlugin + focusElement:(UIScribbleElementIdentifier)elementIdentifier + atPoint:(CGPoint)referencePoint + result:(FlutterResult)callback { + // TODO(justinmc): Switch from the TextInputClient to Scribble channel when + // the framework has finished transitioning to the Scribble channel. + // https://github.com/flutter/flutter/pull/115296 + [self.textInputChannel + invokeMethod:@"TextInputClient.focusElement" + arguments:@[ elementIdentifier, @(referencePoint.x), @(referencePoint.y) ] + result:callback]; +} + +- (void)flutterTextInputPlugin:(FlutterTextInputPlugin*)textInputPlugin + requestElementsInRect:(CGRect)rect + result:(FlutterResult)callback { + // TODO(justinmc): Switch from the TextInputClient to Scribble channel when + // the framework has finished transitioning to the Scribble channel. + // https://github.com/flutter/flutter/pull/115296 + [self.textInputChannel + invokeMethod:@"TextInputClient.requestElementsInRect" + arguments:@[ @(rect.origin.x), @(rect.origin.y), @(rect.size.width), @(rect.size.height) ] + result:callback]; +} + +- (void)flutterTextInputViewScribbleInteractionBegan:(FlutterTextInputView*)textInputView { + // TODO(justinmc): Switch from the TextInputClient to Scribble channel when + // the framework has finished transitioning to the Scribble channel. + // https://github.com/flutter/flutter/pull/115296 + [self.textInputChannel invokeMethod:@"TextInputClient.scribbleInteractionBegan" arguments:nil]; +} + +- (void)flutterTextInputViewScribbleInteractionFinished:(FlutterTextInputView*)textInputView { + // TODO(justinmc): Switch from the TextInputClient to Scribble channel when + // the framework has finished transitioning to the Scribble channel. + // https://github.com/flutter/flutter/pull/115296 + [self.textInputChannel invokeMethod:@"TextInputClient.scribbleInteractionFinished" arguments:nil]; +} + +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + insertTextPlaceholderWithSize:(CGSize)size + withClient:(int)client { + // TODO(justinmc): Switch from the TextInputClient to Scribble channel when + // the framework has finished transitioning to the Scribble channel. + // https://github.com/flutter/flutter/pull/115296 + [self.textInputChannel invokeMethod:@"TextInputClient.insertTextPlaceholder" + arguments:@[ @(client), @(size.width), @(size.height) ]]; +} + +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + removeTextPlaceholder:(int)client { + // TODO(justinmc): Switch from the TextInputClient to Scribble channel when + // the framework has finished transitioning to the Scribble channel. + // https://github.com/flutter/flutter/pull/115296 + [self.textInputChannel invokeMethod:@"TextInputClient.removeTextPlaceholder" + arguments:@[ @(client) ]]; +} + +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + didResignFirstResponderWithTextInputClient:(int)client { + // When flutter text input view resign first responder, send a message to + // framework to ensure the focus state is correct. This is useful when close + // keyboard from platform side. + [self.textInputChannel invokeMethod:@"TextInputClient.onConnectionClosed" + arguments:@[ @(client) ]]; + + // Platform view's first responder detection logic: + // + // All text input widgets (e.g. EditableText) are backed by a dummy UITextInput view + // in the TextInputPlugin. When this dummy UITextInput view resigns first responder, + // check if any platform view becomes first responder. If any platform view becomes + // first responder, send a "viewFocused" channel message to inform the framework to un-focus + // the previously focused text input. + // + // Caveat: + // 1. This detection logic does not cover the scenario when a platform view becomes + // first responder without any flutter text input resigning its first responder status + // (e.g. user tapping on platform view first). For now it works fine because the TextInputPlugin + // does not track the focused platform view id (which is different from Android implementation). + // + // 2. This detection logic assumes that all text input widgets are backed by a dummy + // UITextInput view in the TextInputPlugin, which may not hold true in the future. + + // Have to check in the next run loop, because iOS requests the previous first responder to + // resign before requesting the next view to become first responder. + dispatch_async(dispatch_get_main_queue(), ^(void) { + long platform_view_id = [self.platformViewsController firstResponderPlatformViewId]; + if (platform_view_id == -1) { + return; + } + + [self.platformViewsChannel invokeMethod:@"viewFocused" arguments:@(platform_view_id)]; + }); +} + +#pragma mark - Undo Manager Delegate + +- (void)handleUndoWithDirection:(FlutterUndoRedoDirection)direction { + NSString* action = (direction == FlutterUndoRedoDirectionUndo) ? @"undo" : @"redo"; + [self.undoManagerChannel invokeMethod:@"UndoManagerClient.handleUndo" arguments:@[ action ]]; +} + +- (UIView*)activeTextInputView { + return [[self textInputPlugin] textInputView]; +} + +- (NSUndoManager*)undoManager { + return self.viewController.undoManager; +} + +#pragma mark - Screenshot Delegate + +- (flutter::Rasterizer::Screenshot)takeScreenshot:(flutter::Rasterizer::ScreenshotType)type + asBase64Encoded:(BOOL)base64Encode { + FML_DCHECK(_shell) << "Cannot takeScreenshot without a shell"; + return _shell->Screenshot(type, base64Encode); +} + +- (void)flutterViewAccessibilityDidCall { + if (self.viewController.view.accessibilityElements == nil) { + [self ensureSemanticsEnabled]; + } +} + +- (NSObject*)binaryMessenger { + return _binaryMessenger; +} + +- (NSObject*)textureRegistry { + return _textureRegistry; +} + +// For test only. Ideally we should create a dependency injector for all dependencies and +// remove this. +- (void)setBinaryMessenger:(FlutterBinaryMessengerRelay*)binaryMessenger { + // Discard the previous messenger and keep the new one. + if (binaryMessenger != _binaryMessenger) { + _binaryMessenger.parent = nil; + _binaryMessenger = binaryMessenger; + } +} + +#pragma mark - FlutterBinaryMessenger + +- (void)sendOnChannel:(NSString*)channel message:(NSData*)message { + [self sendOnChannel:channel message:message binaryReply:nil]; +} + +- (void)sendOnChannel:(NSString*)channel + message:(NSData*)message + binaryReply:(FlutterBinaryReply)callback { + NSParameterAssert(channel); + NSAssert(_shell && _shell->IsSetup(), + @"Sending a message before the FlutterEngine has been run."); + fml::RefPtr response = + (callback == nil) ? nullptr + : fml::MakeRefCounted( + ^(NSData* reply) { + callback(reply); + }, + _shell->GetTaskRunners().GetPlatformTaskRunner()); + std::unique_ptr platformMessage = + (message == nil) ? std::make_unique(channel.UTF8String, response) + : std::make_unique( + channel.UTF8String, flutter::CopyNSDataToMapping(message), response); + + _shell->GetPlatformView()->DispatchPlatformMessage(std::move(platformMessage)); + // platformMessage takes ownership of response. + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) +} + +- (NSObject*)makeBackgroundTaskQueue { + return flutter::PlatformMessageHandlerIos::MakeBackgroundTaskQueue(); +} + +- (FlutterBinaryMessengerConnection)setMessageHandlerOnChannel:(NSString*)channel + binaryMessageHandler: + (FlutterBinaryMessageHandler)handler { + return [self setMessageHandlerOnChannel:channel binaryMessageHandler:handler taskQueue:nil]; +} + +- (FlutterBinaryMessengerConnection) + setMessageHandlerOnChannel:(NSString*)channel + binaryMessageHandler:(FlutterBinaryMessageHandler)handler + taskQueue:(NSObject* _Nullable)taskQueue { + NSParameterAssert(channel); + if (_shell && _shell->IsSetup()) { + self.platformView->GetPlatformMessageHandlerIos()->SetMessageHandler(channel.UTF8String, + handler, taskQueue); + return _connections->AquireConnection(channel.UTF8String); + } else { + NSAssert(!handler, @"Setting a message handler before the FlutterEngine has been run."); + // Setting a handler to nil for a channel that has not yet been set up is a no-op. + return flutter::ConnectionCollection::MakeErrorConnection(-1); + } +} + +- (void)cleanUpConnection:(FlutterBinaryMessengerConnection)connection { + if (_shell && _shell->IsSetup()) { + std::string channel = _connections->CleanupConnection(connection); + if (!channel.empty()) { + self.platformView->GetPlatformMessageHandlerIos()->SetMessageHandler(channel.c_str(), nil, + nil); + } + } +} + +#pragma mark - FlutterTextureRegistry + +- (int64_t)registerTexture:(NSObject*)texture { + FML_DCHECK(self.platformView); + int64_t textureId = self.nextTextureId++; + self.platformView->RegisterExternalTexture(textureId, texture); + return textureId; +} + +- (void)unregisterTexture:(int64_t)textureId { + _shell->GetPlatformView()->UnregisterTexture(textureId); +} + +- (void)textureFrameAvailable:(int64_t)textureId { + _shell->GetPlatformView()->MarkTextureFrameAvailable(textureId); +} + +- (NSString*)lookupKeyForAsset:(NSString*)asset { + return [FlutterDartProject lookupKeyForAsset:asset]; +} + +- (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package { + return [FlutterDartProject lookupKeyForAsset:asset fromPackage:package]; +} + +- (id)pluginRegistry { + return self; +} + +#pragma mark - FlutterPluginRegistry + +- (NSObject*)registrarForPlugin:(NSString*)pluginKey { + NSAssert(self.pluginPublications[pluginKey] == nil, @"Duplicate plugin key: %@", pluginKey); + self.pluginPublications[pluginKey] = [NSNull null]; + FlutterEngineRegistrar* result = [[FlutterEngineRegistrar alloc] initWithPlugin:pluginKey + flutterEngine:self]; + self.registrars[pluginKey] = result; + return result; +} + +- (BOOL)hasPlugin:(NSString*)pluginKey { + return _pluginPublications[pluginKey] != nil; +} + +- (NSObject*)valuePublishedByPlugin:(NSString*)pluginKey { + return _pluginPublications[pluginKey]; +} + +#pragma mark - Notifications + +- (void)sceneWillEnterForeground:(NSNotification*)notification API_AVAILABLE(ios(13.0)) { + [self flutterWillEnterForeground:notification]; +} + +- (void)sceneDidEnterBackground:(NSNotification*)notification API_AVAILABLE(ios(13.0)) { + [self flutterDidEnterBackground:notification]; +} + +- (void)applicationWillEnterForeground:(NSNotification*)notification { + [self flutterWillEnterForeground:notification]; +} + +- (void)applicationDidEnterBackground:(NSNotification*)notification { + [self flutterDidEnterBackground:notification]; +} + +- (void)flutterWillEnterForeground:(NSNotification*)notification { + [self setIsGpuDisabled:NO]; +} + +- (void)flutterDidEnterBackground:(NSNotification*)notification { + [self setIsGpuDisabled:YES]; + [self notifyLowMemory]; +} + +- (void)onMemoryWarning:(NSNotification*)notification { + [self notifyLowMemory]; +} + +- (void)setIsGpuDisabled:(BOOL)value { + if (_shell) { + _shell->SetGpuAvailability(value ? flutter::GpuAvailability::kUnavailable + : flutter::GpuAvailability::kAvailable); + } + _isGpuDisabled = value; +} + +#pragma mark - Locale updates + +- (void)onLocaleUpdated:(NSNotification*)notification { + // Get and pass the user's preferred locale list to dart:ui. + NSMutableArray* localeData = [[NSMutableArray alloc] init]; + NSArray* preferredLocales = [NSLocale preferredLanguages]; + for (NSString* localeID in preferredLocales) { + NSLocale* locale = [[NSLocale alloc] initWithLocaleIdentifier:localeID]; + NSString* languageCode = [locale objectForKey:NSLocaleLanguageCode]; + NSString* countryCode = [locale objectForKey:NSLocaleCountryCode]; + NSString* scriptCode = [locale objectForKey:NSLocaleScriptCode]; + NSString* variantCode = [locale objectForKey:NSLocaleVariantCode]; + if (!languageCode) { + continue; + } + [localeData addObject:languageCode]; + [localeData addObject:(countryCode ? countryCode : @"")]; + [localeData addObject:(scriptCode ? scriptCode : @"")]; + [localeData addObject:(variantCode ? variantCode : @"")]; + } + if (localeData.count == 0) { + return; + } + [self.localizationChannel invokeMethod:@"setLocale" arguments:localeData]; +} + +- (void)waitForFirstFrameSync:(NSTimeInterval)timeout + callback:(NS_NOESCAPE void (^_Nonnull)(BOOL didTimeout))callback { + fml::TimeDelta waitTime = fml::TimeDelta::FromMilliseconds(timeout * 1000); + fml::Status status = self.shell.WaitForFirstFrame(waitTime); + callback(status.code() == fml::StatusCode::kDeadlineExceeded); +} + +- (void)waitForFirstFrame:(NSTimeInterval)timeout + callback:(void (^_Nonnull)(BOOL didTimeout))callback { + dispatch_queue_t queue = dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0); + dispatch_group_t group = dispatch_group_create(); + + __weak FlutterEngine* weakSelf = self; + __block BOOL didTimeout = NO; + dispatch_group_async(group, queue, ^{ + FlutterEngine* strongSelf = weakSelf; + if (!strongSelf) { + return; + } + + fml::TimeDelta waitTime = fml::TimeDelta::FromMilliseconds(timeout * 1000); + fml::Status status = strongSelf.shell.WaitForFirstFrame(waitTime); + didTimeout = status.code() == fml::StatusCode::kDeadlineExceeded; + }); + + // Only execute the main queue task once the background task has completely finished executing. + dispatch_group_notify(group, dispatch_get_main_queue(), ^{ + // Strongly capture self on the task dispatched to the main thread. + // + // When we capture weakSelf strongly in the above block on a background thread, we risk the + // possibility that all other strong references to FlutterEngine go out of scope while the block + // executes and that the engine is dealloc'ed at the end of the above block on a background + // thread. FlutterEngine is not safe to release on any thread other than the main thread. + // + // self is never nil here since it's a strong reference that's verified non-nil above, but we + // use a conditional check to avoid an unused expression compiler warning. + FlutterEngine* strongSelf = self; + if (!strongSelf) { + return; + } + callback(didTimeout); + }); +} + +- (FlutterEngine*)spawnWithEntrypoint:(/*nullable*/ NSString*)entrypoint + libraryURI:(/*nullable*/ NSString*)libraryURI + initialRoute:(/*nullable*/ NSString*)initialRoute + entrypointArgs:(/*nullable*/ NSArray*)entrypointArgs { + NSAssert(_shell, @"Spawning from an engine without a shell (possibly not run)."); + FlutterEngine* result = [[FlutterEngine alloc] initWithName:self.labelPrefix + project:self.dartProject + allowHeadlessExecution:self.allowHeadlessExecution]; + flutter::RunConfiguration configuration = + [self.dartProject runConfigurationForEntrypoint:entrypoint + libraryOrNil:libraryURI + entrypointArgs:entrypointArgs]; + + configuration.SetEngineId(result.engineIdentifier); + + fml::WeakPtr platform_view = _shell->GetPlatformView(); + FML_DCHECK(platform_view); + // Static-cast safe since this class always creates PlatformViewIOS instances. + flutter::PlatformViewIOS* ios_platform_view = + static_cast(platform_view.get()); + std::shared_ptr context = ios_platform_view->GetIosContext(); + FML_DCHECK(context); + + // Lambda captures by pointers to ObjC objects are fine here because the + // create call is synchronous. + flutter::Shell::CreateCallback on_create_platform_view = + [result, context](flutter::Shell& shell) { + [result recreatePlatformViewsController]; + result.platformViewsController.taskRunner = shell.GetTaskRunners().GetPlatformTaskRunner(); + return std::make_unique( + shell, context, result.platformViewsController, shell.GetTaskRunners()); + }; + + flutter::Shell::CreateCallback on_create_rasterizer = + [](flutter::Shell& shell) { return std::make_unique(shell); }; + + std::string cppInitialRoute; + if (initialRoute) { + cppInitialRoute = [initialRoute UTF8String]; + } + + std::unique_ptr shell = _shell->Spawn( + std::move(configuration), cppInitialRoute, on_create_platform_view, on_create_rasterizer); + + result->_threadHost = _threadHost; + result->_profiler = _profiler; + result->_isGpuDisabled = _isGpuDisabled; + [result setUpShell:std::move(shell) withVMServicePublication:NO]; + return result; +} + +- (const flutter::ThreadHost&)threadHost { + return *_threadHost; +} + +- (FlutterDartProject*)project { + return self.dartProject; +} + +@end + +@implementation FlutterEngineRegistrar { + NSString* _pluginKey; +} + +- (instancetype)initWithPlugin:(NSString*)pluginKey flutterEngine:(FlutterEngine*)flutterEngine { + self = [super init]; + NSAssert(self, @"Super init cannot be nil"); + _pluginKey = [pluginKey copy]; + _flutterEngine = flutterEngine; + return self; +} + +- (NSObject*)messenger { + return _flutterEngine.binaryMessenger; +} + +- (NSObject*)textures { + return _flutterEngine.textureRegistry; +} + +- (void)publish:(NSObject*)value { + _flutterEngine.pluginPublications[_pluginKey] = value; +} + +- (void)addMethodCallDelegate:(NSObject*)delegate + channel:(FlutterMethodChannel*)channel { + [channel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { + [delegate handleMethodCall:call result:result]; + }]; +} + +- (void)addApplicationDelegate:(NSObject*)delegate + NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in plugins used in app extensions") { + id appDelegate = [[UIApplication sharedApplication] delegate]; + if ([appDelegate conformsToProtocol:@protocol(FlutterAppLifeCycleProvider)]) { + id lifeCycleProvider = + (id)appDelegate; + [lifeCycleProvider addApplicationLifeCycleDelegate:delegate]; + } +} + +- (NSString*)lookupKeyForAsset:(NSString*)asset { + return [_flutterEngine lookupKeyForAsset:asset]; +} + +- (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package { + return [_flutterEngine lookupKeyForAsset:asset fromPackage:package]; +} + +- (void)registerViewFactory:(NSObject*)factory + withId:(NSString*)factoryId { + [self registerViewFactory:factory + withId:factoryId + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; +} + +- (void)registerViewFactory:(NSObject*)factory + withId:(NSString*)factoryId + gestureRecognizersBlockingPolicy: + (FlutterPlatformViewGestureRecognizersBlockingPolicy)gestureRecognizersBlockingPolicy { + [_flutterEngine.platformViewsController registerViewFactory:factory + withId:factoryId + gestureRecognizersBlockingPolicy:gestureRecognizersBlockingPolicy]; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngineGroup.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngineGroup.mm new file mode 100644 index 0000000000000000000000000000000000000000..3202c195d9db2b933719dd72c2c2ed6182e67e17 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngineGroup.mm @@ -0,0 +1,84 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterEngineGroup.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h" + +FLUTTER_ASSERT_ARC + +@implementation FlutterEngineGroupOptions +@end + +@interface FlutterEngineGroup () +@property(nonatomic, copy) NSString* name; +@property(nonatomic, strong) NSPointerArray* engines; +@property(nonatomic, copy) FlutterDartProject* project; +@property(nonatomic, assign) NSUInteger enginesCreatedCount; +@end + +@implementation FlutterEngineGroup + +- (instancetype)initWithName:(NSString*)name project:(nullable FlutterDartProject*)project { + self = [super init]; + if (self) { + _name = [name copy]; + _engines = [NSPointerArray weakObjectsPointerArray]; + _project = project; + } + return self; +} + +- (FlutterEngine*)makeEngineWithEntrypoint:(nullable NSString*)entrypoint + libraryURI:(nullable NSString*)libraryURI { + return [self makeEngineWithEntrypoint:entrypoint libraryURI:libraryURI initialRoute:nil]; +} + +- (FlutterEngine*)makeEngineWithEntrypoint:(nullable NSString*)entrypoint + libraryURI:(nullable NSString*)libraryURI + initialRoute:(nullable NSString*)initialRoute { + FlutterEngineGroupOptions* options = [[FlutterEngineGroupOptions alloc] init]; + options.entrypoint = entrypoint; + options.libraryURI = libraryURI; + options.initialRoute = initialRoute; + return [self makeEngineWithOptions:options]; +} + +- (FlutterEngine*)makeEngineWithOptions:(nullable FlutterEngineGroupOptions*)options { + NSString* entrypoint = options.entrypoint; + NSString* libraryURI = options.libraryURI; + NSString* initialRoute = options.initialRoute; + NSArray* entrypointArgs = options.entrypointArgs; + + FlutterEngine* engine; + // NSPointerArray is clever and assumes that unless a mutation operation has occurred on it that + // has set one of its values to nil, nothing could have changed and it can skip compaction. + // That's reasonable behaviour on a regular NSPointerArray but not for a weakObjectPointerArray. + // As a workaround, we mutate it first. See: http://www.openradar.me/15396578 + [self.engines addPointer:nil]; + [self.engines compact]; + if (self.engines.count <= 0) { + engine = [self makeEngine]; + [engine runWithEntrypoint:entrypoint + libraryURI:libraryURI + initialRoute:initialRoute + entrypointArgs:entrypointArgs]; + } else { + FlutterEngine* spawner = (__bridge FlutterEngine*)[self.engines pointerAtIndex:0]; + engine = [spawner spawnWithEntrypoint:entrypoint + libraryURI:libraryURI + initialRoute:initialRoute + entrypointArgs:entrypointArgs]; + } + [self.engines addPointer:(__bridge void*)engine]; + + return engine; +} + +- (FlutterEngine*)makeEngine { + NSString* engineName = + [NSString stringWithFormat:@"%@.%lu", self.name, ++self.enginesCreatedCount]; + return [[FlutterEngine alloc] initWithName:engineName project:self.project]; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngineGroupTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngineGroupTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..2d25d457c02810a9706cdc936c99fa6514509e5c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngineGroupTest.mm @@ -0,0 +1,149 @@ +// 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. + +#import +#import + +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterEngineGroup.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Test.h" + +FLUTTER_ASSERT_ARC + +@interface FlutterEngineGroup () +- (FlutterEngine*)makeEngine; +@end + +@interface FlutterEngineGroupTest : XCTestCase +@end + +@implementation FlutterEngineGroupTest + +- (void)testMake { + FlutterEngineGroup* group = [[FlutterEngineGroup alloc] initWithName:@"foo" project:nil]; + FlutterEngine* engine = [group makeEngineWithEntrypoint:nil libraryURI:nil]; + XCTAssertNotNil(engine); +} + +- (void)testSpawn { + FlutterEngineGroup* group = [[FlutterEngineGroup alloc] initWithName:@"foo" project:nil]; + FlutterEngine* spawner = [group makeEngineWithEntrypoint:nil libraryURI:nil]; + spawner.isGpuDisabled = YES; + FlutterEngine* spawnee = [group makeEngineWithEntrypoint:nil libraryURI:nil]; + XCTAssertNotNil(spawner); + XCTAssertNotNil(spawnee); + XCTAssertEqual(&spawner.threadHost, &spawnee.threadHost); + XCTAssertEqual(spawner.isGpuDisabled, spawnee.isGpuDisabled); +} + +- (void)testDeleteLastEngine { + __weak FlutterEngine* weakSpawner; + FlutterEngineGroup* group = [[FlutterEngineGroup alloc] initWithName:@"foo" project:nil]; + @autoreleasepool { + FlutterEngine* spawner = [group makeEngineWithEntrypoint:nil libraryURI:nil]; + weakSpawner = spawner; + XCTAssertNotNil(spawner); + XCTAssertNotNil(weakSpawner); + } + XCTAssertNil(weakSpawner); + + FlutterEngine* spawnee = [group makeEngineWithEntrypoint:nil libraryURI:nil]; + XCTAssertNotNil(spawnee); +} + +- (void)testCustomEntrypoint { + FlutterEngineGroup* group = OCMPartialMock([[FlutterEngineGroup alloc] initWithName:@"foo" + project:nil]); + FlutterEngine* mockEngine = OCMClassMock([FlutterEngine class]); + OCMStub([group makeEngine]).andReturn(mockEngine); + OCMStub([mockEngine spawnWithEntrypoint:[OCMArg any] + libraryURI:[OCMArg any] + initialRoute:[OCMArg any] + entrypointArgs:[OCMArg any]]) + .andReturn(OCMClassMock([FlutterEngine class])); + FlutterEngine* spawner = [group makeEngineWithEntrypoint:@"firstEntrypoint" + libraryURI:@"firstLibraryURI"]; + XCTAssertNotNil(spawner); + OCMVerify([spawner runWithEntrypoint:@"firstEntrypoint" + libraryURI:@"firstLibraryURI" + initialRoute:nil + entrypointArgs:nil]); + + FlutterEngine* spawnee = [group makeEngineWithEntrypoint:@"secondEntrypoint" + libraryURI:@"secondLibraryURI"]; + XCTAssertNotNil(spawnee); + OCMVerify([spawner spawnWithEntrypoint:@"secondEntrypoint" + libraryURI:@"secondLibraryURI" + initialRoute:nil + entrypointArgs:nil]); +} + +- (void)testCustomInitialRoute { + FlutterEngineGroup* group = OCMPartialMock([[FlutterEngineGroup alloc] initWithName:@"foo" + project:nil]); + FlutterEngine* mockEngine = OCMClassMock([FlutterEngine class]); + OCMStub([group makeEngine]).andReturn(mockEngine); + OCMStub([mockEngine spawnWithEntrypoint:[OCMArg any] + libraryURI:[OCMArg any] + initialRoute:[OCMArg any] + entrypointArgs:[OCMArg any]]) + .andReturn(OCMClassMock([FlutterEngine class])); + FlutterEngine* spawner = [group makeEngineWithEntrypoint:nil libraryURI:nil initialRoute:@"foo"]; + XCTAssertNotNil(spawner); + OCMVerify([spawner runWithEntrypoint:nil libraryURI:nil initialRoute:@"foo" entrypointArgs:nil]); + + FlutterEngine* spawnee = [group makeEngineWithEntrypoint:nil libraryURI:nil initialRoute:@"bar"]; + XCTAssertNotNil(spawnee); + OCMVerify([spawner spawnWithEntrypoint:nil + libraryURI:nil + initialRoute:@"bar" + entrypointArgs:nil]); +} + +- (void)testCustomEntrypointArgs { + FlutterEngineGroup* group = OCMPartialMock([[FlutterEngineGroup alloc] initWithName:@"foo" + project:nil]); + FlutterEngine* mockEngine = OCMClassMock([FlutterEngine class]); + OCMStub([group makeEngine]).andReturn(mockEngine); + OCMStub([mockEngine spawnWithEntrypoint:[OCMArg any] + libraryURI:[OCMArg any] + initialRoute:[OCMArg any] + entrypointArgs:[OCMArg any]]) + .andReturn(OCMClassMock([FlutterEngine class])); + FlutterEngineGroupOptions* firstOptions = [[FlutterEngineGroupOptions alloc] init]; + NSArray* firstEntrypointArgs = @[ @"foo", @"first" ]; + firstOptions.entrypointArgs = firstEntrypointArgs; + FlutterEngine* spawner = [group makeEngineWithOptions:firstOptions]; + XCTAssertNotNil(spawner); + OCMVerify([spawner runWithEntrypoint:nil + libraryURI:nil + initialRoute:nil + entrypointArgs:firstEntrypointArgs]); + + NSArray* secondEntrypointArgs = @[ @"bar", @"second" ]; + FlutterEngineGroupOptions* secondOptions = [[FlutterEngineGroupOptions alloc] init]; + secondOptions.entrypointArgs = secondEntrypointArgs; + FlutterEngine* spawnee = [group makeEngineWithOptions:secondOptions]; + XCTAssertNotNil(spawnee); + OCMVerify([spawner spawnWithEntrypoint:nil + libraryURI:nil + initialRoute:nil + entrypointArgs:secondEntrypointArgs]); +} + +- (void)testReleasesProjectOnDealloc { + __weak FlutterDartProject* weakProject; + @autoreleasepool { + FlutterDartProject* mockProject = OCMClassMock([FlutterDartProject class]); + FlutterEngineGroup* group = [[FlutterEngineGroup alloc] initWithName:@"foo" + project:mockProject]; + XCTAssertNotNil(group); + weakProject = mockProject; + XCTAssertNotNil(weakProject); + group = nil; + mockProject = nil; + } + XCTAssertNil(weakProject); +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEnginePlatformViewTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEnginePlatformViewTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..7f885321eacab4cbc4665c90a523374bae551796 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEnginePlatformViewTest.mm @@ -0,0 +1,132 @@ +// 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 +#define FML_USED_ON_EMBEDDER + +#import +#import + +#include "flutter/fml/message_loop.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Test.h" +#import "flutter/shell/platform/darwin/ios/platform_view_ios.h" + +FLUTTER_ASSERT_ARC + +namespace flutter { +namespace { + +class FakeDelegate : public PlatformView::Delegate { + public: + void OnPlatformViewCreated(std::unique_ptr surface) override {} + void OnPlatformViewDestroyed() override {} + void OnPlatformViewScheduleFrame() override {} + void OnPlatformViewAddView(int64_t view_id, + const ViewportMetrics& viewport_metrics, + AddViewCallback callback) override {} + void OnPlatformViewRemoveView(int64_t view_id, RemoveViewCallback callback) override {} + void OnPlatformViewSendViewFocusEvent(const ViewFocusEvent& event) override {} + void OnPlatformViewSetNextFrameCallback(const fml::closure& closure) override {} + void OnPlatformViewSetViewportMetrics(int64_t view_id, const ViewportMetrics& metrics) override {} + const flutter::Settings& OnPlatformViewGetSettings() const override { return settings_; } + void OnPlatformViewDispatchPlatformMessage(std::unique_ptr message) override {} + void OnPlatformViewDispatchPointerDataPacket(std::unique_ptr packet) override { + } + void OnPlatformViewDispatchSemanticsAction(int64_t view_id, + int32_t node_id, + SemanticsAction action, + fml::MallocMapping args) override {} + void OnPlatformViewSetSemanticsEnabled(bool enabled) override {} + void OnPlatformViewSetAccessibilityFeatures(int32_t flags) override {} + void OnPlatformViewRegisterTexture(std::shared_ptr texture) override {} + void OnPlatformViewUnregisterTexture(int64_t texture_id) override {} + void OnPlatformViewMarkTextureFrameAvailable(int64_t texture_id) override {} + + void LoadDartDeferredLibrary(intptr_t loading_unit_id, + std::unique_ptr snapshot_data, + std::unique_ptr snapshot_instructions) override { + } + void LoadDartDeferredLibraryError(intptr_t loading_unit_id, + const std::string error_message, + bool transient) override {} + void UpdateAssetResolverByType(std::unique_ptr updated_asset_resolver, + AssetResolver::AssetResolverType type) override {} + + flutter::Settings settings_; +}; + +} // namespace +} // namespace flutter + +@interface FlutterEnginePlatformViewTest : XCTestCase +@end + +@implementation FlutterEnginePlatformViewTest +std::unique_ptr platform_view; +std::unique_ptr> weak_factory; +flutter::FakeDelegate fake_delegate; + +- (void)setUp { + fml::MessageLoop::EnsureInitializedForCurrentThread(); + auto thread_task_runner = fml::MessageLoop::GetCurrent().GetTaskRunner(); + auto sync_switch = std::make_shared(); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + platform_view = std::make_unique( + /*delegate=*/fake_delegate, + /*rendering_api=*/fake_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/sync_switch); + weak_factory = std::make_unique>(platform_view.get()); +} + +- (void)tearDown { + weak_factory.reset(); + platform_view.reset(); +} + +- (fml::WeakPtr)platformViewReplacement { + return weak_factory->GetWeakPtr(); +} + +- (void)testCallsNotifyLowMemory { + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"tester"]; + XCTAssertNotNil(engine); + id mockEngine = OCMPartialMock(engine); + OCMStub([mockEngine notifyLowMemory]); + OCMStub([mockEngine platformView]).andReturn(platform_view.get()); + + [engine setViewController:nil]; + OCMVerify([mockEngine notifyLowMemory]); + OCMReject([mockEngine notifyLowMemory]); + + XCTNSNotificationExpectation* memoryExpectation = [[XCTNSNotificationExpectation alloc] + initWithName:UIApplicationDidReceiveMemoryWarningNotification]; + [[NSNotificationCenter defaultCenter] + postNotificationName:UIApplicationDidReceiveMemoryWarningNotification + object:nil]; + [self waitForExpectations:@[ memoryExpectation ] timeout:5.0]; + OCMVerify([mockEngine notifyLowMemory]); + OCMReject([mockEngine notifyLowMemory]); + + XCTNSNotificationExpectation* backgroundExpectation = [[XCTNSNotificationExpectation alloc] + initWithName:UIApplicationDidEnterBackgroundNotification]; + [[NSNotificationCenter defaultCenter] + postNotificationName:UIApplicationDidEnterBackgroundNotification + object:nil]; + [self waitForExpectations:@[ backgroundExpectation ] timeout:5.0]; + + OCMVerify([mockEngine notifyLowMemory]); +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngineTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngineTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..3770bf8c6a5aea6e0473391f78f697cc489c684b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngineTest.mm @@ -0,0 +1,541 @@ +// 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. + +#import +#import +#import + +#import + +#import "flutter/common/settings.h" +#include "flutter/fml/synchronization/sync_switch.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Test.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterSharedApplication.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h" +#import "flutter/shell/platform/darwin/ios/platform_view_ios.h" +FLUTTER_ASSERT_ARC + +@interface FlutterEngineSpy : FlutterEngine +@property(nonatomic) BOOL ensureSemanticsEnabledCalled; +@end + +@implementation FlutterEngineSpy + +- (void)ensureSemanticsEnabled { + _ensureSemanticsEnabledCalled = YES; +} + +@end + +@interface FlutterEngine () + +@end + +/// FlutterBinaryMessengerRelay used for testing that setting FlutterEngine.binaryMessenger to +/// the current instance doesn't trigger a use-after-free bug. +/// +/// See: testSetBinaryMessengerToSameBinaryMessenger +@interface FakeBinaryMessengerRelay : FlutterBinaryMessengerRelay +@property(nonatomic, assign) BOOL failOnDealloc; +@end + +@implementation FakeBinaryMessengerRelay +- (void)dealloc { + if (_failOnDealloc) { + XCTFail("FakeBinaryMessageRelay should not be deallocated"); + } +} +@end + +@interface FlutterEngineTest : XCTestCase +@end + +@implementation FlutterEngineTest + +- (void)setUp { +} + +- (void)tearDown { +} + +- (void)testCreate { + FlutterDartProject* project = [[FlutterDartProject alloc] init]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project]; + XCTAssertNotNil(engine); +} + +- (void)testShellGetters { + FlutterDartProject* project = [[FlutterDartProject alloc] init]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project]; + XCTAssertNotNil(engine); + + // Ensure getters don't deref _shell when it's null, and instead return nullptr. + XCTAssertEqual(engine.platformTaskRunner.get(), nullptr); + XCTAssertEqual(engine.uiTaskRunner.get(), nullptr); + XCTAssertEqual(engine.rasterTaskRunner.get(), nullptr); +} + +- (void)testInfoPlist { + // Check the embedded Flutter.framework Info.plist, not the linked dylib. + NSURL* flutterFrameworkURL = + [NSBundle.mainBundle.privateFrameworksURL URLByAppendingPathComponent:@"Flutter.framework"]; + NSBundle* flutterBundle = [NSBundle bundleWithURL:flutterFrameworkURL]; + XCTAssertEqualObjects(flutterBundle.bundleIdentifier, @"io.flutter.flutter"); + + NSDictionary* infoDictionary = flutterBundle.infoDictionary; + + // OS version can have one, two, or three digits: "8", "8.0", "8.0.0" + NSError* regexError = NULL; + NSRegularExpression* osVersionRegex = + [NSRegularExpression regularExpressionWithPattern:@"((0|[1-9]\\d*)\\.)*(0|[1-9]\\d*)" + options:NSRegularExpressionCaseInsensitive + error:®exError]; + XCTAssertNil(regexError); + + // Smoke test the test regex. + NSString* testString = @"9"; + NSUInteger versionMatches = + [osVersionRegex numberOfMatchesInString:testString + options:NSMatchingAnchored + range:NSMakeRange(0, testString.length)]; + XCTAssertEqual(versionMatches, 1UL); + testString = @"9.1"; + versionMatches = [osVersionRegex numberOfMatchesInString:testString + options:NSMatchingAnchored + range:NSMakeRange(0, testString.length)]; + XCTAssertEqual(versionMatches, 1UL); + testString = @"9.0.1"; + versionMatches = [osVersionRegex numberOfMatchesInString:testString + options:NSMatchingAnchored + range:NSMakeRange(0, testString.length)]; + XCTAssertEqual(versionMatches, 1UL); + testString = @".0.1"; + versionMatches = [osVersionRegex numberOfMatchesInString:testString + options:NSMatchingAnchored + range:NSMakeRange(0, testString.length)]; + XCTAssertEqual(versionMatches, 0UL); + + // Test Info.plist values. + NSString* minimumOSVersion = infoDictionary[@"MinimumOSVersion"]; + versionMatches = [osVersionRegex numberOfMatchesInString:minimumOSVersion + options:NSMatchingAnchored + range:NSMakeRange(0, minimumOSVersion.length)]; + XCTAssertEqual(versionMatches, 1UL); + + // SHA length is 40. + XCTAssertEqual(((NSString*)infoDictionary[@"FlutterEngine"]).length, 40UL); + + // {clang_version} placeholder is 15 characters. The clang string version + // is longer than that, so check if the placeholder has been replaced, without + // actually checking a literal string, which could be different on various machines. + XCTAssertTrue(((NSString*)infoDictionary[@"ClangVersion"]).length > 15UL); +} + +- (void)testDeallocated { + __weak FlutterEngine* weakEngine = nil; + @autoreleasepool { + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar"]; + weakEngine = engine; + [engine run]; + XCTAssertNotNil(weakEngine); + } + XCTAssertNil(weakEngine); +} + +- (void)testSendMessageBeforeRun { + FlutterDartProject* project = [[FlutterDartProject alloc] init]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project]; + XCTAssertNotNil(engine); + XCTAssertThrows([engine.binaryMessenger + sendOnChannel:@"foo" + message:[@"bar" dataUsingEncoding:NSUTF8StringEncoding] + binaryReply:nil]); +} + +- (void)testSetMessageHandlerBeforeRun { + FlutterDartProject* project = [[FlutterDartProject alloc] init]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project]; + XCTAssertNotNil(engine); + XCTAssertThrows([engine.binaryMessenger + setMessageHandlerOnChannel:@"foo" + binaryMessageHandler:^(NSData* _Nullable message, FlutterBinaryReply _Nonnull reply){ + + }]); +} + +- (void)testNilSetMessageHandlerBeforeRun { + FlutterDartProject* project = [[FlutterDartProject alloc] init]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project]; + XCTAssertNotNil(engine); + XCTAssertNoThrow([engine.binaryMessenger setMessageHandlerOnChannel:@"foo" + binaryMessageHandler:nil]); +} + +- (void)testNotifyPluginOfDealloc { + id plugin = OCMProtocolMock(@protocol(FlutterPlugin)); + OCMStub([plugin detachFromEngineForRegistrar:[OCMArg any]]); + { + FlutterDartProject* project = [[FlutterDartProject alloc] init]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"engine" project:project]; + NSObject* registrar = [engine registrarForPlugin:@"plugin"]; + [registrar publish:plugin]; + engine = nil; + } + OCMVerify([plugin detachFromEngineForRegistrar:[OCMArg any]]); +} + +- (void)testSetBinaryMessengerToSameBinaryMessenger { + FakeBinaryMessengerRelay* fakeBinaryMessenger = [[FakeBinaryMessengerRelay alloc] init]; + + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine setBinaryMessenger:fakeBinaryMessenger]; + + // Verify that the setter doesn't free the old messenger before setting the new messenger. + fakeBinaryMessenger.failOnDealloc = YES; + [engine setBinaryMessenger:fakeBinaryMessenger]; + + // Don't fail when ARC releases the binary messenger. + fakeBinaryMessenger.failOnDealloc = NO; +} + +- (void)testRunningInitialRouteSendsNavigationMessage { + id mockBinaryMessenger = OCMClassMock([FlutterBinaryMessengerRelay class]); + + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine setBinaryMessenger:mockBinaryMessenger]; + + // Run with an initial route. + [engine runWithEntrypoint:FlutterDefaultDartEntrypoint initialRoute:@"test"]; + + // Now check that an encoded method call has been made on the binary messenger to set the + // initial route to "test". + FlutterMethodCall* setInitialRouteMethodCall = + [FlutterMethodCall methodCallWithMethodName:@"setInitialRoute" arguments:@"test"]; + NSData* encodedSetInitialRouteMethod = + [[FlutterJSONMethodCodec sharedInstance] encodeMethodCall:setInitialRouteMethodCall]; + OCMVerify([mockBinaryMessenger sendOnChannel:@"flutter/navigation" + message:encodedSetInitialRouteMethod]); +} + +- (void)testInitialRouteSettingsSendsNavigationMessage { + id mockBinaryMessenger = OCMClassMock([FlutterBinaryMessengerRelay class]); + + auto settings = FLTDefaultSettingsForBundle(); + settings.route = "test"; + FlutterDartProject* project = [[FlutterDartProject alloc] initWithSettings:settings]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project]; + [engine setBinaryMessenger:mockBinaryMessenger]; + [engine run]; + + // Now check that an encoded method call has been made on the binary messenger to set the + // initial route to "test". + FlutterMethodCall* setInitialRouteMethodCall = + [FlutterMethodCall methodCallWithMethodName:@"setInitialRoute" arguments:@"test"]; + NSData* encodedSetInitialRouteMethod = + [[FlutterJSONMethodCodec sharedInstance] encodeMethodCall:setInitialRouteMethodCall]; + OCMVerify([mockBinaryMessenger sendOnChannel:@"flutter/navigation" + message:encodedSetInitialRouteMethod]); +} + +- (void)testPlatformViewsControllerRenderingMetalBackend { + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine run]; + flutter::IOSRenderingAPI renderingApi = [engine platformViewsRenderingAPI]; + + XCTAssertEqual(renderingApi, flutter::IOSRenderingAPI::kMetal); +} + +- (void)testWaitForFirstFrameTimeout { + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar"]; + [engine run]; + XCTestExpectation* timeoutFirstFrame = [self expectationWithDescription:@"timeoutFirstFrame"]; + [engine waitForFirstFrame:0.1 + callback:^(BOOL didTimeout) { + if (timeoutFirstFrame) { + [timeoutFirstFrame fulfill]; + } + }]; + [self waitForExpectations:@[ timeoutFirstFrame ]]; +} + +- (void)testSpawn { + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar"]; + [engine run]; + FlutterEngine* spawn = [engine spawnWithEntrypoint:nil + libraryURI:nil + initialRoute:nil + entrypointArgs:nil]; + XCTAssertNotNil(spawn); +} + +- (void)testEngineId { + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar"]; + [engine run]; + int64_t id1 = engine.engineIdentifier; + XCTAssertTrue(id1 != 0); + FlutterEngine* spawn = [engine spawnWithEntrypoint:nil + libraryURI:nil + initialRoute:nil + entrypointArgs:nil]; + int64_t id2 = spawn.engineIdentifier; + XCTAssertEqual([FlutterEngine engineForIdentifier:id1], engine); + XCTAssertEqual([FlutterEngine engineForIdentifier:id2], spawn); +} + +- (void)testSetHandlerAfterRun { + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar"]; + XCTestExpectation* gotMessage = [self expectationWithDescription:@"gotMessage"]; + dispatch_async(dispatch_get_main_queue(), ^{ + NSObject* registrar = [engine registrarForPlugin:@"foo"]; + fml::AutoResetWaitableEvent latch; + [engine run]; + flutter::Shell& shell = engine.shell; + fml::TaskRunner::RunNowOrPostTask( + engine.shell.GetTaskRunners().GetUITaskRunner(), [&latch, &shell] { + flutter::Engine::Delegate& delegate = shell; + auto message = std::make_unique("foo", nullptr); + delegate.OnEngineHandlePlatformMessage(std::move(message)); + latch.Signal(); + }); + latch.Wait(); + [registrar.messenger setMessageHandlerOnChannel:@"foo" + binaryMessageHandler:^(NSData* message, FlutterBinaryReply reply) { + [gotMessage fulfill]; + }]; + }); + [self waitForExpectations:@[ gotMessage ]]; +} + +- (void)testThreadPrioritySetCorrectly { + XCTestExpectation* prioritiesSet = [self expectationWithDescription:@"prioritiesSet"]; + prioritiesSet.expectedFulfillmentCount = 2; + + IMP mockSetThreadPriority = + imp_implementationWithBlock(^(NSThread* thread, double threadPriority) { + if ([thread.name hasSuffix:@".raster"]) { + XCTAssertEqual(threadPriority, 1.0); + [prioritiesSet fulfill]; + } else if ([thread.name hasSuffix:@".io"]) { + XCTAssertEqual(threadPriority, 0.5); + [prioritiesSet fulfill]; + } + }); + Method method = class_getInstanceMethod([NSThread class], @selector(setThreadPriority:)); + IMP originalSetThreadPriority = method_getImplementation(method); + method_setImplementation(method, mockSetThreadPriority); + + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine run]; + [self waitForExpectations:@[ prioritiesSet ]]; + + method_setImplementation(method, originalSetThreadPriority); +} + +- (void)testCanEnableDisableEmbedderAPIThroughInfoPlist { + { + // Not enable embedder API by default + auto settings = FLTDefaultSettingsForBundle(); + settings.enable_software_rendering = true; + FlutterDartProject* project = [[FlutterDartProject alloc] initWithSettings:settings]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project]; + XCTAssertFalse(engine.enableEmbedderAPI); + } + { + // Enable embedder api + id mockMainBundle = OCMPartialMock([NSBundle mainBundle]); + OCMStub([mockMainBundle objectForInfoDictionaryKey:@"FLTEnableIOSEmbedderAPI"]) + .andReturn(@"YES"); + auto settings = FLTDefaultSettingsForBundle(); + settings.enable_software_rendering = true; + FlutterDartProject* project = [[FlutterDartProject alloc] initWithSettings:settings]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project]; + XCTAssertTrue(engine.enableEmbedderAPI); + } +} + +- (void)testFlutterTextInputViewDidResignFirstResponderWillCallTextInputClientConnectionClosed { + id mockBinaryMessenger = OCMClassMock([FlutterBinaryMessengerRelay class]); + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine setBinaryMessenger:mockBinaryMessenger]; + [engine runWithEntrypoint:FlutterDefaultDartEntrypoint initialRoute:@"test"]; + [engine flutterTextInputView:nil didResignFirstResponderWithTextInputClient:1]; + FlutterMethodCall* methodCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInputClient.onConnectionClosed" + arguments:@[ @(1) ]]; + NSData* encodedMethodCall = [[FlutterJSONMethodCodec sharedInstance] encodeMethodCall:methodCall]; + OCMVerify([mockBinaryMessenger sendOnChannel:@"flutter/textinput" message:encodedMethodCall]); +} + +- (void)testFlutterEngineUpdatesDisplays { + FlutterEngine* engine = [[FlutterEngine alloc] init]; + id mockEngine = OCMPartialMock(engine); + + [engine run]; + OCMVerify(times(1), [mockEngine updateDisplays]); + engine.viewController = nil; + OCMVerify(times(2), [mockEngine updateDisplays]); +} + +- (void)testLifeCycleNotificationDidEnterBackgroundForApplication { + FlutterDartProject* project = [[FlutterDartProject alloc] init]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project]; + [engine run]; + NSNotification* sceneNotification = + [NSNotification notificationWithName:UISceneDidEnterBackgroundNotification + object:nil + userInfo:nil]; + NSNotification* applicationNotification = + [NSNotification notificationWithName:UIApplicationDidEnterBackgroundNotification + object:nil + userInfo:nil]; + id mockEngine = OCMPartialMock(engine); + [NSNotificationCenter.defaultCenter postNotification:sceneNotification]; + [NSNotificationCenter.defaultCenter postNotification:applicationNotification]; + OCMVerify(times(1), [mockEngine applicationDidEnterBackground:[OCMArg any]]); + XCTAssertTrue(engine.isGpuDisabled); + BOOL gpuDisabled = NO; + [engine shell].GetIsGpuDisabledSyncSwitch()->Execute( + fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] { + gpuDisabled = NO; + })); + XCTAssertTrue(gpuDisabled); +} + +- (void)testLifeCycleNotificationDidEnterBackgroundForScene { + id mockBundle = OCMPartialMock([NSBundle mainBundle]); + OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{ + @"NSExtensionPointIdentifier" : @"com.apple.share-services" + }); + FlutterDartProject* project = [[FlutterDartProject alloc] init]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project]; + [engine run]; + NSNotification* sceneNotification = + [NSNotification notificationWithName:UISceneDidEnterBackgroundNotification + object:nil + userInfo:nil]; + NSNotification* applicationNotification = + [NSNotification notificationWithName:UIApplicationDidEnterBackgroundNotification + object:nil + userInfo:nil]; + id mockEngine = OCMPartialMock(engine); + [NSNotificationCenter.defaultCenter postNotification:sceneNotification]; + [NSNotificationCenter.defaultCenter postNotification:applicationNotification]; + OCMVerify(times(1), [mockEngine sceneDidEnterBackground:[OCMArg any]]); + XCTAssertTrue(engine.isGpuDisabled); + BOOL gpuDisabled = NO; + [engine shell].GetIsGpuDisabledSyncSwitch()->Execute( + fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] { + gpuDisabled = NO; + })); + XCTAssertTrue(gpuDisabled); + [mockBundle stopMocking]; +} + +- (void)testLifeCycleNotificationWillEnterForegroundForApplication { + FlutterDartProject* project = [[FlutterDartProject alloc] init]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project]; + [engine run]; + NSNotification* sceneNotification = + [NSNotification notificationWithName:UISceneWillEnterForegroundNotification + object:nil + userInfo:nil]; + NSNotification* applicationNotification = + [NSNotification notificationWithName:UIApplicationWillEnterForegroundNotification + object:nil + userInfo:nil]; + id mockEngine = OCMPartialMock(engine); + [NSNotificationCenter.defaultCenter postNotification:sceneNotification]; + [NSNotificationCenter.defaultCenter postNotification:applicationNotification]; + OCMVerify(times(1), [mockEngine applicationWillEnterForeground:[OCMArg any]]); + XCTAssertFalse(engine.isGpuDisabled); + BOOL gpuDisabled = YES; + [engine shell].GetIsGpuDisabledSyncSwitch()->Execute( + fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] { + gpuDisabled = NO; + })); + XCTAssertFalse(gpuDisabled); +} + +- (void)testLifeCycleNotificationWillEnterForegroundForScene { + id mockBundle = OCMPartialMock([NSBundle mainBundle]); + OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{ + @"NSExtensionPointIdentifier" : @"com.apple.share-services" + }); + FlutterDartProject* project = [[FlutterDartProject alloc] init]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project]; + [engine run]; + NSNotification* sceneNotification = + [NSNotification notificationWithName:UISceneWillEnterForegroundNotification + object:nil + userInfo:nil]; + NSNotification* applicationNotification = + [NSNotification notificationWithName:UIApplicationWillEnterForegroundNotification + object:nil + userInfo:nil]; + id mockEngine = OCMPartialMock(engine); + [NSNotificationCenter.defaultCenter postNotification:sceneNotification]; + [NSNotificationCenter.defaultCenter postNotification:applicationNotification]; + OCMVerify(times(1), [mockEngine sceneWillEnterForeground:[OCMArg any]]); + XCTAssertFalse(engine.isGpuDisabled); + BOOL gpuDisabled = YES; + [engine shell].GetIsGpuDisabledSyncSwitch()->Execute( + fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] { + gpuDisabled = NO; + })); + XCTAssertFalse(gpuDisabled); + [mockBundle stopMocking]; +} + +- (void)testSpawnsShareGpuContext { + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar"]; + [engine run]; + FlutterEngine* spawn = [engine spawnWithEntrypoint:nil + libraryURI:nil + initialRoute:nil + entrypointArgs:nil]; + XCTAssertNotNil(spawn); + XCTAssertTrue(engine.platformView != nullptr); + XCTAssertTrue(spawn.platformView != nullptr); + std::shared_ptr engine_context = engine.platformView->GetIosContext(); + std::shared_ptr spawn_context = spawn.platformView->GetIosContext(); + XCTAssertEqual(engine_context, spawn_context); +} + +- (void)testEnableSemanticsWhenFlutterViewAccessibilityDidCall { + FlutterEngineSpy* engine = [[FlutterEngineSpy alloc] initWithName:@"foobar"]; + engine.ensureSemanticsEnabledCalled = NO; + [engine flutterViewAccessibilityDidCall]; + XCTAssertTrue(engine.ensureSemanticsEnabledCalled); +} + +- (void)testCanMergePlatformAndUIThread { +#if defined(TARGET_IPHONE_SIMULATOR) && TARGET_IPHONE_SIMULATOR + auto settings = FLTDefaultSettingsForBundle(); + FlutterDartProject* project = [[FlutterDartProject alloc] initWithSettings:settings]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project]; + [engine run]; + + XCTAssertEqual(engine.shell.GetTaskRunners().GetUITaskRunner(), + engine.shell.GetTaskRunners().GetPlatformTaskRunner()); +#endif // defined(TARGET_IPHONE_SIMULATOR) && TARGET_IPHONE_SIMULATOR +} + +- (void)testCanUnMergePlatformAndUIThread { +#if defined(TARGET_IPHONE_SIMULATOR) && TARGET_IPHONE_SIMULATOR + auto settings = FLTDefaultSettingsForBundle(); + settings.merged_platform_ui_thread = false; + FlutterDartProject* project = [[FlutterDartProject alloc] initWithSettings:settings]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project]; + [engine run]; + + XCTAssertNotEqual(engine.shell.GetTaskRunners().GetUITaskRunner(), + engine.shell.GetTaskRunners().GetPlatformTaskRunner()); +#endif // defined(TARGET_IPHONE_SIMULATOR) && TARGET_IPHONE_SIMULATOR +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h new file mode 100644 index 0000000000000000000000000000000000000000..de79d011c5c46269ee46189383e17ece7389d74e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h @@ -0,0 +1,110 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERENGINE_INTERNAL_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERENGINE_INTERNAL_H_ + +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterEngine.h" + +#include "flutter/fml/memory/weak_ptr.h" +#include "flutter/fml/task_runner.h" +#include "flutter/lib/ui/window/pointer_data_packet.h" +#include "flutter/lib/ui/window/viewport_metrics.h" +#include "flutter/shell/common/platform_view.h" +#include "flutter/shell/common/rasterizer.h" +#include "flutter/shell/common/shell.h" + +#include "flutter/shell/platform/embedder/embedder.h" + +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterEngine.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterIndirectScribbleDelegate.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPlugin.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterRestorationPlugin.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface FlutterEngine () + +- (void)updateViewportMetrics:(flutter::ViewportMetrics)viewportMetrics; +- (void)dispatchPointerDataPacket:(std::unique_ptr)packet; + +- (fml::RefPtr)platformTaskRunner; +- (fml::RefPtr)uiTaskRunner; +- (fml::RefPtr)rasterTaskRunner; + +- (void)installFirstFrameCallback:(void (^)(void))block; +- (void)enableSemantics:(BOOL)enabled withFlags:(int64_t)flags; +- (void)notifyViewCreated; +- (void)notifyViewDestroyed; + +- (flutter::Rasterizer::Screenshot)screenshot:(flutter::Rasterizer::ScreenshotType)type + base64Encode:(bool)base64Encode; + +- (FlutterPlatformPlugin*)platformPlugin; +- (FlutterTextInputPlugin*)textInputPlugin; +- (FlutterRestorationPlugin*)restorationPlugin; +- (void)launchEngine:(nullable NSString*)entrypoint + libraryURI:(nullable NSString*)libraryOrNil + entrypointArgs:(nullable NSArray*)entrypointArgs; +- (BOOL)createShell:(nullable NSString*)entrypoint + libraryURI:(nullable NSString*)libraryOrNil + initialRoute:(nullable NSString*)initialRoute; +- (void)attachView; +- (void)notifyLowMemory; + +/// Blocks until the first frame is presented or the timeout is exceeded, then invokes callback. +- (void)waitForFirstFrameSync:(NSTimeInterval)timeout + callback:(NS_NOESCAPE void (^)(BOOL didTimeout))callback; + +/// Asynchronously waits until the first frame is presented or the timeout is exceeded, then invokes +/// callback. +- (void)waitForFirstFrame:(NSTimeInterval)timeout callback:(void (^)(BOOL didTimeout))callback; + +/** + * Creates one running FlutterEngine from another, sharing components between them. + * + * This results in a faster creation time and a smaller memory footprint engine. + * This should only be called on a FlutterEngine that is running. + */ +- (FlutterEngine*)spawnWithEntrypoint:(nullable NSString*)entrypoint + libraryURI:(nullable NSString*)libraryURI + initialRoute:(nullable NSString*)initialRoute + entrypointArgs:(nullable NSArray*)entrypointArgs; + +/** + * Dispatches the given key event data to the framework through the engine. + * The callback is called once the response from the framework is received. + */ +- (void)sendKeyEvent:(const FlutterKeyEvent&)event + callback:(nullable FlutterKeyEventCallback)callback + userData:(nullable void*)userData; + +@property(nonatomic, readonly) FlutterDartProject* project; + +/** + * Returns the engine handle. Used in FlutterEngineTest. + */ +- (int64_t)engineIdentifier; + +/** + * Returns engine for the identifier. The identifier must be valid for an engine + * that is currently running, otherwise the behavior is undefined. + * + * The identifier can be obtained in Dart code through + * `PlatformDispatcher.instance.engineId`. + * + * This function must be called on the main thread. + */ ++ (nullable FlutterEngine*)engineForIdentifier:(int64_t)identifier; + +@end + +NS_ASSUME_NONNULL_END + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERENGINE_INTERNAL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Test.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Test.h new file mode 100644 index 0000000000000000000000000000000000000000..b20ef4176492059995e8d964e5a7cfbe2e7be75b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Test.h @@ -0,0 +1,49 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERENGINE_TEST_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERENGINE_TEST_H_ + +#import "flutter/shell/common/shell.h" +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterEngine.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h" +#include "flutter/shell/platform/darwin/ios/platform_view_ios.h" +#import "flutter/shell/platform/darwin/ios/rendering_api_selection.h" +#include "flutter/shell/platform/embedder/embedder.h" + +@class FlutterBinaryMessengerRelay; + +namespace flutter { +class ThreadHost; +} + +// Category to add test-only visibility. +@interface FlutterEngine (Test) + +@property(readonly, nonatomic) FlutterEngineProcTable& embedderAPI; +@property(readonly, nonatomic) BOOL enableEmbedderAPI; + +- (flutter::Shell&)shell; +- (flutter::PlatformViewIOS*)platformView; + +- (void)setBinaryMessenger:(FlutterBinaryMessengerRelay*)binaryMessenger; +- (flutter::IOSRenderingAPI)platformViewsRenderingAPI; +- (void)waitForFirstFrame:(NSTimeInterval)timeout callback:(void (^)(BOOL didTimeout))callback; +- (FlutterEngine*)spawnWithEntrypoint:(/*nullable*/ NSString*)entrypoint + libraryURI:(/*nullable*/ NSString*)libraryURI + initialRoute:(/*nullable*/ NSString*)initialRoute + entrypointArgs:(/*nullable*/ NSArray*)entrypointArgs; +- (const flutter::ThreadHost&)threadHost; +- (void)updateDisplays; +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + performAction:(FlutterTextInputAction)action + withClient:(int)client; +- (void)sceneWillEnterForeground:(NSNotification*)notification API_AVAILABLE(ios(13.0)); +- (void)sceneDidEnterBackground:(NSNotification*)notification API_AVAILABLE(ios(13.0)); +- (void)applicationWillEnterForeground:(NSNotification*)notification; +- (void)applicationDidEnterBackground:(NSNotification*)notification; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERENGINE_TEST_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.h new file mode 100644 index 0000000000000000000000000000000000000000..42d4626fa37209686ff23d83ab9283fbd5c49b38 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.h @@ -0,0 +1,75 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERFAKEKEYEVENTS_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERFAKEKEYEVENTS_H_ + +#import +#import +#import + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h" + +API_AVAILABLE(ios(13.4)) +@interface FakeUIPressProxy : FlutterUIPressProxy +- (instancetype)initWithData:(UIPressPhase)phase + key:(UIKey*)key + type:(UIEventType)type + timestamp:(NSTimeInterval)timestamp API_AVAILABLE(ios(13.4)); + +- (UIPressPhase)phase API_AVAILABLE(ios(13.4)); +- (UIKey*)key API_AVAILABLE(ios(13.4)); +- (UIEventType)type API_AVAILABLE(ios(13.4)); +- (NSTimeInterval)timestamp API_AVAILABLE(ios(13.4)); + +@property(nonatomic, readonly) UIPressPhase dataPhase; +@property(nonatomic, readonly) UIKey* dataKey; +@property(nonatomic, readonly) UIEventType dataType; +@property(nonatomic, readonly) NSTimeInterval dataTimestamp; +@end + +API_AVAILABLE(ios(13.4)) +@interface FakeUIKey : UIKey +- (instancetype)initWithData:(UIKeyboardHIDUsage)keyCode + modifierFlags:(UIKeyModifierFlags)modifierFlags + characters:(NSString*)characters + charactersIgnoringModifiers:(NSString*)charactersIgnoringModifiers API_AVAILABLE(ios(13.4)); + +- (UIKeyboardHIDUsage)keyCode; +- (UIKeyModifierFlags)modifierFlags; +- (NSString*)characters; +- (NSString*)charactersIgnoringModifiers; + +@property(assign, nonatomic) UIKeyboardHIDUsage dataKeyCode; +@property(assign, nonatomic) UIKeyModifierFlags dataModifierFlags; +@property(readwrite, nonatomic) NSString* dataCharacters; +@property(readwrite, nonatomic) NSString* dataCharactersIgnoringModifiers; +@end + +namespace flutter { +namespace testing { +extern FlutterUIPressProxy* keyDownEvent(UIKeyboardHIDUsage keyCode, + UIKeyModifierFlags modifierFlags = 0x0, + NSTimeInterval timestamp = 0.0f, + const char* characters = "", + const char* charactersIgnoringModifiers = "") + API_AVAILABLE(ios(13.4)); + +extern FlutterUIPressProxy* keyUpEvent(UIKeyboardHIDUsage keyCode, + UIKeyModifierFlags modifierFlags = 0x0, + NSTimeInterval timestamp = 0.0f, + const char* characters = "", + const char* charactersIgnoringModifiers = "") + API_AVAILABLE(ios(13.4)); + +extern FlutterUIPressProxy* keyEventWithPhase(UIPressPhase phase, + UIKeyboardHIDUsage keyCode, + UIKeyModifierFlags modifierFlags = 0x0, + NSTimeInterval timestamp = 0.0f, + const char* characters = "", + const char* charactersIgnoringModifiers = "") + API_AVAILABLE(ios(13.4)); +} // namespace testing +} // namespace flutter +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERFAKEKEYEVENTS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.mm new file mode 100644 index 0000000000000000000000000000000000000000..aaca2b898581aee350d1e2c5997ead761dfd6519 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.mm @@ -0,0 +1,130 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.h" + +#include "flutter/fml/logging.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/KeyCodeMap_Internal.h" + +FLUTTER_ASSERT_ARC; + +@implementation FakeUIPressProxy +- (instancetype)initWithData:(UIPressPhase)phase + key:(UIKey*)key + type:(UIEventType)type + timestamp:(NSTimeInterval)timestamp API_AVAILABLE(ios(13.4)) { + self = [super init]; + if (self) { + _dataPhase = phase; + _dataKey = [key copy]; + _dataType = type; + _dataTimestamp = timestamp; + } + return self; +} + +- (UIPressPhase)phase API_AVAILABLE(ios(13.4)) { + return _dataPhase; +} + +- (UIKey*)key API_AVAILABLE(ios(13.4)) { + return _dataKey; +} + +- (UIEventType)type API_AVAILABLE(ios(13.4)) { + return _dataType; +} + +- (NSTimeInterval)timestamp API_AVAILABLE(ios(13.4)) { + return _dataTimestamp; +} +@end + +@implementation FakeUIKey +- (instancetype)initWithData:(UIKeyboardHIDUsage)keyCode + modifierFlags:(UIKeyModifierFlags)modifierFlags + characters:(NSString*)characters + charactersIgnoringModifiers:(NSString*)charactersIgnoringModifiers API_AVAILABLE(ios(13.4)) { + self = [super init]; + if (self) { + _dataKeyCode = keyCode; + _dataModifierFlags = modifierFlags; + _dataCharacters = characters; + _dataCharactersIgnoringModifiers = charactersIgnoringModifiers; + } + return self; +} + +- (id)copyWithZone:(NSZone*)zone { + FakeUIKey* another = [super copyWithZone:zone]; + another.dataKeyCode = _dataKeyCode; + another.dataModifierFlags = _dataModifierFlags; + another.dataCharacters = [_dataCharacters copyWithZone:zone]; + another.dataCharactersIgnoringModifiers = [_dataCharactersIgnoringModifiers copyWithZone:zone]; + + return another; +} + +- (UIKeyboardHIDUsage)keyCode API_AVAILABLE(ios(13.4)) { + return _dataKeyCode; +} + +- (UIKeyModifierFlags)modifierFlags API_AVAILABLE(ios(13.4)) { + return _dataModifierFlags; +} + +- (NSString*)characters API_AVAILABLE(ios(13.4)) { + return _dataCharacters; +} + +- (NSString*)charactersIgnoringModifiers API_AVAILABLE(ios(13.4)) { + return _dataCharactersIgnoringModifiers; +} +@end + +namespace flutter { +namespace testing { + +FlutterUIPressProxy* keyDownEvent(UIKeyboardHIDUsage keyCode, + UIKeyModifierFlags modifierFlags, + NSTimeInterval timestamp, + const char* characters, + const char* charactersIgnoringModifiers) + API_AVAILABLE(ios(13.4)) { + return keyEventWithPhase(UIPressPhaseBegan, keyCode, modifierFlags, timestamp, characters, + charactersIgnoringModifiers); +} + +FlutterUIPressProxy* keyUpEvent(UIKeyboardHIDUsage keyCode, + UIKeyModifierFlags modifierFlags, + NSTimeInterval timestamp, + const char* characters, + const char* charactersIgnoringModifiers) API_AVAILABLE(ios(13.4)) { + return keyEventWithPhase(UIPressPhaseEnded, keyCode, modifierFlags, timestamp, characters, + charactersIgnoringModifiers); +} + +FlutterUIPressProxy* keyEventWithPhase(UIPressPhase phase, + UIKeyboardHIDUsage keyCode, + UIKeyModifierFlags modifierFlags, + NSTimeInterval timestamp, + const char* characters, + const char* charactersIgnoringModifiers) + API_AVAILABLE(ios(13.4)) { + FML_DCHECK(!(modifierFlags & kModifierFlagSidedMask)) + << "iOS doesn't supply modifier side flags, so don't create events with them."; + UIKey* key = + [[FakeUIKey alloc] initWithData:keyCode + modifierFlags:modifierFlags + characters:[NSString stringWithUTF8String:characters] + charactersIgnoringModifiers:[NSString stringWithUTF8String:charactersIgnoringModifiers]]; + + return [[FakeUIPressProxy alloc] initWithData:phase + key:key + type:UIEventTypePresses + timestamp:timestamp]; +} +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterHeadlessDartRunner.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterHeadlessDartRunner.mm new file mode 100644 index 0000000000000000000000000000000000000000..f85da98240a17168f35db54d5b6d921c8af10864 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterHeadlessDartRunner.mm @@ -0,0 +1,61 @@ +// 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. + +#define FML_USED_ON_EMBEDDER + +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterHeadlessDartRunner.h" + +#include + +#include "flutter/fml/make_copyable.h" +#include "flutter/fml/message_loop.h" +#include "flutter/shell/common/engine.h" +#include "flutter/shell/common/rasterizer.h" +#include "flutter/shell/common/run_configuration.h" +#include "flutter/shell/common/shell.h" +#include "flutter/shell/common/switches.h" +#include "flutter/shell/common/thread_host.h" +#import "flutter/shell/platform/darwin/common/command_line.h" +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterPlugin.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/platform_message_response_darwin.h" +#import "flutter/shell/platform/darwin/ios/platform_view_ios.h" + +FLUTTER_ASSERT_ARC + +@implementation FlutterHeadlessDartRunner + +- (instancetype)initWithName:(NSString*)labelPrefix project:(FlutterDartProject*)projectOrNil { + return [self initWithName:labelPrefix project:projectOrNil allowHeadlessExecution:YES]; +} + +- (instancetype)initWithName:(NSString*)labelPrefix + project:(FlutterDartProject*)projectOrNil + allowHeadlessExecution:(BOOL)allowHeadlessExecution { + NSAssert(allowHeadlessExecution == YES, + @"Cannot initialize a FlutterHeadlessDartRunner without headless execution."); + return [self initWithName:labelPrefix + project:projectOrNil + allowHeadlessExecution:allowHeadlessExecution + restorationEnabled:NO]; +} + +- (instancetype)initWithName:(NSString*)labelPrefix + project:(FlutterDartProject*)projectOrNil + allowHeadlessExecution:(BOOL)allowHeadlessExecution + restorationEnabled:(BOOL)restorationEnabled { + NSAssert(allowHeadlessExecution == YES, + @"Cannot initialize a FlutterHeadlessDartRunner without headless execution."); + return [super initWithName:labelPrefix + project:projectOrNil + allowHeadlessExecution:allowHeadlessExecution + restorationEnabled:restorationEnabled]; +} + +- (instancetype)init { + return [self initWithName:@"io.flutter.headless" project:nil]; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterIndirectScribbleDelegate.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterIndirectScribbleDelegate.h new file mode 100644 index 0000000000000000000000000000000000000000..1611941e8c81e57f900ef9e9a1b94663aac8784b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterIndirectScribbleDelegate.h @@ -0,0 +1,24 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERINDIRECTSCRIBBLEDELEGATE_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERINDIRECTSCRIBBLEDELEGATE_H_ + +#import + +NS_ASSUME_NONNULL_BEGIN +@class FlutterTextInputPlugin; + +@protocol FlutterIndirectScribbleDelegate +- (void)flutterTextInputPlugin:(FlutterTextInputPlugin*)textInputPlugin + focusElement:(UIScribbleElementIdentifier)elementIdentifier + atPoint:(CGPoint)referencePoint + result:(FlutterResult)callback; +- (void)flutterTextInputPlugin:(FlutterTextInputPlugin*)textInputPlugin + requestElementsInRect:(CGRect)rect + result:(FlutterResult)callback; +@end +NS_ASSUME_NONNULL_END + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERINDIRECTSCRIBBLEDELEGATE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyPrimaryResponder.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyPrimaryResponder.h new file mode 100644 index 0000000000000000000000000000000000000000..2843e5d5d35cf064782cf3aad1827f4431fe4aa5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyPrimaryResponder.h @@ -0,0 +1,34 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERKEYPRIMARYRESPONDER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERKEYPRIMARYRESPONDER_H_ + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h" + +typedef void (^FlutterAsyncKeyCallback)(BOOL handled); + +/** + * An interface for a responder that can process a key press event and decides + * whether to handle the event asynchronously. + * + * To use this class, add it to a |FlutterKeyboardManager| with + * |addPrimaryResponder|. + */ +@protocol FlutterKeyPrimaryResponder + +/** + * Process the event. + * + * The |callback| should be called with a value that indicates whether the + * responder has handled the given press event. The |callback| must be called + * exactly once, and can be called before the return of this method, or after. + */ +@required +- (void)handlePress:(nonnull FlutterUIPressProxy*)press + callback:(nonnull FlutterAsyncKeyCallback)callback API_AVAILABLE(ios(13.4)); + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERKEYPRIMARYRESPONDER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeySecondaryResponder.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeySecondaryResponder.h new file mode 100644 index 0000000000000000000000000000000000000000..7a23014fa8a9e77c67b9b1a5e7e0977554334c2f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeySecondaryResponder.h @@ -0,0 +1,31 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERKEYSECONDARYRESPONDER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERKEYSECONDARYRESPONDER_H_ + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h" + +/** + * An interface for a responder that can process a key event and synchronously + * decide whether to handle the event. + * + * To use this class, add it to a |FlutterKeyboardManager| with + * |addSecondaryResponder|. + */ +@protocol FlutterKeySecondaryResponder + +/** + * Informs the receiver that the user has interacted with a key. + * + * The return value indicates whether it has handled the given event. + * + * Default implementation returns NO. + */ +@required + +- (BOOL)handlePress:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)); +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERKEYSECONDARYRESPONDER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.h new file mode 100644 index 0000000000000000000000000000000000000000..33763f7499dccd7db08c370f6f316a3ed78997e9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.h @@ -0,0 +1,74 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERKEYBOARDMANAGER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERKEYBOARDMANAGER_H_ + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyPrimaryResponder.h" + +#import +#import + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyPrimaryResponder.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeySecondaryResponder.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h" + +typedef void (^KeyEventCompleteCallback)(bool, FlutterUIPressProxy* _Nonnull) + API_AVAILABLE(ios(13.4)); + +/** + * A hub that manages how key events are dispatched to various Flutter key + * responders, and propagates it to the superclass if the Flutter key responders + * do not handle it. + * + * This class manages one or more primary responders, as well as zero or more + * secondary responders. + * + * An event that is received by |handlePresses| is first dispatched to *all* + * primary responders. Each primary responder responds *asynchronously* with a + * boolean, indicating whether it handles the event. + * + * An event that is not handled by any primary responders is then passed to to + * the first secondary responder (in the chronological order of addition), + * which responds *synchronously* with a boolean, indicating whether it handles + * the event. If not, the event is passed to the next secondary responder, and + * so on. + * + * The event is then handed back to the |completeCallback| from the original + * call to |handlePresses| so that it can respond synchronously to the OS if the + * event was not handled by the responders. The |completeCallback| is called on + * the platform thread because the platform thread is blocked by a nested event + * loop while the response from the framework is being collected, and it needs + * to be called on the platform thread to unblock the thread by exiting the + * nested event loop. + * + * Preventing primary responders from receiving events is not supported, because + * in reality this class only supports two hardcoded responders + * (FlutterChannelKeyResponder and FlutterEmbedderKeyResponder), where the only purpose + * of supporting two is to maintain the legacy channel API during the + * deprecation window, after which the channel responder should be removed, and + * only one primary responder will exist. + */ +@interface FlutterKeyboardManager : NSObject +/** + * Add a primary responder, which asynchronously decides whether to handle an + * event. + */ +- (void)addPrimaryResponder:(nonnull id)responder; + +/** + * Add a secondary responder, which synchronously decides whether to handle an + * event in order if no earlier responders handle. + */ +- (void)addSecondaryResponder:(nonnull id)responder; + +/** + * Dispatches a key press event to all responders, gathering their responses, + * and then calls the |nextAction| if the event was not handled. + */ +- (void)handlePress:(nonnull FlutterUIPressProxy*)press + nextAction:(nonnull void (^)())next API_AVAILABLE(ios(13.4)); +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERKEYBOARDMANAGER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.mm new file mode 100644 index 0000000000000000000000000000000000000000..83d1e22a1aabe2355bc5263e193b9fb998bd33d8 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.mm @@ -0,0 +1,133 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.h" + +#include "flutter/fml/platform/darwin/message_loop_darwin.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" + +FLUTTER_ASSERT_ARC + +static constexpr CFTimeInterval kDistantFuture = 1.0e10; + +@interface FlutterKeyboardManager () + +/** + * The primary responders added by addPrimaryResponder. + */ +@property(nonatomic, copy, readonly) + NSMutableArray>* primaryResponders; + +/** + * The secondary responders added by addSecondaryResponder. + */ +@property(nonatomic, copy, readonly) + NSMutableArray>* secondaryResponders; + +- (void)dispatchToSecondaryResponders:(nonnull FlutterUIPressProxy*)press + complete:(nonnull KeyEventCompleteCallback)callback + API_AVAILABLE(ios(13.4)); + +@end + +@implementation FlutterKeyboardManager + +- (nonnull instancetype)init { + self = [super init]; + if (self != nil) { + _primaryResponders = [[NSMutableArray alloc] init]; + _secondaryResponders = [[NSMutableArray alloc] init]; + } + return self; +} + +- (void)addPrimaryResponder:(nonnull id)responder { + [_primaryResponders addObject:responder]; +} + +- (void)addSecondaryResponder:(nonnull id)responder { + [_secondaryResponders addObject:responder]; +} + +- (void)handlePress:(nonnull FlutterUIPressProxy*)press + nextAction:(nonnull void (^)())next API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + // no-op + } else { + return; + } + + bool __block wasHandled = false; + KeyEventCompleteCallback completeCallback = ^void(bool handled, FlutterUIPressProxy* press) { + wasHandled = handled; + CFRunLoopStop(CFRunLoopGetCurrent()); + }; + switch (press.phase) { + case UIPressPhaseBegan: + case UIPressPhaseEnded: { + // Having no primary responders requires extra logic, but Flutter hard-codes + // all primary responders, so this is a situation that Flutter will never + // encounter. + NSAssert([_primaryResponders count] >= 0, @"At least one primary responder must be added."); + + __block __weak __typeof(self) weakSelf = self; + __block NSUInteger unreplied = [self.primaryResponders count]; + __block BOOL anyHandled = false; + FlutterAsyncKeyCallback replyCallback = ^(BOOL handled) { + unreplied--; + NSAssert(unreplied >= 0, @"More primary responders replied than expected."); + anyHandled = anyHandled || handled; + if (unreplied == 0) { + if (!anyHandled && weakSelf) { + [weakSelf dispatchToSecondaryResponders:press complete:completeCallback]; + } else { + completeCallback(true, press); + } + } + }; + for (id responder in _primaryResponders) { + [responder handlePress:press callback:replyCallback]; + } + // Create a nested run loop while we wait for a response from the + // framework. Once the completeCallback is called, this run loop will exit + // and the main one will resume. The completeCallback MUST be called, or + // the app will get stuck in this run loop indefinitely. + // + // We need to run in this mode so that UIKit doesn't give us new + // events until we are done processing this one. + CFRunLoopRunInMode(fml::MessageLoopDarwin::kMessageLoopCFRunLoopMode, kDistantFuture, NO); + break; + } + case UIPressPhaseChanged: + case UIPressPhaseCancelled: + case UIPressPhaseStationary: + break; + } + if (!wasHandled) { + next(); + } +} + +#pragma mark - Private + +- (void)dispatchToSecondaryResponders:(nonnull FlutterUIPressProxy*)press + complete:(nonnull KeyEventCompleteCallback)callback + API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + // no-op + } else { + callback(false, press); + return; + } + + for (id responder in _secondaryResponders) { + if ([responder handlePress:press]) { + callback(true, press); + return; + } + } + callback(false, press); +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManagerTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManagerTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..7ebd7c01a3ace739aaa2daf31026e99917ec9f7b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManagerTest.mm @@ -0,0 +1,313 @@ +// 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. + +#import +#import +#import +#import +#include <_types/_uint32_t.h> + +#include "flutter/fml/platform/darwin/message_loop_darwin.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h" + +FLUTTER_ASSERT_ARC; + +namespace flutter { +class PointerDataPacket {}; +} // namespace flutter + +using namespace flutter::testing; + +namespace { + +typedef void (^KeyCallbackSetter)(FlutterUIPressProxy* press, FlutterAsyncKeyCallback callback) + API_AVAILABLE(ios(13.4)); +typedef BOOL (^BoolGetter)(); + +} // namespace + +// These tests were designed to run on iOS 13.4 or later. +API_AVAILABLE(ios(13.4)) +@interface FlutterKeyboardManagerTest : XCTestCase +@end + +@implementation FlutterKeyboardManagerTest + +- (id)mockPrimaryResponder:(KeyCallbackSetter)callbackSetter { + id mock = + OCMStrictProtocolMock(@protocol(FlutterKeyPrimaryResponder)); + OCMStub([mock handlePress:[OCMArg any] callback:[OCMArg any]]) + .andDo((^(NSInvocation* invocation) { + __unsafe_unretained FlutterUIPressProxy* pressUnsafe; + __unsafe_unretained FlutterAsyncKeyCallback callbackUnsafe; + + [invocation getArgument:&pressUnsafe atIndex:2]; + [invocation getArgument:&callbackUnsafe atIndex:3]; + + // Retain the unretained parameters so they can + // be run in the perform block when this invocation goes out of scope. + FlutterUIPressProxy* press = pressUnsafe; + FlutterAsyncKeyCallback callback = callbackUnsafe; + CFRunLoopPerformBlock(CFRunLoopGetCurrent(), + fml::MessageLoopDarwin::kMessageLoopCFRunLoopMode, ^() { + callbackSetter(press, callback); + }); + })); + return mock; +} + +- (id)mockSecondaryResponder:(BoolGetter)resultGetter { + id mock = + OCMStrictProtocolMock(@protocol(FlutterKeySecondaryResponder)); + OCMStub([mock handlePress:[OCMArg any]]).andDo((^(NSInvocation* invocation) { + BOOL result = resultGetter(); + [invocation setReturnValue:&result]; + })); + return mock; +} + +- (void)testNextResponderShouldThrowOnPressesEnded { + // The nextResponder is a strict mock and hasn't stubbed pressesEnded. + // An error will be thrown on pressesEnded. + UIResponder* nextResponder = OCMStrictClassMock([UIResponder class]); + OCMStub([nextResponder pressesBegan:OCMOCK_ANY withEvent:OCMOCK_ANY]); + + id mockEngine = OCMClassMock([FlutterEngine class]); + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + FlutterViewController* owner = OCMPartialMock(viewController); + OCMStub([owner nextResponder]).andReturn(nextResponder); + + XCTAssertThrowsSpecificNamed([owner.nextResponder pressesEnded:[[NSSet alloc] init] + withEvent:[[UIPressesEvent alloc] init]], + NSException, NSInternalInconsistencyException); + + [mockEngine stopMocking]; +} + +- (void)testSinglePrimaryResponder { + FlutterKeyboardManager* manager = [[FlutterKeyboardManager alloc] init]; + __block BOOL primaryResponse = FALSE; + __block int callbackCount = 0; + [manager addPrimaryResponder:[self mockPrimaryResponder:^(FlutterUIPressProxy* press, + FlutterAsyncKeyCallback callback) { + callbackCount++; + callback(primaryResponse); + }]]; + constexpr UIKeyboardHIDUsage keyId = (UIKeyboardHIDUsage)0x50; + // Case: The responder reports TRUE + __block bool completeHandled = true; + primaryResponse = TRUE; + [manager handlePress:keyDownEvent(keyId) + nextAction:^() { + completeHandled = false; + }]; + XCTAssertEqual(callbackCount, 1); + XCTAssertTrue(completeHandled); + completeHandled = true; + callbackCount = 0; + + // Case: The responder reports FALSE + primaryResponse = FALSE; + [manager handlePress:keyUpEvent(keyId) + nextAction:^() { + completeHandled = false; + }]; + XCTAssertEqual(callbackCount, 1); + XCTAssertFalse(completeHandled); +} + +- (void)testDoublePrimaryResponder { + FlutterKeyboardManager* manager = [[FlutterKeyboardManager alloc] init]; + + __block BOOL callback1Response = FALSE; + __block int callback1Count = 0; + [manager addPrimaryResponder:[self mockPrimaryResponder:^(FlutterUIPressProxy* press, + FlutterAsyncKeyCallback callback) { + callback1Count++; + callback(callback1Response); + }]]; + + __block BOOL callback2Response = FALSE; + __block int callback2Count = 0; + [manager addPrimaryResponder:[self mockPrimaryResponder:^(FlutterUIPressProxy* press, + FlutterAsyncKeyCallback callback) { + callback2Count++; + callback(callback2Response); + }]]; + + // Case: Both responders report TRUE. + __block bool somethingWasHandled = true; + constexpr UIKeyboardHIDUsage keyId = (UIKeyboardHIDUsage)0x50; + callback1Response = TRUE; + callback2Response = TRUE; + [manager handlePress:keyUpEvent(keyId) + nextAction:^() { + somethingWasHandled = false; + }]; + XCTAssertEqual(callback1Count, 1); + XCTAssertEqual(callback2Count, 1); + XCTAssertTrue(somethingWasHandled); + + somethingWasHandled = true; + callback1Count = 0; + callback2Count = 0; + + // Case: One responder reports TRUE. + callback1Response = TRUE; + callback2Response = FALSE; + [manager handlePress:keyUpEvent(keyId) + nextAction:^() { + somethingWasHandled = false; + }]; + XCTAssertEqual(callback1Count, 1); + XCTAssertEqual(callback2Count, 1); + XCTAssertTrue(somethingWasHandled); + + somethingWasHandled = true; + callback1Count = 0; + callback2Count = 0; + + // Case: Both responders report FALSE. + callback1Response = FALSE; + callback2Response = FALSE; + [manager handlePress:keyDownEvent(keyId) + nextAction:^() { + somethingWasHandled = false; + }]; + XCTAssertEqual(callback1Count, 1); + XCTAssertEqual(callback2Count, 1); + XCTAssertFalse(somethingWasHandled); +} + +- (void)testSingleSecondaryResponder { + FlutterKeyboardManager* manager = [[FlutterKeyboardManager alloc] init]; + + __block BOOL primaryResponse = FALSE; + __block int callbackCount = 0; + [manager addPrimaryResponder:[self mockPrimaryResponder:^(FlutterUIPressProxy* press, + FlutterAsyncKeyCallback callback) { + callbackCount++; + callback(primaryResponse); + }]]; + + __block BOOL secondaryResponse; + [manager addSecondaryResponder:[self mockSecondaryResponder:^() { + return secondaryResponse; + }]]; + + // Case: Primary responder responds TRUE. The event shouldn't be handled by + // the secondary responder. + constexpr UIKeyboardHIDUsage keyId = (UIKeyboardHIDUsage)0x50; + secondaryResponse = FALSE; + primaryResponse = TRUE; + __block bool completeHandled = true; + [manager handlePress:keyUpEvent(keyId) + nextAction:^() { + completeHandled = false; + }]; + XCTAssertEqual(callbackCount, 1); + XCTAssertTrue(completeHandled); + completeHandled = true; + callbackCount = 0; + + // Case: Primary responder responds FALSE. The secondary responder returns + // TRUE. + secondaryResponse = TRUE; + primaryResponse = FALSE; + [manager handlePress:keyUpEvent(keyId) + nextAction:^() { + completeHandled = false; + }]; + XCTAssertEqual(callbackCount, 1); + XCTAssertTrue(completeHandled); + completeHandled = true; + callbackCount = 0; + + // Case: Primary responder responds FALSE. The secondary responder returns FALSE. + secondaryResponse = FALSE; + primaryResponse = FALSE; + [manager handlePress:keyDownEvent(keyId) + nextAction:^() { + completeHandled = false; + }]; + XCTAssertEqual(callbackCount, 1); + XCTAssertFalse(completeHandled); +} + +- (void)testEventsProcessedSequentially { + constexpr UIKeyboardHIDUsage keyId1 = (UIKeyboardHIDUsage)0x50; + constexpr UIKeyboardHIDUsage keyId2 = (UIKeyboardHIDUsage)0x51; + FlutterUIPressProxy* event1 = keyDownEvent(keyId1); + FlutterUIPressProxy* event2 = keyDownEvent(keyId2); + __block FlutterAsyncKeyCallback key1Callback; + __block FlutterAsyncKeyCallback key2Callback; + __block bool key1Handled = true; + __block bool key2Handled = true; + + FlutterKeyboardManager* manager = [[FlutterKeyboardManager alloc] init]; + [manager addPrimaryResponder:[self mockPrimaryResponder:^(FlutterUIPressProxy* press, + FlutterAsyncKeyCallback callback) { + if (press == event1) { + key1Callback = callback; + } else if (press == event2) { + key2Callback = callback; + } + }]]; + + // Add both presses into the main CFRunLoop queue + CFRunLoopTimerRef timer0 = CFRunLoopTimerCreateWithHandler( + kCFAllocatorDefault, CFAbsoluteTimeGetCurrent(), 0, 0, 0, ^(CFRunLoopTimerRef timerRef) { + [manager handlePress:event1 + nextAction:^() { + key1Handled = false; + }]; + }); + CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer0, kCFRunLoopCommonModes); + CFRunLoopTimerRef timer1 = CFRunLoopTimerCreateWithHandler( + kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + 1, 0, 0, 0, ^(CFRunLoopTimerRef timerRef) { + // key1 should be completely finished by now + XCTAssertFalse(key1Handled); + [manager handlePress:event2 + nextAction:^() { + key2Handled = false; + }]; + // End the nested CFRunLoop + CFRunLoopStop(CFRunLoopGetCurrent()); + }); + CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer1, kCFRunLoopCommonModes); + + // Add the callbacks to the CFRunLoop with mode kMessageLoopCFRunLoopMode + // This allows them to interrupt the loop started within handlePress + CFRunLoopTimerRef timer2 = CFRunLoopTimerCreateWithHandler( + kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + 2, 0, 0, 0, ^(CFRunLoopTimerRef timerRef) { + // No processing should be done on key2 yet + XCTAssertTrue(key1Callback != nil); + XCTAssertTrue(key2Callback == nil); + key1Callback(false); + }); + CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer2, + fml::MessageLoopDarwin::kMessageLoopCFRunLoopMode); + CFRunLoopTimerRef timer3 = CFRunLoopTimerCreateWithHandler( + kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + 3, 0, 0, 0, ^(CFRunLoopTimerRef timerRef) { + // Both keys should be processed by now + XCTAssertTrue(key1Callback != nil); + XCTAssertTrue(key2Callback != nil); + key2Callback(false); + }); + CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer3, + fml::MessageLoopDarwin::kMessageLoopCFRunLoopMode); + + // Start a nested CFRunLoop so we can wait for both presses to complete before exiting the test + CFRunLoopRun(); + XCTAssertFalse(key2Handled); + XCTAssertFalse(key1Handled); +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.h new file mode 100644 index 0000000000000000000000000000000000000000..7aab78db946c84e734de94d8634eb653703cc2da --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.h @@ -0,0 +1,47 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERMETALLAYER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERMETALLAYER_H_ + +#import + +/// Drop-in replacement (as far as Flutter is concerned) for CAMetalLayer +/// that can present with transaction from a background thread. +/// +/// Properties and method declarations must exactly match those in the +/// CAMetalLayer interface declaration. +@interface FlutterMetalLayer : CALayer + +@property(nullable, retain) id device; +@property(nullable, readonly) + id preferredDevice API_AVAILABLE(macos(10.15), ios(13.0), tvos(13.0)) + API_UNAVAILABLE(watchos); +@property MTLPixelFormat pixelFormat; +@property BOOL framebufferOnly; +@property CGSize drawableSize; +@property BOOL presentsWithTransaction; +@property(nullable) CGColorSpaceRef colorspace; + +- (nullable id)nextDrawable; + +/// Returns whether the Metal layer is enabled. +/// This is controlled by FLTUseFlutterMetalLayer value in Info.plist. ++ (BOOL)enabled; + +@end + +@protocol MTLCommandBuffer; + +@protocol FlutterMetalDrawable + +/// In order for FlutterMetalLayer to provide back pressure it must have access +/// to the command buffer that is used to render into the drawable to schedule +/// a completion handler. +/// This method must be called before the command buffer is committed. +- (void)flutterPrepareForPresent:(nonnull id)commandBuffer; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERMETALLAYER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.mm new file mode 100644 index 0000000000000000000000000000000000000000..f31eda904b92d03a8434866e79a7a01a648773ad --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.mm @@ -0,0 +1,453 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.h" + +#include +#include +#include +#include + +#include "flutter/fml/logging.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" + +FLUTTER_ASSERT_ARC + +@interface DisplayLinkManager : NSObject +@property(class, nonatomic, readonly) BOOL maxRefreshRateEnabledOnIPhone; ++ (double)displayRefreshRate; +@end + +@class FlutterTexture; +@class FlutterDrawable; + +extern CFTimeInterval display_link_target; + +@interface FlutterMetalLayer () { + id _preferredDevice; + CGSize _drawableSize; + + NSUInteger _nextDrawableId; + + NSMutableSet* _availableTextures; + NSUInteger _totalTextures; + + FlutterTexture* _front; + + // There must be a CADisplayLink scheduled *on main thread* otherwise + // core animation only updates layers 60 times a second. + CADisplayLink* _displayLink; + NSUInteger _displayLinkPauseCountdown; + + // Used to track whether the content was set during this display link. + // When unlocking phone the layer (main thread) display link and raster thread + // display link get out of sync for several seconds. Even worse, layer display + // link does not seem to reflect actual vsync. Forcing the layer link + // to max rate (instead range) temporarily seems to fix the issue. + BOOL _didSetContentsDuringThisDisplayLinkPeriod; + + // Whether layer displayLink is forced to max rate. + BOOL _displayLinkForcedMaxRate; +} + +- (void)onDisplayLink:(CADisplayLink*)link; +- (void)presentTexture:(FlutterTexture*)texture; +- (void)returnTexture:(FlutterTexture*)texture; + +@end + +@interface FlutterTexture : NSObject + +@property(readonly, nonatomic) id texture; +@property(readonly, nonatomic) IOSurface* surface; +@property(readwrite, nonatomic) CFTimeInterval presentedTime; +@property(readwrite, atomic) BOOL waitingForCompletion; + +@end + +@implementation FlutterTexture + +- (instancetype)initWithTexture:(id)texture surface:(IOSurface*)surface { + if (self = [super init]) { + _texture = texture; + _surface = surface; + } + return self; +} + +@end + +@interface FlutterDrawable : NSObject { + FlutterTexture* _texture; + __weak FlutterMetalLayer* _layer; + NSUInteger _drawableId; + BOOL _presented; +} + +- (instancetype)initWithTexture:(FlutterTexture*)texture + layer:(FlutterMetalLayer*)layer + drawableId:(NSUInteger)drawableId; + +@end + +@implementation FlutterDrawable + +- (instancetype)initWithTexture:(FlutterTexture*)texture + layer:(FlutterMetalLayer*)layer + drawableId:(NSUInteger)drawableId { + if (self = [super init]) { + _texture = texture; + _layer = layer; + _drawableId = drawableId; + } + return self; +} + +- (id)texture { + return self->_texture.texture; +} + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability-new" +- (CAMetalLayer*)layer { + return (id)self->_layer; +} +#pragma clang diagnostic pop + +- (NSUInteger)drawableID { + return self->_drawableId; +} + +- (CFTimeInterval)presentedTime { + return 0; +} + +- (void)present { + [_layer presentTexture:self->_texture]; + self->_presented = YES; +} + +- (void)dealloc { + if (!_presented) { + [_layer returnTexture:self->_texture]; + } +} + +- (void)addPresentedHandler:(nonnull MTLDrawablePresentedHandler)block { + FML_LOG(WARNING) << "FlutterMetalLayer drawable does not implement addPresentedHandler:"; +} + +- (void)presentAtTime:(CFTimeInterval)presentationTime { + FML_LOG(WARNING) << "FlutterMetalLayer drawable does not implement presentAtTime:"; +} + +- (void)presentAfterMinimumDuration:(CFTimeInterval)duration { + FML_LOG(WARNING) << "FlutterMetalLayer drawable does not implement presentAfterMinimumDuration:"; +} + +- (void)flutterPrepareForPresent:(nonnull id)commandBuffer { + FlutterTexture* texture = _texture; + texture.waitingForCompletion = YES; + [commandBuffer addCompletedHandler:^(id buffer) { + texture.waitingForCompletion = NO; + }]; +} + +@end + +@interface FlutterMetalLayerDisplayLinkProxy : NSObject { + __weak FlutterMetalLayer* _layer; +} + +@end + +@implementation FlutterMetalLayerDisplayLinkProxy +- (instancetype)initWithLayer:(FlutterMetalLayer*)layer { + if (self = [super init]) { + _layer = layer; + } + return self; +} + +- (void)onDisplayLink:(CADisplayLink*)link { + [_layer onDisplayLink:link]; +} + +@end + +@implementation FlutterMetalLayer + +- (instancetype)init { + if (self = [super init]) { + _preferredDevice = MTLCreateSystemDefaultDevice(); + self.device = self.preferredDevice; + self.pixelFormat = MTLPixelFormatBGRA8Unorm; + _availableTextures = [[NSMutableSet alloc] init]; + + FlutterMetalLayerDisplayLinkProxy* proxy = + [[FlutterMetalLayerDisplayLinkProxy alloc] initWithLayer:self]; + _displayLink = [CADisplayLink displayLinkWithTarget:proxy selector:@selector(onDisplayLink:)]; + [self setMaxRefreshRate:DisplayLinkManager.displayRefreshRate forceMax:NO]; + [_displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(didEnterBackground:) + name:UIApplicationDidEnterBackgroundNotification + object:nil]; + } + return self; +} + +- (void)dealloc { + [_displayLink invalidate]; + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +- (void)setMaxRefreshRate:(double)refreshRate forceMax:(BOOL)forceMax { + // This is copied from vsync_waiter_ios.mm. The vsync waiter has display link scheduled on UI + // thread which does not trigger actual core animation frame. As a workaround FlutterMetalLayer + // has it's own displaylink scheduled on main thread, which is used to trigger core animation + // frame allowing for 120hz updates. + if (!DisplayLinkManager.maxRefreshRateEnabledOnIPhone) { + return; + } + double maxFrameRate = fmax(refreshRate, 60); + double minFrameRate = fmax(maxFrameRate / 2, 60); + if (@available(iOS 15.0, *)) { + _displayLink.preferredFrameRateRange = + CAFrameRateRangeMake(forceMax ? maxFrameRate : minFrameRate, maxFrameRate, maxFrameRate); + } else { + _displayLink.preferredFramesPerSecond = maxFrameRate; + } +} + +- (void)onDisplayLink:(CADisplayLink*)link { + _didSetContentsDuringThisDisplayLinkPeriod = NO; + // Do not pause immediately, this seems to prevent 120hz while touching. + if (_displayLinkPauseCountdown == 3) { + _displayLink.paused = YES; + if (_displayLinkForcedMaxRate) { + [self setMaxRefreshRate:DisplayLinkManager.displayRefreshRate forceMax:NO]; + _displayLinkForcedMaxRate = NO; + } + } else { + ++_displayLinkPauseCountdown; + } +} + +- (BOOL)isKindOfClass:(Class)aClass { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability-new" + // Pretend that we're a CAMetalLayer so that the rest of Flutter plays along + if ([aClass isEqual:[CAMetalLayer class]]) { + return YES; + } +#pragma clang diagnostic pop + return [super isKindOfClass:aClass]; +} + +- (void)setDrawableSize:(CGSize)drawableSize { + [_availableTextures removeAllObjects]; + _front = nil; + _totalTextures = 0; + _drawableSize = drawableSize; +} + +- (void)didEnterBackground:(id)notification { + [_availableTextures removeAllObjects]; + _totalTextures = _front != nil ? 1 : 0; + _displayLink.paused = YES; +} + +- (CGSize)drawableSize { + return _drawableSize; +} + +- (IOSurface*)createIOSurface { + unsigned pixelFormat; + unsigned bytesPerElement; + if (self.pixelFormat == MTLPixelFormatRGBA16Float) { + pixelFormat = kCVPixelFormatType_64RGBAHalf; + bytesPerElement = 8; + } else if (self.pixelFormat == MTLPixelFormatBGRA8Unorm) { + pixelFormat = kCVPixelFormatType_32BGRA; + bytesPerElement = 4; + } else if (self.pixelFormat == MTLPixelFormatBGRA10_XR) { + pixelFormat = kCVPixelFormatType_40ARGBLEWideGamut; + bytesPerElement = 8; + } else { + FML_LOG(ERROR) << "Unsupported pixel format: " << self.pixelFormat; + return nil; + } + size_t bytesPerRow = + IOSurfaceAlignProperty(kIOSurfaceBytesPerRow, _drawableSize.width * bytesPerElement); + size_t totalBytes = + IOSurfaceAlignProperty(kIOSurfaceAllocSize, _drawableSize.height * bytesPerRow); + NSDictionary* options = @{ + (id)kIOSurfaceWidth : @(_drawableSize.width), + (id)kIOSurfaceHeight : @(_drawableSize.height), + (id)kIOSurfacePixelFormat : @(pixelFormat), + (id)kIOSurfaceBytesPerElement : @(bytesPerElement), + (id)kIOSurfaceBytesPerRow : @(bytesPerRow), + (id)kIOSurfaceAllocSize : @(totalBytes), + }; + + IOSurfaceRef res = IOSurfaceCreate((CFDictionaryRef)options); + if (res == nil) { + FML_LOG(ERROR) << "Failed to create IOSurface with options " + << options.debugDescription.UTF8String; + return nil; + } + + if (self.colorspace != nil) { + CFStringRef name = CGColorSpaceGetName(self.colorspace); + IOSurfaceSetValue(res, kIOSurfaceColorSpace, name); + } else { + IOSurfaceSetValue(res, kIOSurfaceColorSpace, kCGColorSpaceSRGB); + } + return (__bridge_transfer IOSurface*)res; +} + +- (FlutterTexture*)nextTexture { + CFTimeInterval start = CACurrentMediaTime(); + while (true) { + FlutterTexture* texture = [self tryNextTexture]; + if (texture != nil) { + return texture; + } + CFTimeInterval elapsed = CACurrentMediaTime() - start; + if (elapsed > 1.0) { + NSLog(@"Waited %f seconds for a drawable, giving up.", elapsed); + return nil; + } + } +} + +- (FlutterTexture*)tryNextTexture { + @synchronized(self) { + if (_front != nil && _front.waitingForCompletion) { + return nil; + } + if (_totalTextures < 3) { + ++_totalTextures; + IOSurface* surface = [self createIOSurface]; + if (surface == nil) { + return nil; + } + MTLTextureDescriptor* textureDescriptor = + [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:_pixelFormat + width:_drawableSize.width + height:_drawableSize.height + mipmapped:NO]; + + if (_framebufferOnly) { + textureDescriptor.usage = MTLTextureUsageRenderTarget; + } else { + textureDescriptor.usage = + MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead | MTLTextureUsageShaderWrite; + } + id texture = [self.device newTextureWithDescriptor:textureDescriptor + iosurface:(__bridge IOSurfaceRef)surface + plane:0]; + FlutterTexture* flutterTexture = [[FlutterTexture alloc] initWithTexture:texture + surface:surface]; + return flutterTexture; + } else { + // Prefer surface that is not in use and has been presented the longest + // time ago. + // When isInUse is false, the surface is definitely not used by the compositor. + // When isInUse is true, the surface may be used by the compositor. + // When both surfaces are in use, the one presented earlier will be returned. + // The assumption here is that the compositor is already aware of the + // newer texture and is unlikely to read from the older one, even though it + // has not decreased the use count yet (there seems to be certain latency). + FlutterTexture* res = nil; + for (FlutterTexture* texture in _availableTextures) { + if (res == nil) { + res = texture; + } else if (res.surface.isInUse && !texture.surface.isInUse) { + // prefer texture that is not in use. + res = texture; + } else if (res.surface.isInUse == texture.surface.isInUse && + texture.presentedTime < res.presentedTime) { + // prefer texture with older presented time. + res = texture; + } + } + if (res != nil) { + [_availableTextures removeObject:res]; + } + return res; + } + } +} + +- (id)nextDrawable { + FlutterTexture* texture = [self nextTexture]; + if (texture == nil) { + return nil; + } + FlutterDrawable* drawable = [[FlutterDrawable alloc] initWithTexture:texture + layer:self + drawableId:_nextDrawableId++]; + return drawable; +} + +- (void)presentOnMainThread:(FlutterTexture*)texture { + // This is needed otherwise frame gets skipped on touch begin / end. Go figure. + // Might also be placebo + [self setNeedsDisplay]; + + [CATransaction begin]; + [CATransaction setDisableActions:YES]; + self.contents = texture.surface; + [CATransaction commit]; + _displayLink.paused = NO; + _displayLinkPauseCountdown = 0; + if (!_didSetContentsDuringThisDisplayLinkPeriod) { + _didSetContentsDuringThisDisplayLinkPeriod = YES; + } else if (!_displayLinkForcedMaxRate) { + _displayLinkForcedMaxRate = YES; + [self setMaxRefreshRate:DisplayLinkManager.displayRefreshRate forceMax:YES]; + } +} + +- (void)presentTexture:(FlutterTexture*)texture { + @synchronized(self) { + if (_front != nil) { + [_availableTextures addObject:_front]; + } + _front = texture; + texture.presentedTime = CACurrentMediaTime(); + if ([NSThread isMainThread]) { + [self presentOnMainThread:texture]; + } else { + // Core animation layers can only be updated on main thread. + dispatch_async(dispatch_get_main_queue(), ^{ + [self presentOnMainThread:texture]; + }); + } + } +} + +- (void)returnTexture:(FlutterTexture*)texture { + @synchronized(self) { + [_availableTextures addObject:texture]; + } +} + ++ (BOOL)enabled { + static BOOL enabled = YES; + static BOOL didCheckInfoPlist = NO; + if (!didCheckInfoPlist) { + didCheckInfoPlist = YES; + NSNumber* use_flutter_metal_layer = + [[NSBundle mainBundle] objectForInfoDictionaryKey:@"FLTUseFlutterMetalLayer"]; + if (use_flutter_metal_layer != nil && ![use_flutter_metal_layer boolValue]) { + enabled = NO; + } + } + return enabled; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayerTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayerTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..042edcc12b528113e97394ccbc2eaace525e39a0 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayerTest.mm @@ -0,0 +1,296 @@ +// 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. + +#import +#import +#import +#import + +#include "flutter/fml/logging.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.h" + +@interface FlutterMetalLayerTest : XCTestCase +@end + +@interface TestFlutterMetalLayerView : UIView +@end + +@implementation TestFlutterMetalLayerView + ++ (Class)layerClass { + return [FlutterMetalLayer class]; +} + +@end + +/// A fake compositor that simulates presenting layer surface by increasing +/// and decreasing IOSurface use count. +@interface TestCompositor : NSObject { + FlutterMetalLayer* _layer; + IOSurfaceRef _presentedSurface; +} +@end + +@implementation TestCompositor + +- (instancetype)initWithLayer:(FlutterMetalLayer*)layer { + self = [super init]; + if (self) { + self->_layer = layer; + } + return self; +} + +/// Increment use count of currently presented surface and decrement use count +/// of previously presented surface. +- (void)commitTransaction { + IOSurfaceRef surface = (__bridge IOSurfaceRef)self->_layer.contents; + if (self->_presentedSurface) { + IOSurfaceDecrementUseCount(self->_presentedSurface); + } + IOSurfaceIncrementUseCount(surface); + self->_presentedSurface = surface; +} + +- (void)dealloc { + if (self->_presentedSurface) { + IOSurfaceDecrementUseCount(self->_presentedSurface); + } +} + +@end + +@implementation FlutterMetalLayerTest + +- (FlutterMetalLayer*)addMetalLayer { + TestFlutterMetalLayerView* view = + [[TestFlutterMetalLayerView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; + FlutterMetalLayer* layer = (FlutterMetalLayer*)view.layer; + layer.drawableSize = CGSizeMake(100, 100); + return layer; +} + +- (void)removeMetalLayer:(FlutterMetalLayer*)layer { +} + +// For unknown reason sometimes CI fails to create IOSurface. Bail out +// to prevent flakiness. +#define BAIL_IF_NO_DRAWABLE(drawable) \ + if (drawable == nil) { \ + FML_LOG(ERROR) << "Could not allocate drawable"; \ + return; \ + } + +- (void)testFlip { + FlutterMetalLayer* layer = [self addMetalLayer]; + TestCompositor* compositor = [[TestCompositor alloc] initWithLayer:layer]; + + id t1, t2, t3; + + id drawable = [layer nextDrawable]; + BAIL_IF_NO_DRAWABLE(drawable); + t1 = drawable.texture; + [drawable present]; + [compositor commitTransaction]; + + drawable = [layer nextDrawable]; + BAIL_IF_NO_DRAWABLE(drawable); + t2 = drawable.texture; + [drawable present]; + [compositor commitTransaction]; + + drawable = [layer nextDrawable]; + BAIL_IF_NO_DRAWABLE(drawable); + t3 = drawable.texture; + [drawable present]; + [compositor commitTransaction]; + + // If there was no frame drop, layer should return oldest presented + // texture. + + drawable = [layer nextDrawable]; + XCTAssertEqual(drawable.texture, t1); + + [drawable present]; + [compositor commitTransaction]; + + drawable = [layer nextDrawable]; + XCTAssertEqual(drawable.texture, t2); + [drawable present]; + [compositor commitTransaction]; + + drawable = [layer nextDrawable]; + XCTAssertEqual(drawable.texture, t3); + [drawable present]; + [compositor commitTransaction]; + + drawable = [layer nextDrawable]; + XCTAssertEqual(drawable.texture, t1); + [drawable present]; + + [self removeMetalLayer:layer]; +} + +- (void)testFlipWithDroppedFrame { + FlutterMetalLayer* layer = [self addMetalLayer]; + TestCompositor* compositor = [[TestCompositor alloc] initWithLayer:layer]; + + id t1, t2, t3; + + id drawable = [layer nextDrawable]; + BAIL_IF_NO_DRAWABLE(drawable); + t1 = drawable.texture; + [drawable present]; + [compositor commitTransaction]; + XCTAssertTrue(IOSurfaceIsInUse(t1.iosurface)); + + drawable = [layer nextDrawable]; + BAIL_IF_NO_DRAWABLE(drawable); + t2 = drawable.texture; + [drawable present]; + [compositor commitTransaction]; + + drawable = [layer nextDrawable]; + BAIL_IF_NO_DRAWABLE(drawable); + t3 = drawable.texture; + [drawable present]; + [compositor commitTransaction]; + + // Simulate compositor holding on to t3 for a while. + IOSurfaceIncrementUseCount(t3.iosurface); + + // Here the drawable is presented, but immediately replaced by another drawable + // (before the compositor has a chance to pick it up). This should result + // in same drawable returned in next call to nextDrawable. + drawable = [layer nextDrawable]; + XCTAssertEqual(drawable.texture, t1); + XCTAssertFalse(IOSurfaceIsInUse(drawable.texture.iosurface)); + [drawable present]; + + drawable = [layer nextDrawable]; + XCTAssertEqual(drawable.texture, t2); + [drawable present]; + [compositor commitTransaction]; + + // Next drawable should be t1, since it was never picked up by compositor. + drawable = [layer nextDrawable]; + XCTAssertEqual(drawable.texture, t1); + + IOSurfaceDecrementUseCount(t3.iosurface); + + [self removeMetalLayer:layer]; +} + +- (void)testDroppedDrawableReturnsTextureToPool { + FlutterMetalLayer* layer = [self addMetalLayer]; + // FlutterMetalLayer will keep creating new textures until it has 3. + @autoreleasepool { + for (int i = 0; i < 3; ++i) { + id drawable = [layer nextDrawable]; + BAIL_IF_NO_DRAWABLE(drawable); + } + } + id texture; + { + @autoreleasepool { + id drawable = [layer nextDrawable]; + XCTAssertNotNil(drawable); + texture = drawable.texture; + // Dropping the drawable must return texture to pool, so + // next drawable should return the same texture. + } + } + { + id drawable = [layer nextDrawable]; + XCTAssertEqual(texture, drawable.texture); + } + + [self removeMetalLayer:layer]; +} + +- (void)testLayerLimitsDrawableCount { + FlutterMetalLayer* layer = [self addMetalLayer]; + + id d1 = [layer nextDrawable]; + BAIL_IF_NO_DRAWABLE(d1); + id d2 = [layer nextDrawable]; + BAIL_IF_NO_DRAWABLE(d2); + id d3 = [layer nextDrawable]; + BAIL_IF_NO_DRAWABLE(d3); + XCTAssertNotNil(d3); + + // Layer should not return more than 3 drawables. + id d4 = [layer nextDrawable]; + XCTAssertNil(d4); + + [d1 present]; + + // Still no drawable, until the front buffer returns to pool + id d5 = [layer nextDrawable]; + XCTAssertNil(d5); + + [d2 present]; + id d6 = [layer nextDrawable]; + XCTAssertNotNil(d6); + + [self removeMetalLayer:layer]; +} + +- (void)testTimeout { + FlutterMetalLayer* layer = [self addMetalLayer]; + TestCompositor* compositor = [[TestCompositor alloc] initWithLayer:layer]; + + id drawable = [layer nextDrawable]; + BAIL_IF_NO_DRAWABLE(drawable); + + __block MTLCommandBufferHandler handler; + + id mockCommandBuffer = OCMProtocolMock(@protocol(MTLCommandBuffer)); + OCMStub([mockCommandBuffer addCompletedHandler:OCMOCK_ANY]).andDo(^(NSInvocation* invocation) { + MTLCommandBufferHandler handlerOnStack; + [invocation getArgument:&handlerOnStack atIndex:2]; + // Required to copy stack block to heap. + handler = handlerOnStack; + }); + + [(id)drawable flutterPrepareForPresent:mockCommandBuffer]; + [drawable present]; + [compositor commitTransaction]; + + // Drawable will not be available until the command buffer completes. + drawable = [layer nextDrawable]; + XCTAssertNil(drawable); + + handler(mockCommandBuffer); + + drawable = [layer nextDrawable]; + XCTAssertNotNil(drawable); + + [self removeMetalLayer:layer]; +} + +- (void)testDealloc { + __weak FlutterMetalLayer* weakLayer; + @autoreleasepool { + FlutterMetalLayer* layer = [self addMetalLayer]; + weakLayer = layer; + TestCompositor* compositor = [[TestCompositor alloc] initWithLayer:layer]; + + id drawable = [layer nextDrawable]; + BAIL_IF_NO_DRAWABLE(drawable); + [drawable present]; + [compositor commitTransaction]; + + [self removeMetalLayer:layer]; + } + CFTimeInterval start = CACurrentMediaTime(); + while (weakLayer != nil && CACurrentMediaTime() - start < 1) { + // Deallocating the layer after removing is not synchronous. + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.01, YES); + } + + XCTAssertNil(weakLayer); +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterOverlayView.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterOverlayView.h new file mode 100644 index 0000000000000000000000000000000000000000..fe050d1ffccdc3b84c55520c961ebfdc9bbfd59d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterOverlayView.h @@ -0,0 +1,32 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTEROVERLAYVIEW_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTEROVERLAYVIEW_H_ + +#include +#include + +/// UIViews that are used by |FlutterPlatformViews| to present Flutter +/// rendering on top of system compositor rendering (ex. a web view). +/// +/// When there is a view composited by the system compositor within a Flutter +/// view hierarchy, instead of rendering into a single render target, Flutter +/// renders into multiple render targets (depending on the number of +/// interleaving levels between Flutter & non-Flutter contents). While the +/// FlutterView contains the backing store for the root render target, the +/// FlutterOverlay view contains the backing stores for the rest. The overlay +/// views also handle touch propagation and the like for touches that occurs +/// either on overlays or otherwise may be intercepted by the platform views. +@interface FlutterOverlayView : UIView +- (instancetype)initWithFrame:(CGRect)frame NS_UNAVAILABLE; +- (instancetype)initWithCoder:(NSCoder*)aDecoder NS_UNAVAILABLE; + +- (instancetype)init NS_DESIGNATED_INITIALIZER; +- (instancetype)initWithContentsScale:(CGFloat)contentsScale + pixelFormat:(MTLPixelFormat)pixelFormat; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTEROVERLAYVIEW_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterOverlayView.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterOverlayView.mm new file mode 100644 index 0000000000000000000000000000000000000000..8000df2830f20d552db4d637564063388dc6e34a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterOverlayView.mm @@ -0,0 +1,68 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterOverlayView.h" + +#include + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h" +#include "fml/platform/darwin/cf_utils.h" + +FLUTTER_ASSERT_ARC + +// This is mostly a duplication of FlutterView. +@implementation FlutterOverlayView { + fml::CFRef _colorSpaceRef; +} + +- (instancetype)initWithFrame:(CGRect)frame { + NSAssert(NO, @"FlutterOverlayView must init or initWithContentsScale"); + return nil; +} + +- (instancetype)initWithCoder:(NSCoder*)aDecoder { + NSAssert(NO, @"FlutterOverlayView must init or initWithContentsScale"); + return nil; +} + +- (instancetype)init { + self = [super initWithFrame:CGRectZero]; + + if (self) { + self.layer.opaque = NO; + self.userInteractionEnabled = NO; + self.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); + } + + return self; +} + +- (instancetype)initWithContentsScale:(CGFloat)contentsScale + pixelFormat:(MTLPixelFormat)pixelFormat { + self = [self init]; + + if ([self.layer isKindOfClass:[CAMetalLayer class]]) { + self.layer.allowsGroupOpacity = NO; + self.layer.contentsScale = contentsScale; + self.layer.rasterizationScale = contentsScale; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability-new" + CAMetalLayer* layer = (CAMetalLayer*)self.layer; +#pragma clang diagnostic pop + layer.pixelFormat = pixelFormat; + if (pixelFormat == MTLPixelFormatRGBA16Float || pixelFormat == MTLPixelFormatBGRA10_XR) { + self->_colorSpaceRef = fml::CFRef(CGColorSpaceCreateWithName(kCGColorSpaceExtendedSRGB)); + layer.colorspace = self->_colorSpaceRef; + } + } + return self; +} + ++ (Class)layerClass { + return [FlutterView layerClass]; +} + +// TODO(amirh): implement drawLayer to support snapshotting. + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPlugin.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPlugin.h new file mode 100644 index 0000000000000000000000000000000000000000..f8f40edabd824a510040f33ca5c2968ffbda1ba9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPlugin.h @@ -0,0 +1,31 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMPLUGIN_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMPLUGIN_H_ + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterEngine.h" + +@interface FlutterPlatformPlugin : NSObject +- (instancetype)init NS_UNAVAILABLE; ++ (instancetype)new NS_UNAVAILABLE; +- (instancetype)initWithEngine:(FlutterEngine*)engine NS_DESIGNATED_INITIALIZER; +- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result; + +- (void)showShareViewController:(NSString*)content; +- (void)searchWeb:(NSString*)searchTerm; +- (void)showLookUpViewController:(NSString*)term; +@end + +namespace flutter { + +extern const char* const kOrientationUpdateNotificationName; +extern const char* const kOrientationUpdateNotificationKey; +extern const char* const kOverlayStyleUpdateNotificationName; +extern const char* const kOverlayStyleUpdateNotificationKey; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMPLUGIN_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPlugin.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPlugin.mm new file mode 100644 index 0000000000000000000000000000000000000000..f716407e3a24c6928296ca301eee9d6c527fe3a3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPlugin.mm @@ -0,0 +1,448 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPlugin.h" + +#import +#import +#import +#import + +#include "flutter/fml/logging.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterSharedApplication.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/UIViewController+FlutterScreenAndSceneIfLoaded.h" + +FLUTTER_ASSERT_ARC + +namespace { + +constexpr char kTextPlainFormat[] = "text/plain"; +const UInt32 kKeyPressClickSoundId = 1306; + +NSString* const kSearchURLPrefix = @"x-web-search://?"; + +} // namespace + +namespace flutter { + +// TODO(abarth): Move these definitions from system_chrome_impl.cc to here. +const char* const kOrientationUpdateNotificationName = + "io.flutter.plugin.platform.SystemChromeOrientationNotificationName"; +const char* const kOrientationUpdateNotificationKey = + "io.flutter.plugin.platform.SystemChromeOrientationNotificationKey"; +const char* const kOverlayStyleUpdateNotificationName = + "io.flutter.plugin.platform.SystemChromeOverlayNotificationName"; +const char* const kOverlayStyleUpdateNotificationKey = + "io.flutter.plugin.platform.SystemChromeOverlayNotificationKey"; + +} // namespace flutter + +using namespace flutter; + +static void SetStatusBarHiddenForSharedApplication(BOOL hidden) { + UIApplication* flutterApplication = FlutterSharedApplication.application; + if (flutterApplication) { + flutterApplication.statusBarHidden = hidden; + } else { + FML_LOG(WARNING) << "Application based status bar styling is not available in app extension."; + } +} + +static void SetStatusBarStyleForSharedApplication(UIStatusBarStyle style) { + UIApplication* flutterApplication = FlutterSharedApplication.application; + if (flutterApplication) { + // Note: -[UIApplication setStatusBarStyle] is deprecated in iOS9 + // in favor of delegating to the view controller. + [flutterApplication setStatusBarStyle:style]; + } else { + FML_LOG(WARNING) << "Application based status bar styling is not available in app extension."; + } +} + +@interface FlutterPlatformPlugin () + +/** + * @brief Whether the status bar appearance is based on the style preferred for this ViewController. + * + * The default value is YES. + * Explicitly add `UIViewControllerBasedStatusBarAppearance` as `false` in + * info.plist makes this value to be false. + */ +@property(nonatomic, assign) BOOL enableViewControllerBasedStatusBarAppearance; +@property(nonatomic, weak) FlutterEngine* engine; + +/** + * @brief Used to detect whether or not this device supports live text input from the camera. + */ +@property(nonatomic, strong) UITextField* textField; +@end + +@implementation FlutterPlatformPlugin + +- (instancetype)initWithEngine:(FlutterEngine*)engine { + FML_DCHECK(engine) << "engine must be set"; + self = [super init]; + + if (self) { + _engine = engine; + NSObject* infoValue = [[NSBundle mainBundle] + objectForInfoDictionaryKey:@"UIViewControllerBasedStatusBarAppearance"]; +#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG + if (infoValue != nil && ![infoValue isKindOfClass:[NSNumber class]]) { + FML_LOG(ERROR) << "The value of UIViewControllerBasedStatusBarAppearance in info.plist must " + "be a Boolean type."; + } +#endif + _enableViewControllerBasedStatusBarAppearance = + (infoValue == nil || [(NSNumber*)infoValue boolValue]); + } + + return self; +} + +- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { + NSString* method = call.method; + id args = call.arguments; + if ([method isEqualToString:@"SystemSound.play"]) { + [self playSystemSound:args]; + result(nil); + } else if ([method isEqualToString:@"HapticFeedback.vibrate"]) { + [self vibrateHapticFeedback:args]; + result(nil); + } else if ([method isEqualToString:@"SystemChrome.setPreferredOrientations"]) { + [self setSystemChromePreferredOrientations:args]; + result(nil); + } else if ([method isEqualToString:@"SystemChrome.setApplicationSwitcherDescription"]) { + [self setSystemChromeApplicationSwitcherDescription:args]; + result(nil); + } else if ([method isEqualToString:@"SystemChrome.setEnabledSystemUIOverlays"]) { + [self setSystemChromeEnabledSystemUIOverlays:args]; + result(nil); + } else if ([method isEqualToString:@"SystemChrome.setEnabledSystemUIMode"]) { + [self setSystemChromeEnabledSystemUIMode:args]; + result(nil); + } else if ([method isEqualToString:@"SystemChrome.restoreSystemUIOverlays"]) { + [self restoreSystemChromeSystemUIOverlays]; + result(nil); + } else if ([method isEqualToString:@"SystemChrome.setSystemUIOverlayStyle"]) { + [self setSystemChromeSystemUIOverlayStyle:args]; + result(nil); + } else if ([method isEqualToString:@"SystemNavigator.pop"]) { + NSNumber* isAnimated = args; + [self popSystemNavigator:isAnimated.boolValue]; + result(nil); + } else if ([method isEqualToString:@"Clipboard.getData"]) { + result([self getClipboardData:args]); + } else if ([method isEqualToString:@"Clipboard.setData"]) { + [self setClipboardData:args]; + result(nil); + } else if ([method isEqualToString:@"Clipboard.hasStrings"]) { + result([self clipboardHasStrings]); + } else if ([method isEqualToString:@"LiveText.isLiveTextInputAvailable"]) { + result(@([self isLiveTextInputAvailable])); + } else if ([method isEqualToString:@"SearchWeb.invoke"]) { + [self searchWeb:args]; + result(nil); + } else if ([method isEqualToString:@"LookUp.invoke"]) { + [self showLookUpViewController:args]; + result(nil); + } else if ([method isEqualToString:@"Share.invoke"]) { + [self showShareViewController:args]; + result(nil); + } else if ([method isEqualToString:@"ContextMenu.showSystemContextMenu"]) { + [self showSystemContextMenu:args]; + result(nil); + } else if ([method isEqualToString:@"ContextMenu.hideSystemContextMenu"]) { + [self hideSystemContextMenu]; + result(nil); + } else { + result(FlutterMethodNotImplemented); + } +} + +- (void)showSystemContextMenu:(NSDictionary*)args { + if (@available(iOS 16.0, *)) { + FlutterTextInputPlugin* textInputPlugin = [self.engine textInputPlugin]; + BOOL shownEditMenu = [textInputPlugin showEditMenu:args]; + if (!shownEditMenu) { + FML_LOG(ERROR) << "Only text input supports system context menu for now. Ensure the system " + "context menu is shown with an active text input connection. See " + "https://github.com/flutter/flutter/issues/143033."; + } + } +} + +- (void)hideSystemContextMenu { + if (@available(iOS 16.0, *)) { + FlutterTextInputPlugin* textInputPlugin = [self.engine textInputPlugin]; + [textInputPlugin hideEditMenu]; + } +} + +- (void)showShareViewController:(NSString*)content { + UIViewController* engineViewController = [self.engine viewController]; + + NSArray* itemsToShare = @[ content ?: [NSNull null] ]; + UIActivityViewController* activityViewController = + [[UIActivityViewController alloc] initWithActivityItems:itemsToShare + applicationActivities:nil]; + + if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { + // On iPad, the share screen is presented in a popover view, and requires a + // sourceView and sourceRect + FlutterTextInputPlugin* _textInputPlugin = [self.engine textInputPlugin]; + UITextRange* range = _textInputPlugin.textInputView.selectedTextRange; + + // firstRectForRange cannot be used here as it's current implementation does + // not always return the full rect of the range. + CGRect firstRect = [(FlutterTextInputView*)_textInputPlugin.textInputView + caretRectForPosition:(FlutterTextPosition*)range.start]; + CGRect transformedFirstRect = [(FlutterTextInputView*)_textInputPlugin.textInputView + localRectFromFrameworkTransform:firstRect]; + CGRect lastRect = [(FlutterTextInputView*)_textInputPlugin.textInputView + caretRectForPosition:(FlutterTextPosition*)range.end]; + CGRect transformedLastRect = [(FlutterTextInputView*)_textInputPlugin.textInputView + localRectFromFrameworkTransform:lastRect]; + + activityViewController.popoverPresentationController.sourceView = engineViewController.view; + // In case of RTL Language, get the minimum x coordinate + activityViewController.popoverPresentationController.sourceRect = + CGRectMake(fmin(transformedFirstRect.origin.x, transformedLastRect.origin.x), + transformedFirstRect.origin.y, + abs(transformedLastRect.origin.x - transformedFirstRect.origin.x), + transformedFirstRect.size.height); + } + + [engineViewController presentViewController:activityViewController animated:YES completion:nil]; +} + +- (void)searchWeb:(NSString*)searchTerm { + UIApplication* flutterApplication = FlutterSharedApplication.application; + if (flutterApplication == nil) { + FML_LOG(WARNING) << "SearchWeb.invoke is not availabe in app extension."; + return; + } + + NSString* escapedText = [searchTerm + stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet + URLHostAllowedCharacterSet]]; + NSString* searchURL = [NSString stringWithFormat:@"%@%@", kSearchURLPrefix, escapedText]; + + [flutterApplication openURL:[NSURL URLWithString:searchURL] options:@{} completionHandler:nil]; +} + +- (void)playSystemSound:(NSString*)soundType { + if ([soundType isEqualToString:@"SystemSoundType.click"]) { + // All feedback types are specific to Android and are treated as equal on + // iOS. + AudioServicesPlaySystemSound(kKeyPressClickSoundId); + } +} + +- (void)vibrateHapticFeedback:(NSString*)feedbackType { + if (!feedbackType) { + AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); + return; + } + + if ([@"HapticFeedbackType.lightImpact" isEqualToString:feedbackType]) { + [[[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight] impactOccurred]; + } else if ([@"HapticFeedbackType.mediumImpact" isEqualToString:feedbackType]) { + [[[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium] impactOccurred]; + } else if ([@"HapticFeedbackType.heavyImpact" isEqualToString:feedbackType]) { + [[[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleHeavy] impactOccurred]; + } else if ([@"HapticFeedbackType.selectionClick" isEqualToString:feedbackType]) { + [[[UISelectionFeedbackGenerator alloc] init] selectionChanged]; + } +} + +- (void)setSystemChromePreferredOrientations:(NSArray*)orientations { + UIInterfaceOrientationMask mask = 0; + + if (orientations.count == 0) { + mask |= UIInterfaceOrientationMaskAll; + } else { + for (NSString* orientation in orientations) { + if ([orientation isEqualToString:@"DeviceOrientation.portraitUp"]) { + mask |= UIInterfaceOrientationMaskPortrait; + } else if ([orientation isEqualToString:@"DeviceOrientation.portraitDown"]) { + mask |= UIInterfaceOrientationMaskPortraitUpsideDown; + } else if ([orientation isEqualToString:@"DeviceOrientation.landscapeLeft"]) { + mask |= UIInterfaceOrientationMaskLandscapeLeft; + } else if ([orientation isEqualToString:@"DeviceOrientation.landscapeRight"]) { + mask |= UIInterfaceOrientationMaskLandscapeRight; + } + } + } + + if (!mask) { + return; + } + [[NSNotificationCenter defaultCenter] + postNotificationName:@(kOrientationUpdateNotificationName) + object:nil + userInfo:@{@(kOrientationUpdateNotificationKey) : @(mask)}]; +} + +- (void)setSystemChromeApplicationSwitcherDescription:(NSDictionary*)object { + // No counterpart on iOS but is a benign operation. So no asserts. +} + +- (void)setSystemChromeEnabledSystemUIOverlays:(NSArray*)overlays { + BOOL statusBarShouldBeHidden = ![overlays containsObject:@"SystemUiOverlay.top"]; + if ([overlays containsObject:@"SystemUiOverlay.bottom"]) { + [[NSNotificationCenter defaultCenter] + postNotificationName:FlutterViewControllerShowHomeIndicator + object:nil]; + } else { + [[NSNotificationCenter defaultCenter] + postNotificationName:FlutterViewControllerHideHomeIndicator + object:nil]; + } + if (self.enableViewControllerBasedStatusBarAppearance) { + [self.engine viewController].prefersStatusBarHidden = statusBarShouldBeHidden; + } else { + // Checks if the top status bar should be visible. This platform ignores all + // other overlays + + // We opt out of view controller based status bar visibility since we want + // to be able to modify this on the fly. The key used is + // UIViewControllerBasedStatusBarAppearance. + SetStatusBarHiddenForSharedApplication(statusBarShouldBeHidden); + } +} + +- (void)setSystemChromeEnabledSystemUIMode:(NSString*)mode { + BOOL edgeToEdge = [mode isEqualToString:@"SystemUiMode.edgeToEdge"]; + if (self.enableViewControllerBasedStatusBarAppearance) { + [self.engine viewController].prefersStatusBarHidden = !edgeToEdge; + } else { + // Checks if the top status bar should be visible, reflected by edge to edge setting. This + // platform ignores all other system ui modes. + + // We opt out of view controller based status bar visibility since we want + // to be able to modify this on the fly. The key used is + // UIViewControllerBasedStatusBarAppearance. + SetStatusBarHiddenForSharedApplication(!edgeToEdge); + } + [[NSNotificationCenter defaultCenter] + postNotificationName:edgeToEdge ? FlutterViewControllerShowHomeIndicator + : FlutterViewControllerHideHomeIndicator + object:nil]; +} + +- (void)restoreSystemChromeSystemUIOverlays { + // Nothing to do on iOS. +} + +- (void)setSystemChromeSystemUIOverlayStyle:(NSDictionary*)message { + NSString* brightness = message[@"statusBarBrightness"]; + if (brightness == (id)[NSNull null]) { + return; + } + + UIStatusBarStyle statusBarStyle; + if ([brightness isEqualToString:@"Brightness.dark"]) { + statusBarStyle = UIStatusBarStyleLightContent; + } else if ([brightness isEqualToString:@"Brightness.light"]) { + if (@available(iOS 13, *)) { + statusBarStyle = UIStatusBarStyleDarkContent; + } else { + statusBarStyle = UIStatusBarStyleDefault; + } + } else { + return; + } + + if (self.enableViewControllerBasedStatusBarAppearance) { + // This notification is respected by the iOS embedder. + [[NSNotificationCenter defaultCenter] + postNotificationName:@(kOverlayStyleUpdateNotificationName) + object:nil + userInfo:@{@(kOverlayStyleUpdateNotificationKey) : @(statusBarStyle)}]; + } else { + SetStatusBarStyleForSharedApplication(statusBarStyle); + } +} + +- (void)popSystemNavigator:(BOOL)isAnimated { + // Apple's human user guidelines say not to terminate iOS applications. However, if the + // root view of the app is a navigation controller, it is instructed to back up a level + // in the navigation hierarchy. + // It's also possible in an Add2App scenario that the FlutterViewController was presented + // outside the context of a UINavigationController, and still wants to be popped. + + FlutterViewController* engineViewController = [self.engine viewController]; + UINavigationController* navigationController = [engineViewController navigationController]; + if (navigationController) { + [navigationController popViewControllerAnimated:isAnimated]; + } else { + UIViewController* rootViewController = nil; + UIApplication* flutterApplication = FlutterSharedApplication.application; + if (flutterApplication) { + rootViewController = flutterApplication.keyWindow.rootViewController; + } else { + if (@available(iOS 15.0, *)) { + rootViewController = + [engineViewController flutterWindowSceneIfViewLoaded].keyWindow.rootViewController; + } else { + FML_LOG(WARNING) + << "rootViewController is not available in application extension prior to iOS 15.0."; + } + } + + if (engineViewController != rootViewController) { + [engineViewController dismissViewControllerAnimated:isAnimated completion:nil]; + } + } +} + +- (NSDictionary*)getClipboardData:(NSString*)format { + UIPasteboard* pasteboard = [UIPasteboard generalPasteboard]; + if (!format || [format isEqualToString:@(kTextPlainFormat)]) { + NSString* stringInPasteboard = pasteboard.string; + // The pasteboard may contain an item but it may not be a string (an image for instance). + return stringInPasteboard == nil ? nil : @{@"text" : stringInPasteboard}; + } + return nil; +} + +- (void)setClipboardData:(NSDictionary*)data { + UIPasteboard* pasteboard = [UIPasteboard generalPasteboard]; + id copyText = data[@"text"]; + if ([copyText isKindOfClass:[NSString class]]) { + pasteboard.string = copyText; + } else { + pasteboard.string = @"null"; + } +} + +- (NSDictionary*)clipboardHasStrings { + return @{@"value" : @([UIPasteboard generalPasteboard].hasStrings)}; +} + +- (BOOL)isLiveTextInputAvailable { + return [[self textField] canPerformAction:@selector(captureTextFromCamera:) withSender:nil]; +} + +- (void)showLookUpViewController:(NSString*)term { + UIViewController* engineViewController = [self.engine viewController]; + UIReferenceLibraryViewController* referenceLibraryViewController = + [[UIReferenceLibraryViewController alloc] initWithTerm:term]; + [engineViewController presentViewController:referenceLibraryViewController + animated:YES + completion:nil]; +} + +- (UITextField*)textField { + if (_textField == nil) { + _textField = [[UITextField alloc] init]; + } + return _textField; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPluginTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPluginTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..d3eec569a938017e8afc1e95c32d320cf6d1f319 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPluginTest.mm @@ -0,0 +1,543 @@ +// 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. + +#import +#import + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPlugin.h" +#import "flutter/shell/platform/darwin/ios/platform_view_ios.h" + +FLUTTER_ASSERT_ARC + +@interface FlutterPlatformPluginTest : XCTestCase +@end + +@interface FlutterPlatformPlugin () +- (BOOL)isLiveTextInputAvailable; +- (void)searchWeb:(NSString*)searchTerm; +- (void)showLookUpViewController:(NSString*)term; +- (void)showShareViewController:(NSString*)content; +@end + +@interface UIViewController () +- (void)presentViewController:(UIViewController*)viewControllerToPresent + animated:(BOOL)flag + completion:(void (^)(void))completion; +@end + +@implementation FlutterPlatformPluginTest + +- (void)testSearchWebInvokedWithEscapedTerm { + id mockApplication = OCMClassMock([UIApplication class]); + OCMStub([mockApplication sharedApplication]).andReturn(mockApplication); + + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil]; + [engine runWithEntrypoint:nil]; + + XCTestExpectation* invokeExpectation = + [self expectationWithDescription:@"Web search launched with escaped search term"]; + + FlutterPlatformPlugin* plugin = [[FlutterPlatformPlugin alloc] initWithEngine:engine]; + FlutterPlatformPlugin* mockPlugin = OCMPartialMock(plugin); + + FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"SearchWeb.invoke" + arguments:@"Testing Word!"]; + + FlutterResult result = ^(id result) { + OCMVerify([mockPlugin searchWeb:@"Testing Word!"]); + OCMVerify([mockApplication openURL:[NSURL URLWithString:@"x-web-search://?Testing%20Word!"] + options:@{} + completionHandler:nil]); + [invokeExpectation fulfill]; + }; + + [mockPlugin handleMethodCall:methodCall result:result]; + [self waitForExpectationsWithTimeout:1 handler:nil]; + [mockApplication stopMocking]; +} + +- (void)testSearchWebSkippedIfAppExtension { + id mockBundle = OCMPartialMock([NSBundle mainBundle]); + OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{ + @"NSExtensionPointIdentifier" : @"com.apple.share-services" + }); + id mockApplication = OCMClassMock([UIApplication class]); + OCMStub([mockApplication sharedApplication]).andReturn(mockApplication); + OCMReject([mockApplication openURL:OCMOCK_ANY options:OCMOCK_ANY completionHandler:OCMOCK_ANY]); + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil]; + [engine runWithEntrypoint:nil]; + + XCTestExpectation* invokeExpectation = + [self expectationWithDescription:@"Web search launched with non escaped search term"]; + + FlutterPlatformPlugin* plugin = [[FlutterPlatformPlugin alloc] initWithEngine:engine]; + FlutterPlatformPlugin* mockPlugin = OCMPartialMock(plugin); + + FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"SearchWeb.invoke" + arguments:@"Test"]; + + FlutterResult result = ^(id result) { + OCMVerify([mockPlugin searchWeb:@"Test"]); + + [invokeExpectation fulfill]; + }; + + [mockPlugin handleMethodCall:methodCall result:result]; + [self waitForExpectationsWithTimeout:1 handler:nil]; + [mockBundle stopMocking]; + [mockApplication stopMocking]; +} + +- (void)testLookUpCallInitiated { + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil]; + [engine runWithEntrypoint:nil]; + + XCTestExpectation* presentExpectation = + [self expectationWithDescription:@"Look Up view controller presented"]; + + FlutterViewController* engineViewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + FlutterViewController* mockEngineViewController = OCMPartialMock(engineViewController); + + FlutterPlatformPlugin* plugin = [[FlutterPlatformPlugin alloc] initWithEngine:engine]; + FlutterPlatformPlugin* mockPlugin = OCMPartialMock(plugin); + + FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"LookUp.invoke" + arguments:@"Test"]; + FlutterResult result = ^(id result) { + OCMVerify([mockEngineViewController + presentViewController:[OCMArg isKindOfClass:[UIReferenceLibraryViewController class]] + animated:YES + completion:nil]); + [presentExpectation fulfill]; + }; + [mockPlugin handleMethodCall:methodCall result:result]; + [self waitForExpectationsWithTimeout:2 handler:nil]; +} + +- (void)testShareScreenInvoked { + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil]; + [engine runWithEntrypoint:nil]; + + XCTestExpectation* presentExpectation = + [self expectationWithDescription:@"Share view controller presented"]; + + FlutterViewController* engineViewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + FlutterViewController* mockEngineViewController = OCMPartialMock(engineViewController); + OCMStub([mockEngineViewController + presentViewController:[OCMArg isKindOfClass:[UIActivityViewController class]] + animated:YES + completion:nil]); + + FlutterPlatformPlugin* plugin = [[FlutterPlatformPlugin alloc] initWithEngine:engine]; + FlutterPlatformPlugin* mockPlugin = OCMPartialMock(plugin); + + FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"Share.invoke" + arguments:@"Test"]; + FlutterResult result = ^(id result) { + OCMVerify([mockEngineViewController + presentViewController:[OCMArg isKindOfClass:[UIActivityViewController class]] + animated:YES + completion:nil]); + [presentExpectation fulfill]; + }; + [mockPlugin handleMethodCall:methodCall result:result]; + [self waitForExpectationsWithTimeout:1 handler:nil]; +} + +- (void)testShareScreenInvokedOnIPad { + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil]; + [engine runWithEntrypoint:nil]; + + XCTestExpectation* presentExpectation = + [self expectationWithDescription:@"Share view controller presented on iPad"]; + + FlutterViewController* engineViewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + FlutterViewController* mockEngineViewController = OCMPartialMock(engineViewController); + OCMStub([mockEngineViewController + presentViewController:[OCMArg isKindOfClass:[UIActivityViewController class]] + animated:YES + completion:nil]); + + id mockTraitCollection = OCMClassMock([UITraitCollection class]); + OCMStub([mockTraitCollection userInterfaceIdiom]).andReturn(UIUserInterfaceIdiomPad); + + FlutterPlatformPlugin* plugin = [[FlutterPlatformPlugin alloc] initWithEngine:engine]; + FlutterPlatformPlugin* mockPlugin = OCMPartialMock(plugin); + + FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"Share.invoke" + arguments:@"Test"]; + FlutterResult result = ^(id result) { + OCMVerify([mockEngineViewController + presentViewController:[OCMArg isKindOfClass:[UIActivityViewController class]] + animated:YES + completion:nil]); + [presentExpectation fulfill]; + }; + [mockPlugin handleMethodCall:methodCall result:result]; + [self waitForExpectationsWithTimeout:1 handler:nil]; +} + +- (void)testClipboardHasCorrectStrings { + [UIPasteboard generalPasteboard].string = nil; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil]; + FlutterPlatformPlugin* plugin = [[FlutterPlatformPlugin alloc] initWithEngine:engine]; + + XCTestExpectation* setStringExpectation = [self expectationWithDescription:@"setString"]; + FlutterResult resultSet = ^(id result) { + [setStringExpectation fulfill]; + }; + FlutterMethodCall* methodCallSet = + [FlutterMethodCall methodCallWithMethodName:@"Clipboard.setData" + arguments:@{@"text" : @"some string"}]; + [plugin handleMethodCall:methodCallSet result:resultSet]; + [self waitForExpectationsWithTimeout:1 handler:nil]; + + XCTestExpectation* hasStringsExpectation = [self expectationWithDescription:@"hasStrings"]; + FlutterResult result = ^(id result) { + XCTAssertTrue([result[@"value"] boolValue]); + [hasStringsExpectation fulfill]; + }; + FlutterMethodCall* methodCall = + [FlutterMethodCall methodCallWithMethodName:@"Clipboard.hasStrings" arguments:nil]; + [plugin handleMethodCall:methodCall result:result]; + [self waitForExpectationsWithTimeout:1 handler:nil]; + + XCTestExpectation* getDataExpectation = [self expectationWithDescription:@"getData"]; + FlutterResult getDataResult = ^(id result) { + XCTAssertEqualObjects(result[@"text"], @"some string"); + [getDataExpectation fulfill]; + }; + FlutterMethodCall* methodCallGetData = + [FlutterMethodCall methodCallWithMethodName:@"Clipboard.getData" arguments:@"text/plain"]; + [plugin handleMethodCall:methodCallGetData result:getDataResult]; + [self waitForExpectationsWithTimeout:1 handler:nil]; +} + +- (void)testClipboardSetDataToNullDoNotCrash { + [UIPasteboard generalPasteboard].string = nil; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil]; + FlutterPlatformPlugin* plugin = [[FlutterPlatformPlugin alloc] initWithEngine:engine]; + + XCTestExpectation* setStringExpectation = [self expectationWithDescription:@"setData"]; + FlutterResult resultSet = ^(id result) { + [setStringExpectation fulfill]; + }; + FlutterMethodCall* methodCallSet = + [FlutterMethodCall methodCallWithMethodName:@"Clipboard.setData" + arguments:@{@"text" : [NSNull null]}]; + [plugin handleMethodCall:methodCallSet result:resultSet]; + + XCTestExpectation* getDataExpectation = [self expectationWithDescription:@"getData"]; + FlutterResult result = ^(id result) { + XCTAssertEqualObjects(result[@"text"], @"null"); + [getDataExpectation fulfill]; + }; + FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"Clipboard.getData" + arguments:@"text/plain"]; + [plugin handleMethodCall:methodCall result:result]; + [self waitForExpectationsWithTimeout:1 handler:nil]; +} + +- (void)testPopSystemNavigator { + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil]; + [engine runWithEntrypoint:nil]; + FlutterViewController* flutterViewController = + [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; + UINavigationController* navigationController = + [[UINavigationController alloc] initWithRootViewController:flutterViewController]; + UITabBarController* tabBarController = [[UITabBarController alloc] init]; + tabBarController.viewControllers = @[ navigationController ]; + FlutterPlatformPlugin* plugin = [[FlutterPlatformPlugin alloc] initWithEngine:engine]; + + id navigationControllerMock = OCMPartialMock(navigationController); + OCMStub([navigationControllerMock popViewControllerAnimated:YES]); + // Set some string to the pasteboard. + XCTestExpectation* navigationPopCalled = [self expectationWithDescription:@"SystemNavigator.pop"]; + FlutterResult resultSet = ^(id result) { + [navigationPopCalled fulfill]; + }; + FlutterMethodCall* methodCallSet = + [FlutterMethodCall methodCallWithMethodName:@"SystemNavigator.pop" arguments:@(YES)]; + [plugin handleMethodCall:methodCallSet result:resultSet]; + [self waitForExpectationsWithTimeout:1 handler:nil]; + OCMVerify([navigationControllerMock popViewControllerAnimated:YES]); + + [flutterViewController deregisterNotifications]; +} + +- (void)testWhetherDeviceHasLiveTextInputInvokeCorrectly { + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil]; + XCTestExpectation* invokeExpectation = + [self expectationWithDescription:@"isLiveTextInputAvailableInvoke"]; + FlutterPlatformPlugin* plugin = [[FlutterPlatformPlugin alloc] initWithEngine:engine]; + FlutterPlatformPlugin* mockPlugin = OCMPartialMock(plugin); + FlutterMethodCall* methodCall = + [FlutterMethodCall methodCallWithMethodName:@"LiveText.isLiveTextInputAvailable" + arguments:nil]; + FlutterResult result = ^(id result) { + OCMVerify([mockPlugin isLiveTextInputAvailable]); + [invokeExpectation fulfill]; + }; + [mockPlugin handleMethodCall:methodCall result:result]; + [self waitForExpectationsWithTimeout:1 handler:nil]; +} + +- (void)testViewControllerBasedStatusBarHiddenUpdate { + id bundleMock = OCMPartialMock([NSBundle mainBundle]); + OCMStub([bundleMock objectForInfoDictionaryKey:@"UIViewControllerBasedStatusBarAppearance"]) + .andReturn(@YES); + { + // Enabling system UI overlays to update status bar. + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil]; + [engine runWithEntrypoint:nil]; + FlutterViewController* flutterViewController = + [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; + XCTAssertFalse(flutterViewController.prefersStatusBarHidden); + + // Update to hidden. + FlutterPlatformPlugin* plugin = [engine platformPlugin]; + + XCTestExpectation* enableSystemUIOverlaysCalled = + [self expectationWithDescription:@"setEnabledSystemUIOverlays"]; + FlutterResult resultSet = ^(id result) { + [enableSystemUIOverlaysCalled fulfill]; + }; + FlutterMethodCall* methodCallSet = + [FlutterMethodCall methodCallWithMethodName:@"SystemChrome.setEnabledSystemUIOverlays" + arguments:@[ @"SystemUiOverlay.bottom" ]]; + [plugin handleMethodCall:methodCallSet result:resultSet]; + [self waitForExpectationsWithTimeout:1 handler:nil]; + XCTAssertTrue(flutterViewController.prefersStatusBarHidden); + + // Update to shown. + XCTestExpectation* enableSystemUIOverlaysCalled2 = + [self expectationWithDescription:@"setEnabledSystemUIOverlays"]; + FlutterResult resultSet2 = ^(id result) { + [enableSystemUIOverlaysCalled2 fulfill]; + }; + FlutterMethodCall* methodCallSet2 = + [FlutterMethodCall methodCallWithMethodName:@"SystemChrome.setEnabledSystemUIOverlays" + arguments:@[ @"SystemUiOverlay.top" ]]; + [plugin handleMethodCall:methodCallSet2 result:resultSet2]; + [self waitForExpectationsWithTimeout:1 handler:nil]; + XCTAssertFalse(flutterViewController.prefersStatusBarHidden); + + [flutterViewController deregisterNotifications]; + } + { + // Enable system UI mode to update status bar. + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil]; + [engine runWithEntrypoint:nil]; + FlutterViewController* flutterViewController = + [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; + XCTAssertFalse(flutterViewController.prefersStatusBarHidden); + + // Update to hidden. + FlutterPlatformPlugin* plugin = [engine platformPlugin]; + + XCTestExpectation* enableSystemUIModeCalled = + [self expectationWithDescription:@"setEnabledSystemUIMode"]; + FlutterResult resultSet = ^(id result) { + [enableSystemUIModeCalled fulfill]; + }; + FlutterMethodCall* methodCallSet = + [FlutterMethodCall methodCallWithMethodName:@"SystemChrome.setEnabledSystemUIMode" + arguments:@"SystemUiMode.immersive"]; + [plugin handleMethodCall:methodCallSet result:resultSet]; + [self waitForExpectationsWithTimeout:1 handler:nil]; + XCTAssertTrue(flutterViewController.prefersStatusBarHidden); + + // Update to shown. + XCTestExpectation* enableSystemUIModeCalled2 = + [self expectationWithDescription:@"setEnabledSystemUIMode"]; + FlutterResult resultSet2 = ^(id result) { + [enableSystemUIModeCalled2 fulfill]; + }; + FlutterMethodCall* methodCallSet2 = + [FlutterMethodCall methodCallWithMethodName:@"SystemChrome.setEnabledSystemUIMode" + arguments:@"SystemUiMode.edgeToEdge"]; + [plugin handleMethodCall:methodCallSet2 result:resultSet2]; + [self waitForExpectationsWithTimeout:1 handler:nil]; + XCTAssertFalse(flutterViewController.prefersStatusBarHidden); + + [flutterViewController deregisterNotifications]; + } + [bundleMock stopMocking]; +} + +- (void)testStatusBarHiddenUpdate { + id bundleMock = OCMPartialMock([NSBundle mainBundle]); + OCMStub([bundleMock objectForInfoDictionaryKey:@"UIViewControllerBasedStatusBarAppearance"]) + .andReturn(@NO); + id mockApplication = OCMClassMock([UIApplication class]); + OCMStub([mockApplication sharedApplication]).andReturn(mockApplication); + + // Enabling system UI overlays to update status bar. + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil]; + [engine runWithEntrypoint:nil]; + FlutterViewController* flutterViewController = + [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; + + // Update the visibility of the status bar to hidden. + FlutterPlatformPlugin* plugin = [engine platformPlugin]; + + XCTestExpectation* systemOverlaysBottomExpectation = + [self expectationWithDescription:@"setEnabledSystemUIOverlays"]; + FlutterResult systemOverlaysBottomResult = ^(id result) { + [systemOverlaysBottomExpectation fulfill]; + }; + FlutterMethodCall* setSystemOverlaysBottomCall = + [FlutterMethodCall methodCallWithMethodName:@"SystemChrome.setEnabledSystemUIOverlays" + arguments:@[ @"SystemUiOverlay.bottom" ]]; + [plugin handleMethodCall:setSystemOverlaysBottomCall result:systemOverlaysBottomResult]; + [self waitForExpectationsWithTimeout:1 handler:nil]; + OCMVerify([mockApplication setStatusBarHidden:YES]); + + // Update the visibility of the status bar to shown. + XCTestExpectation* systemOverlaysTopExpectation = + [self expectationWithDescription:@"setEnabledSystemUIOverlays"]; + FlutterResult systemOverlaysTopResult = ^(id result) { + [systemOverlaysTopExpectation fulfill]; + }; + FlutterMethodCall* setSystemOverlaysTopCall = + [FlutterMethodCall methodCallWithMethodName:@"SystemChrome.setEnabledSystemUIOverlays" + arguments:@[ @"SystemUiOverlay.top" ]]; + [plugin handleMethodCall:setSystemOverlaysTopCall result:systemOverlaysTopResult]; + [self waitForExpectationsWithTimeout:1 handler:nil]; + OCMVerify([mockApplication setStatusBarHidden:NO]); + + [flutterViewController deregisterNotifications]; + [mockApplication stopMocking]; + [bundleMock stopMocking]; +} + +- (void)testStatusBarHiddenNotUpdatedInAppExtension { + id bundleMock = OCMPartialMock([NSBundle mainBundle]); + OCMStub([bundleMock objectForInfoDictionaryKey:@"UIViewControllerBasedStatusBarAppearance"]) + .andReturn(@NO); + OCMStub([bundleMock objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{ + @"NSExtensionPointIdentifier" : @"com.apple.share-services" + }); + id mockApplication = OCMClassMock([UIApplication class]); + OCMStub([mockApplication sharedApplication]).andReturn(mockApplication); + OCMReject([mockApplication setStatusBarHidden:OCMOCK_ANY]); + + // Enabling system UI overlays to update status bar. + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil]; + [engine runWithEntrypoint:nil]; + FlutterViewController* flutterViewController = + [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; + + // Update the visibility of the status bar to hidden does not occur with extensions. + FlutterPlatformPlugin* plugin = [engine platformPlugin]; + + XCTestExpectation* systemOverlaysBottomExpectation = + [self expectationWithDescription:@"setEnabledSystemUIOverlays"]; + FlutterResult systemOverlaysBottomResult = ^(id result) { + [systemOverlaysBottomExpectation fulfill]; + }; + FlutterMethodCall* setSystemOverlaysBottomCall = + [FlutterMethodCall methodCallWithMethodName:@"SystemChrome.setEnabledSystemUIOverlays" + arguments:@[ @"SystemUiOverlay.bottom" ]]; + [plugin handleMethodCall:setSystemOverlaysBottomCall result:systemOverlaysBottomResult]; + [self waitForExpectationsWithTimeout:1 handler:nil]; + OCMReject([mockApplication setStatusBarHidden:YES]); + + // Update the visibility of the status bar to shown does not occur with extensions. + XCTestExpectation* systemOverlaysTopExpectation = + [self expectationWithDescription:@"setEnabledSystemUIOverlays"]; + FlutterResult systemOverlaysTopResult = ^(id result) { + [systemOverlaysTopExpectation fulfill]; + }; + FlutterMethodCall* setSystemOverlaysTopCall = + [FlutterMethodCall methodCallWithMethodName:@"SystemChrome.setEnabledSystemUIOverlays" + arguments:@[ @"SystemUiOverlay.top" ]]; + [plugin handleMethodCall:setSystemOverlaysTopCall result:systemOverlaysTopResult]; + [self waitForExpectationsWithTimeout:1 handler:nil]; + OCMReject([mockApplication setStatusBarHidden:NO]); + + [flutterViewController deregisterNotifications]; + [mockApplication stopMocking]; + [bundleMock stopMocking]; +} + +- (void)testStatusBarStyle { + id bundleMock = OCMPartialMock([NSBundle mainBundle]); + OCMStub([bundleMock objectForInfoDictionaryKey:@"UIViewControllerBasedStatusBarAppearance"]) + .andReturn(@NO); + id mockApplication = OCMClassMock([UIApplication class]); + OCMStub([mockApplication sharedApplication]).andReturn(mockApplication); + + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil]; + [engine runWithEntrypoint:nil]; + FlutterViewController* flutterViewController = + [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; + XCTAssertFalse(flutterViewController.prefersStatusBarHidden); + + FlutterPlatformPlugin* plugin = [engine platformPlugin]; + + XCTestExpectation* enableSystemUIModeCalled = + [self expectationWithDescription:@"setSystemUIOverlayStyle"]; + FlutterResult resultSet = ^(id result) { + [enableSystemUIModeCalled fulfill]; + }; + FlutterMethodCall* methodCallSet = + [FlutterMethodCall methodCallWithMethodName:@"SystemChrome.setSystemUIOverlayStyle" + arguments:@{@"statusBarBrightness" : @"Brightness.dark"}]; + [plugin handleMethodCall:methodCallSet result:resultSet]; + [self waitForExpectationsWithTimeout:1 handler:nil]; + + OCMVerify([mockApplication setStatusBarStyle:UIStatusBarStyleLightContent]); + + [flutterViewController deregisterNotifications]; + [mockApplication stopMocking]; + [bundleMock stopMocking]; +} + +- (void)testStatusBarStyleNotUpdatedInAppExtension { + id bundleMock = OCMPartialMock([NSBundle mainBundle]); + OCMStub([bundleMock objectForInfoDictionaryKey:@"UIViewControllerBasedStatusBarAppearance"]) + .andReturn(@NO); + OCMStub([bundleMock objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{ + @"NSExtensionPointIdentifier" : @"com.apple.share-services" + }); + id mockApplication = OCMClassMock([UIApplication class]); + OCMStub([mockApplication sharedApplication]).andReturn(mockApplication); + OCMReject([mockApplication setStatusBarHidden:OCMOCK_ANY]); + + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil]; + [engine runWithEntrypoint:nil]; + FlutterViewController* flutterViewController = + [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; + XCTAssertFalse(flutterViewController.prefersStatusBarHidden); + + FlutterPlatformPlugin* plugin = [engine platformPlugin]; + + XCTestExpectation* enableSystemUIModeCalled = + [self expectationWithDescription:@"setSystemUIOverlayStyle"]; + FlutterResult resultSet = ^(id result) { + [enableSystemUIModeCalled fulfill]; + }; + FlutterMethodCall* methodCallSet = + [FlutterMethodCall methodCallWithMethodName:@"SystemChrome.setSystemUIOverlayStyle" + arguments:@{@"statusBarBrightness" : @"Brightness.dark"}]; + [plugin handleMethodCall:methodCallSet result:resultSet]; + [self waitForExpectationsWithTimeout:1 handler:nil]; + + [flutterViewController deregisterNotifications]; + [mockApplication stopMocking]; + [bundleMock stopMocking]; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews.mm new file mode 100644 index 0000000000000000000000000000000000000000..7cd80bdab5136dcb8adfe5f47fb01427c59a936b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews.mm @@ -0,0 +1,792 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h" + +#import + +#include "flutter/display_list/effects/dl_image_filter.h" +#include "flutter/fml/platform/darwin/cf_utils.h" +#import "flutter/shell/platform/darwin/ios/ios_surface.h" + +FLUTTER_ASSERT_ARC + +namespace { +static CGRect GetCGRectFromDlRect(const flutter::DlRect& clipDlRect) { + return CGRectMake(clipDlRect.GetX(), // + clipDlRect.GetY(), // + clipDlRect.GetWidth(), // + clipDlRect.GetHeight()); +} + +CATransform3D GetCATransform3DFromDlMatrix(const flutter::DlMatrix& matrix) { + CATransform3D transform = CATransform3DIdentity; + transform.m11 = matrix.m[0]; + transform.m12 = matrix.m[1]; + transform.m13 = matrix.m[2]; + transform.m14 = matrix.m[3]; + + transform.m21 = matrix.m[4]; + transform.m22 = matrix.m[5]; + transform.m23 = matrix.m[6]; + transform.m24 = matrix.m[7]; + + transform.m31 = matrix.m[8]; + transform.m32 = matrix.m[9]; + transform.m33 = matrix.m[10]; + transform.m34 = matrix.m[11]; + + transform.m41 = matrix.m[12]; + transform.m42 = matrix.m[13]; + transform.m43 = matrix.m[14]; + transform.m44 = matrix.m[15]; + return transform; +} + +class CGPathReceiver final : public flutter::DlPathReceiver { + public: + void SetPathInfo(flutter::DlPathFillType type, bool is_convex) override { + // CGPaths do not have an inherit fill type, we would need to remember + // the fill type and employ it when we use the path. + // see https://github.com/flutter/flutter/issues/164826 + } + void MoveTo(const flutter::DlPoint& p2) override { // + CGPathMoveToPoint(path_ref_, nil, p2.x, p2.y); + } + void LineTo(const flutter::DlPoint& p2) override { + CGPathAddLineToPoint(path_ref_, nil, p2.x, p2.y); + } + void QuadTo(const flutter::DlPoint& cp, const flutter::DlPoint& p2) override { + CGPathAddQuadCurveToPoint(path_ref_, nil, cp.x, cp.y, p2.x, p2.y); + } + // bool conic_to(...) { CGPath has no equivalent to the conic curve type } + void CubicTo(const flutter::DlPoint& cp1, + const flutter::DlPoint& cp2, + const flutter::DlPoint& p2) override { + CGPathAddCurveToPoint(path_ref_, nil, // + cp1.x, cp1.y, cp2.x, cp2.y, p2.x, p2.y); + } + void Close() override { CGPathCloseSubpath(path_ref_); } + + CGMutablePathRef TakePath() { return path_ref_; } + + private: + CGMutablePathRef path_ref_ = CGPathCreateMutable(); +}; +} // namespace + +@interface PlatformViewFilter () + +// `YES` if the backdropFilterView has been configured at least once. +@property(nonatomic) BOOL backdropFilterViewConfigured; +@property(nonatomic) UIVisualEffectView* backdropFilterView; + +// Updates the `visualEffectView` with the current filter parameters. +// Also sets `self.backdropFilterView` to the updated visualEffectView. +- (void)updateVisualEffectView:(UIVisualEffectView*)visualEffectView; + +@end + +@implementation PlatformViewFilter + +static NSObject* _gaussianBlurFilter = nil; +// The index of "_UIVisualEffectBackdropView" in UIVisualEffectView's subViews. +static NSInteger _indexOfBackdropView = -1; +// The index of "_UIVisualEffectSubview" in UIVisualEffectView's subViews. +static NSInteger _indexOfVisualEffectSubview = -1; +static BOOL _preparedOnce = NO; + +- (instancetype)initWithFrame:(CGRect)frame + blurRadius:(CGFloat)blurRadius + visualEffectView:(UIVisualEffectView*)visualEffectView { + if (self = [super init]) { + _frame = frame; + _blurRadius = blurRadius; + [PlatformViewFilter prepareOnce:visualEffectView]; + if (![PlatformViewFilter isUIVisualEffectViewImplementationValid]) { + FML_DLOG(ERROR) << "Apple's API for UIVisualEffectView changed. Update the implementation to " + "access the gaussianBlur CAFilter."; + return nil; + } + _backdropFilterView = visualEffectView; + _backdropFilterViewConfigured = NO; + } + return self; +} + ++ (void)resetPreparation { + _preparedOnce = NO; + _gaussianBlurFilter = nil; + _indexOfBackdropView = -1; + _indexOfVisualEffectSubview = -1; +} + ++ (void)prepareOnce:(UIVisualEffectView*)visualEffectView { + if (_preparedOnce) { + return; + } + for (NSUInteger i = 0; i < visualEffectView.subviews.count; i++) { + UIView* view = visualEffectView.subviews[i]; + if ([NSStringFromClass([view class]) hasSuffix:@"BackdropView"]) { + _indexOfBackdropView = i; + for (NSObject* filter in view.layer.filters) { + if ([[filter valueForKey:@"name"] isEqual:@"gaussianBlur"] && + [[filter valueForKey:@"inputRadius"] isKindOfClass:[NSNumber class]]) { + _gaussianBlurFilter = filter; + break; + } + } + } else if ([NSStringFromClass([view class]) hasSuffix:@"VisualEffectSubview"]) { + _indexOfVisualEffectSubview = i; + } + } + _preparedOnce = YES; +} + ++ (BOOL)isUIVisualEffectViewImplementationValid { + return _indexOfBackdropView > -1 && _indexOfVisualEffectSubview > -1 && _gaussianBlurFilter; +} + +- (UIVisualEffectView*)backdropFilterView { + FML_DCHECK(_backdropFilterView); + if (!self.backdropFilterViewConfigured) { + [self updateVisualEffectView:_backdropFilterView]; + self.backdropFilterViewConfigured = YES; + } + return _backdropFilterView; +} + +- (void)updateVisualEffectView:(UIVisualEffectView*)visualEffectView { + NSObject* gaussianBlurFilter = [_gaussianBlurFilter copy]; + FML_DCHECK(gaussianBlurFilter); + UIView* backdropView = visualEffectView.subviews[_indexOfBackdropView]; + [gaussianBlurFilter setValue:@(_blurRadius) forKey:@"inputRadius"]; + backdropView.layer.filters = @[ gaussianBlurFilter ]; + + UIView* visualEffectSubview = visualEffectView.subviews[_indexOfVisualEffectSubview]; + visualEffectSubview.layer.backgroundColor = UIColor.clearColor.CGColor; + visualEffectView.frame = _frame; + + self.backdropFilterView = visualEffectView; +} + +@end + +@interface ChildClippingView () + +@property(nonatomic, copy) NSArray* filters; +@property(nonatomic) NSMutableArray* backdropFilterSubviews; + +@end + +@implementation ChildClippingView + +// The ChildClippingView's frame is the bounding rect of the platform view. we only want touches to +// be hit tested and consumed by this view if they are inside the embedded platform view which could +// be smaller the embedded platform view is rotated. +- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event { + for (UIView* view in self.subviews) { + if ([view pointInside:[self convertPoint:point toView:view] withEvent:event]) { + return YES; + } + } + return NO; +} + +- (void)applyBlurBackdropFilters:(NSArray*)filters { + FML_DCHECK(self.filters.count == self.backdropFilterSubviews.count); + if (self.filters.count == 0 && filters.count == 0) { + return; + } + self.filters = filters; + NSUInteger index = 0; + for (index = 0; index < self.filters.count; index++) { + UIVisualEffectView* backdropFilterView; + PlatformViewFilter* filter = self.filters[index]; + if (self.backdropFilterSubviews.count <= index) { + backdropFilterView = filter.backdropFilterView; + [self addSubview:backdropFilterView]; + [self.backdropFilterSubviews addObject:backdropFilterView]; + } else { + [filter updateVisualEffectView:self.backdropFilterSubviews[index]]; + } + } + for (NSUInteger i = self.backdropFilterSubviews.count; i > index; i--) { + [self.backdropFilterSubviews[i - 1] removeFromSuperview]; + [self.backdropFilterSubviews removeLastObject]; + } +} + +- (NSMutableArray*)backdropFilterSubviews { + if (!_backdropFilterSubviews) { + _backdropFilterSubviews = [[NSMutableArray alloc] init]; + } + return _backdropFilterSubviews; +} + +@end + +@interface FlutterClippingMaskView () + +// A `CATransform3D` matrix represnts a scale transform that revese UIScreen.scale. +// +// The transform matrix passed in clipRect/clipRRect/clipPath methods are in device coordinate +// space. The transfrom matrix concats `reverseScreenScale` to create a transform matrix in the iOS +// logical coordinates (points). +// +// See https://developer.apple.com/documentation/uikit/uiscreen/1617836-scale?language=objc for +// information about screen scale. +@property(nonatomic) CATransform3D reverseScreenScale; + +- (fml::CFRef)getTransformedPath:(CGPathRef)path matrix:(CATransform3D)matrix; + +@end + +@implementation FlutterClippingMaskView { + std::vector> paths_; + BOOL containsNonRectPath_; + CGRect rectSoFar_; +} + +- (instancetype)initWithFrame:(CGRect)frame { + return [self initWithFrame:frame screenScale:[UIScreen mainScreen].scale]; +} + +- (instancetype)initWithFrame:(CGRect)frame screenScale:(CGFloat)screenScale { + if (self = [super initWithFrame:frame]) { + self.backgroundColor = UIColor.clearColor; + _reverseScreenScale = CATransform3DMakeScale(1 / screenScale, 1 / screenScale, 1); + rectSoFar_ = self.bounds; + containsNonRectPath_ = NO; + } + return self; +} + ++ (Class)layerClass { + return [CAShapeLayer class]; +} + +- (CAShapeLayer*)shapeLayer { + return (CAShapeLayer*)self.layer; +} + +- (void)reset { + paths_.clear(); + rectSoFar_ = self.bounds; + containsNonRectPath_ = NO; + [self shapeLayer].path = nil; + [self setNeedsDisplay]; +} + +// In some scenarios, when we add this view as a maskView of the ChildClippingView, iOS added +// this view as a subview of the ChildClippingView. +// This results this view blocking touch events on the ChildClippingView. +// So we should always ignore any touch events sent to this view. +// See https://github.com/flutter/flutter/issues/66044 +- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event { + return NO; +} + +- (void)drawRect:(CGRect)rect { + // It's hard to compute intersection of arbitrary non-rect paths. + // So we fallback to software rendering. + if (containsNonRectPath_ && paths_.size() > 1) { + CGContextRef context = UIGraphicsGetCurrentContext(); + CGContextSaveGState(context); + + // For mask view, only the alpha channel is used. + CGContextSetAlpha(context, 1); + + for (size_t i = 0; i < paths_.size(); i++) { + CGContextAddPath(context, paths_.at(i)); + CGContextClip(context); + } + CGContextFillRect(context, rect); + CGContextRestoreGState(context); + } else { + // Either a single path, or multiple rect paths. + // Use hardware rendering with CAShapeLayer. + [super drawRect:rect]; + if (![self shapeLayer].path) { + if (paths_.size() == 1) { + // A single path, either rect or non-rect. + [self shapeLayer].path = paths_.at(0); + } else { + // Multiple paths, all paths must be rects. + CGPathRef pathSoFar = CGPathCreateWithRect(rectSoFar_, nil); + [self shapeLayer].path = pathSoFar; + CGPathRelease(pathSoFar); + } + } + } +} + +- (void)clipRect:(const flutter::DlRect&)clipDlRect matrix:(const flutter::DlMatrix&)matrix { + CGRect clipRect = GetCGRectFromDlRect(clipDlRect); + CGPathRef path = CGPathCreateWithRect(clipRect, nil); + // The `matrix` is based on the physical pixels, convert it to UIKit points. + CATransform3D matrixInPoints = + CATransform3DConcat(GetCATransform3DFromDlMatrix(matrix), _reverseScreenScale); + paths_.push_back([self getTransformedPath:path matrix:matrixInPoints]); + CGAffineTransform affine = [self affineWithMatrix:matrixInPoints]; + // Make sure the rect is not rotated (only translated or scaled). + if (affine.b == 0 && affine.c == 0) { + rectSoFar_ = CGRectIntersection(rectSoFar_, CGRectApplyAffineTransform(clipRect, affine)); + } else { + containsNonRectPath_ = YES; + } +} + +- (void)clipRRect:(const flutter::DlRoundRect&)clipDlRRect matrix:(const flutter::DlMatrix&)matrix { + if (clipDlRRect.IsEmpty()) { + return; + } else if (clipDlRRect.IsRect()) { + [self clipRect:clipDlRRect.GetBounds() matrix:matrix]; + return; + } else { + CGPathRef pathRef = nullptr; + containsNonRectPath_ = YES; + + if (clipDlRRect.GetRadii().AreAllCornersSame()) { + CGRect clipRect = GetCGRectFromDlRect(clipDlRRect.GetBounds()); + auto radii = clipDlRRect.GetRadii(); + pathRef = + CGPathCreateWithRoundedRect(clipRect, radii.top_left.width, radii.top_left.height, nil); + } else { + CGMutablePathRef mutablePathRef = CGPathCreateMutable(); + // Complex types, we manually add each corner. + flutter::DlRect clipDlRect = clipDlRRect.GetBounds(); + auto left = clipDlRect.GetLeft(); + auto top = clipDlRect.GetTop(); + auto right = clipDlRect.GetRight(); + auto bottom = clipDlRect.GetBottom(); + flutter::DlRoundingRadii radii = clipDlRRect.GetRadii(); + auto& top_left = radii.top_left; + auto& top_right = radii.top_right; + auto& bottom_left = radii.bottom_left; + auto& bottom_right = radii.bottom_right; + + // Start drawing RRect + // These calculations are off, the AddCurve methods add a Bezier curve + // which, for round rects should be a "magic distance" from the end + // point of the horizontal/vertical section to the corner. + // Move point to the top left corner adding the top left radii's x. + CGPathMoveToPoint(mutablePathRef, nil, // + left + top_left.width, top); + // Move point horizontally right to the top right corner and add the top right curve. + CGPathAddLineToPoint(mutablePathRef, nil, // + right - top_right.width, top); + CGPathAddCurveToPoint(mutablePathRef, nil, // + right, top, // + right, top + top_right.height, // + right, top + top_right.height); + // Move point vertically down to the bottom right corner and add the bottom right curve. + CGPathAddLineToPoint(mutablePathRef, nil, // + right, bottom - bottom_right.height); + CGPathAddCurveToPoint(mutablePathRef, nil, // + right, bottom, // + right - bottom_right.width, bottom, // + right - bottom_right.width, bottom); + // Move point horizontally left to the bottom left corner and add the bottom left curve. + CGPathAddLineToPoint(mutablePathRef, nil, // + left + bottom_left.width, bottom); + CGPathAddCurveToPoint(mutablePathRef, nil, // + left, bottom, // + left, bottom - bottom_left.height, // + left, bottom - bottom_left.height); + // Move point vertically up to the top left corner and add the top left curve. + CGPathAddLineToPoint(mutablePathRef, nil, // + left, top + top_left.height); + CGPathAddCurveToPoint(mutablePathRef, nil, // + left, top, // + left + top_left.width, top, // + left + top_left.width, top); + CGPathCloseSubpath(mutablePathRef); + pathRef = mutablePathRef; + } + // The `matrix` is based on the physical pixels, convert it to UIKit points. + CATransform3D matrixInPoints = + CATransform3DConcat(GetCATransform3DFromDlMatrix(matrix), _reverseScreenScale); + // TODO(cyanglaz): iOS does not seem to support hard edge on CAShapeLayer. It clearly stated + // that the CAShaperLayer will be drawn antialiased. Need to figure out a way to do the hard + // edge clipping on iOS. + paths_.push_back([self getTransformedPath:pathRef matrix:matrixInPoints]); + } +} + +- (void)clipPath:(const flutter::DlPath&)dlPath matrix:(const flutter::DlMatrix&)matrix { + containsNonRectPath_ = YES; + + CGPathReceiver receiver; + + dlPath.Dispatch(receiver); + + // The `matrix` is based on the physical pixels, convert it to UIKit points. + CATransform3D matrixInPoints = + CATransform3DConcat(GetCATransform3DFromDlMatrix(matrix), _reverseScreenScale); + paths_.push_back([self getTransformedPath:receiver.TakePath() matrix:matrixInPoints]); +} + +- (CGAffineTransform)affineWithMatrix:(CATransform3D)matrix { + return CGAffineTransformMake(matrix.m11, matrix.m12, matrix.m21, matrix.m22, matrix.m41, + matrix.m42); +} + +- (fml::CFRef)getTransformedPath:(CGPathRef)path matrix:(CATransform3D)matrix { + CGAffineTransform affine = [self affineWithMatrix:matrix]; + CGPathRef transformedPath = CGPathCreateCopyByTransformingPath(path, &affine); + + CGPathRelease(path); + return fml::CFRef(transformedPath); +} + +@end + +@interface FlutterClippingMaskViewPool () + +// The maximum number of `FlutterClippingMaskView` the pool can contain. +// This prevents the pool to grow infinately and limits the maximum memory a pool can use. +@property(nonatomic) NSUInteger capacity; + +// The pool contains the views that are available to use. +// The number of items in the pool must not excceds `capacity`. +@property(nonatomic) NSMutableSet* pool; + +@end + +@implementation FlutterClippingMaskViewPool : NSObject + +- (instancetype)initWithCapacity:(NSInteger)capacity { + if (self = [super init]) { + // Most of cases, there are only one PlatformView in the scene. + // Thus init with the capacity of 1. + _pool = [[NSMutableSet alloc] initWithCapacity:1]; + _capacity = capacity; + } + return self; +} + +- (FlutterClippingMaskView*)getMaskViewWithFrame:(CGRect)frame { + FML_DCHECK(self.pool.count <= self.capacity); + if (self.pool.count == 0) { + // The pool is empty, alloc a new one. + return [[FlutterClippingMaskView alloc] initWithFrame:frame + screenScale:UIScreen.mainScreen.scale]; + } + FlutterClippingMaskView* maskView = [self.pool anyObject]; + maskView.frame = frame; + [maskView reset]; + [self.pool removeObject:maskView]; + return maskView; +} + +- (void)insertViewToPoolIfNeeded:(FlutterClippingMaskView*)maskView { + FML_DCHECK(![self.pool containsObject:maskView]); + FML_DCHECK(self.pool.count <= self.capacity); + if (self.pool.count == self.capacity) { + return; + } + [self.pool addObject:maskView]; +} + +@end + +@implementation UIView (FirstResponder) +- (BOOL)flt_hasFirstResponderInViewHierarchySubtree { + if (self.isFirstResponder) { + return YES; + } + for (UIView* subview in self.subviews) { + if (subview.flt_hasFirstResponderInViewHierarchySubtree) { + return YES; + } + } + return NO; +} +@end + +@interface FlutterTouchInterceptingView () +@property(nonatomic, weak, readonly) UIView* embeddedView; +@property(nonatomic, readonly) FlutterDelayingGestureRecognizer* delayingRecognizer; +@property(nonatomic, readonly) FlutterPlatformViewGestureRecognizersBlockingPolicy blockingPolicy; +@end + +@implementation FlutterTouchInterceptingView +- (instancetype)initWithEmbeddedView:(UIView*)embeddedView + platformViewsController:(FlutterPlatformViewsController*)platformViewsController + gestureRecognizersBlockingPolicy: + (FlutterPlatformViewGestureRecognizersBlockingPolicy)blockingPolicy { + self = [super initWithFrame:embeddedView.frame]; + if (self) { + self.multipleTouchEnabled = YES; + _embeddedView = embeddedView; + embeddedView.autoresizingMask = + (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); + + [self addSubview:embeddedView]; + + ForwardingGestureRecognizer* forwardingRecognizer = + [[ForwardingGestureRecognizer alloc] initWithTarget:self + platformViewsController:platformViewsController]; + + _delayingRecognizer = + [[FlutterDelayingGestureRecognizer alloc] initWithTarget:self + action:nil + forwardingRecognizer:forwardingRecognizer]; + _blockingPolicy = blockingPolicy; + + [self addGestureRecognizer:_delayingRecognizer]; + [self addGestureRecognizer:forwardingRecognizer]; + } + return self; +} + +- (void)forceResetForwardingGestureRecognizerState { + // When iPad pencil is involved in a finger touch gesture, the gesture is not reset to "possible" + // state and is stuck on "failed" state, which causes subsequent touches to be blocked. As a + // workaround, we force reset the state by recreating the forwarding gesture recognizer. See: + // https://github.com/flutter/flutter/issues/136244 + ForwardingGestureRecognizer* oldForwardingRecognizer = + (ForwardingGestureRecognizer*)self.delayingRecognizer.forwardingRecognizer; + ForwardingGestureRecognizer* newForwardingRecognizer = + [oldForwardingRecognizer recreateRecognizerWithTarget:self]; + self.delayingRecognizer.forwardingRecognizer = newForwardingRecognizer; + [self removeGestureRecognizer:oldForwardingRecognizer]; + [self addGestureRecognizer:newForwardingRecognizer]; +} + +- (void)releaseGesture { + self.delayingRecognizer.state = UIGestureRecognizerStateFailed; +} + +- (BOOL)containsWebView:(UIView*)view remainingSubviewDepth:(int)remainingSubviewDepth { + if (remainingSubviewDepth < 0) { + return NO; + } + if ([view isKindOfClass:[WKWebView class]]) { + return YES; + } + for (UIView* subview in view.subviews) { + if ([self containsWebView:subview remainingSubviewDepth:remainingSubviewDepth - 1]) { + return YES; + } + } + return NO; +} + +- (void)blockGesture { + switch (_blockingPolicy) { + case FlutterPlatformViewGestureRecognizersBlockingPolicyEager: + // We block all other gesture recognizers immediately in this policy. + self.delayingRecognizer.state = UIGestureRecognizerStateEnded; + + // On iOS 18.2, WKWebView's internal recognizer likely caches the old state of its blocking + // recognizers (i.e. delaying recognizer), resulting in non-tappable links. See + // https://github.com/flutter/flutter/issues/158961. Removing and adding back the delaying + // recognizer solves the problem, possibly because UIKit notifies all the recognizers related + // to (blocking or blocked by) this recognizer. It is not possible to inject this workaround + // from the web view plugin level. Right now we only observe this issue for + // FlutterPlatformViewGestureRecognizersBlockingPolicyEager, but we should try it if a similar + // issue arises for the other policy. + if (@available(iOS 18.2, *)) { + // This workaround is designed for WKWebView only. The 1P web view plugin provides a + // WKWebView itself as the platform view. However, some 3P plugins provide wrappers of + // WKWebView instead. So we perform DFS to search the view hierarchy (with a depth limit). + // Passing a limit of 0 means only searching for platform view itself; Pass 1 to include its + // children as well, and so on. We should be conservative and start with a small number. The + // AdMob banner has a WKWebView at depth 7. + if ([self containsWebView:self.embeddedView remainingSubviewDepth:1]) { + [self removeGestureRecognizer:self.delayingRecognizer]; + [self addGestureRecognizer:self.delayingRecognizer]; + } + } + + break; + case FlutterPlatformViewGestureRecognizersBlockingPolicyWaitUntilTouchesEnded: + if (self.delayingRecognizer.touchedEndedWithoutBlocking) { + // If touchesEnded of the `DelayingGesureRecognizer` has been already invoked, + // we want to set the state of the `DelayingGesureRecognizer` to + // `UIGestureRecognizerStateEnded` as soon as possible. + self.delayingRecognizer.state = UIGestureRecognizerStateEnded; + } else { + // If touchesEnded of the `DelayingGesureRecognizer` has not been invoked, + // We will set a flag to notify the `DelayingGesureRecognizer` to set the state to + // `UIGestureRecognizerStateEnded` when touchesEnded is called. + self.delayingRecognizer.shouldEndInNextTouchesEnded = YES; + } + break; + default: + break; + } +} + +// We want the intercepting view to consume the touches and not pass the touches up to the parent +// view. Make the touch event method not call super will not pass the touches up to the parent view. +// Hence we overide the touch event methods and do nothing. +- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event { +} + +- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event { +} + +- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event { +} + +- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event { +} + +- (id)accessibilityContainer { + return self.flutterAccessibilityContainer; +} + +@end + +@implementation FlutterDelayingGestureRecognizer + +- (instancetype)initWithTarget:(id)target + action:(SEL)action + forwardingRecognizer:(UIGestureRecognizer*)forwardingRecognizer { + self = [super initWithTarget:target action:action]; + if (self) { + self.delaysTouchesBegan = YES; + self.delaysTouchesEnded = YES; + self.delegate = self; + _shouldEndInNextTouchesEnded = NO; + _touchedEndedWithoutBlocking = NO; + _forwardingRecognizer = forwardingRecognizer; + } + return self; +} + +- (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer + shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer*)otherGestureRecognizer { + // The forwarding gesture recognizer should always get all touch events, so it should not be + // required to fail by any other gesture recognizer. + return otherGestureRecognizer != _forwardingRecognizer && otherGestureRecognizer != self; +} + +- (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer + shouldRequireFailureOfGestureRecognizer:(UIGestureRecognizer*)otherGestureRecognizer { + return otherGestureRecognizer == self; +} + +- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event { + self.touchedEndedWithoutBlocking = NO; + [super touchesBegan:touches withEvent:event]; +} + +- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event { + if (self.shouldEndInNextTouchesEnded) { + self.state = UIGestureRecognizerStateEnded; + self.shouldEndInNextTouchesEnded = NO; + } else { + self.touchedEndedWithoutBlocking = YES; + } + [super touchesEnded:touches withEvent:event]; +} + +- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event { + self.state = UIGestureRecognizerStateFailed; +} +@end + +@implementation ForwardingGestureRecognizer { + // Weak reference to PlatformViewsController. The PlatformViewsController has + // a reference to the FlutterViewController, where we can dispatch pointer events to. + // + // The lifecycle of PlatformViewsController is bind to FlutterEngine, which should always + // outlives the FlutterViewController. And ForwardingGestureRecognizer is owned by a subview of + // FlutterView, so the ForwardingGestureRecognizer never out lives FlutterViewController. + // Therefore, `_platformViewsController` should never be nullptr. + __weak FlutterPlatformViewsController* _platformViewsController; + // Counting the pointers that has started in one touch sequence. + NSInteger _currentTouchPointersCount; + // We can't dispatch events to the framework without this back pointer. + // This gesture recognizer retains the `FlutterViewController` until the + // end of a gesture sequence, that is all the touches in touchesBegan are concluded + // with |touchesCancelled| or |touchesEnded|. + UIViewController* _flutterViewController; +} + +- (instancetype)initWithTarget:(id)target + platformViewsController:(FlutterPlatformViewsController*)platformViewsController { + self = [super initWithTarget:target action:nil]; + if (self) { + self.delegate = self; + FML_DCHECK(platformViewsController); + _platformViewsController = platformViewsController; + _currentTouchPointersCount = 0; + } + return self; +} + +- (ForwardingGestureRecognizer*)recreateRecognizerWithTarget:(id)target { + return [[ForwardingGestureRecognizer alloc] initWithTarget:target + platformViewsController:_platformViewsController]; +} + +- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event { + FML_DCHECK(_currentTouchPointersCount >= 0); + if (_currentTouchPointersCount == 0) { + // At the start of each gesture sequence, we reset the `_flutterViewController`, + // so that all the touch events in the same sequence are forwarded to the same + // `_flutterViewController`. + _flutterViewController = _platformViewsController.flutterViewController; + } + [_flutterViewController touchesBegan:touches withEvent:event]; + _currentTouchPointersCount += touches.count; +} + +- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event { + [_flutterViewController touchesMoved:touches withEvent:event]; +} + +- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event { + [_flutterViewController touchesEnded:touches withEvent:event]; + _currentTouchPointersCount -= touches.count; + // Touches in one touch sequence are sent to the touchesEnded method separately if different + // fingers stop touching the screen at different time. So one touchesEnded method triggering does + // not necessarially mean the touch sequence has ended. We Only set the state to + // UIGestureRecognizerStateFailed when all the touches in the current touch sequence is ended. + if (_currentTouchPointersCount == 0) { + self.state = UIGestureRecognizerStateFailed; + _flutterViewController = nil; + [self forceResetStateIfNeeded]; + } +} + +- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event { + // In the event of platform view is removed, iOS generates a "stationary" change type instead of + // "cancelled" change type. + // Flutter needs all the cancelled touches to be "cancelled" change types in order to correctly + // handle gesture sequence. + // We always override the change type to "cancelled". + [_flutterViewController forceTouchesCancelled:touches]; + _currentTouchPointersCount -= touches.count; + if (_currentTouchPointersCount == 0) { + self.state = UIGestureRecognizerStateFailed; + _flutterViewController = nil; + [self forceResetStateIfNeeded]; + } +} + +- (void)forceResetStateIfNeeded { + __weak ForwardingGestureRecognizer* weakSelf = self; + dispatch_async(dispatch_get_main_queue(), ^{ + ForwardingGestureRecognizer* strongSelf = weakSelf; + if (!strongSelf) { + return; + } + if (strongSelf.state != UIGestureRecognizerStatePossible) { + [(FlutterTouchInterceptingView*)strongSelf.view forceResetForwardingGestureRecognizerState]; + } + }); +} + +- (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer + shouldRecognizeSimultaneouslyWithGestureRecognizer: + (UIGestureRecognizer*)otherGestureRecognizer { + return YES; +} +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViewsController.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViewsController.h new file mode 100644 index 0000000000000000000000000000000000000000..0a259856164e021c92580df313c77c3ae3e722db --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViewsController.h @@ -0,0 +1,148 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMVIEWSCONTROLLER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMVIEWSCONTROLLER_H_ + +#include +#include +#include +#include + +#include "flutter/flow/surface.h" +#include "flutter/fml/task_runner.h" +#include "flutter/fml/trace_event.h" +#include "impeller/base/thread_safety.h" + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterPlatformViews.h" +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterPlugin.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewResponder.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/overlay_layer_pool.h" +#import "flutter/shell/platform/darwin/ios/ios_context.h" + +NS_ASSUME_NONNULL_BEGIN + +@class FlutterTouchInterceptingView; +@class FlutterClippingMaskViewPool; + +@interface FlutterPlatformViewsController : NSObject + +- (instancetype)init NS_DESIGNATED_INITIALIZER; + +/// The task runner used to post rendering tasks to the platform thread. +@property(nonatomic, assign) const fml::RefPtr& taskRunner; + +/// The flutter view. +@property(nonatomic, weak) UIView* _Nullable flutterView; + +/// @brief The flutter view controller. +@property(nonatomic, weak) UIViewController* _Nullable flutterViewController; + +/// @brief set the factory used to construct embedded UI Views. +- (void)registerViewFactory:(NSObject*)factory + withId:(NSString*)factoryId + gestureRecognizersBlockingPolicy: + (FlutterPlatformViewGestureRecognizersBlockingPolicy)gestureRecognizerBlockingPolicy; + +/// @brief Mark the beginning of a frame and record the size of the onscreen. +- (void)beginFrameWithSize:(SkISize)frameSize; + +/// @brief Cancel the current frame, indicating that no platform views are composited. +/// +/// Additionally, reverts the composition order to its original state at the beginning of the +/// frame. +- (void)cancelFrame; + +/// @brief Record a platform view in the layer tree to be rendered, along with the positioning and +/// mutator parameters. +/// +/// Called from the raster thread. +- (void)prerollCompositeEmbeddedView:(int64_t)viewId + withParams:(std::unique_ptr)params; + +/// @brief Returns the`FlutterTouchInterceptingView` with the provided view_id. +/// +/// Returns nil if there is no platform view with the provided id. Called +/// from the platform thread. +- (FlutterTouchInterceptingView*)flutterTouchInterceptingViewForId:(int64_t)viewId; + +/// @brief Determine if thread merging is required after prerolling platform views. +/// +/// Called from the raster thread. +- (flutter::PostPrerollResult)postPrerollActionWithThreadMerger: + (const fml::RefPtr&)rasterThreadMerger; + +/// @brief Mark the end of a compositor frame. +/// +/// May determine changes are required to the thread merging state. +/// Called from the raster thread. +- (void)endFrameWithResubmit:(BOOL)shouldResubmitFrame + threadMerger:(const fml::RefPtr&)rasterThreadMerger; + +/// @brief Returns the Canvas for the overlay slice for the given platform view. +/// +/// Called from the raster thread. +- (flutter::DlCanvas*)compositeEmbeddedViewWithId:(int64_t)viewId; + +/// @brief Discards all platform views instances and auxiliary resources. +/// +/// Called from the raster thread. +- (void)reset; + +/// @brief Encode rendering for the Flutter overlay views and queue up perform platform view +/// mutations. +/// +/// Called from the raster thread. +- (BOOL)submitFrame:(std::unique_ptr)frame + withIosContext:(const std::shared_ptr&)iosContext; + +/// @brief Handler for platform view message channels. +- (void)onMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result; + +/// @brief Returns the platform view id if the platform view (or any of its descendant view) is +/// the first responder. +/// +/// Returns -1 if no such platform view is found. +- (long)firstResponderPlatformViewId; + +/// @brief Pushes backdrop filter mutation to the mutator stack of each visited platform view. +- (void)pushFilterToVisitedPlatformViews:(const std::shared_ptr&)filter + withRect:(const SkRect&)filterRect; + +/// @brief Pushes the view id of a visted platform view to the list of visied platform views. +- (void)pushVisitedPlatformViewId:(int64_t)viewId; + +@end + +@interface FlutterPlatformViewsController (Testing) + +- (size_t)embeddedViewCount; + +// Returns the `FlutterPlatformView`'s `view` object associated with the view_id. +// +// If the `PlatformViewsController` does not contain any `FlutterPlatformView` object or +// a `FlutterPlatformView` object associated with the view_id cannot be found, the method +// returns nil. +- (UIView* _Nullable)platformViewForId:(int64_t)viewId; + +// Composite the PlatformView with `viewId`. +// +// Every frame, during the paint traversal of the layer tree, this method is called for all +// the PlatformViews in `_viewsToRecomposite`. +// +// Note that `_viewsToRecomposite` does not represent all the views in the view hierarchy, +// if a PlatformView does not change its composition parameter from last frame, it is not +// included in the `views_to_recomposite_`. +- (void)compositeView:(int64_t)viewId withParams:(const flutter::EmbeddedViewParams&)params; + +- (const flutter::EmbeddedViewParams&)compositionParamsForView:(int64_t)viewId; + +- (std::vector&)previousCompositionOrder; + +@end + +NS_ASSUME_NONNULL_END + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMVIEWSCONTROLLER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViewsController.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViewsController.mm new file mode 100644 index 0000000000000000000000000000000000000000..20e3b15bf36e8204bf10a09d4e3997ab07f14ffc --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViewsController.mm @@ -0,0 +1,1006 @@ +// 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. + +#import "shell/platform/darwin/ios/framework/Source/FlutterPlatformViewsController.h" + +#include "flutter/display_list/effects/image_filters/dl_blur_image_filter.h" +#include "flutter/display_list/utils/dl_matrix_clip_tracker.h" +#include "flutter/flow/surface_frame.h" +#include "flutter/flow/view_slicer.h" +#include "flutter/fml/make_copyable.h" +#include "flutter/fml/synchronization/count_down_latch.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterOverlayView.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h" +#include "flutter/shell/platform/darwin/ios/framework/Source/overlay_layer_pool.h" +#import "flutter/shell/platform/darwin/ios/ios_surface.h" + +using flutter::DlMatrix; +using flutter::DlRect; +using flutter::DlRoundRect; + +static constexpr NSUInteger kFlutterClippingMaskViewPoolCapacity = 5; + +struct LayerData { + SkRect rect; + int64_t view_id; + int64_t overlay_id; + std::shared_ptr layer; +}; +using LayersMap = std::unordered_map; + +/// Each of the following structs stores part of the platform view hierarchy according to its +/// ID. +/// +/// This data must only be accessed on the platform thread. +struct PlatformViewData { + NSObject* view; + FlutterTouchInterceptingView* touch_interceptor; + UIView* root_view; +}; + +// Converts a SkMatrix to CATransform3D. +// +// Certain fields are ignored in CATransform3D since SkMatrix is 3x3 and CATransform3D is 4x4. +static CATransform3D GetCATransform3DFromDlMatrix(const DlMatrix& matrix) { + CATransform3D transform = CATransform3DIdentity; + transform.m11 = matrix.m[0]; + transform.m12 = matrix.m[1]; + transform.m13 = matrix.m[2]; + transform.m14 = matrix.m[3]; + + transform.m21 = matrix.m[4]; + transform.m22 = matrix.m[5]; + transform.m23 = matrix.m[6]; + transform.m24 = matrix.m[7]; + + transform.m31 = matrix.m[8]; + transform.m32 = matrix.m[9]; + transform.m33 = matrix.m[10]; + transform.m34 = matrix.m[11]; + + transform.m41 = matrix.m[12]; + transform.m42 = matrix.m[13]; + transform.m43 = matrix.m[14]; + transform.m44 = matrix.m[15]; + return transform; +} + +// Reset the anchor of `layer` to match the transform operation from flow. +// +// The position of the `layer` should be unchanged after resetting the anchor. +static void ResetAnchor(CALayer* layer) { + // Flow uses (0, 0) to apply transform matrix so we need to match that in Quartz. + layer.anchorPoint = CGPointZero; + layer.position = CGPointZero; +} + +static CGRect GetCGRectFromDlRect(const DlRect& clipDlRect) { + return CGRectMake(clipDlRect.GetLeft(), // + clipDlRect.GetTop(), // + clipDlRect.GetWidth(), // + clipDlRect.GetHeight()); +} + +@interface FlutterPlatformViewsController () + +// The pool of reusable view layers. The pool allows to recycle layer in each frame. +@property(nonatomic, readonly) flutter::OverlayLayerPool* layerPool; + +// The platform view's |EmbedderViewSlice| keyed off the view id, which contains any subsequent +// operation until the next platform view or the end of the last leaf node in the layer tree. +// +// The Slices are deleted by the PlatformViewsController.reset(). +@property(nonatomic, readonly) + std::unordered_map>& slices; + +@property(nonatomic, readonly) FlutterClippingMaskViewPool* maskViewPool; + +@property(nonatomic, readonly) + std::unordered_map*>& factories; + +// The FlutterPlatformViewGestureRecognizersBlockingPolicy for each type of platform view. +@property(nonatomic, readonly) + std::unordered_map& + gestureRecognizersBlockingPolicies; + +/// The size of the current onscreen surface in physical pixels. +@property(nonatomic, assign) SkISize frameSize; + +/// The task runner for posting tasks to the platform thread. +@property(nonatomic, readonly) const fml::RefPtr& platformTaskRunner; + +/// This data must only be accessed on the platform thread. +@property(nonatomic, readonly) std::unordered_map& platformViews; + +/// The composition parameters for each platform view. +/// +/// This state is only modified on the raster thread. +@property(nonatomic, readonly) + std::unordered_map& currentCompositionParams; + +/// Method channel `OnDispose` calls adds the views to be disposed to this set to be disposed on +/// the next frame. +/// +/// This state is modified on both the platform and raster thread. +@property(nonatomic, readonly) std::unordered_set& viewsToDispose; + +/// view IDs in composition order. +/// +/// This state is only modified on the raster thread. +@property(nonatomic, readonly) std::vector& compositionOrder; + +/// platform view IDs visited during layer tree composition. +/// +/// This state is only modified on the raster thread. +@property(nonatomic, readonly) std::vector& visitedPlatformViews; + +/// Only composite platform views in this set. +/// +/// This state is only modified on the raster thread. +@property(nonatomic, readonly) std::unordered_set& viewsToRecomposite; + +/// @brief The composition order from the previous thread. +/// +/// Only accessed from the platform thread. +@property(nonatomic, readonly) std::vector& previousCompositionOrder; + +/// Whether the previous frame had any platform views in active composition order. +/// +/// This state is tracked so that the first frame after removing the last platform view +/// runs through the platform view rendering code path, giving us a chance to remove the +/// platform view from the UIView hierarchy. +/// +/// Only accessed from the raster thread. +@property(nonatomic, assign) BOOL hadPlatformViews; + +/// Whether blurred backdrop filters can be applied. +/// +/// Defaults to YES, but becomes NO if blurred backdrop filters cannot be applied. +@property(nonatomic, assign) BOOL canApplyBlurBackdrop; + +/// Populate any missing overlay layers. +/// +/// This requires posting a task to the platform thread and blocking on its completion. +- (void)createMissingOverlays:(size_t)requiredOverlayLayers + withIosContext:(const std::shared_ptr&)iosContext; + +/// Update the buffers and mutate the platform views in CATransaction on the platform thread. +- (void)performSubmit:(const LayersMap&)platformViewLayers + currentCompositionParams: + (std::unordered_map&)currentCompositionParams + viewsToRecomposite:(const std::unordered_set&)viewsToRecomposite + compositionOrder:(const std::vector&)compositionOrder + unusedLayers: + (const std::vector>&)unusedLayers + surfaceFrames: + (const std::vector>&)surfaceFrames; + +- (void)onCreate:(FlutterMethodCall*)call result:(FlutterResult)result; +- (void)onDispose:(FlutterMethodCall*)call result:(FlutterResult)result; +- (void)onAcceptGesture:(FlutterMethodCall*)call result:(FlutterResult)result; +- (void)onRejectGesture:(FlutterMethodCall*)call result:(FlutterResult)result; + +- (void)clipViewSetMaskView:(UIView*)clipView; + +// Applies the mutators in the mutatorsStack to the UIView chain that was constructed by +// `ReconstructClipViewsChain` +// +// Clips are applied to the `embeddedView`'s super view(|ChildClippingView|) using a +// |FlutterClippingMaskView|. Transforms are applied to `embeddedView` +// +// The `boundingRect` is the final bounding rect of the PlatformView +// (EmbeddedViewParams::finalBoundingRect). If a clip mutator's rect contains the final bounding +// rect of the PlatformView, the clip mutator is not applied for performance optimization. +// +// This method is only called when the `embeddedView` needs to be re-composited at the current +// frame. See: `compositeView:withParams:` for details. +- (void)applyMutators:(const flutter::MutatorsStack&)mutatorsStack + embeddedView:(UIView*)embeddedView + boundingRect:(const SkRect&)boundingRect; + +// Appends the overlay views and platform view and sets their z index based on the composition +// order. +- (void)bringLayersIntoView:(const LayersMap&)layerMap + withCompositionOrder:(const std::vector&)compositionOrder; + +- (std::shared_ptr)nextLayerInPool; + +/// Runs on the platform thread. +- (void)createLayerWithIosContext:(const std::shared_ptr&)iosContext + pixelFormat:(MTLPixelFormat)pixelFormat; + +/// Removes overlay views and platform views that aren't needed in the current frame. +/// Must run on the platform thread. +- (void)removeUnusedLayers:(const std::vector>&)unusedLayers + withCompositionOrder:(const std::vector&)compositionOrder; + +/// Computes and returns all views to be disposed on the platform thread, removes them from +/// self.platformViews, self.viewsToRecomposite, and self.currentCompositionParams. Any views that +/// still require compositing are not returned, but instead added to `viewsToDelayDispose` for +/// disposal on the next call. +- (std::vector)computeViewsToDispose; + +/// Resets the state of the frame. +- (void)resetFrameState; +@end + +@implementation FlutterPlatformViewsController { + // TODO(cbracken): Replace with Obj-C types and use @property declarations to automatically + // synthesize the ivars. + // + // These ivars are required because we're transitioning the previous C++ implementation to Obj-C. + // We require ivars to declare the concrete types and then wrap with @property declarations that + // return a reference to the ivar, allowing for use like `self.layerPool` and + // `self.slices[viewId] = x`. + std::unique_ptr _layerPool; + std::unordered_map> _slices; + std::unordered_map*> _factories; + std::unordered_map + _gestureRecognizersBlockingPolicies; + fml::RefPtr _platformTaskRunner; + std::unordered_map _platformViews; + std::unordered_map _currentCompositionParams; + std::unordered_set _viewsToDispose; + std::vector _compositionOrder; + std::vector _visitedPlatformViews; + std::unordered_set _viewsToRecomposite; + std::vector _previousCompositionOrder; +} + +- (id)init { + if (self = [super init]) { + _layerPool = std::make_unique(); + _maskViewPool = + [[FlutterClippingMaskViewPool alloc] initWithCapacity:kFlutterClippingMaskViewPoolCapacity]; + _hadPlatformViews = NO; + _canApplyBlurBackdrop = YES; + } + return self; +} + +- (const fml::RefPtr&)taskRunner { + return _platformTaskRunner; +} + +- (void)setTaskRunner:(const fml::RefPtr&)platformTaskRunner { + _platformTaskRunner = platformTaskRunner; +} + +- (void)onMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { + if ([[call method] isEqualToString:@"create"]) { + [self onCreate:call result:result]; + } else if ([[call method] isEqualToString:@"dispose"]) { + [self onDispose:call result:result]; + } else if ([[call method] isEqualToString:@"acceptGesture"]) { + [self onAcceptGesture:call result:result]; + } else if ([[call method] isEqualToString:@"rejectGesture"]) { + [self onRejectGesture:call result:result]; + } else { + result(FlutterMethodNotImplemented); + } +} + +- (void)onCreate:(FlutterMethodCall*)call result:(FlutterResult)result { + NSDictionary* args = [call arguments]; + + int64_t viewId = [args[@"id"] longLongValue]; + NSString* viewTypeString = args[@"viewType"]; + std::string viewType(viewTypeString.UTF8String); + + if (self.platformViews.count(viewId) != 0) { + result([FlutterError errorWithCode:@"recreating_view" + message:@"trying to create an already created view" + details:[NSString stringWithFormat:@"view id: '%lld'", viewId]]); + return; + } + + NSObject* factory = self.factories[viewType]; + if (factory == nil) { + result([FlutterError + errorWithCode:@"unregistered_view_type" + message:[NSString stringWithFormat:@"A UIKitView widget is trying to create a " + @"PlatformView with an unregistered type: < %@ >", + viewTypeString] + details:@"If you are the author of the PlatformView, make sure `registerViewFactory` " + @"is invoked.\n" + @"See: " + @"https://docs.flutter.dev/development/platform-integration/" + @"platform-views#on-the-platform-side-1 for more details.\n" + @"If you are not the author of the PlatformView, make sure to call " + @"`GeneratedPluginRegistrant.register`."]); + return; + } + + id params = nil; + if ([factory respondsToSelector:@selector(createArgsCodec)]) { + NSObject* codec = [factory createArgsCodec]; + if (codec != nil && args[@"params"] != nil) { + FlutterStandardTypedData* paramsData = args[@"params"]; + params = [codec decode:paramsData.data]; + } + } + + NSObject* embeddedView = [factory createWithFrame:CGRectZero + viewIdentifier:viewId + arguments:params]; + UIView* platformView = [embeddedView view]; + // Set a unique view identifier, so the platform view can be identified in unit tests. + platformView.accessibilityIdentifier = [NSString stringWithFormat:@"platform_view[%lld]", viewId]; + + FlutterTouchInterceptingView* touchInterceptor = [[FlutterTouchInterceptingView alloc] + initWithEmbeddedView:platformView + platformViewsController:self + gestureRecognizersBlockingPolicy:self.gestureRecognizersBlockingPolicies[viewType]]; + + ChildClippingView* clippingView = [[ChildClippingView alloc] initWithFrame:CGRectZero]; + [clippingView addSubview:touchInterceptor]; + + self.platformViews.emplace(viewId, PlatformViewData{ + .view = embeddedView, // + .touch_interceptor = touchInterceptor, // + .root_view = clippingView // + }); + + result(nil); +} + +- (void)onDispose:(FlutterMethodCall*)call result:(FlutterResult)result { + NSNumber* arg = [call arguments]; + int64_t viewId = [arg longLongValue]; + + if (self.platformViews.count(viewId) == 0) { + result([FlutterError errorWithCode:@"unknown_view" + message:@"trying to dispose an unknown" + details:[NSString stringWithFormat:@"view id: '%lld'", viewId]]); + return; + } + // We wait for next submitFrame to dispose views. + self.viewsToDispose.insert(viewId); + result(nil); +} + +- (void)onAcceptGesture:(FlutterMethodCall*)call result:(FlutterResult)result { + NSDictionary* args = [call arguments]; + int64_t viewId = [args[@"id"] longLongValue]; + + if (self.platformViews.count(viewId) == 0) { + result([FlutterError errorWithCode:@"unknown_view" + message:@"trying to set gesture state for an unknown view" + details:[NSString stringWithFormat:@"view id: '%lld'", viewId]]); + return; + } + + FlutterTouchInterceptingView* view = self.platformViews[viewId].touch_interceptor; + [view releaseGesture]; + + result(nil); +} + +- (void)onRejectGesture:(FlutterMethodCall*)call result:(FlutterResult)result { + NSDictionary* args = [call arguments]; + int64_t viewId = [args[@"id"] longLongValue]; + + if (self.platformViews.count(viewId) == 0) { + result([FlutterError errorWithCode:@"unknown_view" + message:@"trying to set gesture state for an unknown view" + details:[NSString stringWithFormat:@"view id: '%lld'", viewId]]); + return; + } + + FlutterTouchInterceptingView* view = self.platformViews[viewId].touch_interceptor; + [view blockGesture]; + + result(nil); +} + +- (void)registerViewFactory:(NSObject*)factory + withId:(NSString*)factoryId + gestureRecognizersBlockingPolicy: + (FlutterPlatformViewGestureRecognizersBlockingPolicy)gestureRecognizerBlockingPolicy { + std::string idString([factoryId UTF8String]); + FML_CHECK(self.factories.count(idString) == 0); + self.factories[idString] = factory; + self.gestureRecognizersBlockingPolicies[idString] = gestureRecognizerBlockingPolicy; +} + +- (void)beginFrameWithSize:(SkISize)frameSize { + [self resetFrameState]; + self.frameSize = frameSize; +} + +- (void)cancelFrame { + [self resetFrameState]; +} + +- (flutter::PostPrerollResult)postPrerollActionWithThreadMerger: + (const fml::RefPtr&)rasterThreadMerger { + return flutter::PostPrerollResult::kSuccess; +} + +- (void)endFrameWithResubmit:(BOOL)shouldResubmitFrame + threadMerger:(const fml::RefPtr&)rasterThreadMerger { +} + +- (void)pushFilterToVisitedPlatformViews:(const std::shared_ptr&)filter + withRect:(const SkRect&)filterRect { + for (int64_t id : self.visitedPlatformViews) { + flutter::EmbeddedViewParams params = self.currentCompositionParams[id]; + params.PushImageFilter(filter, filterRect); + self.currentCompositionParams[id] = params; + } +} + +- (void)prerollCompositeEmbeddedView:(int64_t)viewId + withParams:(std::unique_ptr)params { + SkRect viewBounds = SkRect::Make(self.frameSize); + std::unique_ptr view; + view = std::make_unique(viewBounds); + self.slices.insert_or_assign(viewId, std::move(view)); + + self.compositionOrder.push_back(viewId); + + if (self.currentCompositionParams.count(viewId) == 1 && + self.currentCompositionParams[viewId] == *params.get()) { + // Do nothing if the params didn't change. + return; + } + self.currentCompositionParams[viewId] = flutter::EmbeddedViewParams(*params.get()); + self.viewsToRecomposite.insert(viewId); +} + +- (size_t)embeddedViewCount { + return self.compositionOrder.size(); +} + +- (UIView*)platformViewForId:(int64_t)viewId { + return [self flutterTouchInterceptingViewForId:viewId].embeddedView; +} + +- (FlutterTouchInterceptingView*)flutterTouchInterceptingViewForId:(int64_t)viewId { + if (self.platformViews.empty()) { + return nil; + } + return self.platformViews[viewId].touch_interceptor; +} + +- (long)firstResponderPlatformViewId { + for (auto const& [id, platformViewData] : self.platformViews) { + UIView* rootView = platformViewData.root_view; + if (rootView.flt_hasFirstResponderInViewHierarchySubtree) { + return id; + } + } + return -1; +} + +- (void)clipViewSetMaskView:(UIView*)clipView { + FML_DCHECK([[NSThread currentThread] isMainThread]); + if (clipView.maskView) { + return; + } + CGRect frame = + CGRectMake(-clipView.frame.origin.x, -clipView.frame.origin.y, + CGRectGetWidth(self.flutterView.bounds), CGRectGetHeight(self.flutterView.bounds)); + clipView.maskView = [self.maskViewPool getMaskViewWithFrame:frame]; +} + +- (void)applyMutators:(const flutter::MutatorsStack&)mutatorsStack + embeddedView:(UIView*)embeddedView + boundingRect:(const SkRect&)boundingRect { + if (self.flutterView == nil) { + return; + } + + ResetAnchor(embeddedView.layer); + ChildClippingView* clipView = (ChildClippingView*)embeddedView.superview; + + DlMatrix transformMatrix; + const DlRect& dlBoundingRect = flutter::ToDlRect(boundingRect); + NSMutableArray* blurFilters = [[NSMutableArray alloc] init]; + FML_DCHECK(!clipView.maskView || + [clipView.maskView isKindOfClass:[FlutterClippingMaskView class]]); + if (clipView.maskView) { + [self.maskViewPool insertViewToPoolIfNeeded:(FlutterClippingMaskView*)(clipView.maskView)]; + clipView.maskView = nil; + } + CGFloat screenScale = [UIScreen mainScreen].scale; + auto iter = mutatorsStack.Begin(); + while (iter != mutatorsStack.End()) { + switch ((*iter)->GetType()) { + case flutter::MutatorType::kTransform: { + transformMatrix = transformMatrix * (*iter)->GetMatrix(); + break; + } + case flutter::MutatorType::kClipRect: { + if (flutter::DisplayListMatrixClipState::TransformedRectCoversBounds( + (*iter)->GetRect(), transformMatrix, dlBoundingRect)) { + break; + } + [self clipViewSetMaskView:clipView]; + [(FlutterClippingMaskView*)clipView.maskView clipRect:(*iter)->GetRect() + matrix:transformMatrix]; + break; + } + case flutter::MutatorType::kClipRRect: { + if (flutter::DisplayListMatrixClipState::TransformedRRectCoversBounds( + (*iter)->GetRRect(), transformMatrix, dlBoundingRect)) { + break; + } + [self clipViewSetMaskView:clipView]; + [(FlutterClippingMaskView*)clipView.maskView clipRRect:(*iter)->GetRRect() + matrix:transformMatrix]; + break; + } + case flutter::MutatorType::kClipRSE: { + if (flutter::DisplayListMatrixClipState::TransformedRoundSuperellipseCoversBounds( + (*iter)->GetRSE(), transformMatrix, dlBoundingRect)) { + break; + } + [self clipViewSetMaskView:clipView]; + [(FlutterClippingMaskView*)clipView.maskView clipRRect:(*iter)->GetRRect() + matrix:transformMatrix]; + break; + } + case flutter::MutatorType::kClipPath: { + // TODO(cyanglaz): Find a way to pre-determine if path contains the PlatformView boudning + // rect. See `ClipRRectContainsPlatformViewBoundingRect`. + // https://github.com/flutter/flutter/issues/118650 + [self clipViewSetMaskView:clipView]; + [(FlutterClippingMaskView*)clipView.maskView clipPath:(*iter)->GetPath() + matrix:transformMatrix]; + break; + } + case flutter::MutatorType::kOpacity: + embeddedView.alpha = (*iter)->GetAlphaFloat() * embeddedView.alpha; + break; + case flutter::MutatorType::kBackdropFilter: { + // Only support DlBlurImageFilter for BackdropFilter. + if (!self.canApplyBlurBackdrop || !(*iter)->GetFilterMutation().GetFilter().asBlur()) { + break; + } + CGRect filterRect = GetCGRectFromDlRect((*iter)->GetFilterMutation().GetFilterRect()); + // `filterRect` is in global coordinates. We need to convert to local space. + filterRect = CGRectApplyAffineTransform( + filterRect, CGAffineTransformMakeScale(1 / screenScale, 1 / screenScale)); + // `filterRect` reprents the rect that should be filtered inside the `_flutterView`. + // The `PlatformViewFilter` needs the frame inside the `clipView` that needs to be + // filtered. + if (CGRectIsNull(CGRectIntersection(filterRect, clipView.frame))) { + break; + } + CGRect intersection = CGRectIntersection(filterRect, clipView.frame); + CGRect frameInClipView = [self.flutterView convertRect:intersection toView:clipView]; + // sigma_x is arbitrarily chosen as the radius value because Quartz sets + // sigma_x and sigma_y equal to each other. DlBlurImageFilter's Tile Mode + // is not supported in Quartz's gaussianBlur CAFilter, so it is not used + // to blur the PlatformView. + CGFloat blurRadius = (*iter)->GetFilterMutation().GetFilter().asBlur()->sigma_x(); + UIVisualEffectView* visualEffectView = [[UIVisualEffectView alloc] + initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]]; + PlatformViewFilter* filter = [[PlatformViewFilter alloc] initWithFrame:frameInClipView + blurRadius:blurRadius + visualEffectView:visualEffectView]; + if (!filter) { + self.canApplyBlurBackdrop = NO; + } else { + [blurFilters addObject:filter]; + } + break; + } + } + ++iter; + } + + if (self.canApplyBlurBackdrop) { + [clipView applyBlurBackdropFilters:blurFilters]; + } + + // The UIKit frame is set based on the logical resolution (points) instead of physical. + // (https://developer.apple.com/library/archive/documentation/DeviceInformation/Reference/iOSDeviceCompatibility/Displays/Displays.html). + // However, flow is based on the physical resolution. For example, 1000 pixels in flow equals + // 500 points in UIKit for devices that has screenScale of 2. We need to scale the transformMatrix + // down to the logical resoltion before applying it to the layer of PlatformView. + flutter::DlScalar pointScale = 1.0 / screenScale; + transformMatrix = DlMatrix::MakeScale({pointScale, pointScale, 1}) * transformMatrix; + + // Reverse the offset of the clipView. + // The clipView's frame includes the final translate of the final transform matrix. + // Thus, this translate needs to be reversed so the platform view can layout at the correct + // offset. + // + // Note that the transforms are not applied to the clipping paths because clipping paths happen on + // the mask view, whose origin is always (0,0) to the _flutterView. + impeller::Vector3 origin = impeller::Vector3(clipView.frame.origin.x, clipView.frame.origin.y); + transformMatrix = DlMatrix::MakeTranslation(-origin) * transformMatrix; + + embeddedView.layer.transform = GetCATransform3DFromDlMatrix(transformMatrix); +} + +- (void)compositeView:(int64_t)viewId withParams:(const flutter::EmbeddedViewParams&)params { + // TODO(https://github.com/flutter/flutter/issues/109700) + CGRect frame = CGRectMake(0, 0, params.sizePoints().width(), params.sizePoints().height()); + FlutterTouchInterceptingView* touchInterceptor = self.platformViews[viewId].touch_interceptor; + touchInterceptor.layer.transform = CATransform3DIdentity; + touchInterceptor.frame = frame; + touchInterceptor.alpha = 1; + + const flutter::MutatorsStack& mutatorStack = params.mutatorsStack(); + UIView* clippingView = self.platformViews[viewId].root_view; + // The frame of the clipping view should be the final bounding rect. + // Because the translate matrix in the Mutator Stack also includes the offset, + // when we apply the transforms matrix in |applyMutators:embeddedView:boundingRect|, we need + // to remember to do a reverse translate. + const SkRect& rect = params.finalBoundingRect(); + CGFloat screenScale = [UIScreen mainScreen].scale; + clippingView.frame = CGRectMake(rect.x() / screenScale, rect.y() / screenScale, + rect.width() / screenScale, rect.height() / screenScale); + [self applyMutators:mutatorStack embeddedView:touchInterceptor boundingRect:rect]; +} + +- (flutter::DlCanvas*)compositeEmbeddedViewWithId:(int64_t)viewId { + FML_DCHECK(self.slices.find(viewId) != self.slices.end()); + return self.slices[viewId]->canvas(); +} + +- (void)reset { + // Reset will only be called from the raster thread or a merged raster/platform thread. + // _platformViews must only be modified on the platform thread, and any operations that + // read or modify platform views should occur there. + fml::TaskRunner::RunNowOrPostTask(self.platformTaskRunner, [self]() { + for (int64_t viewId : self.compositionOrder) { + [self.platformViews[viewId].root_view removeFromSuperview]; + } + self.platformViews.clear(); + self.previousCompositionOrder.clear(); + }); + + self.compositionOrder.clear(); + self.slices.clear(); + self.currentCompositionParams.clear(); + self.viewsToRecomposite.clear(); + self.layerPool->RecycleLayers(); + self.visitedPlatformViews.clear(); +} + +- (BOOL)submitFrame:(std::unique_ptr)background_frame + withIosContext:(const std::shared_ptr&)iosContext { + TRACE_EVENT0("flutter", "PlatformViewsController::SubmitFrame"); + + // No platform views to render; we're done. + if (self.flutterView == nil || (self.compositionOrder.empty() && !self.hadPlatformViews)) { + self.hadPlatformViews = NO; + return background_frame->Submit(); + } + self.hadPlatformViews = !self.compositionOrder.empty(); + + bool didEncode = true; + LayersMap platformViewLayers; + std::vector> surfaceFrames; + surfaceFrames.reserve(self.compositionOrder.size()); + std::unordered_map viewRects; + + for (int64_t viewId : self.compositionOrder) { + viewRects[viewId] = self.currentCompositionParams[viewId].finalBoundingRect(); + } + + std::unordered_map overlayLayers = + SliceViews(background_frame->Canvas(), self.compositionOrder, self.slices, viewRects); + + size_t requiredOverlayLayers = 0; + for (int64_t viewId : self.compositionOrder) { + std::unordered_map::const_iterator overlay = overlayLayers.find(viewId); + if (overlay == overlayLayers.end()) { + continue; + } + requiredOverlayLayers++; + } + + // If there are not sufficient overlay layers, we must construct them on the platform + // thread, at least until we've refactored iOS surface creation to use IOSurfaces + // instead of CALayers. + [self createMissingOverlays:requiredOverlayLayers withIosContext:iosContext]; + + int64_t overlayId = 0; + for (int64_t viewId : self.compositionOrder) { + std::unordered_map::const_iterator overlay = overlayLayers.find(viewId); + if (overlay == overlayLayers.end()) { + continue; + } + std::shared_ptr layer = self.nextLayerInPool; + if (!layer) { + continue; + } + + std::unique_ptr frame = layer->surface->AcquireFrame(self.frameSize); + // If frame is null, AcquireFrame already printed out an error message. + if (!frame) { + continue; + } + flutter::DlCanvas* overlayCanvas = frame->Canvas(); + int restoreCount = overlayCanvas->GetSaveCount(); + overlayCanvas->Save(); + overlayCanvas->ClipRect(flutter::ToDlRect(overlay->second)); + overlayCanvas->Clear(flutter::DlColor::kTransparent()); + self.slices[viewId]->render_into(overlayCanvas); + overlayCanvas->RestoreToCount(restoreCount); + + // This flutter view is never the last in a frame, since we always submit the + // underlay view last. + frame->set_submit_info({.frame_boundary = false, .present_with_transaction = true}); + layer->did_submit_last_frame = frame->Encode(); + + didEncode &= layer->did_submit_last_frame; + platformViewLayers[viewId] = LayerData{ + .rect = overlay->second, // + .view_id = viewId, // + .overlay_id = overlayId, // + .layer = layer // + }; + surfaceFrames.push_back(std::move(frame)); + overlayId++; + } + + auto previousSubmitInfo = background_frame->submit_info(); + background_frame->set_submit_info({ + .frame_damage = previousSubmitInfo.frame_damage, + .buffer_damage = previousSubmitInfo.buffer_damage, + .present_with_transaction = true, + }); + background_frame->Encode(); + surfaceFrames.push_back(std::move(background_frame)); + + // Mark all layers as available, so they can be used in the next frame. + std::vector> unusedLayers = + self.layerPool->RemoveUnusedLayers(); + self.layerPool->RecycleLayers(); + + auto task = [self, // + platformViewLayers = std::move(platformViewLayers), // + currentCompositionParams = self.currentCompositionParams, // + viewsToRecomposite = self.viewsToRecomposite, // + compositionOrder = self.compositionOrder, // + unusedLayers = std::move(unusedLayers), // + surfaceFrames = std::move(surfaceFrames) // + ]() mutable { + [self performSubmit:platformViewLayers + currentCompositionParams:currentCompositionParams + viewsToRecomposite:viewsToRecomposite + compositionOrder:compositionOrder + unusedLayers:unusedLayers + surfaceFrames:surfaceFrames]; + }; + + fml::TaskRunner::RunNowOrPostTask(self.platformTaskRunner, fml::MakeCopyable(std::move(task))); + + return didEncode; +} + +- (void)createMissingOverlays:(size_t)requiredOverlayLayers + withIosContext:(const std::shared_ptr&)iosContext { + TRACE_EVENT0("flutter", "PlatformViewsController::CreateMissingLayers"); + + if (requiredOverlayLayers <= self.layerPool->size()) { + return; + } + auto missingLayerCount = requiredOverlayLayers - self.layerPool->size(); + + // If the raster thread isn't merged, create layers on the platform thread and block until + // complete. + auto latch = std::make_shared(1u); + fml::TaskRunner::RunNowOrPostTask( + self.platformTaskRunner, [self, missingLayerCount, iosContext, latch]() { + for (auto i = 0u; i < missingLayerCount; i++) { + [self createLayerWithIosContext:iosContext + pixelFormat:((FlutterView*)self.flutterView).pixelFormat]; + } + latch->CountDown(); + }); + if (![[NSThread currentThread] isMainThread]) { + latch->Wait(); + } +} + +- (void)performSubmit:(const LayersMap&)platformViewLayers + currentCompositionParams: + (std::unordered_map&)currentCompositionParams + viewsToRecomposite:(const std::unordered_set&)viewsToRecomposite + compositionOrder:(const std::vector&)compositionOrder + unusedLayers: + (const std::vector>&)unusedLayers + surfaceFrames: + (const std::vector>&)surfaceFrames { + TRACE_EVENT0("flutter", "PlatformViewsController::PerformSubmit"); + FML_DCHECK([[NSThread currentThread] isMainThread]); + + [CATransaction begin]; + + // Configure Flutter overlay views. + for (const auto& [viewId, layerData] : platformViewLayers) { + layerData.layer->UpdateViewState(self.flutterView, // + layerData.rect, // + layerData.view_id, // + layerData.overlay_id // + ); + } + + // Dispose unused Flutter Views. + for (auto& view : [self computeViewsToDispose]) { + [view removeFromSuperview]; + } + + // Composite Platform Views. + for (int64_t viewId : viewsToRecomposite) { + [self compositeView:viewId withParams:currentCompositionParams[viewId]]; + } + + // Present callbacks. + for (const auto& frame : surfaceFrames) { + frame->Submit(); + } + + // If a layer was allocated in the previous frame, but it's not used in the current frame, + // then it can be removed from the scene. + [self removeUnusedLayers:unusedLayers withCompositionOrder:compositionOrder]; + + // Organize the layers by their z indexes. + [self bringLayersIntoView:platformViewLayers withCompositionOrder:compositionOrder]; + + [CATransaction commit]; +} + +- (void)bringLayersIntoView:(const LayersMap&)layerMap + withCompositionOrder:(const std::vector&)compositionOrder { + FML_DCHECK(self.flutterView); + UIView* flutterView = self.flutterView; + + self.previousCompositionOrder.clear(); + NSMutableArray* desiredPlatformSubviews = [NSMutableArray array]; + for (int64_t platformViewId : compositionOrder) { + self.previousCompositionOrder.push_back(platformViewId); + UIView* platformViewRoot = self.platformViews[platformViewId].root_view; + if (platformViewRoot != nil) { + [desiredPlatformSubviews addObject:platformViewRoot]; + } + + auto maybeLayerData = layerMap.find(platformViewId); + if (maybeLayerData != layerMap.end()) { + auto view = maybeLayerData->second.layer->overlay_view_wrapper; + if (view != nil) { + [desiredPlatformSubviews addObject:view]; + } + } + } + + NSSet* desiredPlatformSubviewsSet = [NSSet setWithArray:desiredPlatformSubviews]; + NSArray* existingPlatformSubviews = [flutterView.subviews + filteredArrayUsingPredicate:[NSPredicate + predicateWithBlock:^BOOL(id object, NSDictionary* bindings) { + return [desiredPlatformSubviewsSet containsObject:object]; + }]]; + + // Manipulate view hierarchy only if needed, to address a performance issue where + // this method is called even when view hierarchy stays the same. + // See: https://github.com/flutter/flutter/issues/121833 + // TODO(hellohuanlin): investigate if it is possible to skip unnecessary bringLayersIntoView. + if (![desiredPlatformSubviews isEqualToArray:existingPlatformSubviews]) { + for (UIView* subview in desiredPlatformSubviews) { + // `addSubview` will automatically reorder subview if it is already added. + [flutterView addSubview:subview]; + } + } +} + +- (std::shared_ptr)nextLayerInPool { + return self.layerPool->GetNextLayer(); +} + +- (void)createLayerWithIosContext:(const std::shared_ptr&)iosContext + pixelFormat:(MTLPixelFormat)pixelFormat { + self.layerPool->CreateLayer(iosContext, pixelFormat); +} + +- (void)removeUnusedLayers:(const std::vector>&)unusedLayers + withCompositionOrder:(const std::vector&)compositionOrder { + for (const std::shared_ptr& layer : unusedLayers) { + [layer->overlay_view_wrapper removeFromSuperview]; + } + + std::unordered_set compositionOrderSet; + for (int64_t viewId : compositionOrder) { + compositionOrderSet.insert(viewId); + } + // Remove unused platform views. + for (int64_t viewId : self.previousCompositionOrder) { + if (compositionOrderSet.find(viewId) == compositionOrderSet.end()) { + UIView* platformViewRoot = self.platformViews[viewId].root_view; + [platformViewRoot removeFromSuperview]; + } + } +} + +- (std::vector)computeViewsToDispose { + std::vector views; + if (self.viewsToDispose.empty()) { + return views; + } + + std::unordered_set viewsToComposite(self.compositionOrder.begin(), + self.compositionOrder.end()); + std::unordered_set viewsToDelayDispose; + for (int64_t viewId : self.viewsToDispose) { + if (viewsToComposite.count(viewId)) { + viewsToDelayDispose.insert(viewId); + continue; + } + UIView* rootView = self.platformViews[viewId].root_view; + views.push_back(rootView); + self.currentCompositionParams.erase(viewId); + self.viewsToRecomposite.erase(viewId); + self.platformViews.erase(viewId); + } + self.viewsToDispose = std::move(viewsToDelayDispose); + return views; +} + +- (void)resetFrameState { + self.slices.clear(); + self.compositionOrder.clear(); + self.visitedPlatformViews.clear(); +} + +- (void)pushVisitedPlatformViewId:(int64_t)viewId { + self.visitedPlatformViews.push_back(viewId); +} + +- (const flutter::EmbeddedViewParams&)compositionParamsForView:(int64_t)viewId { + return self.currentCompositionParams.find(viewId)->second; +} + +#pragma mark - Properties + +- (flutter::OverlayLayerPool*)layerPool { + return _layerPool.get(); +} + +- (std::unordered_map>&)slices { + return _slices; +} + +- (std::unordered_map*>&)factories { + return _factories; +} +- (std::unordered_map&) + gestureRecognizersBlockingPolicies { + return _gestureRecognizersBlockingPolicies; +} + +- (std::unordered_map&)platformViews { + return _platformViews; +} + +- (std::unordered_map&)currentCompositionParams { + return _currentCompositionParams; +} + +- (std::unordered_set&)viewsToDispose { + return _viewsToDispose; +} + +- (std::vector&)compositionOrder { + return _compositionOrder; +} + +- (std::vector&)visitedPlatformViews { + return _visitedPlatformViews; +} + +- (std::unordered_set&)viewsToRecomposite { + return _viewsToRecomposite; +} + +- (std::vector&)previousCompositionOrder { + return _previousCompositionOrder; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViewsTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViewsTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..4c781e60deeada8d84e5a0f13402b514ff21d04c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViewsTest.mm @@ -0,0 +1,4622 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterPlatformViews.h" + +#import +#import +#import +#import + +#include + +#include "flutter/display_list/effects/dl_image_filters.h" +#include "flutter/fml/synchronization/count_down_latch.h" +#include "flutter/fml/thread.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Test.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViewsController.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTouchInterceptingView_Test.h" +#include "flutter/shell/platform/darwin/ios/ios_context_noop.h" +#include "flutter/shell/platform/darwin/ios/platform_view_ios.h" + +FLUTTER_ASSERT_ARC + +@class FlutterPlatformViewsTestMockPlatformView; +__weak static UIView* gMockPlatformView = nil; +const float kFloatCompareEpsilon = 0.001; + +@interface FlutterPlatformViewsTestMockPlatformView : UIView +@end +@implementation FlutterPlatformViewsTestMockPlatformView + +- (instancetype)init { + self = [super init]; + if (self) { + gMockPlatformView = self; + } + return self; +} + +- (void)dealloc { + gMockPlatformView = nil; +} + +@end + +@interface FlutterPlatformViewsTestMockFlutterPlatformView : NSObject +@property(nonatomic, strong) UIView* view; +@property(nonatomic, assign) BOOL viewCreated; +@end + +@implementation FlutterPlatformViewsTestMockFlutterPlatformView + +- (instancetype)init { + if (self = [super init]) { + _view = [[FlutterPlatformViewsTestMockPlatformView alloc] init]; + _viewCreated = NO; + } + return self; +} + +- (UIView*)view { + [self checkViewCreatedOnce]; + return _view; +} + +- (void)checkViewCreatedOnce { + if (self.viewCreated) { + abort(); + } + self.viewCreated = YES; +} + +- (void)dealloc { + gMockPlatformView = nil; +} +@end + +@interface FlutterPlatformViewsTestMockFlutterPlatformFactory + : NSObject +@end + +@implementation FlutterPlatformViewsTestMockFlutterPlatformFactory +- (NSObject*)createWithFrame:(CGRect)frame + viewIdentifier:(int64_t)viewId + arguments:(id _Nullable)args { + return [[FlutterPlatformViewsTestMockFlutterPlatformView alloc] init]; +} + +@end + +@interface FlutterPlatformViewsTestMockWebView : NSObject +@property(nonatomic, strong) UIView* view; +@property(nonatomic, assign) BOOL viewCreated; +@end + +@implementation FlutterPlatformViewsTestMockWebView +- (instancetype)init { + if (self = [super init]) { + _view = [[WKWebView alloc] init]; + gMockPlatformView = _view; + _viewCreated = NO; + } + return self; +} + +- (UIView*)view { + [self checkViewCreatedOnce]; + return _view; +} + +- (void)checkViewCreatedOnce { + if (self.viewCreated) { + abort(); + } + self.viewCreated = YES; +} + +- (void)dealloc { + gMockPlatformView = nil; +} +@end + +@interface FlutterPlatformViewsTestMockWebViewFactory : NSObject +@end + +@implementation FlutterPlatformViewsTestMockWebViewFactory +- (NSObject*)createWithFrame:(CGRect)frame + viewIdentifier:(int64_t)viewId + arguments:(id _Nullable)args { + return [[FlutterPlatformViewsTestMockWebView alloc] init]; +} +@end + +@interface FlutterPlatformViewsTestNilFlutterPlatformFactory : NSObject +@end + +@implementation FlutterPlatformViewsTestNilFlutterPlatformFactory +- (NSObject*)createWithFrame:(CGRect)frame + viewIdentifier:(int64_t)viewId + arguments:(id _Nullable)args { + return nil; +} + +@end + +@interface FlutterPlatformViewsTestMockWrapperWebView : NSObject +@property(nonatomic, strong) UIView* view; +@property(nonatomic, assign) BOOL viewCreated; +@end + +@implementation FlutterPlatformViewsTestMockWrapperWebView +- (instancetype)init { + if (self = [super init]) { + _view = [[UIView alloc] init]; + [_view addSubview:[[WKWebView alloc] init]]; + gMockPlatformView = _view; + _viewCreated = NO; + } + return self; +} + +- (UIView*)view { + [self checkViewCreatedOnce]; + return _view; +} + +- (void)checkViewCreatedOnce { + if (self.viewCreated) { + abort(); + } + self.viewCreated = YES; +} + +- (void)dealloc { + gMockPlatformView = nil; +} +@end + +@interface FlutterPlatformViewsTestMockWrapperWebViewFactory : NSObject +@end + +@implementation FlutterPlatformViewsTestMockWrapperWebViewFactory +- (NSObject*)createWithFrame:(CGRect)frame + viewIdentifier:(int64_t)viewId + arguments:(id _Nullable)args { + return [[FlutterPlatformViewsTestMockWrapperWebView alloc] init]; +} +@end + +@interface FlutterPlatformViewsTestMockNestedWrapperWebView : NSObject +@property(nonatomic, strong) UIView* view; +@property(nonatomic, assign) BOOL viewCreated; +@end + +@implementation FlutterPlatformViewsTestMockNestedWrapperWebView +- (instancetype)init { + if (self = [super init]) { + _view = [[UIView alloc] init]; + UIView* childView = [[UIView alloc] init]; + [_view addSubview:childView]; + [childView addSubview:[[WKWebView alloc] init]]; + gMockPlatformView = _view; + _viewCreated = NO; + } + return self; +} + +- (UIView*)view { + [self checkViewCreatedOnce]; + return _view; +} + +- (void)checkViewCreatedOnce { + if (self.viewCreated) { + abort(); + } + self.viewCreated = YES; +} +@end + +@interface FlutterPlatformViewsTestMockNestedWrapperWebViewFactory + : NSObject +@end + +@implementation FlutterPlatformViewsTestMockNestedWrapperWebViewFactory +- (NSObject*)createWithFrame:(CGRect)frame + viewIdentifier:(int64_t)viewId + arguments:(id _Nullable)args { + return [[FlutterPlatformViewsTestMockNestedWrapperWebView alloc] init]; +} +@end + +namespace flutter { +namespace { +class FlutterPlatformViewsTestMockPlatformViewDelegate : public PlatformView::Delegate { + public: + void OnPlatformViewCreated(std::unique_ptr surface) override {} + void OnPlatformViewDestroyed() override {} + void OnPlatformViewScheduleFrame() override {} + void OnPlatformViewAddView(int64_t view_id, + const ViewportMetrics& viewport_metrics, + AddViewCallback callback) override {} + void OnPlatformViewRemoveView(int64_t view_id, RemoveViewCallback callback) override {} + void OnPlatformViewSendViewFocusEvent(const ViewFocusEvent& event) override {}; + void OnPlatformViewSetNextFrameCallback(const fml::closure& closure) override {} + void OnPlatformViewSetViewportMetrics(int64_t view_id, const ViewportMetrics& metrics) override {} + const flutter::Settings& OnPlatformViewGetSettings() const override { return settings_; } + void OnPlatformViewDispatchPlatformMessage(std::unique_ptr message) override {} + void OnPlatformViewDispatchPointerDataPacket(std::unique_ptr packet) override { + } + void OnPlatformViewDispatchSemanticsAction(int64_t view_id, + int32_t node_id, + SemanticsAction action, + fml::MallocMapping args) override {} + void OnPlatformViewSetSemanticsEnabled(bool enabled) override {} + void OnPlatformViewSetAccessibilityFeatures(int32_t flags) override {} + void OnPlatformViewRegisterTexture(std::shared_ptr texture) override {} + void OnPlatformViewUnregisterTexture(int64_t texture_id) override {} + void OnPlatformViewMarkTextureFrameAvailable(int64_t texture_id) override {} + + void LoadDartDeferredLibrary(intptr_t loading_unit_id, + std::unique_ptr snapshot_data, + std::unique_ptr snapshot_instructions) override { + } + void LoadDartDeferredLibraryError(intptr_t loading_unit_id, + const std::string error_message, + bool transient) override {} + void UpdateAssetResolverByType(std::unique_ptr updated_asset_resolver, + flutter::AssetResolver::AssetResolverType type) override {} + + flutter::Settings settings_; +}; + +BOOL BlurRadiusEqualToBlurRadius(CGFloat radius1, CGFloat radius2) { + const CGFloat epsilon = 0.01; + return std::abs(radius1 - radius2) < epsilon; +} + +} // namespace +} // namespace flutter + +@interface FlutterPlatformViewsTest : XCTestCase +@end + +@implementation FlutterPlatformViewsTest + +namespace { +fml::RefPtr GetDefaultTaskRunner() { + fml::MessageLoop::EnsureInitializedForCurrentThread(); + return fml::MessageLoop::GetCurrent().GetTaskRunner(); +} +} // namespace + +- (void)testFlutterViewOnlyCreateOnceInOneFrame { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; + flutterPlatformViewsController.flutterView = flutterView; + // Create embedded view params + flutter::MutatorsStack stack; + // Layer tree always pushes a screen scale factor to the stack + flutter::DlScalar screenScale = [UIScreen mainScreen].scale; + flutter::DlMatrix screenScaleMatrix = flutter::DlMatrix::MakeScale({screenScale, screenScale, 1}); + stack.PushTransform(screenScaleMatrix); + // Push a translate matrix + flutter::DlMatrix translateMatrix = flutter::DlMatrix::MakeTranslation({100, 100}); + stack.PushTransform(translateMatrix); + flutter::DlMatrix finalMatrix = screenScaleMatrix * translateMatrix; + + auto embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(finalMatrix), SkSize::Make(300, 300), stack); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + + XCTAssertNotNil(gMockPlatformView); + + [flutterPlatformViewsController reset]; +} + +- (void)testCanCreatePlatformViewWithoutFlutterView { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); +} + +- (void)testChildClippingViewHitTests { + ChildClippingView* childClippingView = + [[ChildClippingView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; + UIView* childView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)]; + [childClippingView addSubview:childView]; + + XCTAssertFalse([childClippingView pointInside:CGPointMake(50, 50) withEvent:nil]); + XCTAssertFalse([childClippingView pointInside:CGPointMake(99, 100) withEvent:nil]); + XCTAssertFalse([childClippingView pointInside:CGPointMake(100, 99) withEvent:nil]); + XCTAssertFalse([childClippingView pointInside:CGPointMake(201, 200) withEvent:nil]); + XCTAssertFalse([childClippingView pointInside:CGPointMake(200, 201) withEvent:nil]); + XCTAssertFalse([childClippingView pointInside:CGPointMake(99, 200) withEvent:nil]); + XCTAssertFalse([childClippingView pointInside:CGPointMake(200, 299) withEvent:nil]); + + XCTAssertTrue([childClippingView pointInside:CGPointMake(150, 150) withEvent:nil]); + XCTAssertTrue([childClippingView pointInside:CGPointMake(100, 100) withEvent:nil]); + XCTAssertTrue([childClippingView pointInside:CGPointMake(199, 100) withEvent:nil]); + XCTAssertTrue([childClippingView pointInside:CGPointMake(100, 199) withEvent:nil]); + XCTAssertTrue([childClippingView pointInside:CGPointMake(199, 199) withEvent:nil]); +} + +- (void)testReleasesBackdropFilterSubviewsOnChildClippingViewDealloc { + __weak NSMutableArray* weakBackdropFilterSubviews = nil; + __weak UIVisualEffectView* weakVisualEffectView1 = nil; + __weak UIVisualEffectView* weakVisualEffectView2 = nil; + + @autoreleasepool { + ChildClippingView* clippingView = [[ChildClippingView alloc] initWithFrame:CGRectZero]; + UIVisualEffectView* visualEffectView1 = [[UIVisualEffectView alloc] + initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]]; + weakVisualEffectView1 = visualEffectView1; + PlatformViewFilter* platformViewFilter1 = + [[PlatformViewFilter alloc] initWithFrame:CGRectMake(0, 0, 10, 10) + blurRadius:5 + visualEffectView:visualEffectView1]; + + [clippingView applyBlurBackdropFilters:@[ platformViewFilter1 ]]; + + // Replace the blur filter to validate the original and new UIVisualEffectView are released. + UIVisualEffectView* visualEffectView2 = [[UIVisualEffectView alloc] + initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]]; + weakVisualEffectView2 = visualEffectView2; + PlatformViewFilter* platformViewFilter2 = + [[PlatformViewFilter alloc] initWithFrame:CGRectMake(0, 0, 10, 10) + blurRadius:5 + visualEffectView:visualEffectView2]; + [clippingView applyBlurBackdropFilters:@[ platformViewFilter2 ]]; + + weakBackdropFilterSubviews = clippingView.backdropFilterSubviews; + XCTAssertNotNil(weakBackdropFilterSubviews); + clippingView = nil; + } + XCTAssertNil(weakBackdropFilterSubviews); + XCTAssertNil(weakVisualEffectView1); + XCTAssertNil(weakVisualEffectView2); +} + +- (void)testApplyBackdropFilter { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; + flutterPlatformViewsController.flutterView = flutterView; + // Create embedded view params + flutter::MutatorsStack stack; + // Layer tree always pushes a screen scale factor to the stack + flutter::DlScalar screenScale = [UIScreen mainScreen].scale; + flutter::DlMatrix screenScaleMatrix = flutter::DlMatrix::MakeScale({screenScale, screenScale, 1}); + stack.PushTransform(screenScaleMatrix); + // Push a backdrop filter + auto filter = flutter::DlBlurImageFilter::Make(5, 2, flutter::DlTileMode::kClamp); + stack.PushBackdropFilter(filter, + flutter::DlRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); + + auto embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:[ChildClippingView class]]); + ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; + [flutterView addSubview:childClippingView]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + // childClippingView has visual effect view with the correct configurations. + NSUInteger numberOfExpectedVisualEffectView = 0; + for (UIView* subview in childClippingView.subviews) { + if (![subview isKindOfClass:[UIVisualEffectView class]]) { + continue; + } + XCTAssertLessThan(numberOfExpectedVisualEffectView, 1u); + if ([self validateOneVisualEffectView:subview + expectedFrame:CGRectMake(0, 0, 10, 10) + inputRadius:5]) { + numberOfExpectedVisualEffectView++; + } + } + XCTAssertEqual(numberOfExpectedVisualEffectView, 1u); +} + +- (void)testApplyBackdropFilterWithCorrectFrame { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; + flutterPlatformViewsController.flutterView = flutterView; + // Create embedded view params + flutter::MutatorsStack stack; + // Layer tree always pushes a screen scale factor to the stack + flutter::DlScalar screenScale = [UIScreen mainScreen].scale; + flutter::DlMatrix screenScaleMatrix = flutter::DlMatrix::MakeScale({screenScale, screenScale, 1}); + stack.PushTransform(screenScaleMatrix); + // Push a backdrop filter + auto filter = flutter::DlBlurImageFilter::Make(5, 2, flutter::DlTileMode::kClamp); + stack.PushBackdropFilter(filter, + flutter::DlRect::MakeXYWH(0, 0, screenScale * 8, screenScale * 8)); + + auto embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(5, 10), stack); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:[ChildClippingView class]]); + ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; + [flutterView addSubview:childClippingView]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + // childClippingView has visual effect view with the correct configurations. + NSUInteger numberOfExpectedVisualEffectView = 0; + for (UIView* subview in childClippingView.subviews) { + if (![subview isKindOfClass:[UIVisualEffectView class]]) { + continue; + } + XCTAssertLessThan(numberOfExpectedVisualEffectView, 1u); + if ([self validateOneVisualEffectView:subview + expectedFrame:CGRectMake(0, 0, 5, 8) + inputRadius:5]) { + numberOfExpectedVisualEffectView++; + } + } + XCTAssertEqual(numberOfExpectedVisualEffectView, 1u); +} + +- (void)testApplyMultipleBackdropFilters { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; + flutterPlatformViewsController.flutterView = flutterView; + // Create embedded view params + flutter::MutatorsStack stack; + // Layer tree always pushes a screen scale factor to the stack + flutter::DlScalar screenScale = [UIScreen mainScreen].scale; + flutter::DlMatrix screenScaleMatrix = flutter::DlMatrix::MakeScale({screenScale, screenScale, 1}); + stack.PushTransform(screenScaleMatrix); + // Push backdrop filters + for (int i = 0; i < 50; i++) { + auto filter = flutter::DlBlurImageFilter::Make(i, 2, flutter::DlTileMode::kClamp); + stack.PushBackdropFilter(filter, + flutter::DlRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); + } + + auto embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(20, 20), stack); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:ChildClippingView.class]); + ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; + [flutterView addSubview:childClippingView]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + NSUInteger numberOfExpectedVisualEffectView = 0; + for (UIView* subview in childClippingView.subviews) { + if (![subview isKindOfClass:[UIVisualEffectView class]]) { + continue; + } + XCTAssertLessThan(numberOfExpectedVisualEffectView, 50u); + if ([self validateOneVisualEffectView:subview + expectedFrame:CGRectMake(0, 0, 10, 10) + inputRadius:(CGFloat)numberOfExpectedVisualEffectView]) { + numberOfExpectedVisualEffectView++; + } + } + XCTAssertEqual(numberOfExpectedVisualEffectView, (NSUInteger)numberOfExpectedVisualEffectView); +} + +- (void)testAddBackdropFilters { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; + flutterPlatformViewsController.flutterView = flutterView; + // Create embedded view params + flutter::MutatorsStack stack; + // Layer tree always pushes a screen scale factor to the stack + flutter::DlScalar screenScale = [UIScreen mainScreen].scale; + flutter::DlMatrix screenScaleMatrix = flutter::DlMatrix::MakeScale({screenScale, screenScale, 1}); + stack.PushTransform(screenScaleMatrix); + // Push a backdrop filter + auto filter = flutter::DlBlurImageFilter::Make(5, 2, flutter::DlTileMode::kClamp); + stack.PushBackdropFilter(filter, + flutter::DlRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); + + auto embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:[ChildClippingView class]]); + ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; + [flutterView addSubview:childClippingView]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + NSMutableArray* originalVisualEffectViews = [[NSMutableArray alloc] init]; + for (UIView* subview in childClippingView.subviews) { + if (![subview isKindOfClass:[UIVisualEffectView class]]) { + continue; + } + XCTAssertLessThan(originalVisualEffectViews.count, 1u); + if ([self validateOneVisualEffectView:subview + expectedFrame:CGRectMake(0, 0, 10, 10) + inputRadius:(CGFloat)5]) { + [originalVisualEffectViews addObject:subview]; + } + } + XCTAssertEqual(originalVisualEffectViews.count, 1u); + + // + // Simulate adding 1 backdrop filter (create a new mutators stack) + // Create embedded view params + flutter::MutatorsStack stack2; + // Layer tree always pushes a screen scale factor to the stack + stack2.PushTransform(screenScaleMatrix); + // Push backdrop filters + for (int i = 0; i < 2; i++) { + stack2.PushBackdropFilter(filter, + flutter::DlRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); + } + + embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack2); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + NSMutableArray* newVisualEffectViews = [[NSMutableArray alloc] init]; + for (UIView* subview in childClippingView.subviews) { + if (![subview isKindOfClass:[UIVisualEffectView class]]) { + continue; + } + XCTAssertLessThan(newVisualEffectViews.count, 2u); + + if ([self validateOneVisualEffectView:subview + expectedFrame:CGRectMake(0, 0, 10, 10) + inputRadius:(CGFloat)5]) { + [newVisualEffectViews addObject:subview]; + } + } + XCTAssertEqual(newVisualEffectViews.count, 2u); + for (NSUInteger i = 0; i < originalVisualEffectViews.count; i++) { + UIView* originalView = originalVisualEffectViews[i]; + UIView* newView = newVisualEffectViews[i]; + // Compare reference. + XCTAssertEqual(originalView, newView); + id mockOrignalView = OCMPartialMock(originalView); + OCMReject([mockOrignalView removeFromSuperview]); + [mockOrignalView stopMocking]; + } +} + +- (void)testRemoveBackdropFilters { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; + flutterPlatformViewsController.flutterView = flutterView; + // Create embedded view params + flutter::MutatorsStack stack; + // Layer tree always pushes a screen scale factor to the stack + flutter::DlScalar screenScale = [UIScreen mainScreen].scale; + flutter::DlMatrix screenScaleMatrix = flutter::DlMatrix::MakeScale({screenScale, screenScale, 1}); + stack.PushTransform(screenScaleMatrix); + // Push backdrop filters + auto filter = flutter::DlBlurImageFilter::Make(5, 2, flutter::DlTileMode::kClamp); + for (int i = 0; i < 5; i++) { + stack.PushBackdropFilter(filter, + flutter::DlRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); + } + + auto embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:ChildClippingView.class]); + ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; + [flutterView addSubview:childClippingView]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + NSMutableArray* originalVisualEffectViews = [[NSMutableArray alloc] init]; + for (UIView* subview in childClippingView.subviews) { + if (![subview isKindOfClass:[UIVisualEffectView class]]) { + continue; + } + XCTAssertLessThan(originalVisualEffectViews.count, 5u); + if ([self validateOneVisualEffectView:subview + expectedFrame:CGRectMake(0, 0, 10, 10) + inputRadius:(CGFloat)5]) { + [originalVisualEffectViews addObject:subview]; + } + } + + // Simulate removing 1 backdrop filter (create a new mutators stack) + // Create embedded view params + flutter::MutatorsStack stack2; + // Layer tree always pushes a screen scale factor to the stack + stack2.PushTransform(screenScaleMatrix); + // Push backdrop filters + for (int i = 0; i < 4; i++) { + stack2.PushBackdropFilter(filter, + flutter::DlRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); + } + + embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack2); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + NSMutableArray* newVisualEffectViews = [[NSMutableArray alloc] init]; + for (UIView* subview in childClippingView.subviews) { + if (![subview isKindOfClass:[UIVisualEffectView class]]) { + continue; + } + XCTAssertLessThan(newVisualEffectViews.count, 4u); + if ([self validateOneVisualEffectView:subview + expectedFrame:CGRectMake(0, 0, 10, 10) + inputRadius:(CGFloat)5]) { + [newVisualEffectViews addObject:subview]; + } + } + XCTAssertEqual(newVisualEffectViews.count, 4u); + + for (NSUInteger i = 0; i < newVisualEffectViews.count; i++) { + UIView* newView = newVisualEffectViews[i]; + id mockNewView = OCMPartialMock(newView); + UIView* originalView = originalVisualEffectViews[i]; + // Compare reference. + XCTAssertEqual(originalView, newView); + OCMReject([mockNewView removeFromSuperview]); + [mockNewView stopMocking]; + } + + // Simulate removing all backdrop filters (replace the mutators stack) + // Update embedded view params, delete except screenScaleMatrix + for (int i = 0; i < 5; i++) { + stack2.Pop(); + } + // No backdrop filters in the stack, so no nothing to push + + embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack2); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + NSUInteger numberOfExpectedVisualEffectView = 0u; + for (UIView* subview in childClippingView.subviews) { + if ([subview isKindOfClass:[UIVisualEffectView class]]) { + numberOfExpectedVisualEffectView++; + } + } + XCTAssertEqual(numberOfExpectedVisualEffectView, 0u); +} + +- (void)testEditBackdropFilters { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; + flutterPlatformViewsController.flutterView = flutterView; + // Create embedded view params + flutter::MutatorsStack stack; + // Layer tree always pushes a screen scale factor to the stack + flutter::DlScalar screenScale = [UIScreen mainScreen].scale; + flutter::DlMatrix screenScaleMatrix = flutter::DlMatrix::MakeScale({screenScale, screenScale, 1}); + stack.PushTransform(screenScaleMatrix); + // Push backdrop filters + auto filter = flutter::DlBlurImageFilter::Make(5, 2, flutter::DlTileMode::kClamp); + for (int i = 0; i < 5; i++) { + stack.PushBackdropFilter(filter, + flutter::DlRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); + } + + auto embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:ChildClippingView.class]); + ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; + [flutterView addSubview:childClippingView]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + NSMutableArray* originalVisualEffectViews = [[NSMutableArray alloc] init]; + for (UIView* subview in childClippingView.subviews) { + if (![subview isKindOfClass:[UIVisualEffectView class]]) { + continue; + } + XCTAssertLessThan(originalVisualEffectViews.count, 5u); + if ([self validateOneVisualEffectView:subview + expectedFrame:CGRectMake(0, 0, 10, 10) + inputRadius:(CGFloat)5]) { + [originalVisualEffectViews addObject:subview]; + } + } + + // Simulate editing 1 backdrop filter in the middle of the stack (create a new mutators stack) + // Create embedded view params + flutter::MutatorsStack stack2; + // Layer tree always pushes a screen scale factor to the stack + stack2.PushTransform(screenScaleMatrix); + // Push backdrop filters + for (int i = 0; i < 5; i++) { + if (i == 3) { + auto filter2 = flutter::DlBlurImageFilter::Make(2, 5, flutter::DlTileMode::kClamp); + + stack2.PushBackdropFilter( + filter2, flutter::DlRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); + continue; + } + + stack2.PushBackdropFilter(filter, + flutter::DlRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); + } + + embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack2); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + NSMutableArray* newVisualEffectViews = [[NSMutableArray alloc] init]; + for (UIView* subview in childClippingView.subviews) { + if (![subview isKindOfClass:[UIVisualEffectView class]]) { + continue; + } + XCTAssertLessThan(newVisualEffectViews.count, 5u); + CGFloat expectInputRadius = 5; + if (newVisualEffectViews.count == 3) { + expectInputRadius = 2; + } + if ([self validateOneVisualEffectView:subview + expectedFrame:CGRectMake(0, 0, 10, 10) + inputRadius:expectInputRadius]) { + [newVisualEffectViews addObject:subview]; + } + } + XCTAssertEqual(newVisualEffectViews.count, 5u); + for (NSUInteger i = 0; i < newVisualEffectViews.count; i++) { + UIView* newView = newVisualEffectViews[i]; + id mockNewView = OCMPartialMock(newView); + UIView* originalView = originalVisualEffectViews[i]; + // Compare reference. + XCTAssertEqual(originalView, newView); + OCMReject([mockNewView removeFromSuperview]); + [mockNewView stopMocking]; + } + [newVisualEffectViews removeAllObjects]; + + // Simulate editing 1 backdrop filter in the beginning of the stack (replace the mutators stack) + // Update embedded view params, delete except screenScaleMatrix + for (int i = 0; i < 5; i++) { + stack2.Pop(); + } + // Push backdrop filters + for (int i = 0; i < 5; i++) { + if (i == 0) { + auto filter2 = flutter::DlBlurImageFilter::Make(2, 5, flutter::DlTileMode::kClamp); + stack2.PushBackdropFilter( + filter2, flutter::DlRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); + continue; + } + + stack2.PushBackdropFilter(filter, + flutter::DlRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); + } + + embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack2); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + for (UIView* subview in childClippingView.subviews) { + if (![subview isKindOfClass:[UIVisualEffectView class]]) { + continue; + } + XCTAssertLessThan(newVisualEffectViews.count, 5u); + CGFloat expectInputRadius = 5; + if (newVisualEffectViews.count == 0) { + expectInputRadius = 2; + } + if ([self validateOneVisualEffectView:subview + expectedFrame:CGRectMake(0, 0, 10, 10) + inputRadius:expectInputRadius]) { + [newVisualEffectViews addObject:subview]; + } + } + for (NSUInteger i = 0; i < newVisualEffectViews.count; i++) { + UIView* newView = newVisualEffectViews[i]; + id mockNewView = OCMPartialMock(newView); + UIView* originalView = originalVisualEffectViews[i]; + // Compare reference. + XCTAssertEqual(originalView, newView); + OCMReject([mockNewView removeFromSuperview]); + [mockNewView stopMocking]; + } + [newVisualEffectViews removeAllObjects]; + + // Simulate editing 1 backdrop filter in the end of the stack (replace the mutators stack) + // Update embedded view params, delete except screenScaleMatrix + for (int i = 0; i < 5; i++) { + stack2.Pop(); + } + // Push backdrop filters + for (int i = 0; i < 5; i++) { + if (i == 4) { + auto filter2 = flutter::DlBlurImageFilter::Make(2, 5, flutter::DlTileMode::kClamp); + stack2.PushBackdropFilter( + filter2, flutter::DlRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); + continue; + } + + stack2.PushBackdropFilter(filter, + flutter::DlRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); + } + + embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack2); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + for (UIView* subview in childClippingView.subviews) { + if (![subview isKindOfClass:[UIVisualEffectView class]]) { + continue; + } + XCTAssertLessThan(newVisualEffectViews.count, 5u); + CGFloat expectInputRadius = 5; + if (newVisualEffectViews.count == 4) { + expectInputRadius = 2; + } + if ([self validateOneVisualEffectView:subview + expectedFrame:CGRectMake(0, 0, 10, 10) + inputRadius:expectInputRadius]) { + [newVisualEffectViews addObject:subview]; + } + } + XCTAssertEqual(newVisualEffectViews.count, 5u); + + for (NSUInteger i = 0; i < newVisualEffectViews.count; i++) { + UIView* newView = newVisualEffectViews[i]; + id mockNewView = OCMPartialMock(newView); + UIView* originalView = originalVisualEffectViews[i]; + // Compare reference. + XCTAssertEqual(originalView, newView); + OCMReject([mockNewView removeFromSuperview]); + [mockNewView stopMocking]; + } + [newVisualEffectViews removeAllObjects]; + + // Simulate editing all backdrop filters in the stack (replace the mutators stack) + // Update embedded view params, delete except screenScaleMatrix + for (int i = 0; i < 5; i++) { + stack2.Pop(); + } + // Push backdrop filters + for (int i = 0; i < 5; i++) { + auto filter2 = flutter::DlBlurImageFilter::Make(i, 2, flutter::DlTileMode::kClamp); + + stack2.PushBackdropFilter(filter2, + flutter::DlRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); + } + + embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack2); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + for (UIView* subview in childClippingView.subviews) { + if (![subview isKindOfClass:[UIVisualEffectView class]]) { + continue; + } + XCTAssertLessThan(newVisualEffectViews.count, 5u); + if ([self validateOneVisualEffectView:subview + expectedFrame:CGRectMake(0, 0, 10, 10) + inputRadius:(CGFloat)newVisualEffectViews.count]) { + [newVisualEffectViews addObject:subview]; + } + } + XCTAssertEqual(newVisualEffectViews.count, 5u); + + for (NSUInteger i = 0; i < newVisualEffectViews.count; i++) { + UIView* newView = newVisualEffectViews[i]; + id mockNewView = OCMPartialMock(newView); + UIView* originalView = originalVisualEffectViews[i]; + // Compare reference. + XCTAssertEqual(originalView, newView); + OCMReject([mockNewView removeFromSuperview]); + [mockNewView stopMocking]; + } + [newVisualEffectViews removeAllObjects]; +} + +- (void)testApplyBackdropFilterNotDlBlurImageFilter { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; + flutterPlatformViewsController.flutterView = flutterView; + // Create embedded view params + flutter::MutatorsStack stack; + // Layer tree always pushes a screen scale factor to the stack + flutter::DlScalar screenScale = [UIScreen mainScreen].scale; + flutter::DlMatrix screenScaleMatrix = flutter::DlMatrix::MakeScale({screenScale, screenScale, 1}); + stack.PushTransform(screenScaleMatrix); + // Push a dilate backdrop filter + auto dilateFilter = flutter::DlDilateImageFilter::Make(5, 2); + stack.PushBackdropFilter(dilateFilter, flutter::DlRect()); + + auto embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:[ChildClippingView class]]); + ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; + + [flutterView addSubview:childClippingView]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + NSUInteger numberOfExpectedVisualEffectView = 0; + for (UIView* subview in childClippingView.subviews) { + if ([subview isKindOfClass:[UIVisualEffectView class]]) { + numberOfExpectedVisualEffectView++; + } + } + XCTAssertEqual(numberOfExpectedVisualEffectView, 0u); + + // Simulate adding a non-DlBlurImageFilter in the middle of the stack (create a new mutators + // stack) Create embedded view params + flutter::MutatorsStack stack2; + // Layer tree always pushes a screen scale factor to the stack + stack2.PushTransform(screenScaleMatrix); + // Push backdrop filters and dilate filter + auto blurFilter = flutter::DlBlurImageFilter::Make(5, 2, flutter::DlTileMode::kClamp); + + for (int i = 0; i < 5; i++) { + if (i == 2) { + stack2.PushBackdropFilter( + dilateFilter, flutter::DlRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); + continue; + } + + stack2.PushBackdropFilter(blurFilter, + flutter::DlRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); + } + + embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack2); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + numberOfExpectedVisualEffectView = 0; + for (UIView* subview in childClippingView.subviews) { + if (![subview isKindOfClass:[UIVisualEffectView class]]) { + continue; + } + XCTAssertLessThan(numberOfExpectedVisualEffectView, 4u); + if ([self validateOneVisualEffectView:subview + expectedFrame:CGRectMake(0, 0, 10, 10) + inputRadius:(CGFloat)5]) { + numberOfExpectedVisualEffectView++; + } + } + XCTAssertEqual(numberOfExpectedVisualEffectView, 4u); + + // Simulate adding a non-DlBlurImageFilter to the beginning of the stack (replace the mutators + // stack) Update embedded view params, delete except screenScaleMatrix + for (int i = 0; i < 5; i++) { + stack2.Pop(); + } + // Push backdrop filters and dilate filter + for (int i = 0; i < 5; i++) { + if (i == 0) { + stack2.PushBackdropFilter( + dilateFilter, flutter::DlRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); + continue; + } + + stack2.PushBackdropFilter(blurFilter, + flutter::DlRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); + } + + embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack2); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + numberOfExpectedVisualEffectView = 0; + for (UIView* subview in childClippingView.subviews) { + if (![subview isKindOfClass:[UIVisualEffectView class]]) { + continue; + } + XCTAssertLessThan(numberOfExpectedVisualEffectView, 4u); + if ([self validateOneVisualEffectView:subview + expectedFrame:CGRectMake(0, 0, 10, 10) + inputRadius:(CGFloat)5]) { + numberOfExpectedVisualEffectView++; + } + } + XCTAssertEqual(numberOfExpectedVisualEffectView, 4u); + + // Simulate adding a non-DlBlurImageFilter to the end of the stack (replace the mutators stack) + // Update embedded view params, delete except screenScaleMatrix + for (int i = 0; i < 5; i++) { + stack2.Pop(); + } + // Push backdrop filters and dilate filter + for (int i = 0; i < 5; i++) { + if (i == 4) { + stack2.PushBackdropFilter( + dilateFilter, flutter::DlRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); + continue; + } + + stack2.PushBackdropFilter(blurFilter, + flutter::DlRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); + } + + embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack2); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + numberOfExpectedVisualEffectView = 0; + for (UIView* subview in childClippingView.subviews) { + if (![subview isKindOfClass:[UIVisualEffectView class]]) { + continue; + } + XCTAssertLessThan(numberOfExpectedVisualEffectView, 4u); + if ([self validateOneVisualEffectView:subview + expectedFrame:CGRectMake(0, 0, 10, 10) + inputRadius:(CGFloat)5]) { + numberOfExpectedVisualEffectView++; + } + } + XCTAssertEqual(numberOfExpectedVisualEffectView, 4u); + + // Simulate adding only non-DlBlurImageFilter to the stack (replace the mutators stack) + // Update embedded view params, delete except screenScaleMatrix + for (int i = 0; i < 5; i++) { + stack2.Pop(); + } + // Push dilate filters + for (int i = 0; i < 5; i++) { + stack2.PushBackdropFilter(dilateFilter, + flutter::DlRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)); + } + + embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack2); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + numberOfExpectedVisualEffectView = 0; + for (UIView* subview in childClippingView.subviews) { + if ([subview isKindOfClass:[UIVisualEffectView class]]) { + numberOfExpectedVisualEffectView++; + } + } + XCTAssertEqual(numberOfExpectedVisualEffectView, 0u); +} + +- (void)testApplyBackdropFilterCorrectAPI { + [PlatformViewFilter resetPreparation]; + // The gaussianBlur filter is extracted from UIVisualEffectView. + // Each test requires a new PlatformViewFilter + // Valid UIVisualEffectView API + UIVisualEffectView* visualEffectView = [[UIVisualEffectView alloc] + initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]]; + PlatformViewFilter* platformViewFilter = + [[PlatformViewFilter alloc] initWithFrame:CGRectMake(0, 0, 10, 10) + blurRadius:5 + visualEffectView:visualEffectView]; + XCTAssertNotNil(platformViewFilter); +} + +- (void)testApplyBackdropFilterAPIChangedInvalidUIVisualEffectView { + [PlatformViewFilter resetPreparation]; + UIVisualEffectView* visualEffectView = [[UIVisualEffectView alloc] init]; + PlatformViewFilter* platformViewFilter = + [[PlatformViewFilter alloc] initWithFrame:CGRectMake(0, 0, 10, 10) + blurRadius:5 + visualEffectView:visualEffectView]; + XCTAssertNil(platformViewFilter); +} + +- (void)testApplyBackdropFilterAPIChangedNoGaussianBlurFilter { + [PlatformViewFilter resetPreparation]; + UIVisualEffectView* editedUIVisualEffectView = [[UIVisualEffectView alloc] + initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]]; + NSArray* subviews = editedUIVisualEffectView.subviews; + for (UIView* view in subviews) { + if ([NSStringFromClass([view class]) hasSuffix:@"BackdropView"]) { + for (CIFilter* filter in view.layer.filters) { + if ([[filter valueForKey:@"name"] isEqual:@"gaussianBlur"]) { + [filter setValue:@"notGaussianBlur" forKey:@"name"]; + break; + } + } + break; + } + } + PlatformViewFilter* platformViewFilter = + [[PlatformViewFilter alloc] initWithFrame:CGRectMake(0, 0, 10, 10) + blurRadius:5 + visualEffectView:editedUIVisualEffectView]; + XCTAssertNil(platformViewFilter); +} + +- (void)testApplyBackdropFilterAPIChangedInvalidInputRadius { + [PlatformViewFilter resetPreparation]; + UIVisualEffectView* editedUIVisualEffectView = [[UIVisualEffectView alloc] + initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]]; + NSArray* subviews = editedUIVisualEffectView.subviews; + for (UIView* view in subviews) { + if ([NSStringFromClass([view class]) hasSuffix:@"BackdropView"]) { + for (CIFilter* filter in view.layer.filters) { + if ([[filter valueForKey:@"name"] isEqual:@"gaussianBlur"]) { + [filter setValue:@"invalidInputRadius" forKey:@"inputRadius"]; + break; + } + } + break; + } + } + + PlatformViewFilter* platformViewFilter = + [[PlatformViewFilter alloc] initWithFrame:CGRectMake(0, 0, 10, 10) + blurRadius:5 + visualEffectView:editedUIVisualEffectView]; + XCTAssertNil(platformViewFilter); +} + +- (void)testBackdropFilterVisualEffectSubviewBackgroundColor { + __weak UIVisualEffectView* weakVisualEffectView; + + @autoreleasepool { + UIVisualEffectView* visualEffectView = [[UIVisualEffectView alloc] + initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]]; + weakVisualEffectView = visualEffectView; + PlatformViewFilter* platformViewFilter = + [[PlatformViewFilter alloc] initWithFrame:CGRectMake(0, 0, 10, 10) + blurRadius:5 + visualEffectView:visualEffectView]; + CGColorRef visualEffectSubviewBackgroundColor = nil; + for (UIView* view in [platformViewFilter backdropFilterView].subviews) { + if ([NSStringFromClass([view class]) hasSuffix:@"VisualEffectSubview"]) { + visualEffectSubviewBackgroundColor = view.layer.backgroundColor; + } + } + XCTAssertTrue( + CGColorEqualToColor(visualEffectSubviewBackgroundColor, UIColor.clearColor.CGColor)); + } + XCTAssertNil(weakVisualEffectView); +} + +- (void)testCompositePlatformView { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; + flutterPlatformViewsController.flutterView = flutterView; + // Create embedded view params + flutter::MutatorsStack stack; + // Layer tree always pushes a screen scale factor to the stack + flutter::DlScalar screenScale = [UIScreen mainScreen].scale; + flutter::DlMatrix screenScaleMatrix = flutter::DlMatrix::MakeScale({screenScale, screenScale, 1}); + stack.PushTransform(screenScaleMatrix); + // Push a translate matrix + flutter::DlMatrix translateMatrix = flutter::DlMatrix::MakeTranslation({100, 100}); + stack.PushTransform(translateMatrix); + flutter::DlMatrix finalMatrix = screenScaleMatrix * translateMatrix; + + auto embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(finalMatrix), SkSize::Make(300, 300), stack); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + CGRect platformViewRectInFlutterView = [gMockPlatformView convertRect:gMockPlatformView.bounds + toView:flutterView]; + XCTAssertTrue(CGRectEqualToRect(platformViewRectInFlutterView, CGRectMake(100, 100, 300, 300))); +} + +- (void)testBackdropFilterCorrectlyPushedAndReset { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; + flutterPlatformViewsController.flutterView = flutterView; + // Create embedded view params + flutter::MutatorsStack stack; + // Layer tree always pushes a screen scale factor to the stack + flutter::DlScalar screenScale = [UIScreen mainScreen].scale; + flutter::DlMatrix screenScaleMatrix = flutter::DlMatrix::MakeScale({screenScale, screenScale, 1}); + stack.PushTransform(screenScaleMatrix); + + auto embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack); + + [flutterPlatformViewsController beginFrameWithSize:SkISize::Make(0, 0)]; + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController pushVisitedPlatformViewId:2]; + auto filter = flutter::DlBlurImageFilter::Make(5, 2, flutter::DlTileMode::kClamp); + [flutterPlatformViewsController + pushFilterToVisitedPlatformViews:filter + withRect:SkRect::MakeXYWH(0, 0, screenScale * 10, screenScale * 10)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:[ChildClippingView class]]); + ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; + [flutterView addSubview:childClippingView]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + // childClippingView has visual effect view with the correct configurations. + NSUInteger numberOfExpectedVisualEffectView = 0; + for (UIView* subview in childClippingView.subviews) { + if (![subview isKindOfClass:[UIVisualEffectView class]]) { + continue; + } + XCTAssertLessThan(numberOfExpectedVisualEffectView, 1u); + if ([self validateOneVisualEffectView:subview + expectedFrame:CGRectMake(0, 0, 10, 10) + inputRadius:5]) { + numberOfExpectedVisualEffectView++; + } + } + XCTAssertEqual(numberOfExpectedVisualEffectView, 1u); + + // New frame, with no filter pushed. + auto embeddedViewParams2 = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack); + [flutterPlatformViewsController beginFrameWithSize:SkISize::Make(0, 0)]; + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams2)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:[ChildClippingView class]]); + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + numberOfExpectedVisualEffectView = 0; + for (UIView* subview in childClippingView.subviews) { + if (![subview isKindOfClass:[UIVisualEffectView class]]) { + continue; + } + numberOfExpectedVisualEffectView++; + } + XCTAssertEqual(numberOfExpectedVisualEffectView, 0u); +} + +- (void)testChildClippingViewShouldBeTheBoundingRectOfPlatformView { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; + flutterPlatformViewsController.flutterView = flutterView; + // Create embedded view params + flutter::MutatorsStack stack; + // Layer tree always pushes a screen scale factor to the stack + flutter::DlScalar screenScale = [UIScreen mainScreen].scale; + flutter::DlMatrix screenScaleMatrix = flutter::DlMatrix::MakeScale({screenScale, screenScale, 1}); + stack.PushTransform(screenScaleMatrix); + // Push a rotate matrix + flutter::DlMatrix rotateMatrix = flutter::DlMatrix::MakeRotationZ(flutter::DlDegrees(10)); + stack.PushTransform(rotateMatrix); + flutter::DlMatrix finalMatrix = screenScaleMatrix * rotateMatrix; + + auto embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(finalMatrix), SkSize::Make(300, 300), stack); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + CGRect platformViewRectInFlutterView = [gMockPlatformView convertRect:gMockPlatformView.bounds + toView:flutterView]; + XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:ChildClippingView.class]); + ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; + // The childclippingview's frame is set based on flow, but the platform view's frame is set based + // on quartz. Although they should be the same, but we should tolerate small floating point + // errors. + XCTAssertLessThan(fabs(platformViewRectInFlutterView.origin.x - childClippingView.frame.origin.x), + kFloatCompareEpsilon); + XCTAssertLessThan(fabs(platformViewRectInFlutterView.origin.y - childClippingView.frame.origin.y), + kFloatCompareEpsilon); + XCTAssertLessThan( + fabs(platformViewRectInFlutterView.size.width - childClippingView.frame.size.width), + kFloatCompareEpsilon); + XCTAssertLessThan( + fabs(platformViewRectInFlutterView.size.height - childClippingView.frame.size.height), + kFloatCompareEpsilon); +} + +- (void)testClipsDoNotInterceptWithPlatformViewShouldNotAddMaskView { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)]; + flutterPlatformViewsController.flutterView = flutterView; + // Create embedded view params. + flutter::MutatorsStack stack; + // Layer tree always pushes a screen scale factor to the stack. + flutter::DlScalar screenScale = [UIScreen mainScreen].scale; + flutter::DlMatrix screenScaleMatrix = flutter::DlMatrix::MakeScale({screenScale, screenScale, 1}); + stack.PushTransform(screenScaleMatrix); + flutter::DlMatrix translateMatrix = flutter::DlMatrix::MakeTranslation({5, 5}); + // The platform view's rect for this test will be (5, 5, 10, 10). + stack.PushTransform(translateMatrix); + // Push a clip rect, big enough to contain the entire platform view bound. + flutter::DlRect rect = flutter::DlRect::MakeXYWH(0, 0, 25, 25); + stack.PushClipRect(rect); + // Push a clip rrect, big enough to contain the entire platform view bound without clipping it. + // Make the origin (-1, -1) so that the top left rounded corner isn't clipping the PlatformView. + flutter::DlRect rect_for_rrect = flutter::DlRect::MakeXYWH(-1, -1, 25, 25); + flutter::DlRoundRect rrect = flutter::DlRoundRect::MakeRectXY(rect_for_rrect, 1, 1); + stack.PushClipRRect(rrect); + + auto embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix * translateMatrix), SkSize::Make(5, 5), stack); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + gMockPlatformView.backgroundColor = UIColor.redColor; + XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:ChildClippingView.class]); + ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; + [flutterView addSubview:childClippingView]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + XCTAssertNil(childClippingView.maskView); +} + +- (void)testClipRRectOnlyHasCornersInterceptWithPlatformViewShouldAddMaskView { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)]; + flutterPlatformViewsController.flutterView = flutterView; + // Create embedded view params + flutter::MutatorsStack stack; + // Layer tree always pushes a screen scale factor to the stack. + flutter::DlScalar screenScale = [UIScreen mainScreen].scale; + flutter::DlMatrix screenScaleMatrix = flutter::DlMatrix::MakeScale({screenScale, screenScale, 1}); + stack.PushTransform(screenScaleMatrix); + flutter::DlMatrix translateMatrix = flutter::DlMatrix::MakeTranslation({5, 5}); + // The platform view's rect for this test will be (5, 5, 10, 10). + stack.PushTransform(translateMatrix); + + // Push a clip rrect, the rect of the rrect is the same as the PlatformView of the corner should. + // clip the PlatformView. + flutter::DlRect rect_for_rrect = flutter::DlRect::MakeXYWH(0, 0, 10, 10); + flutter::DlRoundRect rrect = flutter::DlRoundRect::MakeRectXY(rect_for_rrect, 1, 1); + stack.PushClipRRect(rrect); + + auto embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix * translateMatrix), SkSize::Make(5, 5), stack); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + gMockPlatformView.backgroundColor = UIColor.redColor; + XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:ChildClippingView.class]); + ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; + [flutterView addSubview:childClippingView]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + XCTAssertNotNil(childClippingView.maskView); +} + +- (void)testClipRect { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; + flutterPlatformViewsController.flutterView = flutterView; + // Create embedded view params + flutter::MutatorsStack stack; + // Layer tree always pushes a screen scale factor to the stack + flutter::DlScalar screenScale = [UIScreen mainScreen].scale; + flutter::DlMatrix screenScaleMatrix = flutter::DlMatrix::MakeScale({screenScale, screenScale, 1}); + stack.PushTransform(screenScaleMatrix); + // Push a clip rect + flutter::DlRect rect = flutter::DlRect::MakeXYWH(2, 2, 3, 3); + stack.PushClipRect(rect); + + auto embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + gMockPlatformView.backgroundColor = UIColor.redColor; + XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:ChildClippingView.class]); + ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; + [flutterView addSubview:childClippingView]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + CGRect insideClipping = CGRectMake(2, 2, 3, 3); + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + CGPoint point = CGPointMake(i, j); + int alpha = [self alphaOfPoint:CGPointMake(i, j) onView:flutterView]; + if (CGRectContainsPoint(insideClipping, point)) { + XCTAssertEqual(alpha, 255); + } else { + XCTAssertEqual(alpha, 0); + } + } + } +} + +- (void)testClipRect_multipleClips { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; + flutterPlatformViewsController.flutterView = flutterView; + // Create embedded view params + flutter::MutatorsStack stack; + // Layer tree always pushes a screen scale factor to the stack + flutter::DlScalar screenScale = [UIScreen mainScreen].scale; + flutter::DlMatrix screenScaleMatrix = flutter::DlMatrix::MakeScale({screenScale, screenScale, 1}); + stack.PushTransform(screenScaleMatrix); + // Push a clip rect + flutter::DlRect rect1 = flutter::DlRect::MakeXYWH(2, 2, 3, 3); + stack.PushClipRect(rect1); + // Push another clip rect + flutter::DlRect rect2 = flutter::DlRect::MakeXYWH(3, 3, 3, 3); + stack.PushClipRect(rect2); + + auto embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + gMockPlatformView.backgroundColor = UIColor.redColor; + XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:ChildClippingView.class]); + ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; + [flutterView addSubview:childClippingView]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + /* + clip 1 clip 2 + 2 3 4 5 6 2 3 4 5 6 + 2 + - - + 2 + 3 | | 3 + - - + + 4 | | 4 | | + 5 + - - + 5 | | + 6 6 + - - + + + Result should be the intersection of 2 clips + 2 3 4 5 6 + 2 + 3 + - + + 4 | | + 5 + - + + 6 + */ + CGRect insideClipping = CGRectMake(3, 3, 2, 2); + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + CGPoint point = CGPointMake(i, j); + int alpha = [self alphaOfPoint:CGPointMake(i, j) onView:flutterView]; + if (CGRectContainsPoint(insideClipping, point)) { + XCTAssertEqual(alpha, 255); + } else { + XCTAssertEqual(alpha, 0); + } + } + } +} + +- (void)testClipRRect { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; + flutterPlatformViewsController.flutterView = flutterView; + // Create embedded view params + flutter::MutatorsStack stack; + // Layer tree always pushes a screen scale factor to the stack + flutter::DlScalar screenScale = [UIScreen mainScreen].scale; + flutter::DlMatrix screenScaleMatrix = flutter::DlMatrix::MakeScale({screenScale, screenScale, 1}); + stack.PushTransform(screenScaleMatrix); + // Push a clip rrect + flutter::DlRoundRect rrect = + flutter::DlRoundRect::MakeRectXY(flutter::DlRect::MakeXYWH(2, 2, 6, 6), 1, 1); + stack.PushClipRRect(rrect); + + auto embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + gMockPlatformView.backgroundColor = UIColor.redColor; + XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:ChildClippingView.class]); + ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; + [flutterView addSubview:childClippingView]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + /* + ClippingMask outterClipping + 2 3 4 5 6 7 2 3 4 5 6 7 + 2 / - - - - \ 2 + - - - - + + 3 | | 3 | | + 4 | | 4 | | + 5 | | 5 | | + 6 | | 6 | | + 7 \ - - - - / 7 + - - - - + + + innerClipping1 innerClipping2 + 2 3 4 5 6 7 2 3 4 5 6 7 + 2 + - - + 2 + 3 | | 3 + - - - - + + 4 | | 4 | | + 5 | | 5 | | + 6 | | 6 + - - - - + + 7 + - - + 7 + */ + CGRect innerClipping1 = CGRectMake(3, 2, 4, 6); + CGRect innerClipping2 = CGRectMake(2, 3, 6, 4); + CGRect outterClipping = CGRectMake(2, 2, 6, 6); + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + CGPoint point = CGPointMake(i, j); + int alpha = [self alphaOfPoint:CGPointMake(i, j) onView:flutterView]; + if (CGRectContainsPoint(innerClipping1, point) || + CGRectContainsPoint(innerClipping2, point)) { + // Pixels inside either of the 2 inner clippings should be fully opaque. + XCTAssertEqual(alpha, 255); + } else if (CGRectContainsPoint(outterClipping, point)) { + // Corner pixels (i.e. (2, 2), (2, 7), (7, 2) and (7, 7)) should be partially transparent. + XCTAssert(0 < alpha && alpha < 255); + } else { + // Pixels outside outterClipping should be fully transparent. + XCTAssertEqual(alpha, 0); + } + } + } +} + +- (void)testClipRRect_multipleClips { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; + flutterPlatformViewsController.flutterView = flutterView; + // Create embedded view params + flutter::MutatorsStack stack; + // Layer tree always pushes a screen scale factor to the stack + flutter::DlScalar screenScale = [UIScreen mainScreen].scale; + flutter::DlMatrix screenScaleMatrix = flutter::DlMatrix::MakeScale({screenScale, screenScale, 1}); + stack.PushTransform(screenScaleMatrix); + // Push a clip rrect + flutter::DlRoundRect rrect = + flutter::DlRoundRect::MakeRectXY(flutter::DlRect::MakeXYWH(2, 2, 6, 6), 1, 1); + stack.PushClipRRect(rrect); + // Push a clip rect + flutter::DlRect rect = flutter::DlRect::MakeXYWH(4, 2, 6, 6); + stack.PushClipRect(rect); + + auto embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + gMockPlatformView.backgroundColor = UIColor.redColor; + XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:ChildClippingView.class]); + ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; + [flutterView addSubview:childClippingView]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + /* + clip 1 clip 2 + 2 3 4 5 6 7 8 9 2 3 4 5 6 7 8 9 + 2 / - - - - \ 2 + - - - - + + 3 | | 3 | | + 4 | | 4 | | + 5 | | 5 | | + 6 | | 6 | | + 7 \ - - - - / 7 + - - - - + + + Result should be the intersection of 2 clips + 2 3 4 5 6 7 8 9 + 2 + - - \ + 3 | | + 4 | | + 5 | | + 6 | | + 7 + - - / + */ + CGRect clipping = CGRectMake(4, 2, 4, 6); + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + CGPoint point = CGPointMake(i, j); + int alpha = [self alphaOfPoint:CGPointMake(i, j) onView:flutterView]; + if (i == 7 && (j == 2 || j == 7)) { + // Upper and lower right corners should be partially transparent. + XCTAssert(0 < alpha && alpha < 255); + } else if ( + // left + (i == 4 && j >= 2 && j <= 7) || + // right + (i == 7 && j >= 2 && j <= 7) || + // top + (j == 2 && i >= 4 && i <= 7) || + // bottom + (j == 7 && i >= 4 && i <= 7)) { + // Since we are falling back to software rendering for this case + // The edge pixels can be anti-aliased, so it may not be fully opaque. + XCTAssert(alpha > 127); + } else if ((i == 3 && j >= 1 && j <= 8) || (i == 8 && j >= 1 && j <= 8) || + (j == 1 && i >= 3 && i <= 8) || (j == 8 && i >= 3 && i <= 8)) { + // Since we are falling back to software rendering for this case + // The edge pixels can be anti-aliased, so it may not be fully transparent. + XCTAssert(alpha < 127); + } else if (CGRectContainsPoint(clipping, point)) { + // Other pixels inside clipping should be fully opaque. + XCTAssertEqual(alpha, 255); + } else { + // Pixels outside clipping should be fully transparent. + XCTAssertEqual(alpha, 0); + } + } + } +} + +- (void)testClipPath { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; + flutterPlatformViewsController.flutterView = flutterView; + // Create embedded view params + flutter::MutatorsStack stack; + // Layer tree always pushes a screen scale factor to the stack + flutter::DlScalar screenScale = [UIScreen mainScreen].scale; + flutter::DlMatrix screenScaleMatrix = flutter::DlMatrix::MakeScale({screenScale, screenScale, 1}); + stack.PushTransform(screenScaleMatrix); + // Push a clip path + flutter::DlPath path = + flutter::DlPath::MakeRoundRectXY(flutter::DlRect::MakeXYWH(2, 2, 6, 6), 1, 1); + stack.PushClipPath(path); + + auto embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + gMockPlatformView.backgroundColor = UIColor.redColor; + XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:ChildClippingView.class]); + ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; + [flutterView addSubview:childClippingView]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + /* + ClippingMask outterClipping + 2 3 4 5 6 7 2 3 4 5 6 7 + 2 / - - - - \ 2 + - - - - + + 3 | | 3 | | + 4 | | 4 | | + 5 | | 5 | | + 6 | | 6 | | + 7 \ - - - - / 7 + - - - - + + + innerClipping1 innerClipping2 + 2 3 4 5 6 7 2 3 4 5 6 7 + 2 + - - + 2 + 3 | | 3 + - - - - + + 4 | | 4 | | + 5 | | 5 | | + 6 | | 6 + - - - - + + 7 + - - + 7 + */ + CGRect innerClipping1 = CGRectMake(3, 2, 4, 6); + CGRect innerClipping2 = CGRectMake(2, 3, 6, 4); + CGRect outterClipping = CGRectMake(2, 2, 6, 6); + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + CGPoint point = CGPointMake(i, j); + int alpha = [self alphaOfPoint:CGPointMake(i, j) onView:flutterView]; + if (CGRectContainsPoint(innerClipping1, point) || + CGRectContainsPoint(innerClipping2, point)) { + // Pixels inside either of the 2 inner clippings should be fully opaque. + XCTAssertEqual(alpha, 255); + } else if (CGRectContainsPoint(outterClipping, point)) { + // Corner pixels (i.e. (2, 2), (2, 7), (7, 2) and (7, 7)) should be partially transparent. + XCTAssert(0 < alpha && alpha < 255); + } else { + // Pixels outside outterClipping should be fully transparent. + XCTAssertEqual(alpha, 0); + } + } + } +} + +- (void)testClipPath_multipleClips { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; + flutterPlatformViewsController.flutterView = flutterView; + // Create embedded view params + flutter::MutatorsStack stack; + // Layer tree always pushes a screen scale factor to the stack + flutter::DlScalar screenScale = [UIScreen mainScreen].scale; + flutter::DlMatrix screenScaleMatrix = flutter::DlMatrix::MakeScale({screenScale, screenScale, 1}); + stack.PushTransform(screenScaleMatrix); + // Push a clip path + flutter::DlPath path = + flutter::DlPath::MakeRoundRectXY(flutter::DlRect::MakeXYWH(2, 2, 6, 6), 1, 1); + stack.PushClipPath(path); + // Push a clip rect + flutter::DlRect rect = flutter::DlRect::MakeXYWH(4, 2, 6, 6); + stack.PushClipRect(rect); + + auto embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + gMockPlatformView.backgroundColor = UIColor.redColor; + XCTAssertTrue([gMockPlatformView.superview.superview isKindOfClass:ChildClippingView.class]); + ChildClippingView* childClippingView = (ChildClippingView*)gMockPlatformView.superview.superview; + [flutterView addSubview:childClippingView]; + + [flutterView setNeedsLayout]; + [flutterView layoutIfNeeded]; + + /* + clip 1 clip 2 + 2 3 4 5 6 7 8 9 2 3 4 5 6 7 8 9 + 2 / - - - - \ 2 + - - - - + + 3 | | 3 | | + 4 | | 4 | | + 5 | | 5 | | + 6 | | 6 | | + 7 \ - - - - / 7 + - - - - + + + Result should be the intersection of 2 clips + 2 3 4 5 6 7 8 9 + 2 + - - \ + 3 | | + 4 | | + 5 | | + 6 | | + 7 + - - / + */ + CGRect clipping = CGRectMake(4, 2, 4, 6); + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + CGPoint point = CGPointMake(i, j); + int alpha = [self alphaOfPoint:CGPointMake(i, j) onView:flutterView]; + if (i == 7 && (j == 2 || j == 7)) { + // Upper and lower right corners should be partially transparent. + XCTAssert(0 < alpha && alpha < 255); + } else if ( + // left + (i == 4 && j >= 2 && j <= 7) || + // right + (i == 7 && j >= 2 && j <= 7) || + // top + (j == 2 && i >= 4 && i <= 7) || + // bottom + (j == 7 && i >= 4 && i <= 7)) { + // Since we are falling back to software rendering for this case + // The edge pixels can be anti-aliased, so it may not be fully opaque. + XCTAssert(alpha > 127); + } else if ((i == 3 && j >= 1 && j <= 8) || (i == 8 && j >= 1 && j <= 8) || + (j == 1 && i >= 3 && i <= 8) || (j == 8 && i >= 3 && i <= 8)) { + // Since we are falling back to software rendering for this case + // The edge pixels can be anti-aliased, so it may not be fully transparent. + XCTAssert(alpha < 127); + } else if (CGRectContainsPoint(clipping, point)) { + // Other pixels inside clipping should be fully opaque. + XCTAssertEqual(alpha, 255); + } else { + // Pixels outside clipping should be fully transparent. + XCTAssertEqual(alpha, 0); + } + } + } +} + +- (void)testSetFlutterViewControllerAfterCreateCanStillDispatchTouchEvents { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + // Find touch inteceptor view + UIView* touchInteceptorView = gMockPlatformView; + while (touchInteceptorView != nil && + ![touchInteceptorView isKindOfClass:[FlutterTouchInterceptingView class]]) { + touchInteceptorView = touchInteceptorView.superview; + } + XCTAssertNotNil(touchInteceptorView); + + // Find ForwardGestureRecognizer + UIGestureRecognizer* forwardGectureRecognizer = nil; + for (UIGestureRecognizer* gestureRecognizer in touchInteceptorView.gestureRecognizers) { + if ([gestureRecognizer isKindOfClass:[ForwardingGestureRecognizer class]]) { + forwardGectureRecognizer = gestureRecognizer; + break; + } + } + + // Before setting flutter view controller, events are not dispatched. + NSSet* touches1 = [[NSSet alloc] init]; + id event1 = OCMClassMock([UIEvent class]); + id flutterViewController = OCMClassMock([FlutterViewController class]); + [forwardGectureRecognizer touchesBegan:touches1 withEvent:event1]; + OCMReject([flutterViewController touchesBegan:touches1 withEvent:event1]); + + // Set flutter view controller allows events to be dispatched. + NSSet* touches2 = [[NSSet alloc] init]; + id event2 = OCMClassMock([UIEvent class]); + flutterPlatformViewsController.flutterViewController = flutterViewController; + [forwardGectureRecognizer touchesBegan:touches2 withEvent:event2]; + OCMVerify([flutterViewController touchesBegan:touches2 withEvent:event2]); +} + +- (void)testSetFlutterViewControllerInTheMiddleOfTouchEventShouldStillAllowGesturesToBeHandled { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + // Find touch inteceptor view + UIView* touchInteceptorView = gMockPlatformView; + while (touchInteceptorView != nil && + ![touchInteceptorView isKindOfClass:[FlutterTouchInterceptingView class]]) { + touchInteceptorView = touchInteceptorView.superview; + } + XCTAssertNotNil(touchInteceptorView); + + // Find ForwardGestureRecognizer + UIGestureRecognizer* forwardGectureRecognizer = nil; + for (UIGestureRecognizer* gestureRecognizer in touchInteceptorView.gestureRecognizers) { + if ([gestureRecognizer isKindOfClass:[ForwardingGestureRecognizer class]]) { + forwardGectureRecognizer = gestureRecognizer; + break; + } + } + id flutterViewController = OCMClassMock([FlutterViewController class]); + { + // ***** Sequence 1, finishing touch event with touchEnded ***** // + flutterPlatformViewsController.flutterViewController = flutterViewController; + + NSSet* touches1 = [[NSSet alloc] init]; + id event1 = OCMClassMock([UIEvent class]); + [forwardGectureRecognizer touchesBegan:touches1 withEvent:event1]; + OCMVerify([flutterViewController touchesBegan:touches1 withEvent:event1]); + + flutterPlatformViewsController.flutterViewController = nil; + + // Allow the touch events to finish + NSSet* touches2 = [[NSSet alloc] init]; + id event2 = OCMClassMock([UIEvent class]); + [forwardGectureRecognizer touchesMoved:touches2 withEvent:event2]; + OCMVerify([flutterViewController touchesMoved:touches2 withEvent:event2]); + + NSSet* touches3 = [[NSSet alloc] init]; + id event3 = OCMClassMock([UIEvent class]); + [forwardGectureRecognizer touchesEnded:touches3 withEvent:event3]; + OCMVerify([flutterViewController touchesEnded:touches3 withEvent:event3]); + + // Now the 2nd touch sequence should not be allowed. + NSSet* touches4 = [[NSSet alloc] init]; + id event4 = OCMClassMock([UIEvent class]); + [forwardGectureRecognizer touchesBegan:touches4 withEvent:event4]; + OCMReject([flutterViewController touchesBegan:touches4 withEvent:event4]); + + NSSet* touches5 = [[NSSet alloc] init]; + id event5 = OCMClassMock([UIEvent class]); + [forwardGectureRecognizer touchesEnded:touches5 withEvent:event5]; + OCMReject([flutterViewController touchesEnded:touches5 withEvent:event5]); + } + + { + // ***** Sequence 2, finishing touch event with touchCancelled ***** // + flutterPlatformViewsController.flutterViewController = flutterViewController; + + NSSet* touches1 = [[NSSet alloc] init]; + id event1 = OCMClassMock([UIEvent class]); + [forwardGectureRecognizer touchesBegan:touches1 withEvent:event1]; + OCMVerify([flutterViewController touchesBegan:touches1 withEvent:event1]); + + flutterPlatformViewsController.flutterViewController = nil; + + // Allow the touch events to finish + NSSet* touches2 = [[NSSet alloc] init]; + id event2 = OCMClassMock([UIEvent class]); + [forwardGectureRecognizer touchesMoved:touches2 withEvent:event2]; + OCMVerify([flutterViewController touchesMoved:touches2 withEvent:event2]); + + NSSet* touches3 = [[NSSet alloc] init]; + id event3 = OCMClassMock([UIEvent class]); + [forwardGectureRecognizer touchesCancelled:touches3 withEvent:event3]; + OCMVerify([flutterViewController forceTouchesCancelled:touches3]); + + // Now the 2nd touch sequence should not be allowed. + NSSet* touches4 = [[NSSet alloc] init]; + id event4 = OCMClassMock([UIEvent class]); + [forwardGectureRecognizer touchesBegan:touches4 withEvent:event4]; + OCMReject([flutterViewController touchesBegan:touches4 withEvent:event4]); + + NSSet* touches5 = [[NSSet alloc] init]; + id event5 = OCMClassMock([UIEvent class]); + [forwardGectureRecognizer touchesEnded:touches5 withEvent:event5]; + OCMReject([flutterViewController touchesEnded:touches5 withEvent:event5]); + } + + [flutterPlatformViewsController reset]; +} + +- (void) + testSetFlutterViewControllerInTheMiddleOfTouchEventAllowsTheNewControllerToHandleSecondTouchSequence { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + // Find touch inteceptor view + UIView* touchInteceptorView = gMockPlatformView; + while (touchInteceptorView != nil && + ![touchInteceptorView isKindOfClass:[FlutterTouchInterceptingView class]]) { + touchInteceptorView = touchInteceptorView.superview; + } + XCTAssertNotNil(touchInteceptorView); + + // Find ForwardGestureRecognizer + UIGestureRecognizer* forwardGectureRecognizer = nil; + for (UIGestureRecognizer* gestureRecognizer in touchInteceptorView.gestureRecognizers) { + if ([gestureRecognizer isKindOfClass:[ForwardingGestureRecognizer class]]) { + forwardGectureRecognizer = gestureRecognizer; + break; + } + } + id flutterViewController = OCMClassMock([FlutterViewController class]); + flutterPlatformViewsController.flutterViewController = flutterViewController; + + // The touches in this sequence requires 1 touch object, we always create the NSSet with one item. + NSSet* touches1 = [NSSet setWithObject:@1]; + id event1 = OCMClassMock([UIEvent class]); + [forwardGectureRecognizer touchesBegan:touches1 withEvent:event1]; + OCMVerify([flutterViewController touchesBegan:touches1 withEvent:event1]); + + FlutterViewController* flutterViewController2 = OCMClassMock([FlutterViewController class]); + flutterPlatformViewsController.flutterViewController = flutterViewController2; + + // Touch events should still send to the old FlutterViewController if FlutterViewController + // is updated in between. + NSSet* touches2 = [NSSet setWithObject:@1]; + id event2 = OCMClassMock([UIEvent class]); + [forwardGectureRecognizer touchesBegan:touches2 withEvent:event2]; + OCMVerify([flutterViewController touchesBegan:touches2 withEvent:event2]); + OCMReject([flutterViewController2 touchesBegan:touches2 withEvent:event2]); + + NSSet* touches3 = [NSSet setWithObject:@1]; + id event3 = OCMClassMock([UIEvent class]); + [forwardGectureRecognizer touchesMoved:touches3 withEvent:event3]; + OCMVerify([flutterViewController touchesMoved:touches3 withEvent:event3]); + OCMReject([flutterViewController2 touchesMoved:touches3 withEvent:event3]); + + NSSet* touches4 = [NSSet setWithObject:@1]; + id event4 = OCMClassMock([UIEvent class]); + [forwardGectureRecognizer touchesEnded:touches4 withEvent:event4]; + OCMVerify([flutterViewController touchesEnded:touches4 withEvent:event4]); + OCMReject([flutterViewController2 touchesEnded:touches4 withEvent:event4]); + + NSSet* touches5 = [NSSet setWithObject:@1]; + id event5 = OCMClassMock([UIEvent class]); + [forwardGectureRecognizer touchesEnded:touches5 withEvent:event5]; + OCMVerify([flutterViewController touchesEnded:touches5 withEvent:event5]); + OCMReject([flutterViewController2 touchesEnded:touches5 withEvent:event5]); + + // Now the 2nd touch sequence should go to the new FlutterViewController + + NSSet* touches6 = [NSSet setWithObject:@1]; + id event6 = OCMClassMock([UIEvent class]); + [forwardGectureRecognizer touchesBegan:touches6 withEvent:event6]; + OCMVerify([flutterViewController2 touchesBegan:touches6 withEvent:event6]); + OCMReject([flutterViewController touchesBegan:touches6 withEvent:event6]); + + // Allow the touch events to finish + NSSet* touches7 = [NSSet setWithObject:@1]; + id event7 = OCMClassMock([UIEvent class]); + [forwardGectureRecognizer touchesMoved:touches7 withEvent:event7]; + OCMVerify([flutterViewController2 touchesMoved:touches7 withEvent:event7]); + OCMReject([flutterViewController touchesMoved:touches7 withEvent:event7]); + + NSSet* touches8 = [NSSet setWithObject:@1]; + id event8 = OCMClassMock([UIEvent class]); + [forwardGectureRecognizer touchesEnded:touches8 withEvent:event8]; + OCMVerify([flutterViewController2 touchesEnded:touches8 withEvent:event8]); + OCMReject([flutterViewController touchesEnded:touches8 withEvent:event8]); + + [flutterPlatformViewsController reset]; +} + +- (void)testFlutterPlatformViewTouchesCancelledEventAreForcedToBeCancelled { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + // Find touch inteceptor view + UIView* touchInteceptorView = gMockPlatformView; + while (touchInteceptorView != nil && + ![touchInteceptorView isKindOfClass:[FlutterTouchInterceptingView class]]) { + touchInteceptorView = touchInteceptorView.superview; + } + XCTAssertNotNil(touchInteceptorView); + + // Find ForwardGestureRecognizer + UIGestureRecognizer* forwardGectureRecognizer = nil; + for (UIGestureRecognizer* gestureRecognizer in touchInteceptorView.gestureRecognizers) { + if ([gestureRecognizer isKindOfClass:[ForwardingGestureRecognizer class]]) { + forwardGectureRecognizer = gestureRecognizer; + break; + } + } + id flutterViewController = OCMClassMock([FlutterViewController class]); + flutterPlatformViewsController.flutterViewController = flutterViewController; + + NSSet* touches1 = [NSSet setWithObject:@1]; + id event1 = OCMClassMock([UIEvent class]); + [forwardGectureRecognizer touchesBegan:touches1 withEvent:event1]; + + [forwardGectureRecognizer touchesCancelled:touches1 withEvent:event1]; + OCMVerify([flutterViewController forceTouchesCancelled:touches1]); + + [flutterPlatformViewsController reset]; +} + +- (void)testFlutterPlatformViewTouchesEndedOrTouchesCancelledEventDoesNotFailTheGestureRecognizer { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + // Find touch inteceptor view + UIView* touchInteceptorView = gMockPlatformView; + while (touchInteceptorView != nil && + ![touchInteceptorView isKindOfClass:[FlutterTouchInterceptingView class]]) { + touchInteceptorView = touchInteceptorView.superview; + } + XCTAssertNotNil(touchInteceptorView); + + // Find ForwardGestureRecognizer + __block UIGestureRecognizer* forwardGestureRecognizer = nil; + for (UIGestureRecognizer* gestureRecognizer in touchInteceptorView.gestureRecognizers) { + if ([gestureRecognizer isKindOfClass:[ForwardingGestureRecognizer class]]) { + forwardGestureRecognizer = gestureRecognizer; + break; + } + } + id flutterViewController = OCMClassMock([FlutterViewController class]); + flutterPlatformViewsController.flutterViewController = flutterViewController; + + NSSet* touches1 = [NSSet setWithObject:@1]; + id event1 = OCMClassMock([UIEvent class]); + XCTAssert(forwardGestureRecognizer.state == UIGestureRecognizerStatePossible, + @"Forwarding gesture recognizer must start with possible state."); + [forwardGestureRecognizer touchesBegan:touches1 withEvent:event1]; + [forwardGestureRecognizer touchesEnded:touches1 withEvent:event1]; + XCTAssert(forwardGestureRecognizer.state == UIGestureRecognizerStateFailed, + @"Forwarding gesture recognizer must end with failed state."); + + XCTestExpectation* touchEndedExpectation = + [self expectationWithDescription:@"Wait for gesture recognizer's state change."]; + dispatch_async(dispatch_get_main_queue(), ^{ + // Re-query forward gesture recognizer since it's recreated. + for (UIGestureRecognizer* gestureRecognizer in touchInteceptorView.gestureRecognizers) { + if ([gestureRecognizer isKindOfClass:[ForwardingGestureRecognizer class]]) { + forwardGestureRecognizer = gestureRecognizer; + break; + } + } + XCTAssert(forwardGestureRecognizer.state == UIGestureRecognizerStatePossible, + @"Forwarding gesture recognizer must be reset to possible state."); + [touchEndedExpectation fulfill]; + }); + [self waitForExpectationsWithTimeout:30 handler:nil]; + + XCTAssert(forwardGestureRecognizer.state == UIGestureRecognizerStatePossible, + @"Forwarding gesture recognizer must start with possible state."); + [forwardGestureRecognizer touchesBegan:touches1 withEvent:event1]; + [forwardGestureRecognizer touchesCancelled:touches1 withEvent:event1]; + XCTAssert(forwardGestureRecognizer.state == UIGestureRecognizerStateFailed, + @"Forwarding gesture recognizer must end with failed state."); + XCTestExpectation* touchCancelledExpectation = + [self expectationWithDescription:@"Wait for gesture recognizer's state change."]; + dispatch_async(dispatch_get_main_queue(), ^{ + // Re-query forward gesture recognizer since it's recreated. + for (UIGestureRecognizer* gestureRecognizer in touchInteceptorView.gestureRecognizers) { + if ([gestureRecognizer isKindOfClass:[ForwardingGestureRecognizer class]]) { + forwardGestureRecognizer = gestureRecognizer; + break; + } + } + XCTAssert(forwardGestureRecognizer.state == UIGestureRecognizerStatePossible, + @"Forwarding gesture recognizer must be reset to possible state."); + [touchCancelledExpectation fulfill]; + }); + [self waitForExpectationsWithTimeout:30 handler:nil]; + + [flutterPlatformViewsController reset]; +} + +- (void) + testFlutterPlatformViewBlockGestureUnderEagerPolicyShouldRemoveAndAddBackDelayingRecognizerForWebView { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockWebViewFactory* factory = + [[FlutterPlatformViewsTestMockWebViewFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockWebView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall + methodCallWithMethodName:@"create" + arguments:@{@"id" : @2, @"viewType" : @"MockWebView"}] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + // Find touch inteceptor view + UIView* touchInteceptorView = gMockPlatformView; + while (touchInteceptorView != nil && + ![touchInteceptorView isKindOfClass:[FlutterTouchInterceptingView class]]) { + touchInteceptorView = touchInteceptorView.superview; + } + XCTAssertNotNil(touchInteceptorView); + + XCTAssert(touchInteceptorView.gestureRecognizers.count == 2); + UIGestureRecognizer* delayingRecognizer = touchInteceptorView.gestureRecognizers[0]; + UIGestureRecognizer* forwardingRecognizer = touchInteceptorView.gestureRecognizers[1]; + + XCTAssert([delayingRecognizer isKindOfClass:[FlutterDelayingGestureRecognizer class]]); + XCTAssert([forwardingRecognizer isKindOfClass:[ForwardingGestureRecognizer class]]); + + [(FlutterTouchInterceptingView*)touchInteceptorView blockGesture]; + + if (@available(iOS 18.2, *)) { + // Since we remove and add back delayingRecognizer, it would be reordered to the last. + XCTAssertEqual(touchInteceptorView.gestureRecognizers[0], forwardingRecognizer); + XCTAssertEqual(touchInteceptorView.gestureRecognizers[1], delayingRecognizer); + } else { + XCTAssertEqual(touchInteceptorView.gestureRecognizers[0], delayingRecognizer); + XCTAssertEqual(touchInteceptorView.gestureRecognizers[1], forwardingRecognizer); + } +} + +- (void) + testFlutterPlatformViewBlockGestureUnderEagerPolicyShouldRemoveAndAddBackDelayingRecognizerForWrapperWebView { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockWrapperWebViewFactory* factory = + [[FlutterPlatformViewsTestMockWrapperWebViewFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockWrapperWebView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall + methodCallWithMethodName:@"create" + arguments:@{@"id" : @2, @"viewType" : @"MockWrapperWebView"}] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + // Find touch inteceptor view + UIView* touchInteceptorView = gMockPlatformView; + while (touchInteceptorView != nil && + ![touchInteceptorView isKindOfClass:[FlutterTouchInterceptingView class]]) { + touchInteceptorView = touchInteceptorView.superview; + } + XCTAssertNotNil(touchInteceptorView); + + XCTAssert(touchInteceptorView.gestureRecognizers.count == 2); + UIGestureRecognizer* delayingRecognizer = touchInteceptorView.gestureRecognizers[0]; + UIGestureRecognizer* forwardingRecognizer = touchInteceptorView.gestureRecognizers[1]; + + XCTAssert([delayingRecognizer isKindOfClass:[FlutterDelayingGestureRecognizer class]]); + XCTAssert([forwardingRecognizer isKindOfClass:[ForwardingGestureRecognizer class]]); + + [(FlutterTouchInterceptingView*)touchInteceptorView blockGesture]; + + if (@available(iOS 18.2, *)) { + // Since we remove and add back delayingRecognizer, it would be reordered to the last. + XCTAssertEqual(touchInteceptorView.gestureRecognizers[0], forwardingRecognizer); + XCTAssertEqual(touchInteceptorView.gestureRecognizers[1], delayingRecognizer); + } else { + XCTAssertEqual(touchInteceptorView.gestureRecognizers[0], delayingRecognizer); + XCTAssertEqual(touchInteceptorView.gestureRecognizers[1], forwardingRecognizer); + } +} + +- (void) + testFlutterPlatformViewBlockGestureUnderEagerPolicyShouldNotRemoveAndAddBackDelayingRecognizerForNestedWrapperWebView { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockNestedWrapperWebViewFactory* factory = + [[FlutterPlatformViewsTestMockNestedWrapperWebViewFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockNestedWrapperWebView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockNestedWrapperWebView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + // Find touch inteceptor view + UIView* touchInteceptorView = gMockPlatformView; + while (touchInteceptorView != nil && + ![touchInteceptorView isKindOfClass:[FlutterTouchInterceptingView class]]) { + touchInteceptorView = touchInteceptorView.superview; + } + XCTAssertNotNil(touchInteceptorView); + + XCTAssert(touchInteceptorView.gestureRecognizers.count == 2); + UIGestureRecognizer* delayingRecognizer = touchInteceptorView.gestureRecognizers[0]; + UIGestureRecognizer* forwardingRecognizer = touchInteceptorView.gestureRecognizers[1]; + + XCTAssert([delayingRecognizer isKindOfClass:[FlutterDelayingGestureRecognizer class]]); + XCTAssert([forwardingRecognizer isKindOfClass:[ForwardingGestureRecognizer class]]); + + [(FlutterTouchInterceptingView*)touchInteceptorView blockGesture]; + + XCTAssertEqual(touchInteceptorView.gestureRecognizers[0], delayingRecognizer); + XCTAssertEqual(touchInteceptorView.gestureRecognizers[1], forwardingRecognizer); +} + +- (void) + testFlutterPlatformViewBlockGestureUnderEagerPolicyShouldNotRemoveAndAddBackDelayingRecognizerForNonWebView { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + // Find touch inteceptor view + UIView* touchInteceptorView = gMockPlatformView; + while (touchInteceptorView != nil && + ![touchInteceptorView isKindOfClass:[FlutterTouchInterceptingView class]]) { + touchInteceptorView = touchInteceptorView.superview; + } + XCTAssertNotNil(touchInteceptorView); + + XCTAssert(touchInteceptorView.gestureRecognizers.count == 2); + UIGestureRecognizer* delayingRecognizer = touchInteceptorView.gestureRecognizers[0]; + UIGestureRecognizer* forwardingRecognizer = touchInteceptorView.gestureRecognizers[1]; + + XCTAssert([delayingRecognizer isKindOfClass:[FlutterDelayingGestureRecognizer class]]); + XCTAssert([forwardingRecognizer isKindOfClass:[ForwardingGestureRecognizer class]]); + + [(FlutterTouchInterceptingView*)touchInteceptorView blockGesture]; + + XCTAssertEqual(touchInteceptorView.gestureRecognizers[0], delayingRecognizer); + XCTAssertEqual(touchInteceptorView.gestureRecognizers[1], forwardingRecognizer); +} + +- (void)testFlutterPlatformViewControllerSubmitFrameWithoutFlutterViewNotCrashing { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + + // Create embedded view params + flutter::MutatorsStack stack; + flutter::DlMatrix finalMatrix; + + auto embeddedViewParams_1 = std::make_unique( + flutter::ToSkMatrix(finalMatrix), SkSize::Make(300, 300), stack); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams_1)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + flutter::SurfaceFrame::FramebufferInfo framebuffer_info; + auto mock_surface = std::make_unique( + nullptr, framebuffer_info, + [](const flutter::SurfaceFrame& surface_frame, flutter::DlCanvas* canvas) { return false; }, + [](const flutter::SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + XCTAssertFalse([flutterPlatformViewsController + submitFrame:std::move(mock_surface) + withIosContext:std::make_shared()]); + + auto embeddedViewParams_2 = std::make_unique( + flutter::ToSkMatrix(finalMatrix), SkSize::Make(300, 300), stack); + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams_2)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + auto mock_surface_submit_true = std::make_unique( + nullptr, framebuffer_info, + [](const flutter::SurfaceFrame& surface_frame, flutter::DlCanvas* canvas) { return true; }, + [](const flutter::SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + XCTAssertTrue([flutterPlatformViewsController + submitFrame:std::move(mock_surface_submit_true) + withIosContext:std::make_shared()]); +} + +- (void) + testFlutterPlatformViewControllerResetDeallocsPlatformViewWhenRootViewsNotBindedToFlutterView { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; + flutterPlatformViewsController.flutterView = flutterView; + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + // autorelease pool to trigger an autorelease for all the root_views_ and touch_interceptors_. + @autoreleasepool { + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + flutter::MutatorsStack stack; + flutter::DlMatrix finalMatrix; + auto embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(finalMatrix), SkSize::Make(300, 300), stack); + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + + // Not calling |[flutterPlatformViewsController submitFrame:withIosContext:]| so that + // the platform views are not added to flutter_view_. + + XCTAssertNotNil(gMockPlatformView); + [flutterPlatformViewsController reset]; + } + XCTAssertNil(gMockPlatformView); +} + +- (void)testFlutterPlatformViewControllerBeginFrameShouldResetCompisitionOrder { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; + flutterPlatformViewsController.flutterView = flutterView; + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @0, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + // First frame, |embeddedViewCount| is not empty after composite. + [flutterPlatformViewsController beginFrameWithSize:SkISize::Make(300, 300)]; + flutter::MutatorsStack stack; + flutter::DlMatrix finalMatrix; + auto embeddedViewParams1 = std::make_unique( + flutter::ToSkMatrix(finalMatrix), SkSize::Make(300, 300), stack); + [flutterPlatformViewsController prerollCompositeEmbeddedView:0 + withParams:std::move(embeddedViewParams1)]; + [flutterPlatformViewsController + compositeView:0 + withParams:[flutterPlatformViewsController compositionParamsForView:0]]; + + XCTAssertEqual(flutterPlatformViewsController.embeddedViewCount, 1UL); + + // Second frame, |embeddedViewCount| should be empty at the start + [flutterPlatformViewsController beginFrameWithSize:SkISize::Make(300, 300)]; + XCTAssertEqual(flutterPlatformViewsController.embeddedViewCount, 0UL); + + auto embeddedViewParams2 = std::make_unique( + flutter::ToSkMatrix(finalMatrix), SkSize::Make(300, 300), stack); + [flutterPlatformViewsController prerollCompositeEmbeddedView:0 + withParams:std::move(embeddedViewParams2)]; + [flutterPlatformViewsController + compositeView:0 + withParams:[flutterPlatformViewsController compositionParamsForView:0]]; + + XCTAssertEqual(flutterPlatformViewsController.embeddedViewCount, 1UL); +} + +- (void) + testFlutterPlatformViewControllerSubmitFrameShouldOrderSubviewsCorrectlyWithDifferentViewHierarchy { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; + flutterPlatformViewsController.flutterView = flutterView; + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @0, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + UIView* view1 = gMockPlatformView; + + // This overwrites `gMockPlatformView` to another view. + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @1, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + UIView* view2 = gMockPlatformView; + + [flutterPlatformViewsController beginFrameWithSize:SkISize::Make(300, 300)]; + flutter::MutatorsStack stack; + flutter::DlMatrix finalMatrix; + auto embeddedViewParams1 = std::make_unique( + flutter::ToSkMatrix(finalMatrix), SkSize::Make(300, 300), stack); + [flutterPlatformViewsController prerollCompositeEmbeddedView:0 + withParams:std::move(embeddedViewParams1)]; + + auto embeddedViewParams2 = std::make_unique( + flutter::ToSkMatrix(finalMatrix), SkSize::Make(500, 500), stack); + [flutterPlatformViewsController prerollCompositeEmbeddedView:1 + withParams:std::move(embeddedViewParams2)]; + + flutter::SurfaceFrame::FramebufferInfo framebuffer_info; + auto mock_surface = std::make_unique( + nullptr, framebuffer_info, + [](const flutter::SurfaceFrame& surface_frame, flutter::DlCanvas* canvas) { return true; }, + [](const flutter::SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600), nullptr, /*display_list_fallback=*/true); + XCTAssertTrue([flutterPlatformViewsController + submitFrame:std::move(mock_surface) + withIosContext:std::make_shared()]); + + // platform view is wrapped by touch interceptor, which itself is wrapped by clipping view. + UIView* clippingView1 = view1.superview.superview; + UIView* clippingView2 = view2.superview.superview; + XCTAssertTrue([flutterView.subviews indexOfObject:clippingView1] < + [flutterView.subviews indexOfObject:clippingView2], + @"The first clipping view should be added before the second clipping view."); + + // Need to recreate these params since they are `std::move`ed. + [flutterPlatformViewsController beginFrameWithSize:SkISize::Make(300, 300)]; + // Process the second frame in the opposite order. + embeddedViewParams2 = std::make_unique( + flutter::ToSkMatrix(finalMatrix), SkSize::Make(500, 500), stack); + [flutterPlatformViewsController prerollCompositeEmbeddedView:1 + withParams:std::move(embeddedViewParams2)]; + + embeddedViewParams1 = std::make_unique( + flutter::ToSkMatrix(finalMatrix), SkSize::Make(300, 300), stack); + [flutterPlatformViewsController prerollCompositeEmbeddedView:0 + withParams:std::move(embeddedViewParams1)]; + + mock_surface = std::make_unique( + nullptr, framebuffer_info, + [](const flutter::SurfaceFrame& surface_frame, flutter::DlCanvas* canvas) { return true; }, + [](const flutter::SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600), nullptr, /*display_list_fallback=*/true); + XCTAssertTrue([flutterPlatformViewsController + submitFrame:std::move(mock_surface) + withIosContext:std::make_shared()]); + + XCTAssertTrue([flutterView.subviews indexOfObject:clippingView1] > + [flutterView.subviews indexOfObject:clippingView2], + @"The first clipping view should be added after the second clipping view."); +} + +- (void) + testFlutterPlatformViewControllerSubmitFrameShouldOrderSubviewsCorrectlyWithSameViewHierarchy { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; + flutterPlatformViewsController.flutterView = flutterView; + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @0, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + UIView* view1 = gMockPlatformView; + + // This overwrites `gMockPlatformView` to another view. + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @1, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + UIView* view2 = gMockPlatformView; + + [flutterPlatformViewsController beginFrameWithSize:SkISize::Make(300, 300)]; + flutter::MutatorsStack stack; + flutter::DlMatrix finalMatrix; + auto embeddedViewParams1 = std::make_unique( + flutter::ToSkMatrix(finalMatrix), SkSize::Make(300, 300), stack); + [flutterPlatformViewsController prerollCompositeEmbeddedView:0 + withParams:std::move(embeddedViewParams1)]; + + auto embeddedViewParams2 = std::make_unique( + flutter::ToSkMatrix(finalMatrix), SkSize::Make(500, 500), stack); + [flutterPlatformViewsController prerollCompositeEmbeddedView:1 + withParams:std::move(embeddedViewParams2)]; + + flutter::SurfaceFrame::FramebufferInfo framebuffer_info; + auto mock_surface = std::make_unique( + nullptr, framebuffer_info, + [](const flutter::SurfaceFrame& surface_frame, flutter::DlCanvas* canvas) { return true; }, + [](const flutter::SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600), nullptr, /*display_list_fallback=*/true); + XCTAssertTrue([flutterPlatformViewsController + submitFrame:std::move(mock_surface) + withIosContext:std::make_shared()]); + + // platform view is wrapped by touch interceptor, which itself is wrapped by clipping view. + UIView* clippingView1 = view1.superview.superview; + UIView* clippingView2 = view2.superview.superview; + XCTAssertTrue([flutterView.subviews indexOfObject:clippingView1] < + [flutterView.subviews indexOfObject:clippingView2], + @"The first clipping view should be added before the second clipping view."); + + // Need to recreate these params since they are `std::move`ed. + [flutterPlatformViewsController beginFrameWithSize:SkISize::Make(300, 300)]; + // Process the second frame in the same order. + embeddedViewParams1 = std::make_unique( + flutter::ToSkMatrix(finalMatrix), SkSize::Make(300, 300), stack); + [flutterPlatformViewsController prerollCompositeEmbeddedView:0 + withParams:std::move(embeddedViewParams1)]; + + embeddedViewParams2 = std::make_unique( + flutter::ToSkMatrix(finalMatrix), SkSize::Make(500, 500), stack); + [flutterPlatformViewsController prerollCompositeEmbeddedView:1 + withParams:std::move(embeddedViewParams2)]; + + mock_surface = std::make_unique( + nullptr, framebuffer_info, + [](const flutter::SurfaceFrame& surface_frame, flutter::DlCanvas* canvas) { return true; }, + [](const flutter::SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600), nullptr, /*display_list_fallback=*/true); + XCTAssertTrue([flutterPlatformViewsController + submitFrame:std::move(mock_surface) + withIosContext:std::make_shared()]); + + XCTAssertTrue([flutterView.subviews indexOfObject:clippingView1] < + [flutterView.subviews indexOfObject:clippingView2], + @"The first clipping view should be added before the second clipping view."); +} + +- (int)alphaOfPoint:(CGPoint)point onView:(UIView*)view { + unsigned char pixel[4] = {0}; + + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + + // Draw the pixel on `point` in the context. + CGContextRef context = CGBitmapContextCreate( + pixel, 1, 1, 8, 4, colorSpace, kCGBitmapAlphaInfoMask & kCGImageAlphaPremultipliedLast); + CGContextTranslateCTM(context, -point.x, -point.y); + [view.layer renderInContext:context]; + + CGContextRelease(context); + CGColorSpaceRelease(colorSpace); + // Get the alpha from the pixel that we just rendered. + return pixel[3]; +} + +- (void)testHasFirstResponderInViewHierarchySubtree_viewItselfBecomesFirstResponder { + // For view to become the first responder, it must be a descendant of a UIWindow + UIWindow* window = [[UIWindow alloc] init]; + UITextField* textField = [[UITextField alloc] init]; + [window addSubview:textField]; + + [textField becomeFirstResponder]; + XCTAssertTrue(textField.isFirstResponder); + XCTAssertTrue(textField.flt_hasFirstResponderInViewHierarchySubtree); + [textField resignFirstResponder]; + XCTAssertFalse(textField.isFirstResponder); + XCTAssertFalse(textField.flt_hasFirstResponderInViewHierarchySubtree); +} + +- (void)testHasFirstResponderInViewHierarchySubtree_descendantViewBecomesFirstResponder { + // For view to become the first responder, it must be a descendant of a UIWindow + UIWindow* window = [[UIWindow alloc] init]; + UIView* view = [[UIView alloc] init]; + UIView* childView = [[UIView alloc] init]; + UITextField* textField = [[UITextField alloc] init]; + [window addSubview:view]; + [view addSubview:childView]; + [childView addSubview:textField]; + + [textField becomeFirstResponder]; + XCTAssertTrue(textField.isFirstResponder); + XCTAssertTrue(view.flt_hasFirstResponderInViewHierarchySubtree); + [textField resignFirstResponder]; + XCTAssertFalse(textField.isFirstResponder); + XCTAssertFalse(view.flt_hasFirstResponderInViewHierarchySubtree); +} + +- (void)testFlutterClippingMaskViewPoolReuseViewsAfterRecycle { + FlutterClippingMaskViewPool* pool = [[FlutterClippingMaskViewPool alloc] initWithCapacity:2]; + FlutterClippingMaskView* view1 = [pool getMaskViewWithFrame:CGRectZero]; + FlutterClippingMaskView* view2 = [pool getMaskViewWithFrame:CGRectZero]; + [pool insertViewToPoolIfNeeded:view1]; + [pool insertViewToPoolIfNeeded:view2]; + CGRect newRect = CGRectMake(0, 0, 10, 10); + FlutterClippingMaskView* view3 = [pool getMaskViewWithFrame:newRect]; + FlutterClippingMaskView* view4 = [pool getMaskViewWithFrame:newRect]; + // view3 and view4 should randomly get either of view1 and view2. + NSSet* set1 = [NSSet setWithObjects:view1, view2, nil]; + NSSet* set2 = [NSSet setWithObjects:view3, view4, nil]; + XCTAssertEqualObjects(set1, set2); + XCTAssertTrue(CGRectEqualToRect(view3.frame, newRect)); + XCTAssertTrue(CGRectEqualToRect(view4.frame, newRect)); +} + +- (void)testFlutterClippingMaskViewPoolAllocsNewMaskViewsAfterReachingCapacity { + FlutterClippingMaskViewPool* pool = [[FlutterClippingMaskViewPool alloc] initWithCapacity:2]; + FlutterClippingMaskView* view1 = [pool getMaskViewWithFrame:CGRectZero]; + FlutterClippingMaskView* view2 = [pool getMaskViewWithFrame:CGRectZero]; + FlutterClippingMaskView* view3 = [pool getMaskViewWithFrame:CGRectZero]; + XCTAssertNotEqual(view1, view3); + XCTAssertNotEqual(view2, view3); +} + +- (void)testMaskViewsReleasedWhenPoolIsReleased { + __weak UIView* weakView; + @autoreleasepool { + FlutterClippingMaskViewPool* pool = [[FlutterClippingMaskViewPool alloc] initWithCapacity:2]; + FlutterClippingMaskView* view = [pool getMaskViewWithFrame:CGRectZero]; + weakView = view; + XCTAssertNotNil(weakView); + } + XCTAssertNil(weakView); +} + +- (void)testClipMaskViewIsReused { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @1, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; + flutterPlatformViewsController.flutterView = flutterView; + // Create embedded view params + flutter::MutatorsStack stack1; + // Layer tree always pushes a screen scale factor to the stack + flutter::DlScalar screenScale = [UIScreen mainScreen].scale; + flutter::DlMatrix screenScaleMatrix = flutter::DlMatrix::MakeScale({screenScale, screenScale, 1}); + stack1.PushTransform(screenScaleMatrix); + // Push a clip rect + flutter::DlRect rect = flutter::DlRect::MakeXYWH(2, 2, 3, 3); + stack1.PushClipRect(rect); + + auto embeddedViewParams1 = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack1); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:1 + withParams:std::move(embeddedViewParams1)]; + [flutterPlatformViewsController + compositeView:1 + withParams:[flutterPlatformViewsController compositionParamsForView:1]]; + + UIView* childClippingView1 = gMockPlatformView.superview.superview; + UIView* maskView1 = childClippingView1.maskView; + XCTAssertNotNil(maskView1); + + // Composite a new frame. + [flutterPlatformViewsController beginFrameWithSize:SkISize::Make(100, 100)]; + flutter::MutatorsStack stack2; + auto embeddedViewParams2 = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack2); + auto embeddedViewParams3 = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack2); + [flutterPlatformViewsController prerollCompositeEmbeddedView:1 + withParams:std::move(embeddedViewParams3)]; + [flutterPlatformViewsController + compositeView:1 + withParams:[flutterPlatformViewsController compositionParamsForView:1]]; + + childClippingView1 = gMockPlatformView.superview.superview; + + // This overrides gMockPlatformView to point to the newly created platform view. + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + auto embeddedViewParams4 = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack1); + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams4)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + UIView* childClippingView2 = gMockPlatformView.superview.superview; + + UIView* maskView2 = childClippingView2.maskView; + XCTAssertEqual(maskView1, maskView2); + XCTAssertNotNil(childClippingView2.maskView); + XCTAssertNil(childClippingView1.maskView); +} + +- (void)testDifferentClipMaskViewIsUsedForEachView { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @1, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + UIView* view1 = gMockPlatformView; + + // This overwrites `gMockPlatformView` to another view. + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + UIView* view2 = gMockPlatformView; + + XCTAssertNotNil(gMockPlatformView); + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; + flutterPlatformViewsController.flutterView = flutterView; + // Create embedded view params + flutter::MutatorsStack stack1; + // Layer tree always pushes a screen scale factor to the stack + flutter::DlScalar screenScale = [UIScreen mainScreen].scale; + flutter::DlMatrix screenScaleMatrix = flutter::DlMatrix::MakeScale({screenScale, screenScale, 1}); + stack1.PushTransform(screenScaleMatrix); + // Push a clip rect + flutter::DlRect rect = flutter::DlRect::MakeXYWH(2, 2, 3, 3); + stack1.PushClipRect(rect); + + auto embeddedViewParams1 = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack1); + + flutter::MutatorsStack stack2; + stack2.PushClipRect(rect); + auto embeddedViewParams2 = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack2); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:1 + withParams:std::move(embeddedViewParams1)]; + [flutterPlatformViewsController + compositeView:1 + withParams:[flutterPlatformViewsController compositionParamsForView:1]]; + + UIView* childClippingView1 = view1.superview.superview; + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams2)]; + [flutterPlatformViewsController + compositeView:2 + withParams:[flutterPlatformViewsController compositionParamsForView:2]]; + + UIView* childClippingView2 = view2.superview.superview; + UIView* maskView1 = childClippingView1.maskView; + UIView* maskView2 = childClippingView2.maskView; + XCTAssertNotEqual(maskView1, maskView2); +} + +- (void)testMaskViewUsesCAShapeLayerAsTheBackingLayer { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @1, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + XCTAssertNotNil(gMockPlatformView); + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; + flutterPlatformViewsController.flutterView = flutterView; + // Create embedded view params + flutter::MutatorsStack stack1; + // Layer tree always pushes a screen scale factor to the stack + flutter::DlScalar screenScale = [UIScreen mainScreen].scale; + flutter::DlMatrix screenScaleMatrix = flutter::DlMatrix::MakeScale({screenScale, screenScale, 1}); + stack1.PushTransform(screenScaleMatrix); + // Push a clip rect + flutter::DlRect rect = flutter::DlRect::MakeXYWH(2, 2, 3, 3); + stack1.PushClipRect(rect); + + auto embeddedViewParams1 = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack1); + + flutter::MutatorsStack stack2; + stack2.PushClipRect(rect); + auto embeddedViewParams2 = std::make_unique( + flutter::ToSkMatrix(screenScaleMatrix), SkSize::Make(10, 10), stack2); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:1 + withParams:std::move(embeddedViewParams1)]; + [flutterPlatformViewsController + compositeView:1 + withParams:[flutterPlatformViewsController compositionParamsForView:1]]; + + UIView* childClippingView = gMockPlatformView.superview.superview; + + UIView* maskView = childClippingView.maskView; + XCTAssert([maskView.layer isKindOfClass:[CAShapeLayer class]], + @"Mask view must use CAShapeLayer as its backing layer."); +} + +// Return true if a correct visual effect view is found. It also implies all the validation in this +// method passes. +// +// There are two fail states for this method. 1. One of the XCTAssert method failed; or 2. No +// correct visual effect view found. +- (BOOL)validateOneVisualEffectView:(UIView*)visualEffectView + expectedFrame:(CGRect)frame + inputRadius:(CGFloat)inputRadius { + XCTAssertTrue(CGRectEqualToRect(visualEffectView.frame, frame)); + for (UIView* view in visualEffectView.subviews) { + if (![NSStringFromClass([view class]) hasSuffix:@"BackdropView"]) { + continue; + } + XCTAssertEqual(view.layer.filters.count, 1u); + NSObject* filter = view.layer.filters.firstObject; + + XCTAssertEqualObjects([filter valueForKey:@"name"], @"gaussianBlur"); + + NSObject* inputRadiusInFilter = [filter valueForKey:@"inputRadius"]; + XCTAssertTrue([inputRadiusInFilter isKindOfClass:[NSNumber class]] && + flutter::BlurRadiusEqualToBlurRadius(((NSNumber*)inputRadiusInFilter).floatValue, + inputRadius)); + return YES; + } + return NO; +} + +- (void)testDisposingViewInCompositionOrderDoNotCrash { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; + flutterPlatformViewsController.flutterView = flutterView; + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @0, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @1, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + { + // **** First frame, view id 0, 1 in the composition_order_, disposing view 0 is called. **** // + // No view should be disposed, or removed from the composition order. + [flutterPlatformViewsController beginFrameWithSize:SkISize::Make(300, 300)]; + flutter::MutatorsStack stack; + flutter::DlMatrix finalMatrix; + auto embeddedViewParams0 = std::make_unique( + flutter::ToSkMatrix(finalMatrix), SkSize::Make(300, 300), stack); + [flutterPlatformViewsController prerollCompositeEmbeddedView:0 + withParams:std::move(embeddedViewParams0)]; + + auto embeddedViewParams1 = std::make_unique( + flutter::ToSkMatrix(finalMatrix), SkSize::Make(300, 300), stack); + [flutterPlatformViewsController prerollCompositeEmbeddedView:1 + withParams:std::move(embeddedViewParams1)]; + + XCTAssertEqual(flutterPlatformViewsController.embeddedViewCount, 2UL); + + XCTestExpectation* expectation = [self expectationWithDescription:@"dispose call ended."]; + FlutterResult disposeResult = ^(id result) { + [expectation fulfill]; + }; + + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"dispose" arguments:@0] + result:disposeResult]; + [self waitForExpectationsWithTimeout:30 handler:nil]; + + flutter::SurfaceFrame::FramebufferInfo framebuffer_info; + auto mock_surface = std::make_unique( + nullptr, framebuffer_info, + [](const flutter::SurfaceFrame& surface_frame, flutter::DlCanvas* canvas) { return true; }, + [](const flutter::SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600), nullptr, + /*display_list_fallback=*/true); + XCTAssertTrue([flutterPlatformViewsController + submitFrame:std::move(mock_surface) + withIosContext:std::make_shared()]); + + // Disposing won't remove embedded views until the view is removed from the composition_order_ + XCTAssertEqual(flutterPlatformViewsController.embeddedViewCount, 2UL); + XCTAssertNotNil([flutterPlatformViewsController platformViewForId:0]); + XCTAssertNotNil([flutterPlatformViewsController platformViewForId:1]); + } + + { + // **** Second frame, view id 1 in the composition_order_, no disposing view is called, **** // + // View 0 is removed from the composition order in this frame, hence also disposed. + [flutterPlatformViewsController beginFrameWithSize:SkISize::Make(300, 300)]; + flutter::MutatorsStack stack; + flutter::DlMatrix finalMatrix; + auto embeddedViewParams1 = std::make_unique( + flutter::ToSkMatrix(finalMatrix), SkSize::Make(300, 300), stack); + [flutterPlatformViewsController prerollCompositeEmbeddedView:1 + withParams:std::move(embeddedViewParams1)]; + + flutter::SurfaceFrame::FramebufferInfo framebuffer_info; + auto mock_surface = std::make_unique( + nullptr, framebuffer_info, + [](const flutter::SurfaceFrame& surface_frame, flutter::DlCanvas* canvas) { return true; }, + [](const flutter::SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600), nullptr, /*display_list_fallback=*/true); + XCTAssertTrue([flutterPlatformViewsController + submitFrame:std::move(mock_surface) + withIosContext:std::make_shared()]); + + // Disposing won't remove embedded views until the view is removed from the composition_order_ + XCTAssertEqual(flutterPlatformViewsController.embeddedViewCount, 1UL); + XCTAssertNil([flutterPlatformViewsController platformViewForId:0]); + XCTAssertNotNil([flutterPlatformViewsController platformViewForId:1]); + } +} +- (void)testOnlyPlatformViewsAreRemovedWhenReset { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; + flutterPlatformViewsController.flutterView = flutterView; + // Create embedded view params + flutter::MutatorsStack stack; + // Layer tree always pushes a screen scale factor to the stack + flutter::DlScalar screenScale = [UIScreen mainScreen].scale; + flutter::DlMatrix screenScaleMatrix = flutter::DlMatrix::MakeScale({screenScale, screenScale, 1}); + stack.PushTransform(screenScaleMatrix); + // Push a translate matrix + flutter::DlMatrix translateMatrix = flutter::DlMatrix::MakeTranslation({100, 100}); + stack.PushTransform(translateMatrix); + flutter::DlMatrix finalMatrix = screenScaleMatrix * translateMatrix; + + auto embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(finalMatrix), SkSize::Make(300, 300), stack); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + + flutter::SurfaceFrame::FramebufferInfo framebuffer_info; + auto mock_surface = std::make_unique( + nullptr, framebuffer_info, + [](const flutter::SurfaceFrame& surface_frame, flutter::DlCanvas* canvas) { return true; }, + [](const flutter::SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600), nullptr, /*display_list_fallback=*/true); + [flutterPlatformViewsController submitFrame:std::move(mock_surface) + withIosContext:std::make_shared()]; + + UIView* someView = [[UIView alloc] init]; + [flutterView addSubview:someView]; + + [flutterPlatformViewsController reset]; + XCTAssertEqual(flutterView.subviews.count, 1u); + XCTAssertEqual(flutterView.subviews.firstObject, someView); +} + +- (void)testResetClearsPreviousCompositionOrder { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; + flutterPlatformViewsController.flutterView = flutterView; + // Create embedded view params + flutter::MutatorsStack stack; + // Layer tree always pushes a screen scale factor to the stack + flutter::DlScalar screenScale = [UIScreen mainScreen].scale; + flutter::DlMatrix screenScaleMatrix = flutter::DlMatrix::MakeScale({screenScale, screenScale, 1}); + stack.PushTransform(screenScaleMatrix); + // Push a translate matrix + flutter::DlMatrix translateMatrix = flutter::DlMatrix::MakeTranslation({100, 100}); + stack.PushTransform(translateMatrix); + flutter::DlMatrix finalMatrix = screenScaleMatrix * translateMatrix; + + auto embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(finalMatrix), SkSize::Make(300, 300), stack); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + + flutter::SurfaceFrame::FramebufferInfo framebuffer_info; + auto mock_surface = std::make_unique( + nullptr, framebuffer_info, + [](const flutter::SurfaceFrame& surface_frame, flutter::DlCanvas* canvas) { return true; }, + [](const flutter::SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600), nullptr, /*display_list_fallback=*/true); + [flutterPlatformViewsController submitFrame:std::move(mock_surface) + withIosContext:std::make_shared()]; + + // The above code should result in previousCompositionOrder having one viewId in it + XCTAssertEqual(flutterPlatformViewsController.previousCompositionOrder.size(), 1ul); + + // reset should clear previousCompositionOrder + [flutterPlatformViewsController reset]; + + // previousCompositionOrder should now be empty + XCTAssertEqual(flutterPlatformViewsController.previousCompositionOrder.size(), 0ul); +} + +- (void)testNilPlatformViewDoesntCrash { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + FlutterPlatformViewsTestNilFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestNilFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; + flutterPlatformViewsController.flutterView = flutterView; + + // Create embedded view params + flutter::MutatorsStack stack; + // Layer tree always pushes a screen scale factor to the stack + flutter::DlScalar screenScale = [UIScreen mainScreen].scale; + flutter::DlMatrix screenScaleMatrix = flutter::DlMatrix::MakeScale({screenScale, screenScale, 1}); + stack.PushTransform(screenScaleMatrix); + // Push a translate matrix + flutter::DlMatrix translateMatrix = flutter::DlMatrix::MakeTranslation({100, 100}); + stack.PushTransform(translateMatrix); + flutter::DlMatrix finalMatrix = screenScaleMatrix * translateMatrix; + + auto embeddedViewParams = std::make_unique( + flutter::ToSkMatrix(finalMatrix), SkSize::Make(300, 300), stack); + + [flutterPlatformViewsController prerollCompositeEmbeddedView:2 + withParams:std::move(embeddedViewParams)]; + + flutter::SurfaceFrame::FramebufferInfo framebuffer_info; + auto mock_surface = std::make_unique( + nullptr, framebuffer_info, + [](const flutter::SurfaceFrame& surface_frame, flutter::DlCanvas* canvas) { return true; }, + [](const flutter::SurfaceFrame& surface_frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600), nullptr, /*display_list_fallback=*/true); + [flutterPlatformViewsController submitFrame:std::move(mock_surface) + withIosContext:std::make_shared()]; + + XCTAssertEqual(flutterView.subviews.count, 1u); +} + +- (void)testFlutterTouchInterceptingViewLinksToAccessibilityContainer { + FlutterTouchInterceptingView* touchInteceptorView = [[FlutterTouchInterceptingView alloc] init]; + NSObject* container = [[NSObject alloc] init]; + [touchInteceptorView setFlutterAccessibilityContainer:container]; + XCTAssertEqualObjects([touchInteceptorView accessibilityContainer], container); +} + +- (void)testLayerPool { + // Create an IOSContext. + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar"]; + [engine run]; + XCTAssertTrue(engine.platformView != nullptr); + auto ios_context = engine.platformView->GetIosContext(); + + auto pool = flutter::OverlayLayerPool{}; + + // Add layers to the pool. + pool.CreateLayer(ios_context, MTLPixelFormatBGRA8Unorm); + XCTAssertEqual(pool.size(), 1u); + pool.CreateLayer(ios_context, MTLPixelFormatBGRA8Unorm); + XCTAssertEqual(pool.size(), 2u); + + // Mark all layers as unused. + pool.RecycleLayers(); + XCTAssertEqual(pool.size(), 2u); + + // Free the unused layers. One should remain. + auto unused_layers = pool.RemoveUnusedLayers(); + XCTAssertEqual(unused_layers.size(), 2u); + XCTAssertEqual(pool.size(), 1u); +} + +- (void)testFlutterPlatformViewControllerSubmitFramePreservingFrameDamage { + flutter::FlutterPlatformViewsTestMockPlatformViewDelegate mock_delegate; + + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/GetDefaultTaskRunner(), + /*raster=*/GetDefaultTaskRunner(), + /*ui=*/GetDefaultTaskRunner(), + /*io=*/GetDefaultTaskRunner()); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = GetDefaultTaskRunner(); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_jsync_switch=*/std::make_shared()); + + UIView* flutterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; + flutterPlatformViewsController.flutterView = flutterView; + + FlutterPlatformViewsTestMockFlutterPlatformFactory* factory = + [[FlutterPlatformViewsTestMockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @0, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + // This overwrites `gMockPlatformView` to another view. + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @1, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + [flutterPlatformViewsController beginFrameWithSize:SkISize::Make(300, 300)]; + flutter::MutatorsStack stack; + flutter::DlMatrix finalMatrix; + auto embeddedViewParams1 = std::make_unique( + flutter::ToSkMatrix(finalMatrix), SkSize::Make(300, 300), stack); + [flutterPlatformViewsController prerollCompositeEmbeddedView:0 + withParams:std::move(embeddedViewParams1)]; + + auto embeddedViewParams2 = std::make_unique( + flutter::ToSkMatrix(finalMatrix), SkSize::Make(500, 500), stack); + [flutterPlatformViewsController prerollCompositeEmbeddedView:1 + withParams:std::move(embeddedViewParams2)]; + + flutter::SurfaceFrame::FramebufferInfo framebuffer_info; + std::optional submit_info; + auto mock_surface = std::make_unique( + nullptr, framebuffer_info, + [](const flutter::SurfaceFrame& surface_frame, flutter::DlCanvas* canvas) { return true; }, + [&](const flutter::SurfaceFrame& surface_frame) { + submit_info = surface_frame.submit_info(); + return true; + }, + /*frame_size=*/SkISize::Make(800, 600), nullptr, + /*display_list_fallback=*/true); + mock_surface->set_submit_info({ + .frame_damage = SkIRect::MakeWH(800, 600), + .buffer_damage = SkIRect::MakeWH(400, 600), + }); + + [flutterPlatformViewsController submitFrame:std::move(mock_surface) + withIosContext:std::make_shared()]; + + XCTAssertTrue(submit_info.has_value()); + XCTAssertEqual(*submit_info->frame_damage, SkIRect::MakeWH(800, 600)); + XCTAssertEqual(*submit_info->buffer_damage, SkIRect::MakeWH(400, 600)); +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h new file mode 100644 index 0000000000000000000000000000000000000000..be0a92cbe8d7ffa5337fce522ad942781768a42d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h @@ -0,0 +1,197 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMVIEWS_INTERNAL_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMVIEWS_INTERNAL_H_ + +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterPlatformViews.h" + +#include + +#include "flutter/flow/surface.h" +#include "flutter/fml/memory/weak_ptr.h" +#include "flutter/fml/task_runner.h" +#include "flutter/fml/trace_event.h" +#include "flutter/impeller/base/thread_safety.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterPlugin.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViewsController.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewResponder.h" +#include "flutter/shell/platform/darwin/ios/ios_context.h" + +// A UIView that acts as a clipping mask for the |ChildClippingView|. +// +// On the [UIView drawRect:] method, this view performs a series of clipping operations and sets the +// alpha channel to the final resulting area to be 1; it also sets the "clipped out" area's alpha +// channel to be 0. +// +// When a UIView sets a |FlutterClippingMaskView| as its `maskView`, the alpha channel of the UIView +// is replaced with the alpha channel of the |FlutterClippingMaskView|. +@interface FlutterClippingMaskView : UIView + +- (instancetype)initWithFrame:(CGRect)frame screenScale:(CGFloat)screenScale; + +- (void)reset; + +// Adds a clip rect operation to the queue. +// +// The `clipSkRect` is transformed with the `matrix` before adding to the queue. +- (void)clipRect:(const flutter::DlRect&)clipDlRect matrix:(const flutter::DlMatrix&)matrix; + +// Adds a clip rrect operation to the queue. +// +// The `clipSkRRect` is transformed with the `matrix` before adding to the queue. +- (void)clipRRect:(const flutter::DlRoundRect&)clipDlRRect matrix:(const flutter::DlMatrix&)matrix; + +// Adds a clip path operation to the queue. +// +// The `path` is transformed with the `matrix` before adding to the queue. +- (void)clipPath:(const flutter::DlPath&)path matrix:(const flutter::DlMatrix&)matrix; + +@end + +// A pool that provides |FlutterClippingMaskView|s. +// +// The pool has a capacity that can be set in the initializer. +// When requesting a FlutterClippingMaskView, the pool will first try to reuse an available maskView +// in the pool. If there are none available, a new FlutterClippingMaskView is constructed. If the +// capacity is reached, the newly constructed FlutterClippingMaskView is not added to the pool. +// +// Call |insertViewToPoolIfNeeded:| to return a maskView to the pool. +@interface FlutterClippingMaskViewPool : NSObject + +// Initialize the pool with `capacity`. When the `capacity` is reached, a FlutterClippingMaskView is +// constructed when requested, and it is not added to the pool. +- (instancetype)initWithCapacity:(NSInteger)capacity; + +// Reuse a maskView from the pool, or allocate a new one. +- (FlutterClippingMaskView*)getMaskViewWithFrame:(CGRect)frame; + +// Insert the `maskView` into the pool. +- (void)insertViewToPoolIfNeeded:(FlutterClippingMaskView*)maskView; + +@end + +// An object represents a blur filter. +// +// This object produces a `backdropFilterView`. +// To blur a View, add `backdropFilterView` as a subView of the View. +@interface PlatformViewFilter : NSObject + +// Determines the rect of the blur effect in the coordinate system of `backdropFilterView`'s +// parentView. +@property(nonatomic, readonly) CGRect frame; + +// Determines the blur intensity. +// +// It is set as the value of `inputRadius` of the `gaussianFilter` that is internally used. +@property(nonatomic, readonly) CGFloat blurRadius; + +// This is the view to use to blur the PlatformView. +// +// It is a modified version of UIKit's `UIVisualEffectView`. +// The inputRadius can be customized and it doesn't add any color saturation to the blurred view. +@property(nonatomic, readonly) UIVisualEffectView* backdropFilterView; + +// For testing only. ++ (void)resetPreparation; + +- (instancetype)init NS_UNAVAILABLE; + +// Initialize the filter object. +// +// The `frame` determines the rect of the blur effect in the coordinate system of +// `backdropFilterView`'s parentView. The `blurRadius` determines the blur intensity. It is set as +// the value of `inputRadius` of the `gaussianFilter` that is internally used. The +// `UIVisualEffectView` is the view that is used to add the blur effects. It is modified to become +// `backdropFilterView`, which better supports the need of Flutter. +// +// Note: if the implementation of UIVisualEffectView changes in a way that affects the +// implementation in `PlatformViewFilter`, this method will return nil. +- (instancetype)initWithFrame:(CGRect)frame + blurRadius:(CGFloat)blurRadius + visualEffectView:(UIVisualEffectView*)visualEffectView NS_DESIGNATED_INITIALIZER; + +@end + +// The parent view handles clipping to its subViews. +@interface ChildClippingView : UIView + +// Applies blur backdrop filters to the ChildClippingView with blur values from +// filters. +- (void)applyBlurBackdropFilters:(NSArray*)filters; + +// For testing only. +- (NSMutableArray*)backdropFilterSubviews; +@end + +// A UIView that is used as the parent for embedded UIViews. +// +// This view has 2 roles: +// 1. Delay or prevent touch events from arriving the embedded view. +// 2. Dispatching all events that are hittested to the embedded view to the FlutterView. +@interface FlutterTouchInterceptingView : UIView +- (instancetype)initWithEmbeddedView:(UIView*)embeddedView + platformViewsController:(FlutterPlatformViewsController*)platformViewsController + gestureRecognizersBlockingPolicy: + (FlutterPlatformViewGestureRecognizersBlockingPolicy)blockingPolicy; + +// Stop delaying any active touch sequence (and let it arrive the embedded view). +- (void)releaseGesture; + +// Prevent the touch sequence from ever arriving to the embedded view. +- (void)blockGesture; + +// Get embedded view +- (UIView*)embeddedView; + +// Sets flutterAccessibilityContainer as this view's accessibilityContainer. +@property(nonatomic, retain) id flutterAccessibilityContainer; +@end + +@interface UIView (FirstResponder) +// Returns YES if a view or any of its descendant view is the first responder. Returns NO otherwise. +@property(nonatomic, readonly) BOOL flt_hasFirstResponderInViewHierarchySubtree; +@end + +// This recognizer delays touch events from being dispatched to the responder chain until it failed +// recognizing a gesture. +// +// We only fail this recognizer when asked to do so by the Flutter framework (which does so by +// invoking an acceptGesture method on the platform_views channel). And this is how we allow the +// Flutter framework to delay or prevent the embedded view from getting a touch sequence. +@interface FlutterDelayingGestureRecognizer : UIGestureRecognizer + +// Indicates that if the `FlutterDelayingGestureRecognizer`'s state should be set to +// `UIGestureRecognizerStateEnded` during next `touchesEnded` call. +@property(nonatomic) BOOL shouldEndInNextTouchesEnded; + +// Indicates that the `FlutterDelayingGestureRecognizer`'s `touchesEnded` has been invoked without +// setting the state to `UIGestureRecognizerStateEnded`. +@property(nonatomic) BOOL touchedEndedWithoutBlocking; + +@property(nonatomic) UIGestureRecognizer* forwardingRecognizer; + +- (instancetype)initWithTarget:(id)target + action:(SEL)action + forwardingRecognizer:(UIGestureRecognizer*)forwardingRecognizer; +@end + +// While the FlutterDelayingGestureRecognizer is preventing touches from hitting the responder chain +// the touch events are not arriving to the FlutterView (and thus not arriving to the Flutter +// framework). We use this gesture recognizer to dispatch the events directly to the FlutterView +// while during this phase. +// +// If the Flutter framework decides to dispatch events to the embedded view, we fail the +// FlutterDelayingGestureRecognizer which sends the events up the responder chain. But since the +// events are handled by the embedded view they are not delivered to the Flutter framework in this +// phase as well. So during this phase as well the ForwardingGestureRecognizer dispatched the events +// directly to the FlutterView. +@interface ForwardingGestureRecognizer : UIGestureRecognizer +- (instancetype)initWithTarget:(id)target + platformViewsController:(FlutterPlatformViewsController*)platformViewsController; +- (ForwardingGestureRecognizer*)recreateRecognizerWithTarget:(id)target; +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMVIEWS_INTERNAL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegate.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegate.mm new file mode 100644 index 0000000000000000000000000000000000000000..7b9dcdf074f657d4039e25a210444c0a2e38d04b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegate.mm @@ -0,0 +1,435 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterPluginAppLifeCycleDelegate.h" + +#include "flutter/fml/logging.h" +#include "flutter/fml/paths.h" +#include "flutter/lib/ui/plugins/callback_cache.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterCallbackCache_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterSharedApplication.h" + +FLUTTER_ASSERT_ARC + +static const char* kCallbackCacheSubDir = "Library/Caches/"; + +static const SEL kSelectorsHandledByPlugins[] = { + @selector(application:didReceiveRemoteNotification:fetchCompletionHandler:), + @selector(application:performFetchWithCompletionHandler:)}; + +@interface FlutterPluginAppLifeCycleDelegate () +- (void)handleDidEnterBackground:(NSNotification*)notification + NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in app extensions"); +- (void)handleWillEnterForeground:(NSNotification*)notification + NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in app extensions"); +- (void)handleWillResignActive:(NSNotification*)notification + NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in app extensions"); +- (void)handleDidBecomeActive:(NSNotification*)notification + NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in app extensions"); +- (void)handleWillTerminate:(NSNotification*)notification + NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in app extensions"); +@end + +@implementation FlutterPluginAppLifeCycleDelegate { + UIBackgroundTaskIdentifier _debugBackgroundTask; + + // Weak references to registered plugins. + NSPointerArray* _delegates; +} + +- (void)addObserverFor:(NSString*)name selector:(SEL)selector { + [[NSNotificationCenter defaultCenter] addObserver:self selector:selector name:name object:nil]; +} + +- (instancetype)init { + if (self = [super init]) { + std::string cachePath = fml::paths::JoinPaths({getenv("HOME"), kCallbackCacheSubDir}); + [FlutterCallbackCache setCachePath:[NSString stringWithUTF8String:cachePath.c_str()]]; + if (FlutterSharedApplication.isAvailable) { + [self addObserverFor:UIApplicationDidEnterBackgroundNotification + selector:@selector(handleDidEnterBackground:)]; + [self addObserverFor:UIApplicationWillEnterForegroundNotification + selector:@selector(handleWillEnterForeground:)]; + [self addObserverFor:UIApplicationWillResignActiveNotification + selector:@selector(handleWillResignActive:)]; + [self addObserverFor:UIApplicationDidBecomeActiveNotification + selector:@selector(handleDidBecomeActive:)]; + [self addObserverFor:UIApplicationWillTerminateNotification + selector:@selector(handleWillTerminate:)]; + } + _delegates = [NSPointerArray weakObjectsPointerArray]; + _debugBackgroundTask = UIBackgroundTaskInvalid; + } + return self; +} + +static BOOL IsPowerOfTwo(NSUInteger x) { + return x != 0 && (x & (x - 1)) == 0; +} + +- (BOOL)isSelectorAddedDynamically:(SEL)selector { + for (const SEL& aSelector : kSelectorsHandledByPlugins) { + if (selector == aSelector) { + return YES; + } + } + return NO; +} + +- (BOOL)hasPluginThatRespondsToSelector:(SEL)selector { + for (NSObject* delegate in [_delegates allObjects]) { + if (!delegate) { + continue; + } + if ([delegate respondsToSelector:selector]) { + return YES; + } + } + return NO; +} + +- (void)addDelegate:(NSObject*)delegate { + [_delegates addPointer:(__bridge void*)delegate]; + if (IsPowerOfTwo([_delegates count])) { + [_delegates compact]; + } +} + +- (BOOL)application:(UIApplication*)application + didFinishLaunchingWithOptions:(NSDictionary*)launchOptions { + for (NSObject* delegate in [_delegates allObjects]) { + if (!delegate) { + continue; + } + if ([delegate respondsToSelector:_cmd]) { + if (![delegate application:application didFinishLaunchingWithOptions:launchOptions]) { + return NO; + } + } + } + return YES; +} + +- (BOOL)application:(UIApplication*)application + willFinishLaunchingWithOptions:(NSDictionary*)launchOptions { + flutter::DartCallbackCache::LoadCacheFromDisk(); + for (NSObject* delegate in [_delegates allObjects]) { + if (!delegate) { + continue; + } + if ([delegate respondsToSelector:_cmd]) { + if (![delegate application:application willFinishLaunchingWithOptions:launchOptions]) { + return NO; + } + } + } + return YES; +} + +- (void)handleDidEnterBackground:(NSNotification*)notification + NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in app extensions") { + UIApplication* application = [UIApplication sharedApplication]; +#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG + // The following keeps the Flutter session alive when the device screen locks + // in debug mode. It allows continued use of features like hot reload and + // taking screenshots once the device unlocks again. + // + // Note the name is not an identifier and multiple instances can exist. + _debugBackgroundTask = [application + beginBackgroundTaskWithName:@"Flutter debug task" + expirationHandler:^{ + if (_debugBackgroundTask != UIBackgroundTaskInvalid) { + [application endBackgroundTask:_debugBackgroundTask]; + _debugBackgroundTask = UIBackgroundTaskInvalid; + } + FML_LOG(WARNING) + << "\nThe OS has terminated the Flutter debug connection for being " + "inactive in the background for too long.\n\n" + "There are no errors with your Flutter application.\n\n" + "To reconnect, launch your application again via 'flutter run'"; + }]; +#endif // FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG + for (NSObject* delegate in _delegates) { + if (!delegate) { + continue; + } + if ([delegate respondsToSelector:@selector(applicationDidEnterBackground:)]) { + [delegate applicationDidEnterBackground:application]; + } + } +} + +- (void)handleWillEnterForeground:(NSNotification*)notification + NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in app extensions") { + UIApplication* application = [UIApplication sharedApplication]; +#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG + if (_debugBackgroundTask != UIBackgroundTaskInvalid) { + [application endBackgroundTask:_debugBackgroundTask]; + _debugBackgroundTask = UIBackgroundTaskInvalid; + } +#endif // FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG + for (NSObject* delegate in _delegates) { + if (!delegate) { + continue; + } + if ([delegate respondsToSelector:@selector(applicationWillEnterForeground:)]) { + [delegate applicationWillEnterForeground:application]; + } + } +} + +- (void)handleWillResignActive:(NSNotification*)notification + NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in app extensions") { + UIApplication* application = [UIApplication sharedApplication]; + for (NSObject* delegate in _delegates) { + if (!delegate) { + continue; + } + if ([delegate respondsToSelector:@selector(applicationWillResignActive:)]) { + [delegate applicationWillResignActive:application]; + } + } +} + +- (void)handleDidBecomeActive:(NSNotification*)notification + NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in app extensions") { + UIApplication* application = [UIApplication sharedApplication]; + for (NSObject* delegate in _delegates) { + if (!delegate) { + continue; + } + if ([delegate respondsToSelector:@selector(applicationDidBecomeActive:)]) { + [delegate applicationDidBecomeActive:application]; + } + } +} + +- (void)handleWillTerminate:(NSNotification*)notification + NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in app extensions") { + UIApplication* application = [UIApplication sharedApplication]; + for (NSObject* delegate in _delegates) { + if (!delegate) { + continue; + } + if ([delegate respondsToSelector:@selector(applicationWillTerminate:)]) { + [delegate applicationWillTerminate:application]; + } + } +} + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +- (void)application:(UIApplication*)application + didRegisterUserNotificationSettings:(UIUserNotificationSettings*)notificationSettings { + for (NSObject* delegate in _delegates) { + if (!delegate) { + continue; + } + if ([delegate respondsToSelector:_cmd]) { + [delegate application:application didRegisterUserNotificationSettings:notificationSettings]; + } + } +} +#pragma GCC diagnostic pop + +- (void)application:(UIApplication*)application + didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken { + for (NSObject* delegate in _delegates) { + if (!delegate) { + continue; + } + if ([delegate respondsToSelector:_cmd]) { + [delegate application:application + didRegisterForRemoteNotificationsWithDeviceToken:deviceToken]; + } + } +} + +- (void)application:(UIApplication*)application + didFailToRegisterForRemoteNotificationsWithError:(NSError*)error { + for (NSObject* delegate in _delegates) { + if (!delegate) { + continue; + } + if ([delegate respondsToSelector:_cmd]) { + [delegate application:application didFailToRegisterForRemoteNotificationsWithError:error]; + } + } +} + +- (void)application:(UIApplication*)application + didReceiveRemoteNotification:(NSDictionary*)userInfo + fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler { + for (NSObject* delegate in _delegates) { + if (!delegate) { + continue; + } + if ([delegate respondsToSelector:_cmd]) { + if ([delegate application:application + didReceiveRemoteNotification:userInfo + fetchCompletionHandler:completionHandler]) { + return; + } + } + } +} + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +- (void)application:(UIApplication*)application + didReceiveLocalNotification:(UILocalNotification*)notification { + for (NSObject* delegate in _delegates) { + if (!delegate) { + continue; + } + if ([delegate respondsToSelector:_cmd]) { + [delegate application:application didReceiveLocalNotification:notification]; + } + } +} +#pragma GCC diagnostic pop + +- (void)userNotificationCenter:(UNUserNotificationCenter*)center + willPresentNotification:(UNNotification*)notification + withCompletionHandler: + (void (^)(UNNotificationPresentationOptions options))completionHandler { + for (NSObject* delegate in _delegates) { + if ([delegate respondsToSelector:_cmd]) { + [delegate userNotificationCenter:center + willPresentNotification:notification + withCompletionHandler:completionHandler]; + } + } +} + +- (void)userNotificationCenter:(UNUserNotificationCenter*)center + didReceiveNotificationResponse:(UNNotificationResponse*)response + withCompletionHandler:(void (^)(void))completionHandler { + for (id delegate in _delegates) { + if ([delegate respondsToSelector:_cmd]) { + [delegate userNotificationCenter:center + didReceiveNotificationResponse:response + withCompletionHandler:completionHandler]; + } + } +} + +- (BOOL)application:(UIApplication*)application + openURL:(NSURL*)url + options:(NSDictionary*)options { + for (NSObject* delegate in _delegates) { + if (!delegate) { + continue; + } + if ([delegate respondsToSelector:_cmd]) { + if ([delegate application:application openURL:url options:options]) { + return YES; + } + } + } + return NO; +} + +- (BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)url { + for (NSObject* delegate in _delegates) { + if (!delegate) { + continue; + } + if ([delegate respondsToSelector:_cmd]) { + if ([delegate application:application handleOpenURL:url]) { + return YES; + } + } + } + return NO; +} + +- (BOOL)application:(UIApplication*)application + openURL:(NSURL*)url + sourceApplication:(NSString*)sourceApplication + annotation:(id)annotation { + for (NSObject* delegate in _delegates) { + if (!delegate) { + continue; + } + if ([delegate respondsToSelector:_cmd]) { + if ([delegate application:application + openURL:url + sourceApplication:sourceApplication + annotation:annotation]) { + return YES; + } + } + } + return NO; +} + +- (void)application:(UIApplication*)application + performActionForShortcutItem:(UIApplicationShortcutItem*)shortcutItem + completionHandler:(void (^)(BOOL succeeded))completionHandler { + for (NSObject* delegate in _delegates) { + if (!delegate) { + continue; + } + if ([delegate respondsToSelector:_cmd]) { + if ([delegate application:application + performActionForShortcutItem:shortcutItem + completionHandler:completionHandler]) { + return; + } + } + } +} + +- (BOOL)application:(UIApplication*)application + handleEventsForBackgroundURLSession:(nonnull NSString*)identifier + completionHandler:(nonnull void (^)())completionHandler { + for (NSObject* delegate in _delegates) { + if (!delegate) { + continue; + } + if ([delegate respondsToSelector:_cmd]) { + if ([delegate application:application + handleEventsForBackgroundURLSession:identifier + completionHandler:completionHandler]) { + return YES; + } + } + } + return NO; +} + +- (BOOL)application:(UIApplication*)application + performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler { + for (NSObject* delegate in _delegates) { + if (!delegate) { + continue; + } + if ([delegate respondsToSelector:_cmd]) { + if ([delegate application:application performFetchWithCompletionHandler:completionHandler]) { + return YES; + } + } + } + return NO; +} + +- (BOOL)application:(UIApplication*)application + continueUserActivity:(NSUserActivity*)userActivity + restorationHandler:(void (^)(NSArray*))restorationHandler { + for (NSObject* delegate in _delegates) { + if (!delegate) { + continue; + } + if ([delegate respondsToSelector:_cmd]) { + if ([delegate application:application + continueUserActivity:userActivity + restorationHandler:restorationHandler]) { + return YES; + } + } + } + return NO; +} +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegateTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegateTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..e82861b24df32a7cb760e24c91f77fb60738c652 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegateTest.mm @@ -0,0 +1,112 @@ +// 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. + +#import +#import + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterPluginAppLifeCycleDelegate.h" + +FLUTTER_ASSERT_ARC + +@interface FakePlugin : NSObject +@end + +@implementation FakePlugin +@end + +@interface FlutterPluginAppLifeCycleDelegateTest : XCTestCase +@end + +@implementation FlutterPluginAppLifeCycleDelegateTest + +- (void)testCreate { + FlutterPluginAppLifeCycleDelegate* delegate = [[FlutterPluginAppLifeCycleDelegate alloc] init]; + XCTAssertNotNil(delegate); +} + +- (void)testDidEnterBackground { + XCTNSNotificationExpectation* expectation = [[XCTNSNotificationExpectation alloc] + initWithName:UIApplicationDidEnterBackgroundNotification]; + FlutterPluginAppLifeCycleDelegate* delegate = [[FlutterPluginAppLifeCycleDelegate alloc] init]; + id plugin = OCMProtocolMock(@protocol(FlutterPlugin)); + [delegate addDelegate:plugin]; + [[NSNotificationCenter defaultCenter] + postNotificationName:UIApplicationDidEnterBackgroundNotification + object:nil]; + + [self waitForExpectations:@[ expectation ] timeout:5.0]; + OCMVerify([plugin applicationDidEnterBackground:[UIApplication sharedApplication]]); +} + +- (void)testWillEnterForeground { + XCTNSNotificationExpectation* expectation = [[XCTNSNotificationExpectation alloc] + initWithName:UIApplicationWillEnterForegroundNotification]; + + FlutterPluginAppLifeCycleDelegate* delegate = [[FlutterPluginAppLifeCycleDelegate alloc] init]; + id plugin = OCMProtocolMock(@protocol(FlutterPlugin)); + [delegate addDelegate:plugin]; + [[NSNotificationCenter defaultCenter] + postNotificationName:UIApplicationWillEnterForegroundNotification + object:nil]; + [self waitForExpectations:@[ expectation ] timeout:5.0]; + OCMVerify([plugin applicationWillEnterForeground:[UIApplication sharedApplication]]); +} + +- (void)testWillResignActive { + XCTNSNotificationExpectation* expectation = + [[XCTNSNotificationExpectation alloc] initWithName:UIApplicationWillResignActiveNotification]; + + FlutterPluginAppLifeCycleDelegate* delegate = [[FlutterPluginAppLifeCycleDelegate alloc] init]; + id plugin = OCMProtocolMock(@protocol(FlutterPlugin)); + [delegate addDelegate:plugin]; + [[NSNotificationCenter defaultCenter] + postNotificationName:UIApplicationWillResignActiveNotification + object:nil]; + [self waitForExpectations:@[ expectation ] timeout:5.0]; + OCMVerify([plugin applicationWillResignActive:[UIApplication sharedApplication]]); +} + +- (void)testDidBecomeActive { + XCTNSNotificationExpectation* expectation = + [[XCTNSNotificationExpectation alloc] initWithName:UIApplicationDidBecomeActiveNotification]; + + FlutterPluginAppLifeCycleDelegate* delegate = [[FlutterPluginAppLifeCycleDelegate alloc] init]; + id plugin = OCMProtocolMock(@protocol(FlutterPlugin)); + [delegate addDelegate:plugin]; + [[NSNotificationCenter defaultCenter] + postNotificationName:UIApplicationDidBecomeActiveNotification + object:nil]; + [self waitForExpectations:@[ expectation ] timeout:5.0]; + OCMVerify([plugin applicationDidBecomeActive:[UIApplication sharedApplication]]); +} + +- (void)testWillTerminate { + XCTNSNotificationExpectation* expectation = + [[XCTNSNotificationExpectation alloc] initWithName:UIApplicationWillTerminateNotification]; + + FlutterPluginAppLifeCycleDelegate* delegate = [[FlutterPluginAppLifeCycleDelegate alloc] init]; + id plugin = OCMProtocolMock(@protocol(FlutterPlugin)); + [delegate addDelegate:plugin]; + [[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationWillTerminateNotification + object:nil]; + [self waitForExpectations:@[ expectation ] timeout:5.0]; + OCMVerify([plugin applicationWillTerminate:[UIApplication sharedApplication]]); +} + +- (void)testReleasesPluginOnDealloc { + __weak id weakPlugin; + __weak FlutterPluginAppLifeCycleDelegate* weakDelegate; + @autoreleasepool { + FakePlugin* fakePlugin = [[FakePlugin alloc] init]; + weakPlugin = fakePlugin; + FlutterPluginAppLifeCycleDelegate* delegate = [[FlutterPluginAppLifeCycleDelegate alloc] init]; + [delegate addDelegate:fakePlugin]; + weakDelegate = delegate; + } + XCTAssertNil(weakPlugin); + XCTAssertNil(weakDelegate); +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegate_internal.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegate_internal.h new file mode 100644 index 0000000000000000000000000000000000000000..6f80221796fbcb960cb8f19638f42da450dacc1e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegate_internal.h @@ -0,0 +1,23 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERPLUGINAPPLIFECYCLEDELEGATE_INTERNAL_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERPLUGINAPPLIFECYCLEDELEGATE_INTERNAL_H_ + +@interface FlutterPluginAppLifeCycleDelegate () + +/** + * Check whether the selector should be handled dynamically. + */ +- (BOOL)isSelectorAddedDynamically:(SEL)selector; + +/** + * Check whether there is at least one plugin responds to the selector. + */ +- (BOOL)hasPluginThatRespondsToSelector:(SEL)selector; + +@end +; + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERPLUGINAPPLIFECYCLEDELEGATE_INTERNAL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterRestorationPlugin.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterRestorationPlugin.h new file mode 100644 index 0000000000000000000000000000000000000000..bb7e1a7873ab8cae69f5df277d52188101b6ba03 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterRestorationPlugin.h @@ -0,0 +1,22 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERRESTORATIONPLUGIN_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERRESTORATIONPLUGIN_H_ + +#import + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" + +@interface FlutterRestorationPlugin : NSObject +- (instancetype)init NS_UNAVAILABLE; ++ (instancetype)new NS_UNAVAILABLE; +- (instancetype)initWithChannel:(FlutterMethodChannel*)channel + restorationEnabled:(BOOL)waitForData NS_DESIGNATED_INITIALIZER; + +@property(nonatomic, copy) NSData* restorationData; +- (void)markRestorationComplete; +- (void)reset; +@end +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERRESTORATIONPLUGIN_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterRestorationPlugin.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterRestorationPlugin.mm new file mode 100644 index 0000000000000000000000000000000000000000..d06cba6c79ae6d5b8d4bd09b782d1f416014a633 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterRestorationPlugin.mm @@ -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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterRestorationPlugin.h" + +#import +#import + +#include "flutter/fml/logging.h" + +FLUTTER_ASSERT_ARC + +@interface FlutterRestorationPlugin () +@property(nonatomic, copy) FlutterResult pendingRequest; +@end + +@implementation FlutterRestorationPlugin { + BOOL _waitForData; + BOOL _restorationEnabled; +} + +- (instancetype)initWithChannel:(FlutterMethodChannel*)channel + restorationEnabled:(BOOL)restorationEnabled { + FML_DCHECK(channel) << "channel must be set"; + self = [super init]; + if (self) { + [channel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { + [self handleMethodCall:call result:result]; + }]; + _restorationEnabled = restorationEnabled; + _waitForData = restorationEnabled; + } + return self; +} + +- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { + if ([[call method] isEqualToString:@"put"]) { + NSAssert(self.pendingRequest == nil, @"Cannot put data while a get request is pending."); + FlutterStandardTypedData* data = [call arguments]; + self.restorationData = [data data]; + result(nil); + } else if ([[call method] isEqualToString:@"get"]) { + if (!_restorationEnabled || !_waitForData) { + result([self dataForFramework]); + return; + } + NSAssert(self.pendingRequest == nil, @"There can only be one pending request."); + self.pendingRequest = result; + } else { + result(FlutterMethodNotImplemented); + } +} + +- (void)setRestorationData:(NSData*)data { + if (data != _restorationData) { + _restorationData = [data copy]; + } + _waitForData = NO; + if (self.pendingRequest != nil) { + self.pendingRequest([self dataForFramework]); + self.pendingRequest = nil; + } +} + +- (void)markRestorationComplete { + _waitForData = NO; + if (self.pendingRequest != nil) { + NSAssert(_restorationEnabled, @"No request can be pending when restoration is disabled."); + self.pendingRequest([self dataForFramework]); + self.pendingRequest = nil; + } +} + +- (void)reset { + self.pendingRequest = nil; + self.restorationData = nil; +} + +- (NSDictionary*)dataForFramework { + if (!_restorationEnabled) { + return @{@"enabled" : @NO}; + } + if (self.restorationData == nil) { + return @{@"enabled" : @YES}; + } + return @{ + @"enabled" : @YES, + @"data" : [FlutterStandardTypedData typedDataWithBytes:self.restorationData] + }; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterRestorationPluginTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterRestorationPluginTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..d61a29e0f31fdfe4753102619a3a66467f2a644a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterRestorationPluginTest.mm @@ -0,0 +1,221 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterRestorationPlugin.h" + +#import +#import + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h" + +FLUTTER_ASSERT_ARC + +@interface FlutterRestorationPlugin () +- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result; +@end + +@interface FlutterRestorationPluginTest : XCTestCase +@end + +@implementation FlutterRestorationPluginTest { + id restorationChannel; +} + +- (void)setUp { + [super setUp]; + restorationChannel = OCMClassMock([FlutterMethodChannel class]); +} + +- (void)tearDown { + [restorationChannel stopMocking]; + + [super tearDown]; +} + +#pragma mark - Tests + +- (void)testRestoratonViewControllerEncodeAndDecode { + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" + project:nil + allowHeadlessExecution:YES + restorationEnabled:YES]; + [engine run]; + FlutterViewController* flutterViewController = + [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; + FlutterRestorationPlugin* restorationPlugin = flutterViewController.restorationPlugin; + + NSData* data = [@"testrestortiondata" dataUsingEncoding:NSUTF8StringEncoding]; + [restorationPlugin setRestorationData:data]; + + NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc] initRequiringSecureCoding:YES]; + [flutterViewController encodeRestorableStateWithCoder:archiver]; + + [restorationPlugin setRestorationData:nil]; + + NSKeyedUnarchiver* unarchiver = + [[NSKeyedUnarchiver alloc] initForReadingWithData:archiver.encodedData]; + [flutterViewController decodeRestorableStateWithCoder:unarchiver]; + + XCTAssert([[restorationPlugin restorationData] isEqualToData:data], + "Restoration state data must be equal"); +} + +- (void)testRestorationEnabledWaitsForData { + FlutterRestorationPlugin* restorationPlugin = + [[FlutterRestorationPlugin alloc] initWithChannel:restorationChannel restorationEnabled:YES]; + + FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"get" arguments:nil]; + __block id capturedResult; + [restorationPlugin handleMethodCall:methodCall + result:^(id _Nullable result) { + capturedResult = result; + }]; + XCTAssertNil(capturedResult); + + NSData* data = [@"testrestortiondata" dataUsingEncoding:NSUTF8StringEncoding]; + [restorationPlugin setRestorationData:data]; + XCTAssertEqual([capturedResult count], 2u); + XCTAssertEqual([capturedResult objectForKey:@"enabled"], @YES); + XCTAssertEqualObjects([[capturedResult objectForKey:@"data"] data], data); +} + +- (void)testRestorationDisabledRespondsRightAway { + FlutterRestorationPlugin* restorationPlugin = + [[FlutterRestorationPlugin alloc] initWithChannel:restorationChannel restorationEnabled:NO]; + + FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"get" arguments:nil]; + __block id capturedResult; + [restorationPlugin handleMethodCall:methodCall + result:^(id _Nullable result) { + capturedResult = result; + }]; + XCTAssertEqual([capturedResult count], 1u); + XCTAssertEqual([capturedResult objectForKey:@"enabled"], @NO); +} + +- (void)testRespondsRightAwayWhenDataIsSet { + FlutterRestorationPlugin* restorationPlugin = + [[FlutterRestorationPlugin alloc] initWithChannel:restorationChannel restorationEnabled:YES]; + + NSData* data = [@"testrestortiondata" dataUsingEncoding:NSUTF8StringEncoding]; + [restorationPlugin setRestorationData:data]; + + __block id capturedResult; + FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"get" arguments:nil]; + [restorationPlugin handleMethodCall:methodCall + result:^(id _Nullable result) { + capturedResult = result; + }]; + XCTAssertEqual([capturedResult count], 2u); + XCTAssertEqual([capturedResult objectForKey:@"enabled"], @YES); + XCTAssertEqualObjects([[capturedResult objectForKey:@"data"] data], data); +} + +- (void)testRespondsWithNoDataWhenRestorationIsCompletedWithoutData { + FlutterRestorationPlugin* restorationPlugin = + [[FlutterRestorationPlugin alloc] initWithChannel:restorationChannel restorationEnabled:YES]; + + FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"get" arguments:nil]; + __block id capturedResult; + [restorationPlugin handleMethodCall:methodCall + result:^(id _Nullable result) { + capturedResult = result; + }]; + XCTAssertNil(capturedResult); + + [restorationPlugin markRestorationComplete]; + XCTAssertEqual([capturedResult count], 1u); + XCTAssertEqual([capturedResult objectForKey:@"enabled"], @YES); +} + +- (void)testRespondsRightAwayWithNoDataWhenRestorationIsCompleted { + FlutterRestorationPlugin* restorationPlugin = + [[FlutterRestorationPlugin alloc] initWithChannel:restorationChannel restorationEnabled:YES]; + + [restorationPlugin markRestorationComplete]; + + __block id capturedResult; + FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"get" arguments:nil]; + [restorationPlugin handleMethodCall:methodCall + result:^(id _Nullable result) { + capturedResult = result; + }]; + XCTAssertEqual([capturedResult count], 1u); + XCTAssertEqual([capturedResult objectForKey:@"enabled"], @YES); +} + +- (void)testReturnsDataSetByFramework { + FlutterRestorationPlugin* restorationPlugin = + [[FlutterRestorationPlugin alloc] initWithChannel:restorationChannel restorationEnabled:YES]; + [restorationPlugin markRestorationComplete]; + + NSData* data = [@"testrestortiondata" dataUsingEncoding:NSUTF8StringEncoding]; + FlutterMethodCall* methodCall = [FlutterMethodCall + methodCallWithMethodName:@"put" + arguments:[FlutterStandardTypedData typedDataWithBytes:data]]; + [restorationPlugin handleMethodCall:methodCall + result:^(id _Nullable result) { + XCTAssertNil(result); + }]; + XCTAssertEqualObjects([restorationPlugin restorationData], data); +} + +- (void)testRespondsWithDataSetByFramework { + FlutterRestorationPlugin* restorationPlugin = + [[FlutterRestorationPlugin alloc] initWithChannel:restorationChannel restorationEnabled:YES]; + [restorationPlugin markRestorationComplete]; + + NSData* data = [@"testrestortiondata" dataUsingEncoding:NSUTF8StringEncoding]; + FlutterMethodCall* methodCall = [FlutterMethodCall + methodCallWithMethodName:@"put" + arguments:[FlutterStandardTypedData typedDataWithBytes:data]]; + [restorationPlugin handleMethodCall:methodCall + result:^(id _Nullable result) { + XCTAssertNil(result); + }]; + XCTAssertEqualObjects([restorationPlugin restorationData], data); + + __block id capturedResult; + methodCall = [FlutterMethodCall methodCallWithMethodName:@"get" arguments:nil]; + [restorationPlugin handleMethodCall:methodCall + result:^(id _Nullable result) { + capturedResult = result; + }]; + XCTAssertEqual([capturedResult count], 2u); + XCTAssertEqual([capturedResult objectForKey:@"enabled"], @YES); + XCTAssertEqualObjects([[capturedResult objectForKey:@"data"] data], data); +} + +- (void)testResetClearsData { + FlutterRestorationPlugin* restorationPlugin = + [[FlutterRestorationPlugin alloc] initWithChannel:restorationChannel restorationEnabled:YES]; + [restorationPlugin markRestorationComplete]; + + NSData* data = [@"testrestortiondata" dataUsingEncoding:NSUTF8StringEncoding]; + FlutterMethodCall* methodCall = [FlutterMethodCall + methodCallWithMethodName:@"put" + arguments:[FlutterStandardTypedData typedDataWithBytes:data]]; + [restorationPlugin handleMethodCall:methodCall + result:^(id _Nullable result) { + XCTAssertNil(result); + }]; + XCTAssertEqualObjects([restorationPlugin restorationData], data); + + [restorationPlugin reset]; + XCTAssertNil([restorationPlugin restorationData]); + + __block id capturedResult; + methodCall = [FlutterMethodCall methodCallWithMethodName:@"get" arguments:nil]; + [restorationPlugin handleMethodCall:methodCall + result:^(id _Nullable result) { + capturedResult = result; + }]; + XCTAssertEqual([capturedResult count], 1u); + XCTAssertEqual([capturedResult objectForKey:@"enabled"], @YES); +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterSemanticsScrollView.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterSemanticsScrollView.h new file mode 100644 index 0000000000000000000000000000000000000000..e5f2f6343b843680fec2a2879a4ebc7ac6c88463 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterSemanticsScrollView.h @@ -0,0 +1,52 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERSEMANTICSSCROLLVIEW_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERSEMANTICSSCROLLVIEW_H_ + +#import + +NS_ASSUME_NONNULL_BEGIN +@class SemanticsObject; + +/** + * A UIScrollView to represent Flutter scrollable in iOS accessibility + * services. + * + * This class is hidden from the user and can't be interacted with. It + * sends all of selector calls from accessibility services to the + * owner SemanticsObject. + */ +@interface FlutterSemanticsScrollView : UIScrollView + +@property(nonatomic, weak, nullable) SemanticsObject* semanticsObject; + +/// Whether this scroll view's content offset is actively being updated by UIKit +/// or other the system services. +/// +/// This flag is set by the `FlutterSemanticsScrollView` itself, typically in +/// one of the `UIScrollViewDelegate` methods. +/// +/// When this flag is true, the `SemanticsObject` implementation ignores all +/// content offset updates coming from the Flutter framework, to prevent +/// potential feedback loops (especially when the framework is only echoing +/// the new content offset back to this scroll view). +/// +/// For example, to scroll a scrollable container with iOS full keyboard access, +/// the iOS focus system uses a display link to scroll the container to the +/// desired offset animatedly. If the user changes the scroll offset during the +/// animation, the display link will be invalidated and the scrolling animation +/// will be interrupted. For simplicity, content offset updates coming from the +/// framework will be ignored in the relatively short animation duration (~1s), +/// allowing the scrolling animation to finish. +@property(nonatomic, readonly) BOOL isDoingSystemScrolling; + +- (instancetype)init NS_UNAVAILABLE; +- (instancetype)initWithFrame:(CGRect)frame NS_UNAVAILABLE; +- (instancetype)initWithCoder:(NSCoder*)coder NS_UNAVAILABLE; +- (instancetype)initWithSemanticsObject:(SemanticsObject*)semanticsObject; + +@end +NS_ASSUME_NONNULL_END +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERSEMANTICSSCROLLVIEW_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterSemanticsScrollView.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterSemanticsScrollView.mm new file mode 100644 index 0000000000000000000000000000000000000000..c6952c72b71ec361dd1f8bf252bbacd5aac162f1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterSemanticsScrollView.mm @@ -0,0 +1,120 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterSemanticsScrollView.h" + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h" + +FLUTTER_ASSERT_ARC + +@implementation FlutterSemanticsScrollView + +- (instancetype)initWithSemanticsObject:(SemanticsObject*)semanticsObject { + self = [super initWithFrame:CGRectZero]; + if (self) { + _semanticsObject = semanticsObject; + _isDoingSystemScrolling = NO; + self.delegate = self; + } + return self; +} + +- (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent*)event { + return nil; +} + +// The following methods are explicitly forwarded to the wrapped SemanticsObject because the +// forwarding logic above doesn't apply to them since they are also implemented in the +// UIScrollView class, the base class. + +- (BOOL)isAccessibilityElement { + if (![self.semanticsObject isAccessibilityBridgeAlive]) { + return NO; + } + + if (self.semanticsObject.isAccessibilityElement) { + return YES; + } + if (self.contentSize.width > self.frame.size.width || + self.contentSize.height > self.frame.size.height) { + // In SwitchControl or VoiceControl, the isAccessibilityElement must return YES + // in order to use scroll actions. + return ![self.semanticsObject bridge]->isVoiceOverRunning(); + } else { + return NO; + } +} + +- (NSString*)accessibilityLabel { + return self.semanticsObject.accessibilityLabel; +} + +- (NSAttributedString*)accessibilityAttributedLabel { + return self.semanticsObject.accessibilityAttributedLabel; +} + +- (NSString*)accessibilityValue { + return self.semanticsObject.accessibilityValue; +} + +- (NSAttributedString*)accessibilityAttributedValue { + return self.semanticsObject.accessibilityAttributedValue; +} + +- (NSString*)accessibilityHint { + return self.semanticsObject.accessibilityHint; +} + +- (NSAttributedString*)accessibilityAttributedHint { + return self.semanticsObject.accessibilityAttributedHint; +} + +- (BOOL)accessibilityActivate { + return [self.semanticsObject accessibilityActivate]; +} + +- (void)accessibilityIncrement { + [self.semanticsObject accessibilityIncrement]; +} + +- (void)accessibilityDecrement { + [self.semanticsObject accessibilityDecrement]; +} + +- (BOOL)accessibilityScroll:(UIAccessibilityScrollDirection)direction { + return [self.semanticsObject accessibilityScroll:direction]; +} + +- (BOOL)accessibilityPerformEscape { + return [self.semanticsObject accessibilityPerformEscape]; +} + +- (void)accessibilityElementDidBecomeFocused { + [self.semanticsObject accessibilityElementDidBecomeFocused]; +} + +- (void)accessibilityElementDidLoseFocus { + [self.semanticsObject accessibilityElementDidLoseFocus]; +} + +- (id)accessibilityContainer { + return self.semanticsObject.accessibilityContainer; +} + +- (NSInteger)accessibilityElementCount { + return self.semanticsObject.children.count; +} + +- (void)scrollViewWillEndDragging:(UIScrollView*)scrollView + withVelocity:(CGPoint)velocity + targetContentOffset:(inout CGPoint*)targetContentOffset { + _isDoingSystemScrolling = YES; +} + +- (void)scrollViewDidEndDecelerating:(UIScrollView*)scrollView { + _isDoingSystemScrolling = NO; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterSharedApplication.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterSharedApplication.h new file mode 100644 index 0000000000000000000000000000000000000000..f7882505da7076b4b319d7ddebd7c84004dc55d4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterSharedApplication.h @@ -0,0 +1,29 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERSHAREDAPPLICATION_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERSHAREDAPPLICATION_H_ + +#import + +@interface FlutterSharedApplication : NSObject + +/** + * Returns YES if the main bundle is an iOS App Extension. + */ +@property(class, nonatomic, readonly) BOOL isAppExtension; + +/** + * Returns YES if the UIApplication is available. UIApplication is not available for App Extensions. + */ +@property(class, nonatomic, readonly) BOOL isAvailable; + +/** + * Returns the `UIApplication.sharedApplication` is available. Otherwise returns nil. + */ +@property(class, nonatomic, readonly) UIApplication* application; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERSHAREDAPPLICATION_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterSharedApplication.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterSharedApplication.mm new file mode 100644 index 0000000000000000000000000000000000000000..4c941b3607040ce1b20b7fd46b3627e82176b6d2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterSharedApplication.mm @@ -0,0 +1,37 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterSharedApplication.h" + +#include "flutter/fml/logging.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" + +FLUTTER_ASSERT_ARC + +@implementation FlutterSharedApplication + ++ (BOOL)isAppExtension { + NSDictionary* nsExtension = [NSBundle.mainBundle objectForInfoDictionaryKey:@"NSExtension"]; + return [nsExtension isKindOfClass:[NSDictionary class]]; +} + ++ (BOOL)isAvailable { + // If the bundle is an App Extension, the application is not available. + // Therefore access to `UIApplication.sharedApplication` is not allowed. + return !FlutterSharedApplication.isAppExtension; +} + ++ (UIApplication*)application { + if (FlutterSharedApplication.isAvailable) { + return FlutterSharedApplication.sharedApplication; + } + return nil; +} + ++ (UIApplication*) + sharedApplication NS_EXTENSION_UNAVAILABLE_IOS("Accesses unavailable sharedApplication.") { + return UIApplication.sharedApplication; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterSharedApplicationTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterSharedApplicationTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..2f4553b5c9aa4431b14525214e8ff74e7d24708f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterSharedApplicationTest.mm @@ -0,0 +1,66 @@ +// 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. + +#import +#import + +#include "flutter/common/constants.h" +#include "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterSharedApplication.h" + +FLUTTER_ASSERT_ARC + +@interface FlutterSharedApplicationTest : XCTestCase +@end + +@implementation FlutterSharedApplicationTest + +- (void)testWhenNSExtensionInBundle { + id mockBundle = OCMPartialMock([NSBundle mainBundle]); + OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{ + @"NSExtensionPointIdentifier" : @"com.apple.share-services" + }); + XCTAssertTrue(FlutterSharedApplication.isAppExtension); + XCTAssertFalse(FlutterSharedApplication.isAvailable); + [mockBundle stopMocking]; +} + +- (void)testWhenNSExtensionEmptyInBundle { + id mockBundle = OCMPartialMock([NSBundle mainBundle]); + OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]) + .andReturn([[NSDictionary alloc] init]); + XCTAssertTrue(FlutterSharedApplication.isAppExtension); + XCTAssertFalse(FlutterSharedApplication.isAvailable); + [mockBundle stopMocking]; +} + +- (void)testWhenNSExtensionNotInBundle { + id mockBundle = OCMPartialMock([NSBundle mainBundle]); + XCTAssertFalse(FlutterSharedApplication.isAppExtension); + XCTAssertTrue(FlutterSharedApplication.isAvailable); + [mockBundle stopMocking]; +} + +- (void)testSharedApplicationNotCalledIfIsAvailableFalse { + id mockBundle = OCMPartialMock([NSBundle mainBundle]); + OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{ + @"NSExtensionPointIdentifier" : @"com.apple.share-services" + }); + id mockApplication = OCMClassMock([UIApplication class]); + XCTAssertFalse(FlutterSharedApplication.isAvailable); + OCMReject([mockApplication sharedApplication]); + XCTAssertNil(FlutterSharedApplication.application); + [mockBundle stopMocking]; +} + +- (void)testSharedApplicationCalledIfIsAvailableTrue { + id mockBundle = OCMPartialMock([NSBundle mainBundle]); + id mockApplication = OCMClassMock([UIApplication class]); + XCTAssertTrue(FlutterSharedApplication.isAvailable); + XCTAssertNotNil(FlutterSharedApplication.application); + OCMVerify([mockApplication sharedApplication]); + [mockBundle stopMocking]; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterSpellCheckPlugin.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterSpellCheckPlugin.h new file mode 100644 index 0000000000000000000000000000000000000000..47a771cd3b4b11a7d9ef05d690a7cd611c378723 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterSpellCheckPlugin.h @@ -0,0 +1,17 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERSPELLCHECKPLUGIN_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERSPELLCHECKPLUGIN_H_ + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h" + +@interface FlutterSpellCheckPlugin : NSObject + +- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERSPELLCHECKPLUGIN_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterSpellCheckPlugin.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterSpellCheckPlugin.mm new file mode 100644 index 0000000000000000000000000000000000000000..a32ba843504cea824c94acfc661c65d625e1c518 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterSpellCheckPlugin.mm @@ -0,0 +1,167 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterSpellCheckPlugin.h" + +#import +#import + +#import "flutter/fml/logging.h" + +FLUTTER_ASSERT_ARC + +// Method Channel name to start spell check. +static NSString* const kInitiateSpellCheck = @"SpellCheck.initiateSpellCheck"; + +@interface FlutterSpellCheckResult : NSObject + +@property(nonatomic, copy, readonly) NSArray* suggestions; +@property(nonatomic, assign, readonly) NSRange misspelledRange; + +- (instancetype)init NS_UNAVAILABLE; ++ (instancetype)new NS_UNAVAILABLE; +- (instancetype)initWithMisspelledRange:(NSRange)range + suggestions:(NSArray*)suggestions NS_DESIGNATED_INITIALIZER; +- (NSDictionary*)toDictionary; + +@end + +@interface FlutterSpellCheckPlugin () + +@property(nonatomic) UITextChecker* textChecker; + +@end + +@implementation FlutterSpellCheckPlugin + +- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { + if (!self.textChecker) { + // UITextChecker is an expensive object to initiate, see: + // https://github.com/flutter/flutter/issues/104454. Lazily initialate the UITextChecker object + // until at first method channel call. We avoid using lazy getter for testing. + self.textChecker = [[UITextChecker alloc] init]; + } + NSString* method = call.method; + NSArray* args = call.arguments; + if ([method isEqualToString:kInitiateSpellCheck]) { + FML_DCHECK(args.count == 2); + id language = args[0]; + id text = args[1]; + if (language == [NSNull null] || text == [NSNull null]) { + // Bail if null arguments are passed from dart. + result(nil); + return; + } + + NSArray*>* spellCheckResult = + [self findAllSpellCheckSuggestionsForText:text inLanguage:language]; + result(spellCheckResult); + } +} + +// Get all the misspelled words and suggestions in the entire String. +// +// The result will be formatted as an NSArray. +// Each item of the array is a dictionary representing a misspelled word and suggestions. +// The format looks like: +// { +// startIndex: 0, +// endIndex: 5, +// suggestions: [hello, ...] +// } +// +// Returns nil if the language is invalid. +// Returns an empty array if no spell check suggestions. +- (NSArray*>*)findAllSpellCheckSuggestionsForText:(NSString*)text + inLanguage:(NSString*)language { + // Transform Dart Locale format to iOS language format if necessary. + if ([language containsString:@"-"]) { + NSArray* languageCodes = [language componentsSeparatedByString:@"-"]; + FML_DCHECK(languageCodes.count == 2); + NSString* lastCode = [[languageCodes lastObject] uppercaseString]; + language = [NSString stringWithFormat:@"%@_%@", [languageCodes firstObject], lastCode]; + } + + if (![UITextChecker.availableLanguages containsObject:language]) { + return nil; + } + + NSMutableArray* allSpellSuggestions = [[NSMutableArray alloc] init]; + + FlutterSpellCheckResult* nextSpellSuggestion; + NSUInteger nextOffset = 0; + do { + nextSpellSuggestion = [self findSpellCheckSuggestionsForText:text + inLanguage:language + startingOffset:nextOffset]; + if (nextSpellSuggestion != nil) { + [allSpellSuggestions addObject:nextSpellSuggestion]; + nextOffset = + nextSpellSuggestion.misspelledRange.location + nextSpellSuggestion.misspelledRange.length; + } + } while (nextSpellSuggestion != nil && nextOffset < text.length); + + NSMutableArray* methodChannelResult = + [[NSMutableArray alloc] initWithCapacity:allSpellSuggestions.count]; + + for (FlutterSpellCheckResult* result in allSpellSuggestions) { + [methodChannelResult addObject:[result toDictionary]]; + } + + return methodChannelResult; +} + +// Get the misspelled word and suggestions. +// +// Returns nil if no spell check suggestions. +- (FlutterSpellCheckResult*)findSpellCheckSuggestionsForText:(NSString*)text + inLanguage:(NSString*)language + startingOffset:(NSInteger)startingOffset { + FML_DCHECK([UITextChecker.availableLanguages containsObject:language]); + NSRange misspelledRange = + [self.textChecker rangeOfMisspelledWordInString:text + range:NSMakeRange(0, text.length) + startingAt:startingOffset + wrap:NO + language:language]; + if (misspelledRange.location == NSNotFound) { + // No misspelled word found + return nil; + } + + // If no possible guesses, the API returns an empty array: + // https://developer.apple.com/documentation/uikit/uitextchecker/1621037-guessesforwordrange?language=objc + NSArray* suggestions = [self.textChecker guessesForWordRange:misspelledRange + inString:text + language:language]; + return [[FlutterSpellCheckResult alloc] initWithMisspelledRange:misspelledRange + suggestions:suggestions]; +} + +@end + +@implementation FlutterSpellCheckResult + +- (instancetype)initWithMisspelledRange:(NSRange)range + suggestions:(NSArray*)suggestions { + self = [super init]; + if (self) { + _suggestions = [suggestions copy]; + _misspelledRange = range; + } + return self; +} + +- (NSDictionary*)toDictionary { + return @{ + @"startIndex" : @(_misspelledRange.location), + // The end index represents the next index after the last character of a misspelled word to + // match the behavior of Dart's TextRange: + // https://api.flutter.dev/flutter/dart-ui/TextRange/end.html + @"endIndex" : @(_misspelledRange.location + _misspelledRange.length), + @"suggestions" : _suggestions, + }; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterSpellCheckPluginTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterSpellCheckPluginTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..d35d72f0154d80342a0b5bb11ffcc722ced0c789 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterSpellCheckPluginTest.mm @@ -0,0 +1,364 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterSpellCheckPlugin.h" + +#import +#import + +#pragma mark - + +// A mock class representing the UITextChecker used in the tests. +// +// Because OCMock doesn't support mocking NSRange as method arguments, +// this is necessary. +@interface MockTextChecker : UITextChecker + +// The range of misspelled word based on the startingIndex. +// +// Key is the starting index, value is the range +@property(strong, nonatomic) NSMutableDictionary* startingIndexToRange; + +// The suggestions of misspelled word based on the starting index of the misspelled word. +// +// Key is a string representing the range of the misspelled word, value is the suggestions. +@property(strong, nonatomic) + NSMutableDictionary*>* rangeToSuggestions; + +// Mock the spell checking results. +// +// When no misspelled word should be detected, pass (NSNotFound, 0) for the `range` parameter, and +// an empty array for `suggestions`. +// +// Call `reset` to remove all the mocks. +- (void)mockResultRange:(NSRange)range + suggestions:(nonnull NSArray*)suggestions + withStartingIndex:(NSInteger)startingIndex; + +// Remove all mocks. +- (void)reset; + +@end + +@implementation MockTextChecker + +- (instancetype)init { + self = [super init]; + if (self) { + _startingIndexToRange = [[NSMutableDictionary alloc] init]; + _rangeToSuggestions = [[NSMutableDictionary alloc] init]; + } + return self; +} + +- (void)mockResultRange:(NSRange)range + suggestions:(NSArray*)suggestions + withStartingIndex:(NSInteger)startingIndex { + NSValue* valueForRange = [NSValue valueWithRange:range]; + self.startingIndexToRange[@(startingIndex)] = valueForRange; + NSString* rangeString = NSStringFromRange(valueForRange.rangeValue); + self.rangeToSuggestions[rangeString] = suggestions; +} + +- (void)reset { + [self.startingIndexToRange removeAllObjects]; + [self.rangeToSuggestions removeAllObjects]; +} + +#pragma mark UITextChecker Overrides + +- (NSRange)rangeOfMisspelledWordInString:(NSString*)stringToCheck + range:(NSRange)range + startingAt:(NSInteger)startingOffset + wrap:(BOOL)wrapFlag + language:(NSString*)language { + return self.startingIndexToRange[@(startingOffset)].rangeValue; +} + +- (NSArray*)guessesForWordRange:(NSRange)range + inString:(NSString*)string + language:(NSString*)language { + return self.rangeToSuggestions[NSStringFromRange(range)]; +} + +@end + +@interface FlutterSpellCheckPlugin () +- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result; +- (UITextChecker*)textChecker; +@end + +@interface FlutterSpellCheckPluginTest : XCTestCase + +@property(strong, nonatomic) id mockMethodChannel; +@property(strong, nonatomic) FlutterSpellCheckPlugin* plugin; +@property(strong, nonatomic) id mockTextChecker; +@property(strong, nonatomic) id partialMockPlugin; + +@end + +#pragma mark - + +@implementation FlutterSpellCheckPluginTest + +- (void)setUp { + [super setUp]; + self.mockMethodChannel = OCMClassMock([FlutterMethodChannel class]); + self.plugin = [[FlutterSpellCheckPlugin alloc] init]; + __weak FlutterSpellCheckPlugin* weakPlugin = self.plugin; + OCMStub([self.mockMethodChannel invokeMethod:[OCMArg any] + arguments:[OCMArg any] + result:[OCMArg any]]) + .andDo(^(NSInvocation* invocation) { + NSString* name; + id args; + FlutterResult result; + [invocation getArgument:&name atIndex:2]; + [invocation getArgument:&args atIndex:3]; + [invocation getArgument:&result atIndex:4]; + FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:name + arguments:args]; + [weakPlugin handleMethodCall:methodCall result:result]; + }); + self.mockTextChecker = [[MockTextChecker alloc] init]; +} + +- (void)tearDown { + self.plugin = nil; + [super tearDown]; +} + +#pragma mark - Tests + +// Test to make sure the while loop that checks all the misspelled word stops when the a +// `NSNotFound` is found. +- (void)testFindAllSpellCheckSuggestionsForText { + self.partialMockPlugin = OCMPartialMock(self.plugin); + OCMStub([self.partialMockPlugin textChecker]).andReturn(self.mockTextChecker); + id textCheckerClassMock = OCMClassMock([UITextChecker class]); + [[[textCheckerClassMock stub] andReturn:@[ @"en" ]] availableLanguages]; + NSArray* suggestions1 = @[ @"suggestion 1", @"suggestion 2" ]; + NSArray* suggestions2 = @[ @"suggestion 3", @"suggestion 4" ]; + // 0-4 is a misspelled word. + [self mockUITextCheckerWithExpectedMisspelledWordRange:NSMakeRange(0, 5) + startingIndex:0 + suggestions:suggestions1]; + // 5-9 is a misspelled word. + [self mockUITextCheckerWithExpectedMisspelledWordRange:NSMakeRange(5, 5) + startingIndex:5 + suggestions:suggestions2]; + // No misspelled word after index 10. + [self mockUITextCheckerWithExpectedMisspelledWordRange:NSMakeRange(NSNotFound, 0) + startingIndex:10 + suggestions:@[]]; + __block NSArray* capturedResult; + [self.mockMethodChannel invokeMethod:@"SpellCheck.initiateSpellCheck" + arguments:@[ @"en", @"ksajlkdf aslkdfl kasdf asdfjk" ] + result:^(id _Nullable result) { + capturedResult = result; + }]; + XCTAssertTrue(capturedResult.count == 2); + NSDictionary* suggestionsJSON1 = capturedResult.firstObject; + XCTAssertEqualObjects(suggestionsJSON1[@"startIndex"], @0); + XCTAssertEqualObjects(suggestionsJSON1[@"endIndex"], @5); + XCTAssertEqualObjects(suggestionsJSON1[@"suggestions"], suggestions1); + NSDictionary* suggestionsJSON2 = capturedResult[1]; + XCTAssertEqualObjects(suggestionsJSON2[@"startIndex"], @5); + XCTAssertEqualObjects(suggestionsJSON2[@"endIndex"], @10); + XCTAssertEqualObjects(suggestionsJSON2[@"suggestions"], suggestions2); + [self.mockTextChecker reset]; + [textCheckerClassMock stopMocking]; +} + +// Test to make sure while loop that checks all the misspelled word stops when the last word is +// misspelled (aka nextIndex is out of bounds) +- (void)testStopFindingMoreWhenTheLastWordIsMisspelled { + self.partialMockPlugin = OCMPartialMock(self.plugin); + OCMStub([self.partialMockPlugin textChecker]).andReturn(self.mockTextChecker); + id textCheckerClassMock = OCMClassMock([UITextChecker class]); + [[[textCheckerClassMock stub] andReturn:@[ @"en" ]] availableLanguages]; + NSArray* suggestions1 = @[ @"suggestion 1", @"suggestion 2" ]; + NSArray* suggestions2 = @[ @"suggestion 3", @"suggestion 4" ]; + // 0-4 is a misspelled word. + [self mockUITextCheckerWithExpectedMisspelledWordRange:NSMakeRange(0, 5) + startingIndex:0 + suggestions:suggestions1]; + // 5-9 is a misspelled word. + [self mockUITextCheckerWithExpectedMisspelledWordRange:NSMakeRange(6, 4) + startingIndex:5 + suggestions:suggestions2]; + + __block NSArray* capturedResult; + [self.mockMethodChannel invokeMethod:@"SpellCheck.initiateSpellCheck" + arguments:@[ @"en", @"hejjo abcd" ] + result:^(id _Nullable result) { + capturedResult = result; + }]; + XCTAssertTrue(capturedResult.count == 2); + NSDictionary* suggestionsJSON1 = capturedResult.firstObject; + XCTAssertEqualObjects(suggestionsJSON1[@"startIndex"], @0); + XCTAssertEqualObjects(suggestionsJSON1[@"endIndex"], @5); + XCTAssertEqualObjects(suggestionsJSON1[@"suggestions"], suggestions1); + NSDictionary* suggestionsJSON2 = capturedResult[1]; + XCTAssertEqualObjects(suggestionsJSON2[@"startIndex"], @6); + XCTAssertEqualObjects(suggestionsJSON2[@"endIndex"], @10); + XCTAssertEqualObjects(suggestionsJSON2[@"suggestions"], suggestions2); + [self.mockTextChecker reset]; + [textCheckerClassMock stopMocking]; +} + +- (void)testStopFindingMoreWhenTheWholeStringIsAMisspelledWord { + self.partialMockPlugin = OCMPartialMock(self.plugin); + OCMStub([self.partialMockPlugin textChecker]).andReturn(self.mockTextChecker); + id textCheckerClassMock = OCMClassMock([UITextChecker class]); + [[[textCheckerClassMock stub] andReturn:@[ @"en" ]] availableLanguages]; + NSArray* suggestions1 = @[ @"suggestion 1", @"suggestion 2" ]; + // 0-4 is a misspelled word. + [self mockUITextCheckerWithExpectedMisspelledWordRange:NSMakeRange(0, 5) + startingIndex:0 + suggestions:suggestions1]; + + __block NSArray* capturedResult; + [self.mockMethodChannel invokeMethod:@"SpellCheck.initiateSpellCheck" + arguments:@[ @"en", @"hejjo" ] + result:^(id _Nullable result) { + capturedResult = result; + }]; + XCTAssertTrue(capturedResult.count == 1); + NSDictionary* suggestionsJSON1 = capturedResult.firstObject; + XCTAssertEqualObjects(suggestionsJSON1[@"startIndex"], @0); + XCTAssertEqualObjects(suggestionsJSON1[@"endIndex"], @5); + XCTAssertEqualObjects(suggestionsJSON1[@"suggestions"], suggestions1); + [self.mockTextChecker reset]; + [textCheckerClassMock stopMocking]; +} + +- (void)testInitiateSpellCheckWithNoMisspelledWord { + self.partialMockPlugin = OCMPartialMock(self.plugin); + OCMStub([self.partialMockPlugin textChecker]).andReturn(self.mockTextChecker); + id textCheckerClassMock = OCMClassMock([UITextChecker class]); + [[[textCheckerClassMock stub] andReturn:@[ @"en" ]] availableLanguages]; + [self mockUITextCheckerWithExpectedMisspelledWordRange:NSMakeRange(NSNotFound, 0) + startingIndex:0 + suggestions:@[]]; + __block id capturedResult; + [self.mockMethodChannel invokeMethod:@"SpellCheck.initiateSpellCheck" + arguments:@[ @"en", @"helloo" ] + result:^(id _Nullable result) { + capturedResult = result; + }]; + XCTAssertEqualObjects(capturedResult, @[]); + [textCheckerClassMock stopMocking]; +} + +- (void)testUnsupportedLanguageShouldReturnNil { + self.partialMockPlugin = OCMPartialMock(self.plugin); + OCMStub([self.partialMockPlugin textChecker]).andReturn(self.mockTextChecker); + id textCheckerClassMock = OCMClassMock([UITextChecker class]); + [[[textCheckerClassMock stub] andReturn:@[ @"en" ]] availableLanguages]; + [self mockUITextCheckerWithExpectedMisspelledWordRange:NSMakeRange(0, 5) + startingIndex:0 + suggestions:@[]]; + __block id capturedResult; + [self.mockMethodChannel invokeMethod:@"SpellCheck.initiateSpellCheck" + arguments:@[ @"xx", @"helloo" ] + result:^(id _Nullable result) { + capturedResult = result; + }]; + XCTAssertNil(capturedResult); + [textCheckerClassMock stopMocking]; +} + +- (void)testSupportSubLanguage { + self.partialMockPlugin = OCMPartialMock(self.plugin); + OCMStub([self.partialMockPlugin textChecker]).andReturn(self.mockTextChecker); + id textCheckerClassMock = OCMClassMock([UITextChecker class]); + [[[textCheckerClassMock stub] andReturn:@[ @"en_US" ]] availableLanguages]; + NSArray* suggestions1 = @[ @"suggestion 1", @"suggestion 2" ]; + + [self mockUITextCheckerWithExpectedMisspelledWordRange:NSMakeRange(0, 5) + startingIndex:0 + suggestions:suggestions1]; + __block NSArray* capturedResult; + [self.mockMethodChannel invokeMethod:@"SpellCheck.initiateSpellCheck" + arguments:@[ @"en-us", @"hejjo" ] + result:^(id _Nullable result) { + capturedResult = result; + }]; + NSDictionary* suggestionsJSON1 = capturedResult.firstObject; + XCTAssertEqualObjects(suggestionsJSON1[@"startIndex"], @0); + XCTAssertEqualObjects(suggestionsJSON1[@"endIndex"], @5); + XCTAssertEqualObjects(suggestionsJSON1[@"suggestions"], suggestions1); + [textCheckerClassMock stopMocking]; +} + +- (void)testEmptyStringShouldReturnEmptyResults { + self.partialMockPlugin = OCMPartialMock(self.plugin); + OCMStub([self.partialMockPlugin textChecker]).andReturn(self.mockTextChecker); + // Use real UITextChecker for this as we want to rely on the actual behavior of UITextChecker + // to ensure that spell checks on an empty result always return empty. + [self.partialMockPlugin stopMocking]; + + id textCheckerClassMock = OCMClassMock([UITextChecker class]); + [[[textCheckerClassMock stub] andReturn:@[ @"en" ]] availableLanguages]; + __block id capturedResult; + [self.mockMethodChannel invokeMethod:@"SpellCheck.initiateSpellCheck" + arguments:@[ @"en", @"" ] + result:^(id _Nullable result) { + capturedResult = result; + }]; + XCTAssertEqualObjects(capturedResult, @[]); + [textCheckerClassMock stopMocking]; +} + +- (void)testNullStringArgumentShouldReturnNilResults { + self.partialMockPlugin = OCMPartialMock(self.plugin); + OCMStub([self.partialMockPlugin textChecker]).andReturn(self.mockTextChecker); + id textCheckerClassMock = OCMClassMock([UITextChecker class]); + [[[textCheckerClassMock stub] andReturn:@[ @"en" ]] availableLanguages]; + __block id capturedResult; + [self.mockMethodChannel invokeMethod:@"SpellCheck.initiateSpellCheck" + arguments:@[ @"en", [NSNull null] ] + result:^(id _Nullable result) { + capturedResult = result; + }]; + XCTAssertNil(capturedResult); + [textCheckerClassMock stopMocking]; +} + +- (void)testNullLanguageArgumentShouldReturnNilResults { + self.partialMockPlugin = OCMPartialMock(self.plugin); + OCMStub([self.partialMockPlugin textChecker]).andReturn(self.mockTextChecker); + id textCheckerClassMock = OCMClassMock([UITextChecker class]); + [[[textCheckerClassMock stub] andReturn:@[ @"en" ]] availableLanguages]; + __block id capturedResult; + [self.mockMethodChannel invokeMethod:@"SpellCheck.initiateSpellCheck" + arguments:@[ [NSNull null], @"some string" ] + result:^(id _Nullable result) { + capturedResult = result; + }]; + XCTAssertNil(capturedResult); + [textCheckerClassMock stopMocking]; +} + +- (void)testUITextCheckerIsInitializedAfterMethodChannelCall { + XCTAssertNil([self.plugin textChecker]); + __block id capturedResult; + [self.mockMethodChannel invokeMethod:@"SpellCheck.initiateSpellCheck" + arguments:@[ [NSNull null], @"some string" ] + result:^(id _Nullable result) { + capturedResult = result; + }]; + XCTAssertNotNil([self.plugin textChecker]); +} + +- (void)mockUITextCheckerWithExpectedMisspelledWordRange:(NSRange)expectedRange + startingIndex:(NSInteger)startingIndex + suggestions:(NSArray*)suggestions { + [self.mockTextChecker mockResultRange:expectedRange + suggestions:suggestions + withStartingIndex:startingIndex]; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h new file mode 100644 index 0000000000000000000000000000000000000000..d2464dcbd10e0c21a47475661b6e10beb3c07561 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h @@ -0,0 +1,78 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERTEXTINPUTDELEGATE_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERTEXTINPUTDELEGATE_H_ + +#import + +@class FlutterTextInputPlugin; +@class FlutterTextInputView; + +typedef NS_ENUM(NSInteger, FlutterTextInputAction) { + // NOLINTBEGIN(readability-identifier-naming) + FlutterTextInputActionUnspecified, + FlutterTextInputActionDone, + FlutterTextInputActionGo, + FlutterTextInputActionSend, + FlutterTextInputActionSearch, + FlutterTextInputActionNext, + FlutterTextInputActionContinue, + FlutterTextInputActionJoin, + FlutterTextInputActionRoute, + FlutterTextInputActionEmergencyCall, + FlutterTextInputActionNewline, + // NOLINTEND(readability-identifier-naming) +}; + +typedef NS_ENUM(NSInteger, FlutterFloatingCursorDragState) { + // NOLINTBEGIN(readability-identifier-naming) + FlutterFloatingCursorDragStateStart, + FlutterFloatingCursorDragStateUpdate, + FlutterFloatingCursorDragStateEnd, + // NOLINTEND(readability-identifier-naming) +}; + +@protocol FlutterTextInputDelegate +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + updateEditingClient:(int)client + withState:(NSDictionary*)state; +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + updateEditingClient:(int)client + withState:(NSDictionary*)state + withTag:(NSString*)tag; +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + updateEditingClient:(int)client + withDelta:(NSDictionary*)state; +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + performAction:(FlutterTextInputAction)action + withClient:(int)client; +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + updateFloatingCursor:(FlutterFloatingCursorDragState)state + withClient:(int)client + withPosition:(NSDictionary*)point; +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + showAutocorrectionPromptRectForStart:(NSUInteger)start + end:(NSUInteger)end + withClient:(int)client; +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView showToolbar:(int)client; +- (void)flutterTextInputViewScribbleInteractionBegan:(FlutterTextInputView*)textInputView; +- (void)flutterTextInputViewScribbleInteractionFinished:(FlutterTextInputView*)textInputView; +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + insertTextPlaceholderWithSize:(CGSize)size + withClient:(int)client; +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView removeTextPlaceholder:(int)client; +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + didResignFirstResponderWithTextInputClient:(int)client; +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + willDismissEditMenuWithTextInputClient:(int)client; +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + shareSelectedText:(NSString*)selectedText; +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + searchWebWithSelectedText:(NSString*)selectedText; +- (void)flutterTextInputView:(FlutterTextInputView*)textInputView + lookUpSelectedText:(NSString*)selectedText; +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERTEXTINPUTDELEGATE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h new file mode 100644 index 0000000000000000000000000000000000000000..3f304944573002182d9e296b267694f41ce99a7c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h @@ -0,0 +1,185 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERTEXTINPUTPLUGIN_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERTEXTINPUTPLUGIN_H_ + +#import + +#import "flutter/shell/platform/common/text_editing_delta.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterIndirectScribbleDelegate.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeySecondaryResponder.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewResponder.h" + +typedef NS_ENUM(NSInteger, FlutterScribbleFocusStatus) { + // NOLINTBEGIN(readability-identifier-naming) + FlutterScribbleFocusStatusUnfocused, + FlutterScribbleFocusStatusFocusing, + FlutterScribbleFocusStatusFocused, + // NOLINTEND(readability-identifier-naming) +}; + +typedef NS_ENUM(NSInteger, FlutterScribbleInteractionStatus) { + // NOLINTBEGIN(readability-identifier-naming) + FlutterScribbleInteractionStatusNone, + FlutterScribbleInteractionStatusStarted, + FlutterScribbleInteractionStatusEnding, + // NOLINTEND(readability-identifier-naming) +}; + +@interface FlutterTextInputPlugin + : NSObject + +@property(nonatomic, weak) UIViewController* viewController; +@property(nonatomic, weak) id indirectScribbleDelegate; +@property(nonatomic, strong) + NSMutableDictionary* scribbleElements; + +- (instancetype)init NS_UNAVAILABLE; ++ (instancetype)new NS_UNAVAILABLE; + +- (instancetype)initWithDelegate:(id)textInputDelegate + NS_DESIGNATED_INITIALIZER; + +- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result; + +/** + * The `UITextInput` implementation used to control text entry. + * + * This is used by `AccessibilityBridge` to forward interactions with iOS' + * accessibility system. + */ +- (UIView*)textInputView; + +/** + * These are used by the UIIndirectScribbleInteractionDelegate methods to handle focusing on the + * correct element. + */ +- (void)setUpIndirectScribbleInteraction:(id)viewResponder; +- (void)resetViewResponder; +- (BOOL)showEditMenu:(NSDictionary*)args API_AVAILABLE(ios(16.0)); +- (void)hideEditMenu API_AVAILABLE(ios(16.0)); + +@end + +/** An indexed position in the buffer of a Flutter text editing widget. */ +@interface FlutterTextPosition : UITextPosition + +@property(nonatomic, readonly) NSUInteger index; +@property(nonatomic, readonly) UITextStorageDirection affinity; + ++ (instancetype)positionWithIndex:(NSUInteger)index; ++ (instancetype)positionWithIndex:(NSUInteger)index affinity:(UITextStorageDirection)affinity; +- (instancetype)initWithIndex:(NSUInteger)index affinity:(UITextStorageDirection)affinity; + +@end + +/** A range of text in the buffer of a Flutter text editing widget. */ +@interface FlutterTextRange : UITextRange + +@property(nonatomic, readonly) NSRange range; + ++ (instancetype)rangeWithNSRange:(NSRange)range; + +@end + +/** A tokenizer used by `FlutterTextInputView` to customize string parsing. */ +@interface FlutterTokenizer : UITextInputStringTokenizer +@end + +@interface FlutterTextSelectionRect : UITextSelectionRect + +@property(nonatomic, assign) CGRect rect; +@property(nonatomic) NSUInteger position; +@property(nonatomic, assign) NSWritingDirection writingDirection; +@property(nonatomic) BOOL containsStart; +@property(nonatomic) BOOL containsEnd; +@property(nonatomic) BOOL isVertical; + ++ (instancetype)selectionRectWithRectAndInfo:(CGRect)rect + position:(NSUInteger)position + writingDirection:(NSWritingDirection)writingDirection + containsStart:(BOOL)containsStart + containsEnd:(BOOL)containsEnd + isVertical:(BOOL)isVertical; + ++ (instancetype)selectionRectWithRect:(CGRect)rect position:(NSUInteger)position; + ++ (instancetype)selectionRectWithRect:(CGRect)rect + position:(NSUInteger)position + writingDirection:(NSWritingDirection)writingDirection; + +- (instancetype)initWithRectAndInfo:(CGRect)rect + position:(NSUInteger)position + writingDirection:(NSWritingDirection)writingDirection + containsStart:(BOOL)containsStart + containsEnd:(BOOL)containsEnd + isVertical:(BOOL)isVertical; + +- (instancetype)init NS_UNAVAILABLE; + +- (BOOL)isRTL; +@end + +API_AVAILABLE(ios(13.0)) @interface FlutterTextPlaceholder : UITextPlaceholder +@end + +#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG +FLUTTER_DARWIN_EXPORT +#endif +@interface FlutterTextInputView + : UIView + +// UITextInput +@property(nonatomic, readonly) NSMutableString* text; +@property(readwrite, copy) UITextRange* selectedTextRange; +@property(nonatomic, strong) UITextRange* markedTextRange; +@property(nonatomic, copy) NSDictionary* markedTextStyle; +@property(nonatomic, weak) id inputDelegate; +@property(nonatomic, strong) NSMutableArray* pendingDeltas; + +// UITextInputTraits +@property(nonatomic) UITextAutocapitalizationType autocapitalizationType; +@property(nonatomic) UITextAutocorrectionType autocorrectionType; +@property(nonatomic) UITextSpellCheckingType spellCheckingType; +@property(nonatomic) BOOL enablesReturnKeyAutomatically; +@property(nonatomic) UIKeyboardAppearance keyboardAppearance; +@property(nonatomic) UIKeyboardType keyboardType; +@property(nonatomic) UIReturnKeyType returnKeyType; +@property(nonatomic, getter=isSecureTextEntry) BOOL secureTextEntry; +@property(nonatomic, getter=isEnableDeltaModel) BOOL enableDeltaModel; +@property(nonatomic) UITextSmartQuotesType smartQuotesType API_AVAILABLE(ios(11.0)); +@property(nonatomic) UITextSmartDashesType smartDashesType API_AVAILABLE(ios(11.0)); +@property(nonatomic, copy) UITextContentType textContentType API_AVAILABLE(ios(10.0)); + +@property(nonatomic, weak) UIAccessibilityElement* backingTextInputAccessibilityObject; + +// Scribble Support +@property(nonatomic, weak) id viewResponder; +@property(nonatomic) FlutterScribbleFocusStatus scribbleFocusStatus; +@property(nonatomic, strong) NSArray* selectionRects; + +@property(nonatomic, strong) UIEditMenuInteraction* editMenuInteraction API_AVAILABLE(ios(16.0)); +- (void)resetScribbleInteractionStatusIfEnding; +- (BOOL)isScribbleAvailable; + +- (instancetype)init NS_UNAVAILABLE; ++ (instancetype)new NS_UNAVAILABLE; +- (instancetype)initWithCoder:(NSCoder*)aDecoder NS_UNAVAILABLE; +- (instancetype)initWithFrame:(CGRect)frame NS_UNAVAILABLE; +- (instancetype)initWithOwner:(FlutterTextInputPlugin*)textInputPlugin NS_DESIGNATED_INITIALIZER; + +// TODO(louisehsu): These are being exposed to support Share in FlutterPlatformPlugin +// Consider moving that feature into FlutterTextInputPlugin to avoid exposing extra methods +- (CGRect)localRectFromFrameworkTransform:(CGRect)incomingRect; +- (CGRect)caretRectForPosition:(UITextPosition*)position; +@end + +@interface UIView (FindFirstResponder) +@property(nonatomic, readonly) id flutterFirstResponder; +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERTEXTINPUTPLUGIN_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.mm new file mode 100644 index 0000000000000000000000000000000000000000..4824835fa10ce03110595dc3403c57e83a91f898 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.mm @@ -0,0 +1,3209 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/UIViewController+FlutterScreenAndSceneIfLoaded.h" + +#import +#import + +#include "unicode/uchar.h" + +#include "flutter/fml/logging.h" +#include "flutter/fml/platform/darwin/string_range_sanitization.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterSharedApplication.h" + +FLUTTER_ASSERT_ARC + +static const char kTextAffinityDownstream[] = "TextAffinity.downstream"; +static const char kTextAffinityUpstream[] = "TextAffinity.upstream"; +// A delay before enabling the accessibility of FlutterTextInputView after +// it is activated. +static constexpr double kUITextInputAccessibilityEnablingDelaySeconds = 0.5; + +// A delay before reenabling the UIView areAnimationsEnabled to YES +// in order for becomeFirstResponder to receive the proper value. +static const NSTimeInterval kKeyboardAnimationDelaySeconds = 0.1; + +// A time set for the screenshot to animate back to the assigned position. +static const NSTimeInterval kKeyboardAnimationTimeToCompleteion = 0.3; + +// The "canonical" invalid CGRect, similar to CGRectNull, used to +// indicate a CGRect involved in firstRectForRange calculation is +// invalid. The specific value is chosen so that if firstRectForRange +// returns kInvalidFirstRect, iOS will not show the IME candidates view. +const CGRect kInvalidFirstRect = {{-1, -1}, {9999, 9999}}; + +#pragma mark - TextInput channel method names. +// See https://api.flutter.dev/flutter/services/SystemChannels/textInput-constant.html +static NSString* const kShowMethod = @"TextInput.show"; +static NSString* const kHideMethod = @"TextInput.hide"; +static NSString* const kSetClientMethod = @"TextInput.setClient"; +static NSString* const kSetPlatformViewClientMethod = @"TextInput.setPlatformViewClient"; +static NSString* const kSetEditingStateMethod = @"TextInput.setEditingState"; +static NSString* const kClearClientMethod = @"TextInput.clearClient"; +static NSString* const kSetEditableSizeAndTransformMethod = + @"TextInput.setEditableSizeAndTransform"; +static NSString* const kSetMarkedTextRectMethod = @"TextInput.setMarkedTextRect"; +static NSString* const kFinishAutofillContextMethod = @"TextInput.finishAutofillContext"; +// TODO(justinmc): Remove the TextInput method constant when the framework has +// finished transitioning to using the Scribble channel. +// https://github.com/flutter/flutter/pull/104128 +static NSString* const kDeprecatedSetSelectionRectsMethod = @"TextInput.setSelectionRects"; +static NSString* const kSetSelectionRectsMethod = @"Scribble.setSelectionRects"; +static NSString* const kStartLiveTextInputMethod = @"TextInput.startLiveTextInput"; +static NSString* const kUpdateConfigMethod = @"TextInput.updateConfig"; +static NSString* const kOnInteractiveKeyboardPointerMoveMethod = + @"TextInput.onPointerMoveForInteractiveKeyboard"; +static NSString* const kOnInteractiveKeyboardPointerUpMethod = + @"TextInput.onPointerUpForInteractiveKeyboard"; + +#pragma mark - TextInputConfiguration Field Names +static NSString* const kSecureTextEntry = @"obscureText"; +static NSString* const kKeyboardType = @"inputType"; +static NSString* const kKeyboardAppearance = @"keyboardAppearance"; +static NSString* const kInputAction = @"inputAction"; +static NSString* const kEnableDeltaModel = @"enableDeltaModel"; +static NSString* const kEnableInteractiveSelection = @"enableInteractiveSelection"; + +static NSString* const kSmartDashesType = @"smartDashesType"; +static NSString* const kSmartQuotesType = @"smartQuotesType"; + +static NSString* const kAssociatedAutofillFields = @"fields"; + +// TextInputConfiguration.autofill and sub-field names +static NSString* const kAutofillProperties = @"autofill"; +static NSString* const kAutofillId = @"uniqueIdentifier"; +static NSString* const kAutofillEditingValue = @"editingValue"; +static NSString* const kAutofillHints = @"hints"; + +static NSString* const kAutocorrectionType = @"autocorrect"; + +#pragma mark - Static Functions + +// Determine if the character at `range` of `text` is an emoji. +static BOOL IsEmoji(NSString* text, NSRange charRange) { + UChar32 codePoint; + BOOL gotCodePoint = [text getBytes:&codePoint + maxLength:sizeof(codePoint) + usedLength:NULL + encoding:NSUTF32StringEncoding + options:kNilOptions + range:charRange + remainingRange:NULL]; + return gotCodePoint && u_hasBinaryProperty(codePoint, UCHAR_EMOJI); +} + +// "TextInputType.none" is a made-up input type that's typically +// used when there's an in-app virtual keyboard. If +// "TextInputType.none" is specified, disable the system +// keyboard. +static BOOL ShouldShowSystemKeyboard(NSDictionary* type) { + NSString* inputType = type[@"name"]; + return ![inputType isEqualToString:@"TextInputType.none"]; +} +static UIKeyboardType ToUIKeyboardType(NSDictionary* type) { + NSString* inputType = type[@"name"]; + if ([inputType isEqualToString:@"TextInputType.address"]) { + return UIKeyboardTypeDefault; + } + if ([inputType isEqualToString:@"TextInputType.datetime"]) { + return UIKeyboardTypeNumbersAndPunctuation; + } + if ([inputType isEqualToString:@"TextInputType.emailAddress"]) { + return UIKeyboardTypeEmailAddress; + } + if ([inputType isEqualToString:@"TextInputType.multiline"]) { + return UIKeyboardTypeDefault; + } + if ([inputType isEqualToString:@"TextInputType.name"]) { + return UIKeyboardTypeNamePhonePad; + } + if ([inputType isEqualToString:@"TextInputType.number"]) { + if ([type[@"signed"] boolValue]) { + return UIKeyboardTypeNumbersAndPunctuation; + } + if ([type[@"decimal"] boolValue]) { + return UIKeyboardTypeDecimalPad; + } + return UIKeyboardTypeNumberPad; + } + if ([inputType isEqualToString:@"TextInputType.phone"]) { + return UIKeyboardTypePhonePad; + } + if ([inputType isEqualToString:@"TextInputType.text"]) { + return UIKeyboardTypeDefault; + } + if ([inputType isEqualToString:@"TextInputType.url"]) { + return UIKeyboardTypeURL; + } + if ([inputType isEqualToString:@"TextInputType.visiblePassword"]) { + return UIKeyboardTypeASCIICapable; + } + if ([inputType isEqualToString:@"TextInputType.webSearch"]) { + return UIKeyboardTypeWebSearch; + } + if ([inputType isEqualToString:@"TextInputType.twitter"]) { + return UIKeyboardTypeTwitter; + } + return UIKeyboardTypeDefault; +} + +static UITextAutocapitalizationType ToUITextAutoCapitalizationType(NSDictionary* type) { + NSString* textCapitalization = type[@"textCapitalization"]; + if ([textCapitalization isEqualToString:@"TextCapitalization.characters"]) { + return UITextAutocapitalizationTypeAllCharacters; + } else if ([textCapitalization isEqualToString:@"TextCapitalization.sentences"]) { + return UITextAutocapitalizationTypeSentences; + } else if ([textCapitalization isEqualToString:@"TextCapitalization.words"]) { + return UITextAutocapitalizationTypeWords; + } + return UITextAutocapitalizationTypeNone; +} + +static UIReturnKeyType ToUIReturnKeyType(NSString* inputType) { + // Where did the term "unspecified" come from? iOS has a "default" and Android + // has "unspecified." These 2 terms seem to mean the same thing but we need + // to pick just one. "unspecified" was chosen because "default" is often a + // reserved word in languages with switch statements (dart, java, etc). + if ([inputType isEqualToString:@"TextInputAction.unspecified"]) { + return UIReturnKeyDefault; + } + + if ([inputType isEqualToString:@"TextInputAction.done"]) { + return UIReturnKeyDone; + } + + if ([inputType isEqualToString:@"TextInputAction.go"]) { + return UIReturnKeyGo; + } + + if ([inputType isEqualToString:@"TextInputAction.send"]) { + return UIReturnKeySend; + } + + if ([inputType isEqualToString:@"TextInputAction.search"]) { + return UIReturnKeySearch; + } + + if ([inputType isEqualToString:@"TextInputAction.next"]) { + return UIReturnKeyNext; + } + + if ([inputType isEqualToString:@"TextInputAction.continueAction"]) { + return UIReturnKeyContinue; + } + + if ([inputType isEqualToString:@"TextInputAction.join"]) { + return UIReturnKeyJoin; + } + + if ([inputType isEqualToString:@"TextInputAction.route"]) { + return UIReturnKeyRoute; + } + + if ([inputType isEqualToString:@"TextInputAction.emergencyCall"]) { + return UIReturnKeyEmergencyCall; + } + + if ([inputType isEqualToString:@"TextInputAction.newline"]) { + return UIReturnKeyDefault; + } + + // Present default key if bad input type is given. + return UIReturnKeyDefault; +} + +static UITextContentType ToUITextContentType(NSArray* hints) { + if (!hints || hints.count == 0) { + // If no hints are specified, use the default content type nil. + return nil; + } + + NSString* hint = hints[0]; + if ([hint isEqualToString:@"addressCityAndState"]) { + return UITextContentTypeAddressCityAndState; + } + + if ([hint isEqualToString:@"addressState"]) { + return UITextContentTypeAddressState; + } + + if ([hint isEqualToString:@"addressCity"]) { + return UITextContentTypeAddressCity; + } + + if ([hint isEqualToString:@"sublocality"]) { + return UITextContentTypeSublocality; + } + + if ([hint isEqualToString:@"streetAddressLine1"]) { + return UITextContentTypeStreetAddressLine1; + } + + if ([hint isEqualToString:@"streetAddressLine2"]) { + return UITextContentTypeStreetAddressLine2; + } + + if ([hint isEqualToString:@"countryName"]) { + return UITextContentTypeCountryName; + } + + if ([hint isEqualToString:@"fullStreetAddress"]) { + return UITextContentTypeFullStreetAddress; + } + + if ([hint isEqualToString:@"postalCode"]) { + return UITextContentTypePostalCode; + } + + if ([hint isEqualToString:@"location"]) { + return UITextContentTypeLocation; + } + + if ([hint isEqualToString:@"creditCardNumber"]) { + return UITextContentTypeCreditCardNumber; + } + + if ([hint isEqualToString:@"email"]) { + return UITextContentTypeEmailAddress; + } + + if ([hint isEqualToString:@"jobTitle"]) { + return UITextContentTypeJobTitle; + } + + if ([hint isEqualToString:@"givenName"]) { + return UITextContentTypeGivenName; + } + + if ([hint isEqualToString:@"middleName"]) { + return UITextContentTypeMiddleName; + } + + if ([hint isEqualToString:@"familyName"]) { + return UITextContentTypeFamilyName; + } + + if ([hint isEqualToString:@"name"]) { + return UITextContentTypeName; + } + + if ([hint isEqualToString:@"namePrefix"]) { + return UITextContentTypeNamePrefix; + } + + if ([hint isEqualToString:@"nameSuffix"]) { + return UITextContentTypeNameSuffix; + } + + if ([hint isEqualToString:@"nickname"]) { + return UITextContentTypeNickname; + } + + if ([hint isEqualToString:@"organizationName"]) { + return UITextContentTypeOrganizationName; + } + + if ([hint isEqualToString:@"telephoneNumber"]) { + return UITextContentTypeTelephoneNumber; + } + + if ([hint isEqualToString:@"password"]) { + return UITextContentTypePassword; + } + + if ([hint isEqualToString:@"oneTimeCode"]) { + return UITextContentTypeOneTimeCode; + } + + if ([hint isEqualToString:@"newPassword"]) { + return UITextContentTypeNewPassword; + } + + return hints[0]; +} + +// Retrieves the autofillId from an input field's configuration. Returns +// nil if the field is nil and the input field is not a password field. +static NSString* AutofillIdFromDictionary(NSDictionary* dictionary) { + NSDictionary* autofill = dictionary[kAutofillProperties]; + if (autofill) { + return autofill[kAutofillId]; + } + + // When autofill is nil, the field may still need an autofill id + // if the field is for password. + return [dictionary[kSecureTextEntry] boolValue] ? @"password" : nil; +} + +// # Autofill Implementation Notes: +// +// Currently there're 2 types of autofills on iOS: +// - Regular autofill, including contact information and one-time-code, +// takes place in the form of predictive text in the quick type bar. +// This type of autofill does not save user input, and the keyboard +// currently only populates the focused field when a predictive text entry +// is selected by the user. +// +// - Password autofill, includes automatic strong password and regular +// password autofill. The former happens automatically when a +// "new password" field is detected and focused, and only that password +// field will be populated. The latter appears in the quick type bar when +// an eligible input field (which either has a UITextContentTypePassword +// contentType, or is a secure text entry) becomes the first responder, and may +// fill both the username and the password fields. iOS will attempt +// to save user input for both kinds of password fields. It's relatively +// tricky to deal with password autofill since it can autofill more than one +// field at a time and may employ heuristics based on what other text fields +// are in the same view controller. +// +// When a flutter text field is focused, and autofill is not explicitly disabled +// for it ("autofillable"), the framework collects its attributes and checks if +// it's in an AutofillGroup, and collects the attributes of other autofillable +// text fields in the same AutofillGroup if so. The attributes are sent to the +// text input plugin via a "TextInput.setClient" platform channel message. If +// autofill is disabled for a text field, its "autofill" field will be nil in +// the configuration json. +// +// The text input plugin then tries to determine which kind of autofill the text +// field needs. If the AutofillGroup the text field belongs to contains an +// autofillable text field that's password related, this text 's autofill type +// will be kFlutterAutofillTypePassword. If autofill is disabled for a text field, +// then its type will be kFlutterAutofillTypeNone. Otherwise the text field will +// have an autofill type of kFlutterAutofillTypeRegular. +// +// The text input plugin creates a new UIView for every kFlutterAutofillTypeNone +// text field. The UIView instance is never reused for other flutter text fields +// since the software keyboard often uses the identity of a UIView to distinguish +// different views and provides the same predictive text suggestions or restore +// the composing region if a UIView is reused for a different flutter text field. +// +// The text input plugin creates a new "autofill context" if the text field has +// the type of kFlutterAutofillTypePassword, to represent the AutofillGroup of +// the text field, and creates one FlutterTextInputView for every text field in +// the AutofillGroup. +// +// The text input plugin will try to reuse a UIView if a flutter text field's +// type is kFlutterAutofillTypeRegular, and has the same autofill id. +typedef NS_ENUM(NSInteger, FlutterAutofillType) { + // The field does not have autofillable content. Additionally if + // the field is currently in the autofill context, it will be + // removed from the context without triggering autofill save. + kFlutterAutofillTypeNone, + kFlutterAutofillTypeRegular, + kFlutterAutofillTypePassword, +}; + +static BOOL IsFieldPasswordRelated(NSDictionary* configuration) { + // Autofill is explicitly disabled if the id isn't present. + if (!AutofillIdFromDictionary(configuration)) { + return NO; + } + + BOOL isSecureTextEntry = [configuration[kSecureTextEntry] boolValue]; + if (isSecureTextEntry) { + return YES; + } + + NSDictionary* autofill = configuration[kAutofillProperties]; + UITextContentType contentType = ToUITextContentType(autofill[kAutofillHints]); + + if ([contentType isEqualToString:UITextContentTypePassword] || + [contentType isEqualToString:UITextContentTypeUsername]) { + return YES; + } + + if ([contentType isEqualToString:UITextContentTypeNewPassword]) { + return YES; + } + + return NO; +} + +static FlutterAutofillType AutofillTypeOf(NSDictionary* configuration) { + for (NSDictionary* field in configuration[kAssociatedAutofillFields]) { + if (IsFieldPasswordRelated(field)) { + return kFlutterAutofillTypePassword; + } + } + + if (IsFieldPasswordRelated(configuration)) { + return kFlutterAutofillTypePassword; + } + + NSDictionary* autofill = configuration[kAutofillProperties]; + UITextContentType contentType = ToUITextContentType(autofill[kAutofillHints]); + return !autofill || [contentType isEqualToString:@""] ? kFlutterAutofillTypeNone + : kFlutterAutofillTypeRegular; +} + +static BOOL IsApproximatelyEqual(float x, float y, float delta) { + return fabsf(x - y) <= delta; +} + +// This is a helper function for floating cursor selection logic to determine which text +// position is closer to a point. +// Checks whether point should be considered closer to selectionRect compared to +// otherSelectionRect. +// +// If `useTrailingBoundaryOfSelectionRect` is not set, it uses the leading-center point +// on selectionRect and otherSelectionRect to compare. +// For left-to-right text, this means the left-center point, and for right-to-left text, +// this means the right-center point. +// +// If useTrailingBoundaryOfSelectionRect is set, the trailing-center point on selectionRect +// will be used instead of the leading-center point, while leading-center point is still used +// for otherSelectionRect. +// +// This uses special (empirically determined using a 1st gen iPad pro, 9.7" model running +// iOS 14.7.1) logic for determining the closer rect, rather than a simple distance calculation. +// - First, the rect with closer y distance wins. +// - Otherwise (same y distance): +// - If the point is above bottom of the rect, the rect boundary with closer x distance wins. +// - Otherwise (point is below bottom of the rect), the rect boundary with farthest x wins. +// This is because when the point is below the bottom line of text, we want to select the +// whole line of text, so we mark the farthest rect as closest. +static BOOL IsSelectionRectBoundaryCloserToPoint(CGPoint point, + CGRect selectionRect, + BOOL selectionRectIsRTL, + BOOL useTrailingBoundaryOfSelectionRect, + CGRect otherSelectionRect, + BOOL otherSelectionRectIsRTL, + CGFloat verticalPrecision) { + // The point is inside the selectionRect's corresponding half-rect area. + if (CGRectContainsPoint( + CGRectMake( + selectionRect.origin.x + ((useTrailingBoundaryOfSelectionRect ^ selectionRectIsRTL) + ? 0.5 * selectionRect.size.width + : 0), + selectionRect.origin.y, 0.5 * selectionRect.size.width, selectionRect.size.height), + point)) { + return YES; + } + // pointForSelectionRect is either leading-center or trailing-center point of selectionRect. + CGPoint pointForSelectionRect = CGPointMake( + selectionRect.origin.x + + (selectionRectIsRTL ^ useTrailingBoundaryOfSelectionRect ? selectionRect.size.width : 0), + selectionRect.origin.y + selectionRect.size.height * 0.5); + float yDist = fabs(pointForSelectionRect.y - point.y); + float xDist = fabs(pointForSelectionRect.x - point.x); + + // pointForOtherSelectionRect is the leading-center point of otherSelectionRect. + CGPoint pointForOtherSelectionRect = CGPointMake( + otherSelectionRect.origin.x + (otherSelectionRectIsRTL ? otherSelectionRect.size.width : 0), + otherSelectionRect.origin.y + otherSelectionRect.size.height * 0.5); + float yDistOther = fabs(pointForOtherSelectionRect.y - point.y); + float xDistOther = fabs(pointForOtherSelectionRect.x - point.x); + + // This serves a similar purpose to IsApproximatelyEqual, allowing a little buffer before + // declaring something closer vertically to account for the small variations in size and position + // of SelectionRects, especially when dealing with emoji. + BOOL isCloserVertically = yDist < yDistOther - verticalPrecision; + BOOL isEqualVertically = IsApproximatelyEqual(yDist, yDistOther, verticalPrecision); + BOOL isAboveBottomOfLine = point.y <= selectionRect.origin.y + selectionRect.size.height; + BOOL isCloserHorizontally = xDist < xDistOther; + BOOL isBelowBottomOfLine = point.y > selectionRect.origin.y + selectionRect.size.height; + // Is "farther away", or is closer to the end of the text line. + BOOL isFarther; + if (selectionRectIsRTL) { + isFarther = selectionRect.origin.x < otherSelectionRect.origin.x; + } else { + isFarther = selectionRect.origin.x + + (useTrailingBoundaryOfSelectionRect ? selectionRect.size.width : 0) > + otherSelectionRect.origin.x; + } + return (isCloserVertically || + (isEqualVertically && + ((isAboveBottomOfLine && isCloserHorizontally) || (isBelowBottomOfLine && isFarther)))); +} + +#pragma mark - FlutterTextPosition + +@implementation FlutterTextPosition + ++ (instancetype)positionWithIndex:(NSUInteger)index { + return [[FlutterTextPosition alloc] initWithIndex:index affinity:UITextStorageDirectionForward]; +} + ++ (instancetype)positionWithIndex:(NSUInteger)index affinity:(UITextStorageDirection)affinity { + return [[FlutterTextPosition alloc] initWithIndex:index affinity:affinity]; +} + +- (instancetype)initWithIndex:(NSUInteger)index affinity:(UITextStorageDirection)affinity { + self = [super init]; + if (self) { + _index = index; + _affinity = affinity; + } + return self; +} + +@end + +#pragma mark - FlutterTextRange + +@implementation FlutterTextRange + ++ (instancetype)rangeWithNSRange:(NSRange)range { + return [[FlutterTextRange alloc] initWithNSRange:range]; +} + +- (instancetype)initWithNSRange:(NSRange)range { + self = [super init]; + if (self) { + _range = range; + } + return self; +} + +- (UITextPosition*)start { + return [FlutterTextPosition positionWithIndex:self.range.location + affinity:UITextStorageDirectionForward]; +} + +- (UITextPosition*)end { + return [FlutterTextPosition positionWithIndex:self.range.location + self.range.length + affinity:UITextStorageDirectionBackward]; +} + +- (BOOL)isEmpty { + return self.range.length == 0; +} + +- (id)copyWithZone:(NSZone*)zone { + return [[FlutterTextRange allocWithZone:zone] initWithNSRange:self.range]; +} + +- (BOOL)isEqualTo:(FlutterTextRange*)other { + return NSEqualRanges(self.range, other.range); +} +@end + +#pragma mark - FlutterTokenizer + +@interface FlutterTokenizer () + +@property(nonatomic, weak) FlutterTextInputView* textInputView; + +@end + +@implementation FlutterTokenizer + +- (instancetype)initWithTextInput:(UIResponder*)textInput { + NSAssert([textInput isKindOfClass:[FlutterTextInputView class]], + @"The FlutterTokenizer can only be used in a FlutterTextInputView"); + self = [super initWithTextInput:textInput]; + if (self) { + _textInputView = (FlutterTextInputView*)textInput; + } + return self; +} + +- (UITextRange*)rangeEnclosingPosition:(UITextPosition*)position + withGranularity:(UITextGranularity)granularity + inDirection:(UITextDirection)direction { + UITextRange* result; + switch (granularity) { + case UITextGranularityLine: + // The default UITextInputStringTokenizer does not handle line granularity + // correctly. We need to implement our own line tokenizer. + result = [self lineEnclosingPosition:position inDirection:direction]; + break; + case UITextGranularityCharacter: + case UITextGranularityWord: + case UITextGranularitySentence: + case UITextGranularityParagraph: + case UITextGranularityDocument: + // The UITextInputStringTokenizer can handle all these cases correctly. + result = [super rangeEnclosingPosition:position + withGranularity:granularity + inDirection:direction]; + break; + } + return result; +} + +- (UITextRange*)lineEnclosingPosition:(UITextPosition*)position + inDirection:(UITextDirection)direction { + // TODO(hellohuanlin): remove iOS 17 check. The same logic should apply to older iOS version. + if (@available(iOS 17.0, *)) { + // According to the API doc if the text position is at a text-unit boundary, it is considered + // enclosed only if the next position in the given direction is entirely enclosed. Link: + // https://developer.apple.com/documentation/uikit/uitextinputtokenizer/1614464-rangeenclosingposition?language=objc + FlutterTextPosition* flutterPosition = (FlutterTextPosition*)position; + if (flutterPosition.index > _textInputView.text.length || + (flutterPosition.index == _textInputView.text.length && + direction == UITextStorageDirectionForward)) { + return nil; + } + } + + // Gets the first line break position after the input position. + NSString* textAfter = [_textInputView + textInRange:[_textInputView textRangeFromPosition:position + toPosition:[_textInputView endOfDocument]]]; + NSArray* linesAfter = [textAfter componentsSeparatedByString:@"\n"]; + NSInteger offSetToLineBreak = [linesAfter firstObject].length; + UITextPosition* lineBreakAfter = [_textInputView positionFromPosition:position + offset:offSetToLineBreak]; + // Gets the first line break position before the input position. + NSString* textBefore = [_textInputView + textInRange:[_textInputView textRangeFromPosition:[_textInputView beginningOfDocument] + toPosition:position]]; + NSArray* linesBefore = [textBefore componentsSeparatedByString:@"\n"]; + NSInteger offSetFromLineBreak = [linesBefore lastObject].length; + UITextPosition* lineBreakBefore = [_textInputView positionFromPosition:position + offset:-offSetFromLineBreak]; + + return [_textInputView textRangeFromPosition:lineBreakBefore toPosition:lineBreakAfter]; +} + +@end + +#pragma mark - FlutterTextSelectionRect + +@implementation FlutterTextSelectionRect + +// Synthesize properties declared readonly in UITextSelectionRect. +@synthesize rect = _rect; +@synthesize writingDirection = _writingDirection; +@synthesize containsStart = _containsStart; +@synthesize containsEnd = _containsEnd; +@synthesize isVertical = _isVertical; + ++ (instancetype)selectionRectWithRectAndInfo:(CGRect)rect + position:(NSUInteger)position + writingDirection:(NSWritingDirection)writingDirection + containsStart:(BOOL)containsStart + containsEnd:(BOOL)containsEnd + isVertical:(BOOL)isVertical { + return [[FlutterTextSelectionRect alloc] initWithRectAndInfo:rect + position:position + writingDirection:writingDirection + containsStart:containsStart + containsEnd:containsEnd + isVertical:isVertical]; +} + ++ (instancetype)selectionRectWithRect:(CGRect)rect position:(NSUInteger)position { + return [[FlutterTextSelectionRect alloc] initWithRectAndInfo:rect + position:position + writingDirection:NSWritingDirectionNatural + containsStart:NO + containsEnd:NO + isVertical:NO]; +} + ++ (instancetype)selectionRectWithRect:(CGRect)rect + position:(NSUInteger)position + writingDirection:(NSWritingDirection)writingDirection { + return [[FlutterTextSelectionRect alloc] initWithRectAndInfo:rect + position:position + writingDirection:writingDirection + containsStart:NO + containsEnd:NO + isVertical:NO]; +} + +- (instancetype)initWithRectAndInfo:(CGRect)rect + position:(NSUInteger)position + writingDirection:(NSWritingDirection)writingDirection + containsStart:(BOOL)containsStart + containsEnd:(BOOL)containsEnd + isVertical:(BOOL)isVertical { + self = [super init]; + if (self) { + self.rect = rect; + self.position = position; + self.writingDirection = writingDirection; + self.containsStart = containsStart; + self.containsEnd = containsEnd; + self.isVertical = isVertical; + } + return self; +} + +- (BOOL)isRTL { + return _writingDirection == NSWritingDirectionRightToLeft; +} + +@end + +#pragma mark - FlutterTextPlaceholder + +@implementation FlutterTextPlaceholder + +- (NSArray*)rects { + // Returning anything other than an empty array here seems to cause PencilKit to enter an + // infinite loop of allocating placeholders until the app crashes + return @[]; +} + +@end + +// A FlutterTextInputView that masquerades as a UITextField, and forwards +// selectors it can't respond to a shared UITextField instance. +// +// Relevant API docs claim that password autofill supports any custom view +// that adopts the UITextInput protocol, automatic strong password seems to +// currently only support UITextFields, and password saving only supports +// UITextFields and UITextViews, as of iOS 13.5. +@interface FlutterSecureTextInputView : FlutterTextInputView +@property(nonatomic, retain, readonly) UITextField* textField; +@end + +@implementation FlutterSecureTextInputView { + UITextField* _textField; +} + +- (UITextField*)textField { + if (!_textField) { + _textField = [[UITextField alloc] init]; + } + return _textField; +} + +- (BOOL)isKindOfClass:(Class)aClass { + return [super isKindOfClass:aClass] || (aClass == [UITextField class]); +} + +- (NSMethodSignature*)methodSignatureForSelector:(SEL)aSelector { + NSMethodSignature* signature = [super methodSignatureForSelector:aSelector]; + if (!signature) { + signature = [self.textField methodSignatureForSelector:aSelector]; + } + return signature; +} + +- (void)forwardInvocation:(NSInvocation*)anInvocation { + [anInvocation invokeWithTarget:self.textField]; +} + +@end + +@interface FlutterTextInputPlugin () +@property(nonatomic, readonly, weak) id textInputDelegate; +@property(nonatomic, readonly) UIView* hostView; +@end + +@interface FlutterTextInputView () +@property(nonatomic, readonly, weak) FlutterTextInputPlugin* textInputPlugin; +@property(nonatomic, copy) NSString* autofillId; +@property(nonatomic, readonly) CATransform3D editableTransform; +@property(nonatomic, assign) CGRect markedRect; +// Disables the cursor from dismissing when firstResponder is resigned +@property(nonatomic, assign) BOOL preventCursorDismissWhenResignFirstResponder; +@property(nonatomic) BOOL isVisibleToAutofill; +@property(nonatomic, assign) BOOL accessibilityEnabled; +@property(nonatomic, assign) int textInputClient; +// The composed character that is temporarily removed by the keyboard API. +// This is cleared at the start of each keyboard interaction. (Enter a character, delete a character +// etc) +@property(nonatomic, copy) NSString* temporarilyDeletedComposedCharacter; +@property(nonatomic, assign) CGRect editMenuTargetRect; +@property(nonatomic, strong) NSArray* editMenuItems; + +- (void)setEditableTransform:(NSArray*)matrix; +@end + +@implementation FlutterTextInputView { + int _textInputClient; + const char* _selectionAffinity; + FlutterTextRange* _selectedTextRange; + UIInputViewController* _inputViewController; + CGRect _cachedFirstRect; + FlutterScribbleInteractionStatus _scribbleInteractionStatus; + BOOL _hasPlaceholder; + // Whether to show the system keyboard when this view + // becomes the first responder. Typically set to false + // when the app shows its own in-flutter keyboard. + bool _isSystemKeyboardEnabled; + bool _isFloatingCursorActive; + CGPoint _floatingCursorOffset; + bool _enableInteractiveSelection; + UITextInteraction* _textInteraction API_AVAILABLE(ios(13.0)); +} + +@synthesize tokenizer = _tokenizer; + +- (instancetype)initWithOwner:(FlutterTextInputPlugin*)textInputPlugin { + self = [super initWithFrame:CGRectZero]; + if (self) { + _textInputPlugin = textInputPlugin; + _textInputClient = 0; + _selectionAffinity = kTextAffinityUpstream; + _preventCursorDismissWhenResignFirstResponder = NO; + + // UITextInput + _text = [[NSMutableString alloc] init]; + _selectedTextRange = [[FlutterTextRange alloc] initWithNSRange:NSMakeRange(0, 0)]; + _markedRect = kInvalidFirstRect; + _cachedFirstRect = kInvalidFirstRect; + _scribbleInteractionStatus = FlutterScribbleInteractionStatusNone; + _pendingDeltas = [[NSMutableArray alloc] init]; + // Initialize with the zero matrix which is not + // an affine transform. + _editableTransform = CATransform3D(); + + // UITextInputTraits + _autocapitalizationType = UITextAutocapitalizationTypeSentences; + _autocorrectionType = UITextAutocorrectionTypeDefault; + _spellCheckingType = UITextSpellCheckingTypeDefault; + _enablesReturnKeyAutomatically = NO; + _keyboardAppearance = UIKeyboardAppearanceDefault; + _keyboardType = UIKeyboardTypeDefault; + _returnKeyType = UIReturnKeyDone; + _secureTextEntry = NO; + _enableDeltaModel = NO; + _enableInteractiveSelection = YES; + _accessibilityEnabled = NO; + _smartQuotesType = UITextSmartQuotesTypeYes; + _smartDashesType = UITextSmartDashesTypeYes; + _selectionRects = [[NSArray alloc] init]; + + if (@available(iOS 14.0, *)) { + UIScribbleInteraction* interaction = [[UIScribbleInteraction alloc] initWithDelegate:self]; + [self addInteraction:interaction]; + } + } + + if (@available(iOS 16.0, *)) { + _editMenuInteraction = [[UIEditMenuInteraction alloc] initWithDelegate:self]; + [self addInteraction:_editMenuInteraction]; + } + + return self; +} + +- (void)handleSearchWebAction { + [self.textInputDelegate flutterTextInputView:self + searchWebWithSelectedText:[self textInRange:_selectedTextRange]]; +} + +- (void)handleLookUpAction { + [self.textInputDelegate flutterTextInputView:self + lookUpSelectedText:[self textInRange:_selectedTextRange]]; +} + +- (void)handleShareAction { + [self.textInputDelegate flutterTextInputView:self + shareSelectedText:[self textInRange:_selectedTextRange]]; +} + +// DFS algorithm to search a UICommand from the menu tree. +- (UICommand*)searchCommandWithSelector:(SEL)selector + element:(UIMenuElement*)element API_AVAILABLE(ios(16.0)) { + if ([element isKindOfClass:UICommand.class]) { + UICommand* command = (UICommand*)element; + return command.action == selector ? command : nil; + } else if ([element isKindOfClass:UIMenu.class]) { + NSArray* children = ((UIMenu*)element).children; + for (UIMenuElement* child in children) { + UICommand* result = [self searchCommandWithSelector:selector element:child]; + if (result) { + return result; + } + } + return nil; + } else { + return nil; + } +} + +- (void)addBasicEditingCommandToItems:(NSMutableArray*)items + type:(NSString*)type + selector:(SEL)selector + suggestedMenu:(UIMenu*)suggestedMenu { + UICommand* command = [self searchCommandWithSelector:selector element:suggestedMenu]; + if (command) { + [items addObject:command]; + } else { + FML_LOG(ERROR) << "Cannot find context menu item of type \"" << type.UTF8String << "\"."; + } +} + +- (void)addAdditionalBasicCommandToItems:(NSMutableArray*)items + type:(NSString*)type + selector:(SEL)selector + encodedItem:(NSDictionary*)encodedItem { + NSString* title = encodedItem[@"title"]; + if (title) { + UICommand* command = [UICommand commandWithTitle:title + image:nil + action:selector + propertyList:nil]; + [items addObject:command]; + } else { + FML_LOG(ERROR) << "Missing title for context menu item of type \"" << type.UTF8String << "\"."; + } +} + +- (UIMenu*)editMenuInteraction:(UIEditMenuInteraction*)interaction + menuForConfiguration:(UIEditMenuConfiguration*)configuration + suggestedActions:(NSArray*)suggestedActions API_AVAILABLE(ios(16.0)) { + UIMenu* suggestedMenu = [UIMenu menuWithChildren:suggestedActions]; + if (!_editMenuItems) { + return suggestedMenu; + } + + NSMutableArray* items = [NSMutableArray array]; + for (NSDictionary* encodedItem in _editMenuItems) { + NSString* type = encodedItem[@"type"]; + if ([type isEqualToString:@"copy"]) { + [self addBasicEditingCommandToItems:items + type:type + selector:@selector(copy:) + suggestedMenu:suggestedMenu]; + } else if ([type isEqualToString:@"paste"]) { + [self addBasicEditingCommandToItems:items + type:type + selector:@selector(paste:) + suggestedMenu:suggestedMenu]; + } else if ([type isEqualToString:@"cut"]) { + [self addBasicEditingCommandToItems:items + type:type + selector:@selector(cut:) + suggestedMenu:suggestedMenu]; + } else if ([type isEqualToString:@"delete"]) { + [self addBasicEditingCommandToItems:items + type:type + selector:@selector(delete:) + suggestedMenu:suggestedMenu]; + } else if ([type isEqualToString:@"selectAll"]) { + [self addBasicEditingCommandToItems:items + type:type + selector:@selector(selectAll:) + suggestedMenu:suggestedMenu]; + } else if ([type isEqualToString:@"searchWeb"]) { + [self addAdditionalBasicCommandToItems:items + type:type + selector:@selector(handleSearchWebAction) + encodedItem:encodedItem]; + } else if ([type isEqualToString:@"share"]) { + [self addAdditionalBasicCommandToItems:items + type:type + selector:@selector(handleShareAction) + encodedItem:encodedItem]; + } else if ([type isEqualToString:@"lookUp"]) { + [self addAdditionalBasicCommandToItems:items + type:type + selector:@selector(handleLookUpAction) + encodedItem:encodedItem]; + } + } + return [UIMenu menuWithChildren:items]; +} + +- (void)editMenuInteraction:(UIEditMenuInteraction*)interaction + willDismissMenuForConfiguration:(UIEditMenuConfiguration*)configuration + animator:(id)animator + API_AVAILABLE(ios(16.0)) { + [self.textInputDelegate flutterTextInputView:self + willDismissEditMenuWithTextInputClient:_textInputClient]; +} + +- (CGRect)editMenuInteraction:(UIEditMenuInteraction*)interaction + targetRectForConfiguration:(UIEditMenuConfiguration*)configuration API_AVAILABLE(ios(16.0)) { + return _editMenuTargetRect; +} + +- (void)showEditMenuWithTargetRect:(CGRect)targetRect + items:(NSArray*)items API_AVAILABLE(ios(16.0)) { + _editMenuTargetRect = targetRect; + _editMenuItems = items; + UIEditMenuConfiguration* config = + [UIEditMenuConfiguration configurationWithIdentifier:nil sourcePoint:CGPointZero]; + [self.editMenuInteraction presentEditMenuWithConfiguration:config]; +} + +- (void)hideEditMenu API_AVAILABLE(ios(16.0)) { + [self.editMenuInteraction dismissMenu]; +} + +- (void)configureWithDictionary:(NSDictionary*)configuration { + NSDictionary* inputType = configuration[kKeyboardType]; + NSString* keyboardAppearance = configuration[kKeyboardAppearance]; + NSDictionary* autofill = configuration[kAutofillProperties]; + + self.secureTextEntry = [configuration[kSecureTextEntry] boolValue]; + self.enableDeltaModel = [configuration[kEnableDeltaModel] boolValue]; + + _isSystemKeyboardEnabled = ShouldShowSystemKeyboard(inputType); + self.keyboardType = ToUIKeyboardType(inputType); + self.returnKeyType = ToUIReturnKeyType(configuration[kInputAction]); + self.autocapitalizationType = ToUITextAutoCapitalizationType(configuration); + _enableInteractiveSelection = [configuration[kEnableInteractiveSelection] boolValue]; + NSString* smartDashesType = configuration[kSmartDashesType]; + // This index comes from the SmartDashesType enum in the framework. + bool smartDashesIsDisabled = smartDashesType && [smartDashesType isEqualToString:@"0"]; + self.smartDashesType = smartDashesIsDisabled ? UITextSmartDashesTypeNo : UITextSmartDashesTypeYes; + NSString* smartQuotesType = configuration[kSmartQuotesType]; + // This index comes from the SmartQuotesType enum in the framework. + bool smartQuotesIsDisabled = smartQuotesType && [smartQuotesType isEqualToString:@"0"]; + self.smartQuotesType = smartQuotesIsDisabled ? UITextSmartQuotesTypeNo : UITextSmartQuotesTypeYes; + if ([keyboardAppearance isEqualToString:@"Brightness.dark"]) { + self.keyboardAppearance = UIKeyboardAppearanceDark; + } else if ([keyboardAppearance isEqualToString:@"Brightness.light"]) { + self.keyboardAppearance = UIKeyboardAppearanceLight; + } else { + self.keyboardAppearance = UIKeyboardAppearanceDefault; + } + NSString* autocorrect = configuration[kAutocorrectionType]; + bool autocorrectIsDisabled = autocorrect && ![autocorrect boolValue]; + self.autocorrectionType = + autocorrectIsDisabled ? UITextAutocorrectionTypeNo : UITextAutocorrectionTypeDefault; + self.spellCheckingType = + autocorrectIsDisabled ? UITextSpellCheckingTypeNo : UITextSpellCheckingTypeDefault; + self.autofillId = AutofillIdFromDictionary(configuration); + if (autofill == nil) { + self.textContentType = @""; + } else { + self.textContentType = ToUITextContentType(autofill[kAutofillHints]); + [self setTextInputState:autofill[kAutofillEditingValue]]; + NSAssert(_autofillId, @"The autofill configuration must contain an autofill id"); + } + // The input field needs to be visible for the system autofill + // to find it. + self.isVisibleToAutofill = autofill || _secureTextEntry; +} + +- (UITextContentType)textContentType { + return _textContentType; +} + +// Prevent UIKit from showing selection handles or highlights. This is needed +// because Scribble interactions require the view to have it's actual frame on +// the screen. They're not needed on iOS 17 with the new +// UITextSelectionDisplayInteraction API. +// +// These are undocumented methods. On iOS 17, the insertion point color is also +// used as the highlighted background of the selected IME candidate: +// https://github.com/flutter/flutter/issues/132548 +// So the respondsToSelector method is overridden to return NO for this method +// on iOS 17+. +- (UIColor*)insertionPointColor { + return [UIColor clearColor]; +} + +- (UIColor*)selectionBarColor { + return [UIColor clearColor]; +} + +- (UIColor*)selectionHighlightColor { + return [UIColor clearColor]; +} + +- (UIInputViewController*)inputViewController { + if (_isSystemKeyboardEnabled) { + return nil; + } + + if (!_inputViewController) { + _inputViewController = [[UIInputViewController alloc] init]; + } + return _inputViewController; +} + +- (id)textInputDelegate { + return _textInputPlugin.textInputDelegate; +} + +- (BOOL)respondsToSelector:(SEL)selector { + if (@available(iOS 17.0, *)) { + // See the comment on this method. + if (selector == @selector(insertionPointColor)) { + return NO; + } + } + return [super respondsToSelector:selector]; +} + +- (void)setTextInputClient:(int)client { + _textInputClient = client; + _hasPlaceholder = NO; +} + +- (UITextInteraction*)textInteraction API_AVAILABLE(ios(13.0)) { + if (!_textInteraction) { + _textInteraction = [UITextInteraction textInteractionForMode:UITextInteractionModeEditable]; + _textInteraction.textInput = self; + } + return _textInteraction; +} + +- (void)setTextInputState:(NSDictionary*)state { + if (@available(iOS 13.0, *)) { + // [UITextInteraction willMoveToView:] sometimes sets the textInput's inputDelegate + // to nil. This is likely a bug in UIKit. In order to inform the keyboard of text + // and selection changes when that happens, add a dummy UITextInteraction to this + // view so it sets a valid inputDelegate that we can call textWillChange et al. on. + // See https://github.com/flutter/engine/pull/32881. + if (!self.inputDelegate && self.isFirstResponder) { + [self addInteraction:self.textInteraction]; + } + } + + NSString* newText = state[@"text"]; + BOOL textChanged = ![self.text isEqualToString:newText]; + if (textChanged) { + [self.inputDelegate textWillChange:self]; + [self.text setString:newText]; + } + NSInteger composingBase = [state[@"composingBase"] intValue]; + NSInteger composingExtent = [state[@"composingExtent"] intValue]; + NSRange composingRange = [self clampSelection:NSMakeRange(MIN(composingBase, composingExtent), + ABS(composingBase - composingExtent)) + forText:self.text]; + + self.markedTextRange = + composingRange.length > 0 ? [FlutterTextRange rangeWithNSRange:composingRange] : nil; + + NSRange selectedRange = [self clampSelectionFromBase:[state[@"selectionBase"] intValue] + extent:[state[@"selectionExtent"] intValue] + forText:self.text]; + + NSRange oldSelectedRange = [(FlutterTextRange*)self.selectedTextRange range]; + if (!NSEqualRanges(selectedRange, oldSelectedRange)) { + [self.inputDelegate selectionWillChange:self]; + + [self setSelectedTextRangeLocal:[FlutterTextRange rangeWithNSRange:selectedRange]]; + + _selectionAffinity = kTextAffinityDownstream; + if ([state[@"selectionAffinity"] isEqualToString:@(kTextAffinityUpstream)]) { + _selectionAffinity = kTextAffinityUpstream; + } + [self.inputDelegate selectionDidChange:self]; + } + + if (textChanged) { + [self.inputDelegate textDidChange:self]; + } + + if (@available(iOS 13.0, *)) { + if (_textInteraction) { + [self removeInteraction:_textInteraction]; + } + } +} + +// Forward touches to the viewResponder to allow tapping inside the UITextField as normal. +- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event { + _scribbleFocusStatus = FlutterScribbleFocusStatusUnfocused; + [self resetScribbleInteractionStatusIfEnding]; + [self.viewResponder touchesBegan:touches withEvent:event]; +} + +- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event { + [self.viewResponder touchesMoved:touches withEvent:event]; +} + +- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event { + [self.viewResponder touchesEnded:touches withEvent:event]; +} + +- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event { + [self.viewResponder touchesCancelled:touches withEvent:event]; +} + +- (void)touchesEstimatedPropertiesUpdated:(NSSet*)touches { + [self.viewResponder touchesEstimatedPropertiesUpdated:touches]; +} + +// Extracts the selection information from the editing state dictionary. +// +// The state may contain an invalid selection, such as when no selection was +// explicitly set in the framework. This is handled here by setting the +// selection to (0,0). In contrast, Android handles this situation by +// clearing the selection, but the result in both cases is that the cursor +// is placed at the beginning of the field. +- (NSRange)clampSelectionFromBase:(int)selectionBase + extent:(int)selectionExtent + forText:(NSString*)text { + int loc = MIN(selectionBase, selectionExtent); + int len = ABS(selectionExtent - selectionBase); + return loc < 0 ? NSMakeRange(0, 0) + : [self clampSelection:NSMakeRange(loc, len) forText:self.text]; +} + +- (NSRange)clampSelection:(NSRange)range forText:(NSString*)text { + NSUInteger start = MIN(MAX(range.location, 0), text.length); + NSUInteger length = MIN(range.length, text.length - start); + return NSMakeRange(start, length); +} + +- (BOOL)isVisibleToAutofill { + return self.frame.size.width > 0 && self.frame.size.height > 0; +} + +// An input view is generally ignored by password autofill attempts, if it's +// not the first responder and is zero-sized. For input fields that are in the +// autofill context but do not belong to the current autofill group, setting +// their frames to CGRectZero prevents ios autofill from taking them into +// account. +- (void)setIsVisibleToAutofill:(BOOL)isVisibleToAutofill { + // This probably needs to change (think it is getting overwritten by the updateSizeAndTransform + // stuff for now). + self.frame = isVisibleToAutofill ? CGRectMake(0, 0, 1, 1) : CGRectZero; +} + +#pragma mark UIScribbleInteractionDelegate + +// Checks whether Scribble features are possibly available – meaning this is an iPad running iOS +// 14 or higher. +- (BOOL)isScribbleAvailable { + if (@available(iOS 14.0, *)) { + if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { + return YES; + } + } + return NO; +} + +- (void)scribbleInteractionWillBeginWriting:(UIScribbleInteraction*)interaction + API_AVAILABLE(ios(14.0)) { + _scribbleInteractionStatus = FlutterScribbleInteractionStatusStarted; + [self.textInputDelegate flutterTextInputViewScribbleInteractionBegan:self]; +} + +- (void)scribbleInteractionDidFinishWriting:(UIScribbleInteraction*)interaction + API_AVAILABLE(ios(14.0)) { + _scribbleInteractionStatus = FlutterScribbleInteractionStatusEnding; + [self.textInputDelegate flutterTextInputViewScribbleInteractionFinished:self]; +} + +- (BOOL)scribbleInteraction:(UIScribbleInteraction*)interaction + shouldBeginAtLocation:(CGPoint)location API_AVAILABLE(ios(14.0)) { + return YES; +} + +- (BOOL)scribbleInteractionShouldDelayFocus:(UIScribbleInteraction*)interaction + API_AVAILABLE(ios(14.0)) { + return NO; +} + +#pragma mark - UIResponder Overrides + +- (BOOL)canBecomeFirstResponder { + // Only the currently focused input field can + // become the first responder. This prevents iOS + // from changing focus by itself (the framework + // focus will be out of sync if that happens). + return _textInputClient != 0; +} + +- (BOOL)resignFirstResponder { + BOOL success = [super resignFirstResponder]; + if (success) { + if (!_preventCursorDismissWhenResignFirstResponder) { + [self.textInputDelegate flutterTextInputView:self + didResignFirstResponderWithTextInputClient:_textInputClient]; + } + } + return success; +} + +- (BOOL)canPerformAction:(SEL)action withSender:(id)sender { + if (action == @selector(paste:)) { + // Forbid pasting images, memojis, or other non-string content. + return [UIPasteboard generalPasteboard].hasStrings; + } else if (action == @selector(copy:) || action == @selector(cut:) || + action == @selector(delete:)) { + return [self textInRange:_selectedTextRange].length > 0; + } else if (action == @selector(selectAll:)) { + return self.hasText; + } + return [super canPerformAction:action withSender:sender]; +} + +#pragma mark - UIResponderStandardEditActions Overrides + +- (void)cut:(id)sender { + [UIPasteboard generalPasteboard].string = [self textInRange:_selectedTextRange]; + [self replaceRange:_selectedTextRange withText:@""]; +} + +- (void)copy:(id)sender { + [UIPasteboard generalPasteboard].string = [self textInRange:_selectedTextRange]; +} + +- (void)paste:(id)sender { + NSString* pasteboardString = [UIPasteboard generalPasteboard].string; + if (pasteboardString != nil) { + [self insertText:pasteboardString]; + } +} + +- (void)delete:(id)sender { + [self replaceRange:_selectedTextRange withText:@""]; +} + +- (void)selectAll:(id)sender { + [self setSelectedTextRange:[self textRangeFromPosition:[self beginningOfDocument] + toPosition:[self endOfDocument]]]; +} + +#pragma mark - UITextInput Overrides + +- (id)tokenizer { + if (_tokenizer == nil) { + _tokenizer = [[FlutterTokenizer alloc] initWithTextInput:self]; + } + return _tokenizer; +} + +- (UITextRange*)selectedTextRange { + return [_selectedTextRange copy]; +} + +// Change the range of selected text, without notifying the framework. +- (void)setSelectedTextRangeLocal:(UITextRange*)selectedTextRange { + if (_selectedTextRange != selectedTextRange) { + if (self.hasText) { + FlutterTextRange* flutterTextRange = (FlutterTextRange*)selectedTextRange; + _selectedTextRange = [[FlutterTextRange + rangeWithNSRange:fml::RangeForCharactersInRange(self.text, flutterTextRange.range)] copy]; + } else { + _selectedTextRange = [selectedTextRange copy]; + } + } +} + +- (void)setSelectedTextRange:(UITextRange*)selectedTextRange { + if (!_enableInteractiveSelection) { + return; + } + + [self setSelectedTextRangeLocal:selectedTextRange]; + + if (_enableDeltaModel) { + [self updateEditingStateWithDelta:flutter::TextEditingDelta([self.text UTF8String])]; + } else { + [self updateEditingState]; + } + + if (_scribbleInteractionStatus != FlutterScribbleInteractionStatusNone || + _scribbleFocusStatus == FlutterScribbleFocusStatusFocused) { + NSAssert([selectedTextRange isKindOfClass:[FlutterTextRange class]], + @"Expected a FlutterTextRange for range (got %@).", [selectedTextRange class]); + FlutterTextRange* flutterTextRange = (FlutterTextRange*)selectedTextRange; + if (flutterTextRange.range.length > 0) { + [self.textInputDelegate flutterTextInputView:self showToolbar:_textInputClient]; + } + } + + [self resetScribbleInteractionStatusIfEnding]; +} + +- (id)insertDictationResultPlaceholder { + return @""; +} + +- (void)removeDictationResultPlaceholder:(id)placeholder willInsertResult:(BOOL)willInsertResult { +} + +- (NSString*)textInRange:(UITextRange*)range { + if (!range) { + return nil; + } + NSAssert([range isKindOfClass:[FlutterTextRange class]], + @"Expected a FlutterTextRange for range (got %@).", [range class]); + NSRange textRange = ((FlutterTextRange*)range).range; + if (textRange.location == NSNotFound) { + // Avoids [crashes](https://github.com/flutter/flutter/issues/138464) from an assertion + // against NSNotFound. + // TODO(hellohuanlin): This is a temp workaround, but we should look into why + // framework is providing NSNotFound to the engine. + // https://github.com/flutter/flutter/issues/160100 + return nil; + } + // Sanitize the range to prevent going out of bounds. + NSUInteger location = MIN(textRange.location, self.text.length); + NSUInteger length = MIN(self.text.length - location, textRange.length); + NSRange safeRange = NSMakeRange(location, length); + return [self.text substringWithRange:safeRange]; +} + +// Replace the text within the specified range with the given text, +// without notifying the framework. +- (void)replaceRangeLocal:(NSRange)range withText:(NSString*)text { + [self.text replaceCharactersInRange:[self clampSelection:range forText:self.text] + withString:text]; + + // Adjust the selected range and the marked text range. There's no + // documentation but UITextField always sets markedTextRange to nil, + // and collapses the selection to the end of the new replacement text. + const NSRange newSelectionRange = + [self clampSelection:NSMakeRange(range.location + text.length, 0) forText:self.text]; + + [self setSelectedTextRangeLocal:[FlutterTextRange rangeWithNSRange:newSelectionRange]]; + self.markedTextRange = nil; +} + +- (void)replaceRange:(UITextRange*)range withText:(NSString*)text { + NSString* textBeforeChange = [self.text copy]; + NSRange replaceRange = ((FlutterTextRange*)range).range; + [self replaceRangeLocal:replaceRange withText:text]; + if (_enableDeltaModel) { + NSRange nextReplaceRange = [self clampSelection:replaceRange forText:textBeforeChange]; + [self updateEditingStateWithDelta:flutter::TextEditingDelta( + [textBeforeChange UTF8String], + flutter::TextRange( + nextReplaceRange.location, + nextReplaceRange.location + nextReplaceRange.length), + [text UTF8String])]; + } else { + [self updateEditingState]; + } +} + +- (BOOL)shouldChangeTextInRange:(UITextRange*)range replacementText:(NSString*)text { + // `temporarilyDeletedComposedCharacter` should only be used during a single text change session. + // So it needs to be cleared at the start of each text editing session. + self.temporarilyDeletedComposedCharacter = nil; + + if (self.returnKeyType == UIReturnKeyDefault && [text isEqualToString:@"\n"]) { + [self.textInputDelegate flutterTextInputView:self + performAction:FlutterTextInputActionNewline + withClient:_textInputClient]; + return YES; + } + + if ([text isEqualToString:@"\n"]) { + FlutterTextInputAction action; + switch (self.returnKeyType) { + case UIReturnKeyDefault: + action = FlutterTextInputActionUnspecified; + break; + case UIReturnKeyDone: + action = FlutterTextInputActionDone; + break; + case UIReturnKeyGo: + action = FlutterTextInputActionGo; + break; + case UIReturnKeySend: + action = FlutterTextInputActionSend; + break; + case UIReturnKeySearch: + case UIReturnKeyGoogle: + case UIReturnKeyYahoo: + action = FlutterTextInputActionSearch; + break; + case UIReturnKeyNext: + action = FlutterTextInputActionNext; + break; + case UIReturnKeyContinue: + action = FlutterTextInputActionContinue; + break; + case UIReturnKeyJoin: + action = FlutterTextInputActionJoin; + break; + case UIReturnKeyRoute: + action = FlutterTextInputActionRoute; + break; + case UIReturnKeyEmergencyCall: + action = FlutterTextInputActionEmergencyCall; + break; + } + + [self.textInputDelegate flutterTextInputView:self + performAction:action + withClient:_textInputClient]; + return NO; + } + + return YES; +} + +// Either replaces the existing marked text or, if none is present, inserts it in +// place of the current selection. +- (void)setMarkedText:(NSString*)markedText selectedRange:(NSRange)markedSelectedRange { + NSString* textBeforeChange = [self.text copy]; + + if (_scribbleInteractionStatus != FlutterScribbleInteractionStatusNone || + _scribbleFocusStatus != FlutterScribbleFocusStatusUnfocused) { + return; + } + + if (markedText == nil) { + markedText = @""; + } + + const FlutterTextRange* currentMarkedTextRange = (FlutterTextRange*)self.markedTextRange; + const NSRange& actualReplacedRange = currentMarkedTextRange && !currentMarkedTextRange.isEmpty + ? currentMarkedTextRange.range + : _selectedTextRange.range; + // No need to call replaceRangeLocal as this method always adjusts the + // selected/marked text ranges anyways. + [self.text replaceCharactersInRange:actualReplacedRange withString:markedText]; + + const NSRange newMarkedRange = NSMakeRange(actualReplacedRange.location, markedText.length); + self.markedTextRange = + newMarkedRange.length > 0 ? [FlutterTextRange rangeWithNSRange:newMarkedRange] : nil; + + [self setSelectedTextRangeLocal: + [FlutterTextRange + rangeWithNSRange:[self clampSelection:NSMakeRange(markedSelectedRange.location + + newMarkedRange.location, + markedSelectedRange.length) + forText:self.text]]]; + if (_enableDeltaModel) { + NSRange nextReplaceRange = [self clampSelection:actualReplacedRange forText:textBeforeChange]; + [self updateEditingStateWithDelta:flutter::TextEditingDelta( + [textBeforeChange UTF8String], + flutter::TextRange( + nextReplaceRange.location, + nextReplaceRange.location + nextReplaceRange.length), + [markedText UTF8String])]; + } else { + [self updateEditingState]; + } +} + +- (void)unmarkText { + if (!self.markedTextRange) { + return; + } + self.markedTextRange = nil; + if (_enableDeltaModel) { + [self updateEditingStateWithDelta:flutter::TextEditingDelta([self.text UTF8String])]; + } else { + [self updateEditingState]; + } +} + +- (UITextRange*)textRangeFromPosition:(UITextPosition*)fromPosition + toPosition:(UITextPosition*)toPosition { + NSUInteger fromIndex = ((FlutterTextPosition*)fromPosition).index; + NSUInteger toIndex = ((FlutterTextPosition*)toPosition).index; + if (toIndex >= fromIndex) { + return [FlutterTextRange rangeWithNSRange:NSMakeRange(fromIndex, toIndex - fromIndex)]; + } else { + // toIndex can be smaller than fromIndex, because + // UITextInputStringTokenizer does not handle CJK characters + // well in some cases. See: + // https://github.com/flutter/flutter/issues/58750#issuecomment-644469521 + // Swap fromPosition and toPosition to match the behavior of native + // UITextViews. + return [FlutterTextRange rangeWithNSRange:NSMakeRange(toIndex, fromIndex - toIndex)]; + } +} + +- (NSUInteger)decrementOffsetPosition:(NSUInteger)position { + return fml::RangeForCharacterAtIndex(self.text, MAX(0, position - 1)).location; +} + +- (NSUInteger)incrementOffsetPosition:(NSUInteger)position { + NSRange charRange = fml::RangeForCharacterAtIndex(self.text, position); + return MIN(position + charRange.length, self.text.length); +} + +- (UITextPosition*)positionFromPosition:(UITextPosition*)position offset:(NSInteger)offset { + NSUInteger offsetPosition = ((FlutterTextPosition*)position).index; + + NSInteger newLocation = (NSInteger)offsetPosition + offset; + if (newLocation < 0 || newLocation > (NSInteger)self.text.length) { + return nil; + } + + if (_scribbleInteractionStatus != FlutterScribbleInteractionStatusNone) { + return [FlutterTextPosition positionWithIndex:newLocation]; + } + + if (offset >= 0) { + for (NSInteger i = 0; i < offset && offsetPosition < self.text.length; ++i) { + offsetPosition = [self incrementOffsetPosition:offsetPosition]; + } + } else { + for (NSInteger i = 0; i < ABS(offset) && offsetPosition > 0; ++i) { + offsetPosition = [self decrementOffsetPosition:offsetPosition]; + } + } + return [FlutterTextPosition positionWithIndex:offsetPosition]; +} + +- (UITextPosition*)positionFromPosition:(UITextPosition*)position + inDirection:(UITextLayoutDirection)direction + offset:(NSInteger)offset { + // TODO(cbracken) Add RTL handling. + switch (direction) { + case UITextLayoutDirectionLeft: + case UITextLayoutDirectionUp: + return [self positionFromPosition:position offset:offset * -1]; + case UITextLayoutDirectionRight: + case UITextLayoutDirectionDown: + return [self positionFromPosition:position offset:1]; + } +} + +- (UITextPosition*)beginningOfDocument { + return [FlutterTextPosition positionWithIndex:0 affinity:UITextStorageDirectionForward]; +} + +- (UITextPosition*)endOfDocument { + return [FlutterTextPosition positionWithIndex:self.text.length + affinity:UITextStorageDirectionBackward]; +} + +- (NSComparisonResult)comparePosition:(UITextPosition*)position toPosition:(UITextPosition*)other { + NSUInteger positionIndex = ((FlutterTextPosition*)position).index; + NSUInteger otherIndex = ((FlutterTextPosition*)other).index; + if (positionIndex < otherIndex) { + return NSOrderedAscending; + } + if (positionIndex > otherIndex) { + return NSOrderedDescending; + } + UITextStorageDirection positionAffinity = ((FlutterTextPosition*)position).affinity; + UITextStorageDirection otherAffinity = ((FlutterTextPosition*)other).affinity; + if (positionAffinity == otherAffinity) { + return NSOrderedSame; + } + if (positionAffinity == UITextStorageDirectionBackward) { + // positionAffinity points backwards, otherAffinity points forwards + return NSOrderedAscending; + } + // positionAffinity points forwards, otherAffinity points backwards + return NSOrderedDescending; +} + +- (NSInteger)offsetFromPosition:(UITextPosition*)from toPosition:(UITextPosition*)toPosition { + return ((FlutterTextPosition*)toPosition).index - ((FlutterTextPosition*)from).index; +} + +- (UITextPosition*)positionWithinRange:(UITextRange*)range + farthestInDirection:(UITextLayoutDirection)direction { + NSUInteger index; + UITextStorageDirection affinity; + switch (direction) { + case UITextLayoutDirectionLeft: + case UITextLayoutDirectionUp: + index = ((FlutterTextPosition*)range.start).index; + affinity = UITextStorageDirectionForward; + break; + case UITextLayoutDirectionRight: + case UITextLayoutDirectionDown: + index = ((FlutterTextPosition*)range.end).index; + affinity = UITextStorageDirectionBackward; + break; + } + return [FlutterTextPosition positionWithIndex:index affinity:affinity]; +} + +- (UITextRange*)characterRangeByExtendingPosition:(UITextPosition*)position + inDirection:(UITextLayoutDirection)direction { + NSUInteger positionIndex = ((FlutterTextPosition*)position).index; + NSUInteger startIndex; + NSUInteger endIndex; + switch (direction) { + case UITextLayoutDirectionLeft: + case UITextLayoutDirectionUp: + startIndex = [self decrementOffsetPosition:positionIndex]; + endIndex = positionIndex; + break; + case UITextLayoutDirectionRight: + case UITextLayoutDirectionDown: + startIndex = positionIndex; + endIndex = [self incrementOffsetPosition:positionIndex]; + break; + } + return [FlutterTextRange rangeWithNSRange:NSMakeRange(startIndex, endIndex - startIndex)]; +} + +#pragma mark - UITextInput text direction handling + +- (UITextWritingDirection)baseWritingDirectionForPosition:(UITextPosition*)position + inDirection:(UITextStorageDirection)direction { + // TODO(cbracken) Add RTL handling. + return UITextWritingDirectionNatural; +} + +- (void)setBaseWritingDirection:(UITextWritingDirection)writingDirection + forRange:(UITextRange*)range { + // TODO(cbracken) Add RTL handling. +} + +#pragma mark - UITextInput cursor, selection rect handling + +- (void)setMarkedRect:(CGRect)markedRect { + _markedRect = markedRect; + // Invalidate the cache. + _cachedFirstRect = kInvalidFirstRect; +} + +// This method expects a 4x4 perspective matrix +// stored in a NSArray in column-major order. +- (void)setEditableTransform:(NSArray*)matrix { + CATransform3D* transform = &_editableTransform; + + transform->m11 = [matrix[0] doubleValue]; + transform->m12 = [matrix[1] doubleValue]; + transform->m13 = [matrix[2] doubleValue]; + transform->m14 = [matrix[3] doubleValue]; + + transform->m21 = [matrix[4] doubleValue]; + transform->m22 = [matrix[5] doubleValue]; + transform->m23 = [matrix[6] doubleValue]; + transform->m24 = [matrix[7] doubleValue]; + + transform->m31 = [matrix[8] doubleValue]; + transform->m32 = [matrix[9] doubleValue]; + transform->m33 = [matrix[10] doubleValue]; + transform->m34 = [matrix[11] doubleValue]; + + transform->m41 = [matrix[12] doubleValue]; + transform->m42 = [matrix[13] doubleValue]; + transform->m43 = [matrix[14] doubleValue]; + transform->m44 = [matrix[15] doubleValue]; + + // Invalidate the cache. + _cachedFirstRect = kInvalidFirstRect; +} + +// Returns the bounding CGRect of the transformed incomingRect, in the view's +// coordinates. +- (CGRect)localRectFromFrameworkTransform:(CGRect)incomingRect { + CGPoint points[] = { + incomingRect.origin, + CGPointMake(incomingRect.origin.x, incomingRect.origin.y + incomingRect.size.height), + CGPointMake(incomingRect.origin.x + incomingRect.size.width, incomingRect.origin.y), + CGPointMake(incomingRect.origin.x + incomingRect.size.width, + incomingRect.origin.y + incomingRect.size.height)}; + + CGPoint origin = CGPointMake(CGFLOAT_MAX, CGFLOAT_MAX); + CGPoint farthest = CGPointMake(-CGFLOAT_MAX, -CGFLOAT_MAX); + + for (int i = 0; i < 4; i++) { + const CGPoint point = points[i]; + + CGFloat x = _editableTransform.m11 * point.x + _editableTransform.m21 * point.y + + _editableTransform.m41; + CGFloat y = _editableTransform.m12 * point.x + _editableTransform.m22 * point.y + + _editableTransform.m42; + + const CGFloat w = _editableTransform.m14 * point.x + _editableTransform.m24 * point.y + + _editableTransform.m44; + + if (w == 0.0) { + return kInvalidFirstRect; + } else if (w != 1.0) { + x /= w; + y /= w; + } + + origin.x = MIN(origin.x, x); + origin.y = MIN(origin.y, y); + farthest.x = MAX(farthest.x, x); + farthest.y = MAX(farthest.y, y); + } + return CGRectMake(origin.x, origin.y, farthest.x - origin.x, farthest.y - origin.y); +} + +// The following methods are required to support force-touch cursor positioning +// and to position the +// candidates view for multi-stage input methods (e.g., Japanese) when using a +// physical keyboard. +// Returns the rect for the queried range, or a subrange through the end of line, if +// the range encompasses multiple lines. +- (CGRect)firstRectForRange:(UITextRange*)range { + NSAssert([range.start isKindOfClass:[FlutterTextPosition class]], + @"Expected a FlutterTextPosition for range.start (got %@).", [range.start class]); + NSAssert([range.end isKindOfClass:[FlutterTextPosition class]], + @"Expected a FlutterTextPosition for range.end (got %@).", [range.end class]); + NSUInteger start = ((FlutterTextPosition*)range.start).index; + NSUInteger end = ((FlutterTextPosition*)range.end).index; + if (_markedTextRange != nil) { + // The candidates view can't be shown if the framework has not sent the + // first caret rect. + if (CGRectEqualToRect(kInvalidFirstRect, _markedRect)) { + return kInvalidFirstRect; + } + + if (CGRectEqualToRect(_cachedFirstRect, kInvalidFirstRect)) { + // If the width returned is too small, that means the framework sent us + // the caret rect instead of the marked text rect. Expand it to 0.2 so + // the IME candidates view would show up. + CGRect rect = _markedRect; + if (CGRectIsEmpty(rect)) { + rect = CGRectInset(rect, -0.1, 0); + } + _cachedFirstRect = [self localRectFromFrameworkTransform:rect]; + } + + UIView* hostView = _textInputPlugin.hostView; + NSAssert(hostView == nil || [self isDescendantOfView:hostView], @"%@ is not a descendant of %@", + self, hostView); + return hostView ? [hostView convertRect:_cachedFirstRect toView:self] : _cachedFirstRect; + } + + if (_scribbleInteractionStatus == FlutterScribbleInteractionStatusNone && + _scribbleFocusStatus == FlutterScribbleFocusStatusUnfocused) { + if (@available(iOS 17.0, *)) { + // Disable auto-correction highlight feature for iOS 17+. + // In iOS 17+, whenever a character is inserted or deleted, the system will always query + // the rect for every single character of the current word. + // GitHub Issue: https://github.com/flutter/flutter/issues/128406 + } else { + // This tells the framework to show the highlight for incorrectly spelled word that is + // about to be auto-corrected. + // There is no other UITextInput API that informs about the auto-correction highlight. + // So we simply add the call here as a workaround. + [self.textInputDelegate flutterTextInputView:self + showAutocorrectionPromptRectForStart:start + end:end + withClient:_textInputClient]; + } + } + + // The iOS 16 system highlight does not repect the height returned by `firstRectForRange` + // API (unlike iOS 17). So we return CGRectZero to hide it (unless if scribble is enabled). + // To support scribble's advanced gestures (e.g. insert a space with a vertical bar), + // at least 1 character's width is required. + if (@available(iOS 17, *)) { + // No-op + } else if (![self isScribbleAvailable]) { + return CGRectZero; + } + + NSUInteger first = start; + if (end < start) { + first = end; + } + + CGRect startSelectionRect = CGRectNull; + CGRect endSelectionRect = CGRectNull; + // Selection rects from different langauges may have different minY/maxY. + // So we need to iterate through each rects to update minY/maxY. + CGFloat minY = CGFLOAT_MAX; + CGFloat maxY = CGFLOAT_MIN; + + FlutterTextRange* textRange = [FlutterTextRange + rangeWithNSRange:fml::RangeForCharactersInRange(self.text, NSMakeRange(0, self.text.length))]; + for (NSUInteger i = 0; i < [_selectionRects count]; i++) { + BOOL startsOnOrBeforeStartOfRange = _selectionRects[i].position <= first; + BOOL isLastSelectionRect = i + 1 == [_selectionRects count]; + BOOL endOfTextIsAfterStartOfRange = isLastSelectionRect && textRange.range.length > first; + BOOL nextSelectionRectIsAfterStartOfRange = + !isLastSelectionRect && _selectionRects[i + 1].position > first; + if (startsOnOrBeforeStartOfRange && + (endOfTextIsAfterStartOfRange || nextSelectionRectIsAfterStartOfRange)) { + // TODO(hellohaunlin): Remove iOS 17 check. The logic should also work for older versions. + if (@available(iOS 17, *)) { + startSelectionRect = _selectionRects[i].rect; + } else { + return _selectionRects[i].rect; + } + } + if (!CGRectIsNull(startSelectionRect)) { + minY = fmin(minY, CGRectGetMinY(_selectionRects[i].rect)); + maxY = fmax(maxY, CGRectGetMaxY(_selectionRects[i].rect)); + BOOL endsOnOrAfterEndOfRange = _selectionRects[i].position >= end - 1; // end is exclusive + BOOL nextSelectionRectIsOnNextLine = + !isLastSelectionRect && + // Selection rects from different langauges in 2 lines may overlap with each other. + // A good approximation is to check if the center of next rect is below the bottom of + // current rect. + // TODO(hellohuanlin): Consider passing the line break info from framework. + CGRectGetMidY(_selectionRects[i + 1].rect) > CGRectGetMaxY(_selectionRects[i].rect); + if (endsOnOrAfterEndOfRange || isLastSelectionRect || nextSelectionRectIsOnNextLine) { + endSelectionRect = _selectionRects[i].rect; + break; + } + } + } + if (CGRectIsNull(startSelectionRect) || CGRectIsNull(endSelectionRect)) { + return CGRectZero; + } else { + // fmin/fmax to support both LTR and RTL languages. + CGFloat minX = fmin(CGRectGetMinX(startSelectionRect), CGRectGetMinX(endSelectionRect)); + CGFloat maxX = fmax(CGRectGetMaxX(startSelectionRect), CGRectGetMaxX(endSelectionRect)); + return CGRectMake(minX, minY, maxX - minX, maxY - minY); + } +} + +- (CGRect)caretRectForPosition:(UITextPosition*)position { + NSInteger index = ((FlutterTextPosition*)position).index; + UITextStorageDirection affinity = ((FlutterTextPosition*)position).affinity; + // Get the selectionRect of the characters before and after the requested caret position. + NSArray* rects = [self + selectionRectsForRange:[FlutterTextRange + rangeWithNSRange:fml::RangeForCharactersInRange( + self.text, + NSMakeRange( + MAX(0, index - 1), + (index >= (NSInteger)self.text.length) + ? 1 + : 2))]]; + if (rects.count == 0) { + return CGRectZero; + } + if (index == 0) { + // There is no character before the caret, so this will be the bounds of the character after the + // caret position. + CGRect characterAfterCaret = rects[0].rect; + // Return a zero-width rectangle along the upstream edge of the character after the caret + // position. + if ([rects[0] isKindOfClass:[FlutterTextSelectionRect class]] && + ((FlutterTextSelectionRect*)rects[0]).isRTL) { + return CGRectMake(characterAfterCaret.origin.x + characterAfterCaret.size.width, + characterAfterCaret.origin.y, 0, characterAfterCaret.size.height); + } else { + return CGRectMake(characterAfterCaret.origin.x, characterAfterCaret.origin.y, 0, + characterAfterCaret.size.height); + } + } else if (rects.count == 2 && affinity == UITextStorageDirectionForward) { + // There are characters before and after the caret, with forward direction affinity. + // It's better to use the character after the caret. + CGRect characterAfterCaret = rects[1].rect; + // Return a zero-width rectangle along the upstream edge of the character after the caret + // position. + if ([rects[1] isKindOfClass:[FlutterTextSelectionRect class]] && + ((FlutterTextSelectionRect*)rects[1]).isRTL) { + return CGRectMake(characterAfterCaret.origin.x + characterAfterCaret.size.width, + characterAfterCaret.origin.y, 0, characterAfterCaret.size.height); + } else { + return CGRectMake(characterAfterCaret.origin.x, characterAfterCaret.origin.y, 0, + characterAfterCaret.size.height); + } + } + + // Covers 2 remaining cases: + // 1. there are characters before and after the caret, with backward direction affinity. + // 2. there is only 1 character before the caret (caret is at the end of text). + // For both cases, return a zero-width rectangle along the downstream edge of the character + // before the caret position. + CGRect characterBeforeCaret = rects[0].rect; + if ([rects[0] isKindOfClass:[FlutterTextSelectionRect class]] && + ((FlutterTextSelectionRect*)rects[0]).isRTL) { + return CGRectMake(characterBeforeCaret.origin.x, characterBeforeCaret.origin.y, 0, + characterBeforeCaret.size.height); + } else { + return CGRectMake(characterBeforeCaret.origin.x + characterBeforeCaret.size.width, + characterBeforeCaret.origin.y, 0, characterBeforeCaret.size.height); + } +} + +- (UITextPosition*)closestPositionToPoint:(CGPoint)point { + if ([_selectionRects count] == 0) { + NSAssert([_selectedTextRange.start isKindOfClass:[FlutterTextPosition class]], + @"Expected a FlutterTextPosition for position (got %@).", + [_selectedTextRange.start class]); + NSUInteger currentIndex = ((FlutterTextPosition*)_selectedTextRange.start).index; + UITextStorageDirection currentAffinity = + ((FlutterTextPosition*)_selectedTextRange.start).affinity; + return [FlutterTextPosition positionWithIndex:currentIndex affinity:currentAffinity]; + } + + FlutterTextRange* range = [FlutterTextRange + rangeWithNSRange:fml::RangeForCharactersInRange(self.text, NSMakeRange(0, self.text.length))]; + return [self closestPositionToPoint:point withinRange:range]; +} + +- (NSArray*)selectionRectsForRange:(UITextRange*)range { + // At least in the simulator, swapping to the Japanese keyboard crashes the app as this method + // is called immediately with a UITextRange with a UITextPosition rather than FlutterTextPosition + // for the start and end. + if (![range.start isKindOfClass:[FlutterTextPosition class]]) { + return @[]; + } + NSAssert([range.start isKindOfClass:[FlutterTextPosition class]], + @"Expected a FlutterTextPosition for range.start (got %@).", [range.start class]); + NSAssert([range.end isKindOfClass:[FlutterTextPosition class]], + @"Expected a FlutterTextPosition for range.end (got %@).", [range.end class]); + NSUInteger start = ((FlutterTextPosition*)range.start).index; + NSUInteger end = ((FlutterTextPosition*)range.end).index; + NSMutableArray* rects = [[NSMutableArray alloc] init]; + for (NSUInteger i = 0; i < [_selectionRects count]; i++) { + if (_selectionRects[i].position >= start && + (_selectionRects[i].position < end || + (start == end && _selectionRects[i].position <= end))) { + float width = _selectionRects[i].rect.size.width; + if (start == end) { + width = 0; + } + CGRect rect = CGRectMake(_selectionRects[i].rect.origin.x, _selectionRects[i].rect.origin.y, + width, _selectionRects[i].rect.size.height); + FlutterTextSelectionRect* selectionRect = [FlutterTextSelectionRect + selectionRectWithRectAndInfo:rect + position:_selectionRects[i].position + writingDirection:NSWritingDirectionNatural + containsStart:(i == 0) + containsEnd:(i == fml::RangeForCharactersInRange( + self.text, NSMakeRange(0, self.text.length)) + .length) + isVertical:NO]; + [rects addObject:selectionRect]; + } + } + return rects; +} + +- (UITextPosition*)closestPositionToPoint:(CGPoint)point withinRange:(UITextRange*)range { + NSAssert([range.start isKindOfClass:[FlutterTextPosition class]], + @"Expected a FlutterTextPosition for range.start (got %@).", [range.start class]); + NSAssert([range.end isKindOfClass:[FlutterTextPosition class]], + @"Expected a FlutterTextPosition for range.end (got %@).", [range.end class]); + NSUInteger start = ((FlutterTextPosition*)range.start).index; + NSUInteger end = ((FlutterTextPosition*)range.end).index; + + // Selecting text using the floating cursor is not as precise as the pencil. + // Allow further vertical deviation and base more of the decision on horizontal comparison. + CGFloat verticalPrecision = _isFloatingCursorActive ? 10 : 1; + + // Find the selectionRect with a leading-center point that is closest to a given point. + BOOL isFirst = YES; + NSUInteger _closestRectIndex = 0; + for (NSUInteger i = 0; i < [_selectionRects count]; i++) { + NSUInteger position = _selectionRects[i].position; + if (position >= start && position <= end) { + if (isFirst || + IsSelectionRectBoundaryCloserToPoint( + point, _selectionRects[i].rect, _selectionRects[i].isRTL, + /*useTrailingBoundaryOfSelectionRect=*/NO, _selectionRects[_closestRectIndex].rect, + _selectionRects[_closestRectIndex].isRTL, verticalPrecision)) { + isFirst = NO; + _closestRectIndex = i; + } + } + } + + FlutterTextPosition* closestPosition = + [FlutterTextPosition positionWithIndex:_selectionRects[_closestRectIndex].position + affinity:UITextStorageDirectionForward]; + + // Check if the far side of the closest rect is a better fit (e.g. tapping end of line) + // Cannot simply check the _closestRectIndex result from the previous for loop due to RTL + // writing direction and the gaps between selectionRects. So we also need to consider + // the adjacent selectionRects to refine _closestRectIndex. + for (NSUInteger i = MAX(0, _closestRectIndex - 1); + i < MIN(_closestRectIndex + 2, [_selectionRects count]); i++) { + NSUInteger position = _selectionRects[i].position + 1; + if (position >= start && position <= end) { + if (IsSelectionRectBoundaryCloserToPoint( + point, _selectionRects[i].rect, _selectionRects[i].isRTL, + /*useTrailingBoundaryOfSelectionRect=*/YES, _selectionRects[_closestRectIndex].rect, + _selectionRects[_closestRectIndex].isRTL, verticalPrecision)) { + // This is an upstream position + closestPosition = [FlutterTextPosition positionWithIndex:position + affinity:UITextStorageDirectionBackward]; + } + } + } + + return closestPosition; +} + +- (UITextRange*)characterRangeAtPoint:(CGPoint)point { + // TODO(cbracken) Implement. + NSUInteger currentIndex = ((FlutterTextPosition*)_selectedTextRange.start).index; + return [FlutterTextRange rangeWithNSRange:fml::RangeForCharacterAtIndex(self.text, currentIndex)]; +} + +// Overall logic for floating cursor's "move" gesture and "selection" gesture: +// +// Floating cursor's "move" gesture takes 1 finger to force press the space bar, and then move the +// cursor. The process starts with `beginFloatingCursorAtPoint`. When the finger is moved, +// `updateFloatingCursorAtPoint` will be called. When the finger is released, `endFloatingCursor` +// will be called. In all cases, we send the point (relative to the initial point registered in +// beginFloatingCursorAtPoint) to the framework, so that framework can animate the floating cursor. +// +// During the move gesture, the framework only animate the cursor visually. It's only +// after the gesture is complete, will the framework update the selection to the cursor's +// new position (with zero selection length). This means during the animation, the visual effect +// of the cursor is temporarily out of sync with the selection state in both framework and engine. +// But it will be in sync again after the animation is complete. +// +// Floating cursor's "selection" gesture also starts with 1 finger to force press the space bar, +// so exactly the same functions as the "move gesture" discussed above will be called. When the +// second finger is pressed, `setSelectedText` will be called. This mechanism requires +// `closestPositionFromPoint` to be implemented, to allow UIKit to translate the finger touch +// location displacement to the text range to select. When the selection is completed +// (i.e. when both of the 2 fingers are released), similar to "move" gesture, +// the `endFloatingCursor` will be called. +// +// When the 2nd finger is pressed, it does not trigger another startFloatingCursor call. So +// floating cursor move/selection logic has to be implemented in iOS embedder rather than +// just the framework side. +// +// Whenever a selection is updated, the engine sends the new selection to the framework. So unlike +// the move gesture, the selections in the framework and the engine are always kept in sync. +- (void)beginFloatingCursorAtPoint:(CGPoint)point { + // For "beginFloatingCursorAtPoint" and "updateFloatingCursorAtPoint", "point" is roughly: + // + // CGPoint( + // width >= 0 ? point.x.clamp(boundingBox.left, boundingBox.right) : point.x, + // height >= 0 ? point.y.clamp(boundingBox.top, boundingBox.bottom) : point.y, + // ) + // where + // point = keyboardPanGestureRecognizer.translationInView(textInputView) + caretRectForPosition + // boundingBox = self.convertRect(bounds, fromView:textInputView) + // bounds = self._selectionClipRect ?? self.bounds + // + // It seems impossible to use a negative "width" or "height", as the "convertRect" + // call always turns a CGRect's negative dimensions into non-negative values, e.g., + // (1, 2, -3, -4) would become (-2, -2, 3, 4). + _isFloatingCursorActive = YES; + _floatingCursorOffset = point; + [self.textInputDelegate flutterTextInputView:self + updateFloatingCursor:FlutterFloatingCursorDragStateStart + withClient:_textInputClient + withPosition:@{@"X" : @0, @"Y" : @0}]; +} + +- (void)updateFloatingCursorAtPoint:(CGPoint)point { + [self.textInputDelegate flutterTextInputView:self + updateFloatingCursor:FlutterFloatingCursorDragStateUpdate + withClient:_textInputClient + withPosition:@{ + @"X" : @(point.x - _floatingCursorOffset.x), + @"Y" : @(point.y - _floatingCursorOffset.y) + }]; +} + +- (void)endFloatingCursor { + _isFloatingCursorActive = NO; + [self.textInputDelegate flutterTextInputView:self + updateFloatingCursor:FlutterFloatingCursorDragStateEnd + withClient:_textInputClient + withPosition:@{@"X" : @0, @"Y" : @0}]; +} + +#pragma mark - UIKeyInput Overrides + +- (void)updateEditingState { + NSUInteger selectionBase = ((FlutterTextPosition*)_selectedTextRange.start).index; + NSUInteger selectionExtent = ((FlutterTextPosition*)_selectedTextRange.end).index; + + // Empty compositing range is represented by the framework's TextRange.empty. + NSInteger composingBase = -1; + NSInteger composingExtent = -1; + if (self.markedTextRange != nil) { + composingBase = ((FlutterTextPosition*)self.markedTextRange.start).index; + composingExtent = ((FlutterTextPosition*)self.markedTextRange.end).index; + } + NSDictionary* state = @{ + @"selectionBase" : @(selectionBase), + @"selectionExtent" : @(selectionExtent), + @"selectionAffinity" : @(_selectionAffinity), + @"selectionIsDirectional" : @(false), + @"composingBase" : @(composingBase), + @"composingExtent" : @(composingExtent), + @"text" : [NSString stringWithString:self.text], + }; + + if (_textInputClient == 0 && _autofillId != nil) { + [self.textInputDelegate flutterTextInputView:self + updateEditingClient:_textInputClient + withState:state + withTag:_autofillId]; + } else { + [self.textInputDelegate flutterTextInputView:self + updateEditingClient:_textInputClient + withState:state]; + } +} + +- (void)updateEditingStateWithDelta:(flutter::TextEditingDelta)delta { + NSUInteger selectionBase = ((FlutterTextPosition*)_selectedTextRange.start).index; + NSUInteger selectionExtent = ((FlutterTextPosition*)_selectedTextRange.end).index; + + // Empty compositing range is represented by the framework's TextRange.empty. + NSInteger composingBase = -1; + NSInteger composingExtent = -1; + if (self.markedTextRange != nil) { + composingBase = ((FlutterTextPosition*)self.markedTextRange.start).index; + composingExtent = ((FlutterTextPosition*)self.markedTextRange.end).index; + } + + NSDictionary* deltaToFramework = @{ + @"oldText" : @(delta.old_text().c_str()), + @"deltaText" : @(delta.delta_text().c_str()), + @"deltaStart" : @(delta.delta_start()), + @"deltaEnd" : @(delta.delta_end()), + @"selectionBase" : @(selectionBase), + @"selectionExtent" : @(selectionExtent), + @"selectionAffinity" : @(_selectionAffinity), + @"selectionIsDirectional" : @(false), + @"composingBase" : @(composingBase), + @"composingExtent" : @(composingExtent), + }; + + [_pendingDeltas addObject:deltaToFramework]; + + if (_pendingDeltas.count == 1) { + __weak FlutterTextInputView* weakSelf = self; + dispatch_async(dispatch_get_main_queue(), ^{ + __strong FlutterTextInputView* strongSelf = weakSelf; + if (strongSelf && strongSelf.pendingDeltas.count > 0) { + NSDictionary* deltas = @{ + @"deltas" : strongSelf.pendingDeltas, + }; + + [strongSelf.textInputDelegate flutterTextInputView:strongSelf + updateEditingClient:strongSelf->_textInputClient + withDelta:deltas]; + [strongSelf.pendingDeltas removeAllObjects]; + } + }); + } +} + +- (BOOL)hasText { + return self.text.length > 0; +} + +- (void)insertText:(NSString*)text { + if (self.temporarilyDeletedComposedCharacter.length > 0 && text.length == 1 && !text.UTF8String && + [text characterAtIndex:0] == [self.temporarilyDeletedComposedCharacter characterAtIndex:0]) { + // Workaround for https://github.com/flutter/flutter/issues/111494 + // TODO(cyanglaz): revert this workaround if when flutter supports a minimum iOS version which + // this bug is fixed by Apple. + text = self.temporarilyDeletedComposedCharacter; + self.temporarilyDeletedComposedCharacter = nil; + } + + NSMutableArray* copiedRects = + [[NSMutableArray alloc] initWithCapacity:[_selectionRects count]]; + NSAssert([_selectedTextRange.start isKindOfClass:[FlutterTextPosition class]], + @"Expected a FlutterTextPosition for position (got %@).", + [_selectedTextRange.start class]); + NSUInteger insertPosition = ((FlutterTextPosition*)_selectedTextRange.start).index; + for (NSUInteger i = 0; i < [_selectionRects count]; i++) { + NSUInteger rectPosition = _selectionRects[i].position; + if (rectPosition == insertPosition) { + for (NSUInteger j = 0; j <= text.length; j++) { + [copiedRects addObject:[FlutterTextSelectionRect + selectionRectWithRect:_selectionRects[i].rect + position:rectPosition + j + writingDirection:_selectionRects[i].writingDirection]]; + } + } else { + if (rectPosition > insertPosition) { + rectPosition = rectPosition + text.length; + } + [copiedRects addObject:[FlutterTextSelectionRect + selectionRectWithRect:_selectionRects[i].rect + position:rectPosition + writingDirection:_selectionRects[i].writingDirection]]; + } + } + + _scribbleFocusStatus = FlutterScribbleFocusStatusUnfocused; + [self resetScribbleInteractionStatusIfEnding]; + self.selectionRects = copiedRects; + _selectionAffinity = kTextAffinityDownstream; + [self replaceRange:_selectedTextRange withText:text]; +} + +- (UITextPlaceholder*)insertTextPlaceholderWithSize:(CGSize)size API_AVAILABLE(ios(13.0)) { + [self.textInputDelegate flutterTextInputView:self + insertTextPlaceholderWithSize:size + withClient:_textInputClient]; + _hasPlaceholder = YES; + return [[FlutterTextPlaceholder alloc] init]; +} + +- (void)removeTextPlaceholder:(UITextPlaceholder*)textPlaceholder API_AVAILABLE(ios(13.0)) { + _hasPlaceholder = NO; + [self.textInputDelegate flutterTextInputView:self removeTextPlaceholder:_textInputClient]; +} + +- (void)deleteBackward { + _selectionAffinity = kTextAffinityDownstream; + _scribbleFocusStatus = FlutterScribbleFocusStatusUnfocused; + [self resetScribbleInteractionStatusIfEnding]; + + // When deleting Thai vowel, _selectedTextRange has location + // but does not have length, so we have to manually set it. + // In addition, we needed to delete only a part of grapheme cluster + // because it is the expected behavior of Thai input. + // https://github.com/flutter/flutter/issues/24203 + // https://github.com/flutter/flutter/issues/21745 + // https://github.com/flutter/flutter/issues/39399 + // + // This is needed for correct handling of the deletion of Thai vowel input. + // TODO(cbracken): Get a good understanding of expected behavior of Thai + // input and ensure that this is the correct solution. + // https://github.com/flutter/flutter/issues/28962 + if (_selectedTextRange.isEmpty && [self hasText]) { + UITextRange* oldSelectedRange = _selectedTextRange; + NSRange oldRange = ((FlutterTextRange*)oldSelectedRange).range; + if (oldRange.location > 0) { + NSRange newRange = NSMakeRange(oldRange.location - 1, 1); + + // We should check if the last character is a part of emoji. + // If so, we must delete the entire emoji to prevent the text from being malformed. + NSRange charRange = fml::RangeForCharacterAtIndex(self.text, oldRange.location - 1); + if (IsEmoji(self.text, charRange)) { + newRange = NSMakeRange(charRange.location, oldRange.location - charRange.location); + } + + _selectedTextRange = [[FlutterTextRange rangeWithNSRange:newRange] copy]; + } + } + + if (!_selectedTextRange.isEmpty) { + // Cache the last deleted emoji to use for an iOS bug where the next + // insertion corrupts the emoji characters. + // See: https://github.com/flutter/flutter/issues/111494#issuecomment-1248441346 + if (IsEmoji(self.text, _selectedTextRange.range)) { + NSString* deletedText = [self.text substringWithRange:_selectedTextRange.range]; + NSRange deleteFirstCharacterRange = fml::RangeForCharacterAtIndex(deletedText, 0); + self.temporarilyDeletedComposedCharacter = + [deletedText substringWithRange:deleteFirstCharacterRange]; + } + [self replaceRange:_selectedTextRange withText:@""]; + } +} + +- (void)postAccessibilityNotification:(UIAccessibilityNotifications)notification target:(id)target { + UIAccessibilityPostNotification(notification, target); +} + +- (void)accessibilityElementDidBecomeFocused { + if ([self accessibilityElementIsFocused]) { + // For most of the cases, this flutter text input view should never + // receive the focus. If we do receive the focus, we make the best effort + // to send the focus back to the real text field. + FML_DCHECK(_backingTextInputAccessibilityObject); + [self postAccessibilityNotification:UIAccessibilityScreenChangedNotification + target:_backingTextInputAccessibilityObject]; + } +} + +- (BOOL)accessibilityElementsHidden { + return !_accessibilityEnabled; +} + +- (void)resetScribbleInteractionStatusIfEnding { + if (_scribbleInteractionStatus == FlutterScribbleInteractionStatusEnding) { + _scribbleInteractionStatus = FlutterScribbleInteractionStatusNone; + } +} + +#pragma mark - Key Events Handling +- (void)pressesBegan:(NSSet*)presses + withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) { + [_textInputPlugin.viewController pressesBegan:presses withEvent:event]; +} + +- (void)pressesChanged:(NSSet*)presses + withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) { + [_textInputPlugin.viewController pressesChanged:presses withEvent:event]; +} + +- (void)pressesEnded:(NSSet*)presses + withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) { + [_textInputPlugin.viewController pressesEnded:presses withEvent:event]; +} + +- (void)pressesCancelled:(NSSet*)presses + withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) { + [_textInputPlugin.viewController pressesCancelled:presses withEvent:event]; +} + +@end + +/** + * Hides `FlutterTextInputView` from iOS accessibility system so it + * does not show up twice, once where it is in the `UIView` hierarchy, + * and a second time as part of the `SemanticsObject` hierarchy. + * + * This prevents the `FlutterTextInputView` from receiving the focus + * due to swiping gesture. + * + * There are other cases the `FlutterTextInputView` may receive + * focus. One example is during screen changes, the accessibility + * tree will undergo a dramatic structural update. The Voiceover may + * decide to focus the `FlutterTextInputView` that is not involved + * in the structural update instead. If that happens, the + * `FlutterTextInputView` will make a best effort to direct the + * focus back to the `SemanticsObject`. + */ +@interface FlutterTextInputViewAccessibilityHider : UIView { +} + +@end + +@implementation FlutterTextInputViewAccessibilityHider { +} + +- (BOOL)accessibilityElementsHidden { + return YES; +} + +@end + +@interface FlutterTextInputPlugin () +- (void)enableActiveViewAccessibility; +@end + +@interface FlutterTimerProxy : NSObject +@property(nonatomic, weak) FlutterTextInputPlugin* target; +@end + +@implementation FlutterTimerProxy + ++ (instancetype)proxyWithTarget:(FlutterTextInputPlugin*)target { + FlutterTimerProxy* proxy = [[self alloc] init]; + if (proxy) { + proxy.target = target; + } + return proxy; +} + +- (void)enableActiveViewAccessibility { + [self.target enableActiveViewAccessibility]; +} + +@end + +@interface FlutterTextInputPlugin () +// The current password-autofillable input fields that have yet to be saved. +@property(nonatomic, readonly) + NSMutableDictionary* autofillContext; +@property(nonatomic, retain) FlutterTextInputView* activeView; +@property(nonatomic, retain) FlutterTextInputViewAccessibilityHider* inputHider; +@property(nonatomic, readonly, weak) id viewResponder; + +@property(nonatomic, strong) UIView* keyboardViewContainer; +@property(nonatomic, strong) UIView* keyboardView; +@property(nonatomic, strong) UIView* cachedFirstResponder; +@property(nonatomic, assign) CGRect keyboardRect; +@property(nonatomic, assign) CGFloat previousPointerYPosition; +@property(nonatomic, assign) CGFloat pointerYVelocity; +@end + +@implementation FlutterTextInputPlugin { + NSTimer* _enableFlutterTextInputViewAccessibilityTimer; +} + +- (instancetype)initWithDelegate:(id)textInputDelegate { + self = [super init]; + if (self) { + // `_textInputDelegate` is a weak reference because it should retain FlutterTextInputPlugin. + _textInputDelegate = textInputDelegate; + _autofillContext = [[NSMutableDictionary alloc] init]; + _inputHider = [[FlutterTextInputViewAccessibilityHider alloc] init]; + _scribbleElements = [[NSMutableDictionary alloc] init]; + _keyboardViewContainer = [[UIView alloc] init]; + + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(handleKeyboardWillShow:) + name:UIKeyboardWillShowNotification + object:nil]; + } + + return self; +} + +- (void)handleKeyboardWillShow:(NSNotification*)notification { + NSDictionary* keyboardInfo = [notification userInfo]; + NSValue* keyboardFrameEnd = [keyboardInfo valueForKey:UIKeyboardFrameEndUserInfoKey]; + _keyboardRect = [keyboardFrameEnd CGRectValue]; +} + +- (void)dealloc { + [self hideTextInput]; +} + +- (void)removeEnableFlutterTextInputViewAccessibilityTimer { + if (_enableFlutterTextInputViewAccessibilityTimer) { + [_enableFlutterTextInputViewAccessibilityTimer invalidate]; + _enableFlutterTextInputViewAccessibilityTimer = nil; + } +} + +- (UIView*)textInputView { + return _activeView; +} + +- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { + NSString* method = call.method; + id args = call.arguments; + if ([method isEqualToString:kShowMethod]) { + [self showTextInput]; + result(nil); + } else if ([method isEqualToString:kHideMethod]) { + [self hideTextInput]; + result(nil); + } else if ([method isEqualToString:kSetClientMethod]) { + [self setTextInputClient:[args[0] intValue] withConfiguration:args[1]]; + result(nil); + } else if ([method isEqualToString:kSetPlatformViewClientMethod]) { + // This method call has a `platformViewId` argument, but we do not need it for iOS for now. + [self setPlatformViewTextInputClient]; + result(nil); + } else if ([method isEqualToString:kSetEditingStateMethod]) { + [self setTextInputEditingState:args]; + result(nil); + } else if ([method isEqualToString:kClearClientMethod]) { + [self clearTextInputClient]; + result(nil); + } else if ([method isEqualToString:kSetEditableSizeAndTransformMethod]) { + [self setEditableSizeAndTransform:args]; + result(nil); + } else if ([method isEqualToString:kSetMarkedTextRectMethod]) { + [self updateMarkedRect:args]; + result(nil); + } else if ([method isEqualToString:kFinishAutofillContextMethod]) { + [self triggerAutofillSave:[args boolValue]]; + result(nil); + // TODO(justinmc): Remove the TextInput method constant when the framework has + // finished transitioning to using the Scribble channel. + // https://github.com/flutter/flutter/pull/104128 + } else if ([method isEqualToString:kDeprecatedSetSelectionRectsMethod]) { + [self setSelectionRects:args]; + result(nil); + } else if ([method isEqualToString:kSetSelectionRectsMethod]) { + [self setSelectionRects:args]; + result(nil); + } else if ([method isEqualToString:kStartLiveTextInputMethod]) { + [self startLiveTextInput]; + result(nil); + } else if ([method isEqualToString:kUpdateConfigMethod]) { + [self updateConfig:args]; + result(nil); + } else if ([method isEqualToString:kOnInteractiveKeyboardPointerMoveMethod]) { + CGFloat pointerY = (CGFloat)[args[@"pointerY"] doubleValue]; + [self handlePointerMove:pointerY]; + result(nil); + } else if ([method isEqualToString:kOnInteractiveKeyboardPointerUpMethod]) { + CGFloat pointerY = (CGFloat)[args[@"pointerY"] doubleValue]; + [self handlePointerUp:pointerY]; + result(nil); + } else { + result(FlutterMethodNotImplemented); + } +} + +- (void)handlePointerUp:(CGFloat)pointerY { + if (_keyboardView.superview != nil) { + // Done to avoid the issue of a pointer up done without a screenshot + // View must be loaded at this point. + UIScreen* screen = _viewController.flutterScreenIfViewLoaded; + CGFloat screenHeight = screen.bounds.size.height; + CGFloat keyboardHeight = _keyboardRect.size.height; + // Negative velocity indicates a downward movement + BOOL shouldDismissKeyboardBasedOnVelocity = _pointerYVelocity < 0; + [UIView animateWithDuration:kKeyboardAnimationTimeToCompleteion + animations:^{ + double keyboardDestination = + shouldDismissKeyboardBasedOnVelocity ? screenHeight : screenHeight - keyboardHeight; + _keyboardViewContainer.frame = CGRectMake( + 0, keyboardDestination, _viewController.flutterScreenIfViewLoaded.bounds.size.width, + _keyboardViewContainer.frame.size.height); + } + completion:^(BOOL finished) { + if (shouldDismissKeyboardBasedOnVelocity) { + [self.textInputDelegate flutterTextInputView:self.activeView + didResignFirstResponderWithTextInputClient:self.activeView.textInputClient]; + [self dismissKeyboardScreenshot]; + } else { + [self showKeyboardAndRemoveScreenshot]; + } + }]; + } +} + +- (void)dismissKeyboardScreenshot { + for (UIView* subView in _keyboardViewContainer.subviews) { + [subView removeFromSuperview]; + } +} + +- (void)showKeyboardAndRemoveScreenshot { + [UIView setAnimationsEnabled:NO]; + [_cachedFirstResponder becomeFirstResponder]; + // UIKit does not immediately access the areAnimationsEnabled Boolean so a delay is needed before + // returned + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, kKeyboardAnimationDelaySeconds * NSEC_PER_SEC), + dispatch_get_main_queue(), ^{ + [UIView setAnimationsEnabled:YES]; + [self dismissKeyboardScreenshot]; + }); +} + +- (void)handlePointerMove:(CGFloat)pointerY { + // View must be loaded at this point. + UIScreen* screen = _viewController.flutterScreenIfViewLoaded; + CGFloat screenHeight = screen.bounds.size.height; + CGFloat keyboardHeight = _keyboardRect.size.height; + if (screenHeight - keyboardHeight <= pointerY) { + // If the pointer is within the bounds of the keyboard. + if (_keyboardView.superview == nil) { + // If no screenshot has been taken. + [self takeKeyboardScreenshotAndDisplay]; + [self hideKeyboardWithoutAnimationAndAvoidCursorDismissUpdate]; + } else { + [self setKeyboardContainerHeight:pointerY]; + _pointerYVelocity = _previousPointerYPosition - pointerY; + } + } else { + if (_keyboardView.superview != nil) { + // Keeps keyboard at proper height. + _keyboardViewContainer.frame = _keyboardRect; + _pointerYVelocity = _previousPointerYPosition - pointerY; + } + } + _previousPointerYPosition = pointerY; +} + +- (void)setKeyboardContainerHeight:(CGFloat)pointerY { + CGRect frameRect = _keyboardRect; + frameRect.origin.y = pointerY; + _keyboardViewContainer.frame = frameRect; +} + +- (void)hideKeyboardWithoutAnimationAndAvoidCursorDismissUpdate { + [UIView setAnimationsEnabled:NO]; + UIApplication* flutterApplication = FlutterSharedApplication.application; + _cachedFirstResponder = + flutterApplication + ? flutterApplication.keyWindow.flutterFirstResponder + : self.viewController.flutterWindowSceneIfViewLoaded.keyWindow.flutterFirstResponder; + + _activeView.preventCursorDismissWhenResignFirstResponder = YES; + [_cachedFirstResponder resignFirstResponder]; + _activeView.preventCursorDismissWhenResignFirstResponder = NO; + [UIView setAnimationsEnabled:YES]; +} + +- (void)takeKeyboardScreenshotAndDisplay { + // View must be loaded at this point + UIScreen* screen = _viewController.flutterScreenIfViewLoaded; + UIView* keyboardSnap = [screen snapshotViewAfterScreenUpdates:YES]; + keyboardSnap = [keyboardSnap resizableSnapshotViewFromRect:_keyboardRect + afterScreenUpdates:YES + withCapInsets:UIEdgeInsetsZero]; + _keyboardView = keyboardSnap; + [_keyboardViewContainer addSubview:_keyboardView]; + if (_keyboardViewContainer.superview == nil) { + UIApplication* flutterApplication = FlutterSharedApplication.application; + UIView* rootView = flutterApplication + ? flutterApplication.delegate.window.rootViewController.view + : self.viewController.viewIfLoaded.window.rootViewController.view; + [rootView addSubview:_keyboardViewContainer]; + } + _keyboardViewContainer.layer.zPosition = NSIntegerMax; + _keyboardViewContainer.frame = _keyboardRect; +} + +- (BOOL)showEditMenu:(NSDictionary*)args API_AVAILABLE(ios(16.0)) { + if (!self.activeView.isFirstResponder) { + return NO; + } + NSDictionary* encodedTargetRect = args[@"targetRect"]; + CGRect globalTargetRect = CGRectMake( + [encodedTargetRect[@"x"] doubleValue], [encodedTargetRect[@"y"] doubleValue], + [encodedTargetRect[@"width"] doubleValue], [encodedTargetRect[@"height"] doubleValue]); + CGRect localTargetRect = [self.hostView convertRect:globalTargetRect toView:self.activeView]; + [self.activeView showEditMenuWithTargetRect:localTargetRect items:args[@"items"]]; + return YES; +} + +- (void)hideEditMenu { + [self.activeView hideEditMenu]; +} + +- (void)setEditableSizeAndTransform:(NSDictionary*)dictionary { + NSArray* transform = dictionary[@"transform"]; + [_activeView setEditableTransform:transform]; + const int leftIndex = 12; + const int topIndex = 13; + if ([_activeView isScribbleAvailable]) { + // This is necessary to set up where the scribble interactable element will be. + _inputHider.frame = + CGRectMake([transform[leftIndex] intValue], [transform[topIndex] intValue], + [dictionary[@"width"] intValue], [dictionary[@"height"] intValue]); + _activeView.frame = + CGRectMake(0, 0, [dictionary[@"width"] intValue], [dictionary[@"height"] intValue]); + _activeView.tintColor = [UIColor clearColor]; + } else { + // TODO(hellohuanlin): Also need to handle iOS 16 case, where the auto-correction highlight does + // not match the size of text. + // See https://github.com/flutter/flutter/issues/131695 + if (@available(iOS 17, *)) { + // Move auto-correction highlight to overlap with the actual text. + // This is to fix an issue where the system auto-correction highlight is displayed at + // the top left corner of the screen on iOS 17+. + // This problem also happens on iOS 16, but the size of highlight does not match the text. + // See https://github.com/flutter/flutter/issues/131695 + // TODO(hellohuanlin): Investigate if we can use non-zero size. + _inputHider.frame = + CGRectMake([transform[leftIndex] intValue], [transform[topIndex] intValue], 0, 0); + } + } +} + +- (void)updateMarkedRect:(NSDictionary*)dictionary { + NSAssert(dictionary[@"x"] != nil && dictionary[@"y"] != nil && dictionary[@"width"] != nil && + dictionary[@"height"] != nil, + @"Expected a dictionary representing a CGRect, got %@", dictionary); + CGRect rect = CGRectMake([dictionary[@"x"] doubleValue], [dictionary[@"y"] doubleValue], + [dictionary[@"width"] doubleValue], [dictionary[@"height"] doubleValue]); + _activeView.markedRect = rect.size.width < 0 && rect.size.height < 0 ? kInvalidFirstRect : rect; +} + +- (void)setSelectionRects:(NSArray*)encodedRects { + NSMutableArray* rectsAsRect = + [[NSMutableArray alloc] initWithCapacity:[encodedRects count]]; + for (NSUInteger i = 0; i < [encodedRects count]; i++) { + NSArray* encodedRect = encodedRects[i]; + [rectsAsRect addObject:[FlutterTextSelectionRect + selectionRectWithRect:CGRectMake([encodedRect[0] floatValue], + [encodedRect[1] floatValue], + [encodedRect[2] floatValue], + [encodedRect[3] floatValue]) + position:[encodedRect[4] unsignedIntegerValue] + writingDirection:[encodedRect[5] unsignedIntegerValue] == 1 + ? NSWritingDirectionLeftToRight + : NSWritingDirectionRightToLeft]]; + } + + // TODO(hellohuanlin): Investigate why notifying the text input system about text changes (via + // textWillChange and textDidChange APIs) causes a bug where we cannot enter text with IME + // keyboards. Issue: https://github.com/flutter/flutter/issues/133908 + _activeView.selectionRects = rectsAsRect; +} + +- (void)startLiveTextInput { + if (@available(iOS 15.0, *)) { + if (_activeView == nil || !_activeView.isFirstResponder) { + return; + } + [_activeView captureTextFromCamera:nil]; + } +} + +- (void)showTextInput { + _activeView.viewResponder = _viewResponder; + [self addToInputParentViewIfNeeded:_activeView]; + // Adds a delay to prevent the text view from receiving accessibility + // focus in case it is activated during semantics updates. + // + // One common case is when the app navigates to a page with an auto + // focused text field. The text field will activate the FlutterTextInputView + // with a semantics update sent to the engine. The voiceover will focus + // the newly attached active view while performing accessibility update. + // This results in accessibility focus stuck at the FlutterTextInputView. + if (!_enableFlutterTextInputViewAccessibilityTimer) { + _enableFlutterTextInputViewAccessibilityTimer = + [NSTimer scheduledTimerWithTimeInterval:kUITextInputAccessibilityEnablingDelaySeconds + target:[FlutterTimerProxy proxyWithTarget:self] + selector:@selector(enableActiveViewAccessibility) + userInfo:nil + repeats:NO]; + } + [_activeView becomeFirstResponder]; +} + +- (void)enableActiveViewAccessibility { + if (_activeView.isFirstResponder) { + _activeView.accessibilityEnabled = YES; + } + [self removeEnableFlutterTextInputViewAccessibilityTimer]; +} + +- (void)hideTextInput { + [self removeEnableFlutterTextInputViewAccessibilityTimer]; + _activeView.accessibilityEnabled = NO; + [_activeView resignFirstResponder]; + [_activeView removeFromSuperview]; + [_inputHider removeFromSuperview]; +} + +- (void)triggerAutofillSave:(BOOL)saveEntries { + [_activeView resignFirstResponder]; + + if (saveEntries) { + // Make all the input fields in the autofill context visible, + // then remove them to trigger autofill save. + [self cleanUpViewHierarchy:YES clearText:YES delayRemoval:NO]; + [_autofillContext removeAllObjects]; + [self changeInputViewsAutofillVisibility:YES]; + } else { + [_autofillContext removeAllObjects]; + } + + [self cleanUpViewHierarchy:YES clearText:!saveEntries delayRemoval:NO]; + [self addToInputParentViewIfNeeded:_activeView]; +} + +- (void)setPlatformViewTextInputClient { + // No need to track the platformViewID (unlike in Android). When a platform view + // becomes the first responder, simply hide this dummy text input view (`_activeView`) + // for the previously focused widget. + [self removeEnableFlutterTextInputViewAccessibilityTimer]; + _activeView.accessibilityEnabled = NO; + [_activeView removeFromSuperview]; + [_inputHider removeFromSuperview]; +} + +- (void)setTextInputClient:(int)client withConfiguration:(NSDictionary*)configuration { + [self resetAllClientIds]; + // Hide all input views from autofill, only make those in the new configuration visible + // to autofill. + [self changeInputViewsAutofillVisibility:NO]; + + // Update the current active view. + switch (AutofillTypeOf(configuration)) { + case kFlutterAutofillTypeNone: + self.activeView = [self createInputViewWith:configuration]; + break; + case kFlutterAutofillTypeRegular: + // If the group does not involve password autofill, only install the + // input view that's being focused. + self.activeView = [self updateAndShowAutofillViews:nil + focusedField:configuration + isPasswordRelated:NO]; + break; + case kFlutterAutofillTypePassword: + self.activeView = [self updateAndShowAutofillViews:configuration[kAssociatedAutofillFields] + focusedField:configuration + isPasswordRelated:YES]; + break; + } + [_activeView setTextInputClient:client]; + [_activeView reloadInputViews]; + + // Clean up views that no longer need to be in the view hierarchy, according to + // the current autofill context. The "garbage" input views are already made + // invisible to autofill and they can't `becomeFirstResponder`, we only remove + // them to free up resources and reduce the number of input views in the view + // hierarchy. + // + // The garbage views are decommissioned immediately, but the removeFromSuperview + // call is scheduled on the runloop and delayed by 0.1s so we don't remove the + // text fields immediately (which seems to make the keyboard flicker). + // See: https://github.com/flutter/flutter/issues/64628. + [self cleanUpViewHierarchy:NO clearText:YES delayRemoval:YES]; +} + +// Creates and shows an input field that is not password related and has no autofill +// info. This method returns a new FlutterTextInputView instance when called, since +// UIKit uses the identity of `UITextInput` instances (or the identity of the input +// views) to decide whether the IME's internal states should be reset. See: +// https://github.com/flutter/flutter/issues/79031 . +- (FlutterTextInputView*)createInputViewWith:(NSDictionary*)configuration { + NSString* autofillId = AutofillIdFromDictionary(configuration); + if (autofillId) { + [_autofillContext removeObjectForKey:autofillId]; + } + FlutterTextInputView* newView = [[FlutterTextInputView alloc] initWithOwner:self]; + [newView configureWithDictionary:configuration]; + [self addToInputParentViewIfNeeded:newView]; + + for (NSDictionary* field in configuration[kAssociatedAutofillFields]) { + NSString* autofillId = AutofillIdFromDictionary(field); + if (autofillId && AutofillTypeOf(field) == kFlutterAutofillTypeNone) { + [_autofillContext removeObjectForKey:autofillId]; + } + } + return newView; +} + +- (FlutterTextInputView*)updateAndShowAutofillViews:(NSArray*)fields + focusedField:(NSDictionary*)focusedField + isPasswordRelated:(BOOL)isPassword { + FlutterTextInputView* focused = nil; + NSString* focusedId = AutofillIdFromDictionary(focusedField); + NSAssert(focusedId, @"autofillId must not be null for the focused field: %@", focusedField); + + if (!fields) { + // DO NOT push the current autofillable input fields to the context even + // if it's password-related, because it is not in an autofill group. + focused = [self getOrCreateAutofillableView:focusedField isPasswordAutofill:isPassword]; + [_autofillContext removeObjectForKey:focusedId]; + } + + for (NSDictionary* field in fields) { + NSString* autofillId = AutofillIdFromDictionary(field); + NSAssert(autofillId, @"autofillId must not be null for field: %@", field); + + BOOL hasHints = AutofillTypeOf(field) != kFlutterAutofillTypeNone; + BOOL isFocused = [focusedId isEqualToString:autofillId]; + + if (isFocused) { + focused = [self getOrCreateAutofillableView:field isPasswordAutofill:isPassword]; + } + + if (hasHints) { + // Push the current input field to the context if it has hints. + _autofillContext[autofillId] = isFocused ? focused + : [self getOrCreateAutofillableView:field + isPasswordAutofill:isPassword]; + } else { + // Mark for deletion. + [_autofillContext removeObjectForKey:autofillId]; + } + } + + NSAssert(focused, @"The current focused input view must not be nil."); + return focused; +} + +// Returns a new non-reusable input view (and put it into the view hierarchy), or get the +// view from the current autofill context, if an input view with the same autofill id +// already exists in the context. +// This is generally used for input fields that are autofillable (UIKit tracks these veiws +// for autofill purposes so they should not be reused for a different type of views). +- (FlutterTextInputView*)getOrCreateAutofillableView:(NSDictionary*)field + isPasswordAutofill:(BOOL)needsPasswordAutofill { + NSString* autofillId = AutofillIdFromDictionary(field); + FlutterTextInputView* inputView = _autofillContext[autofillId]; + if (!inputView) { + inputView = + needsPasswordAutofill ? [FlutterSecureTextInputView alloc] : [FlutterTextInputView alloc]; + inputView = [inputView initWithOwner:self]; + [self addToInputParentViewIfNeeded:inputView]; + } + + [inputView configureWithDictionary:field]; + return inputView; +} + +// The UIView to add FlutterTextInputViews to. +- (UIView*)hostView { + UIView* host = _viewController.view; + NSAssert(host != nullptr, + @"The application must have a host view since the keyboard client " + @"must be part of the responder chain to function. The host view controller is %@", + _viewController); + return host; +} + +// The UIView to add FlutterTextInputViews to. +- (NSArray*)textInputViews { + return _inputHider.subviews; +} + +// Removes every installed input field, unless it's in the current autofill context. +// +// The active view will be removed from its superview too, if includeActiveView is YES. +// When clearText is YES, the text on the input fields will be set to empty before +// they are removed from the view hierarchy, to avoid triggering autofill save. +// If delayRemoval is true, removeFromSuperview will be scheduled on the runloop and +// will be delayed by 0.1s so we don't remove the text fields immediately (which seems +// to make the keyboard flicker). +// See: https://github.com/flutter/flutter/issues/64628. + +- (void)cleanUpViewHierarchy:(BOOL)includeActiveView + clearText:(BOOL)clearText + delayRemoval:(BOOL)delayRemoval { + for (UIView* view in self.textInputViews) { + if ([view isKindOfClass:[FlutterTextInputView class]] && + (includeActiveView || view != _activeView)) { + FlutterTextInputView* inputView = (FlutterTextInputView*)view; + if (_autofillContext[inputView.autofillId] != view) { + if (clearText) { + [inputView replaceRangeLocal:NSMakeRange(0, inputView.text.length) withText:@""]; + } + if (delayRemoval) { + [inputView performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:0.1]; + } else { + [inputView removeFromSuperview]; + } + } + } + } +} + +// Changes the visibility of every FlutterTextInputView currently in the +// view hierarchy. +- (void)changeInputViewsAutofillVisibility:(BOOL)newVisibility { + for (UIView* view in self.textInputViews) { + if ([view isKindOfClass:[FlutterTextInputView class]]) { + FlutterTextInputView* inputView = (FlutterTextInputView*)view; + inputView.isVisibleToAutofill = newVisibility; + } + } +} + +// Resets the client id of every FlutterTextInputView in the view hierarchy +// to 0. +// Called before establishing a new text input connection. +// For views in the current autofill context, they need to +// stay in the view hierachy but should not be allowed to +// send messages (other than autofill related ones) to the +// framework. +- (void)resetAllClientIds { + for (UIView* view in self.textInputViews) { + if ([view isKindOfClass:[FlutterTextInputView class]]) { + FlutterTextInputView* inputView = (FlutterTextInputView*)view; + [inputView setTextInputClient:0]; + } + } +} + +- (void)addToInputParentViewIfNeeded:(FlutterTextInputView*)inputView { + if (![inputView isDescendantOfView:_inputHider]) { + [_inputHider addSubview:inputView]; + } + + if (_viewController.view == nil) { + // If view controller's view has detached from flutter engine, we don't add _inputHider + // in parent view to fallback and avoid crash. + // https://github.com/flutter/flutter/issues/106404. + return; + } + UIView* parentView = self.hostView; + if (_inputHider.superview != parentView) { + [parentView addSubview:_inputHider]; + } +} + +- (void)setTextInputEditingState:(NSDictionary*)state { + [_activeView setTextInputState:state]; +} + +- (void)clearTextInputClient { + [_activeView setTextInputClient:0]; + _activeView.frame = CGRectZero; +} + +- (void)updateConfig:(NSDictionary*)dictionary { + BOOL isSecureTextEntry = [dictionary[kSecureTextEntry] boolValue]; + for (UIView* view in self.textInputViews) { + if ([view isKindOfClass:[FlutterTextInputView class]]) { + FlutterTextInputView* inputView = (FlutterTextInputView*)view; + // The feature of holding and draging spacebar to move cursor is affected by + // secureTextEntry, so when obscureText is updated, we need to update secureTextEntry + // and call reloadInputViews. + // https://github.com/flutter/flutter/issues/122139 + if (inputView.isSecureTextEntry != isSecureTextEntry) { + inputView.secureTextEntry = isSecureTextEntry; + [inputView reloadInputViews]; + } + } + } +} + +#pragma mark UIIndirectScribbleInteractionDelegate + +- (BOOL)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction + isElementFocused:(UIScribbleElementIdentifier)elementIdentifier + API_AVAILABLE(ios(14.0)) { + return _activeView.scribbleFocusStatus == FlutterScribbleFocusStatusFocused; +} + +- (void)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction + focusElementIfNeeded:(UIScribbleElementIdentifier)elementIdentifier + referencePoint:(CGPoint)focusReferencePoint + completion:(void (^)(UIResponder* focusedInput))completion + API_AVAILABLE(ios(14.0)) { + _activeView.scribbleFocusStatus = FlutterScribbleFocusStatusFocusing; + [_indirectScribbleDelegate flutterTextInputPlugin:self + focusElement:elementIdentifier + atPoint:focusReferencePoint + result:^(id _Nullable result) { + _activeView.scribbleFocusStatus = + FlutterScribbleFocusStatusFocused; + completion(_activeView); + }]; +} + +- (BOOL)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction + shouldDelayFocusForElement:(UIScribbleElementIdentifier)elementIdentifier + API_AVAILABLE(ios(14.0)) { + return NO; +} + +- (void)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction + willBeginWritingInElement:(UIScribbleElementIdentifier)elementIdentifier + API_AVAILABLE(ios(14.0)) { +} + +- (void)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction + didFinishWritingInElement:(UIScribbleElementIdentifier)elementIdentifier + API_AVAILABLE(ios(14.0)) { +} + +- (CGRect)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction + frameForElement:(UIScribbleElementIdentifier)elementIdentifier + API_AVAILABLE(ios(14.0)) { + NSValue* elementValue = [_scribbleElements objectForKey:elementIdentifier]; + if (elementValue == nil) { + return CGRectZero; + } + return [elementValue CGRectValue]; +} + +- (void)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction + requestElementsInRect:(CGRect)rect + completion: + (void (^)(NSArray* elements))completion + API_AVAILABLE(ios(14.0)) { + [_indirectScribbleDelegate + flutterTextInputPlugin:self + requestElementsInRect:rect + result:^(id _Nullable result) { + NSMutableArray* elements = + [[NSMutableArray alloc] init]; + if ([result isKindOfClass:[NSArray class]]) { + for (NSArray* elementArray in result) { + [elements addObject:elementArray[0]]; + [_scribbleElements + setObject:[NSValue + valueWithCGRect:CGRectMake( + [elementArray[1] floatValue], + [elementArray[2] floatValue], + [elementArray[3] floatValue], + [elementArray[4] floatValue])] + forKey:elementArray[0]]; + } + } + completion(elements); + }]; +} + +#pragma mark - Methods related to Scribble support + +- (void)setUpIndirectScribbleInteraction:(id)viewResponder { + if (_viewResponder != viewResponder) { + if (@available(iOS 14.0, *)) { + UIView* parentView = viewResponder.view; + if (parentView != nil) { + UIIndirectScribbleInteraction* scribbleInteraction = [[UIIndirectScribbleInteraction alloc] + initWithDelegate:(id)self]; + [parentView addInteraction:scribbleInteraction]; + } + } + } + _viewResponder = viewResponder; +} + +- (void)resetViewResponder { + _viewResponder = nil; +} + +#pragma mark - +#pragma mark FlutterKeySecondaryResponder + +/** + * Handles key down events received from the view controller, responding YES if + * the event was handled. + */ +- (BOOL)handlePress:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)) { + return NO; +} +@end + +/** + * Recursively searches the UIView's subviews to locate the First Responder + */ +@implementation UIView (FindFirstResponder) +- (id)flutterFirstResponder { + if (self.isFirstResponder) { + return self; + } + for (UIView* subView in self.subviews) { + UIView* firstResponder = subView.flutterFirstResponder; + if (firstResponder) { + return firstResponder; + } + } + return nil; +} +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPluginTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPluginTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..11cbd4cde035b03525794c92b474325a704c6372 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPluginTest.mm @@ -0,0 +1,3776 @@ +// 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. + +#import "flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Test.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h" + +#import +#import + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterEngine.h" +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/UIViewController+FlutterScreenAndSceneIfLoaded.h" + +FLUTTER_ASSERT_ARC + +@interface FlutterEngine () +- (nonnull FlutterTextInputPlugin*)textInputPlugin; +@end + +@interface FlutterTextInputView () +@property(nonatomic, copy) NSString* autofillId; +- (void)setEditableTransform:(NSArray*)matrix; +- (void)setTextInputClient:(int)client; +- (void)setTextInputState:(NSDictionary*)state; +- (void)setMarkedRect:(CGRect)markedRect; +- (void)updateEditingState; +- (BOOL)isVisibleToAutofill; +- (id)textInputDelegate; +- (void)configureWithDictionary:(NSDictionary*)configuration; +- (void)handleSearchWebAction; +- (void)handleLookUpAction; +- (void)handleShareAction; +@end + +@interface FlutterTextInputViewSpy : FlutterTextInputView +@property(nonatomic, assign) UIAccessibilityNotifications receivedNotification; +@property(nonatomic, assign) id receivedNotificationTarget; +@property(nonatomic, assign) BOOL isAccessibilityFocused; + +- (void)postAccessibilityNotification:(UIAccessibilityNotifications)notification target:(id)target; + +@end + +@implementation FlutterTextInputViewSpy { +} + +- (void)postAccessibilityNotification:(UIAccessibilityNotifications)notification target:(id)target { + self.receivedNotification = notification; + self.receivedNotificationTarget = target; +} + +- (BOOL)accessibilityElementIsFocused { + return _isAccessibilityFocused; +} + +@end + +@interface FlutterSecureTextInputView : FlutterTextInputView +@property(nonatomic, strong) UITextField* textField; +@end + +@interface FlutterTextInputPlugin () +@property(nonatomic, assign) FlutterTextInputView* activeView; +@property(nonatomic, readonly) UIView* inputHider; +@property(nonatomic, readonly) UIView* keyboardViewContainer; +@property(nonatomic, readonly) UIView* keyboardView; +@property(nonatomic, assign) UIView* cachedFirstResponder; +@property(nonatomic, readonly) CGRect keyboardRect; +@property(nonatomic, readonly) + NSMutableDictionary* autofillContext; + +- (void)cleanUpViewHierarchy:(BOOL)includeActiveView + clearText:(BOOL)clearText + delayRemoval:(BOOL)delayRemoval; +- (NSArray*)textInputViews; +- (UIView*)hostView; +- (void)addToInputParentViewIfNeeded:(FlutterTextInputView*)inputView; +- (void)startLiveTextInput; +- (void)showKeyboardAndRemoveScreenshot; + +@end + +@interface FlutterTextInputPluginTest : XCTestCase +@end + +@implementation FlutterTextInputPluginTest { + NSDictionary* _template; + NSDictionary* _passwordTemplate; + id engine; + FlutterTextInputPlugin* textInputPlugin; + + FlutterViewController* viewController; +} + +- (void)setUp { + [super setUp]; + engine = OCMClassMock([FlutterEngine class]); + + textInputPlugin = [[FlutterTextInputPlugin alloc] initWithDelegate:engine]; + + viewController = [[FlutterViewController alloc] init]; + textInputPlugin.viewController = viewController; + + // Clear pasteboard between tests. + UIPasteboard.generalPasteboard.items = @[]; +} + +- (void)tearDown { + textInputPlugin = nil; + engine = nil; + [textInputPlugin.autofillContext removeAllObjects]; + [textInputPlugin cleanUpViewHierarchy:YES clearText:YES delayRemoval:NO]; + [[[[textInputPlugin textInputView] superview] subviews] + makeObjectsPerformSelector:@selector(removeFromSuperview)]; + viewController = nil; + [super tearDown]; +} + +- (void)setClientId:(int)clientId configuration:(NSDictionary*)config { + FlutterMethodCall* setClientCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ [NSNumber numberWithInt:clientId], config ]]; + [textInputPlugin handleMethodCall:setClientCall + result:^(id _Nullable result){ + }]; +} + +- (void)setTextInputShow { + FlutterMethodCall* setClientCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.show" + arguments:@[]]; + [textInputPlugin handleMethodCall:setClientCall + result:^(id _Nullable result){ + }]; +} + +- (void)setTextInputHide { + FlutterMethodCall* setClientCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.hide" + arguments:@[]]; + [textInputPlugin handleMethodCall:setClientCall + result:^(id _Nullable result){ + }]; +} + +- (void)flushScheduledAsyncBlocks { + __block bool done = false; + XCTestExpectation* expectation = + [[XCTestExpectation alloc] initWithDescription:@"Testing on main queue"]; + dispatch_async(dispatch_get_main_queue(), ^{ + done = true; + }); + dispatch_async(dispatch_get_main_queue(), ^{ + XCTAssertTrue(done); + [expectation fulfill]; + }); + [self waitForExpectations:@[ expectation ] timeout:10]; +} + +- (NSMutableDictionary*)mutableTemplateCopy { + if (!_template) { + _template = @{ + @"inputType" : @{@"name" : @"TextInuptType.text"}, + @"keyboardAppearance" : @"Brightness.light", + @"obscureText" : @NO, + @"inputAction" : @"TextInputAction.unspecified", + @"smartDashesType" : @"0", + @"smartQuotesType" : @"0", + @"autocorrect" : @YES, + @"enableInteractiveSelection" : @YES, + }; + } + + return [_template mutableCopy]; +} + +- (NSArray*)installedInputViews { + return (NSArray*)[textInputPlugin.textInputViews + filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self isKindOfClass: %@", + [FlutterTextInputView class]]]; +} + +- (FlutterTextRange*)getLineRangeFromTokenizer:(id)tokenizer + atIndex:(NSInteger)index { + UITextRange* range = + [tokenizer rangeEnclosingPosition:[FlutterTextPosition positionWithIndex:index] + withGranularity:UITextGranularityLine + inDirection:UITextLayoutDirectionRight]; + XCTAssertTrue([range isKindOfClass:[FlutterTextRange class]]); + return (FlutterTextRange*)range; +} + +- (void)updateConfig:(NSDictionary*)config { + FlutterMethodCall* updateConfigCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.updateConfig" arguments:config]; + [textInputPlugin handleMethodCall:updateConfigCall + result:^(id _Nullable result){ + }]; +} + +#pragma mark - Tests + +- (void)testWillNotCrashWhenViewControllerIsNil { + FlutterEngine* flutterEngine = [[FlutterEngine alloc] init]; + FlutterTextInputPlugin* inputPlugin = + [[FlutterTextInputPlugin alloc] initWithDelegate:(id)flutterEngine]; + XCTAssertNil(inputPlugin.viewController); + FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.show" + arguments:nil]; + XCTestExpectation* expectation = [[XCTestExpectation alloc] initWithDescription:@"result called"]; + + [inputPlugin handleMethodCall:methodCall + result:^(id _Nullable result) { + XCTAssertNil(result); + [expectation fulfill]; + }]; + XCTAssertNil(inputPlugin.activeView); + [self waitForExpectations:@[ expectation ] timeout:1.0]; +} + +- (void)testInvokeStartLiveTextInput { + FlutterMethodCall* methodCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.startLiveTextInput" arguments:nil]; + FlutterTextInputPlugin* mockPlugin = OCMPartialMock(textInputPlugin); + [mockPlugin handleMethodCall:methodCall + result:^(id _Nullable result){ + }]; + OCMVerify([mockPlugin startLiveTextInput]); +} + +- (void)testNoDanglingEnginePointer { + __weak FlutterTextInputPlugin* weakFlutterTextInputPlugin; + FlutterViewController* flutterViewController = [[FlutterViewController alloc] init]; + __weak FlutterEngine* weakFlutterEngine; + + FlutterTextInputView* currentView; + + // The engine instance will be deallocated after the autorelease pool is drained. + @autoreleasepool { + FlutterEngine* flutterEngine = OCMClassMock([FlutterEngine class]); + weakFlutterEngine = flutterEngine; + XCTAssertNotNil(weakFlutterEngine, @"flutter engine must not be nil"); + FlutterTextInputPlugin* flutterTextInputPlugin = [[FlutterTextInputPlugin alloc] + initWithDelegate:(id)flutterEngine]; + weakFlutterTextInputPlugin = flutterTextInputPlugin; + flutterTextInputPlugin.viewController = flutterViewController; + + // Set client so the text input plugin has an active view. + NSDictionary* config = self.mutableTemplateCopy; + FlutterMethodCall* setClientCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ [NSNumber numberWithInt:123], config ]]; + [flutterTextInputPlugin handleMethodCall:setClientCall + result:^(id _Nullable result){ + }]; + currentView = flutterTextInputPlugin.activeView; + } + + XCTAssertNil(weakFlutterEngine, @"flutter engine must be nil"); + XCTAssertNotNil(currentView, @"current view must not be nil"); + + XCTAssertNil(weakFlutterTextInputPlugin); + // Verify that the view can no longer access the deallocated engine/text input plugin + // instance. + XCTAssertNil(currentView.textInputDelegate); +} + +- (void)testSecureInput { + NSDictionary* config = self.mutableTemplateCopy; + [config setValue:@"YES" forKey:@"obscureText"]; + [self setClientId:123 configuration:config]; + + // Find all the FlutterTextInputViews we created. + NSArray* inputFields = self.installedInputViews; + + // There are no autofill and the mock framework requested a secure entry. The first and only + // inserted FlutterTextInputView should be a secure text entry one. + FlutterTextInputView* inputView = inputFields[0]; + + // Verify secureTextEntry is set to the correct value. + XCTAssertTrue(inputView.secureTextEntry); + + // Verify keyboardType is set to the default value. + XCTAssertEqual(inputView.keyboardType, UIKeyboardTypeDefault); + + // We should have only ever created one FlutterTextInputView. + XCTAssertEqual(inputFields.count, 1ul); + + // The one FlutterTextInputView we inserted into the view hierarchy should be the text input + // plugin's active text input view. + XCTAssertEqual(inputView, textInputPlugin.textInputView); + + // Despite not given an id in configuration, inputView has + // an autofill id. + XCTAssert(inputView.autofillId.length > 0); +} + +- (void)testKeyboardType { + NSDictionary* config = self.mutableTemplateCopy; + [config setValue:@{@"name" : @"TextInputType.url"} forKey:@"inputType"]; + [self setClientId:123 configuration:config]; + + // Find all the FlutterTextInputViews we created. + NSArray* inputFields = self.installedInputViews; + + FlutterTextInputView* inputView = inputFields[0]; + + // Verify keyboardType is set to the value specified in config. + XCTAssertEqual(inputView.keyboardType, UIKeyboardTypeURL); +} + +- (void)testKeyboardTypeWebSearch { + NSDictionary* config = self.mutableTemplateCopy; + [config setValue:@{@"name" : @"TextInputType.webSearch"} forKey:@"inputType"]; + [self setClientId:123 configuration:config]; + + // Find all the FlutterTextInputViews we created. + NSArray* inputFields = self.installedInputViews; + + FlutterTextInputView* inputView = inputFields[0]; + + // Verify keyboardType is set to the value specified in config. + XCTAssertEqual(inputView.keyboardType, UIKeyboardTypeWebSearch); +} + +- (void)testKeyboardTypeTwitter { + NSDictionary* config = self.mutableTemplateCopy; + [config setValue:@{@"name" : @"TextInputType.twitter"} forKey:@"inputType"]; + [self setClientId:123 configuration:config]; + + // Find all the FlutterTextInputViews we created. + NSArray* inputFields = self.installedInputViews; + + FlutterTextInputView* inputView = inputFields[0]; + + // Verify keyboardType is set to the value specified in config. + XCTAssertEqual(inputView.keyboardType, UIKeyboardTypeTwitter); +} + +- (void)testVisiblePasswordUseAlphanumeric { + NSDictionary* config = self.mutableTemplateCopy; + [config setValue:@{@"name" : @"TextInputType.visiblePassword"} forKey:@"inputType"]; + [self setClientId:123 configuration:config]; + + // Find all the FlutterTextInputViews we created. + NSArray* inputFields = self.installedInputViews; + + FlutterTextInputView* inputView = inputFields[0]; + + // Verify keyboardType is set to the value specified in config. + XCTAssertEqual(inputView.keyboardType, UIKeyboardTypeASCIICapable); +} + +- (void)testSettingKeyboardTypeNoneDisablesSystemKeyboard { + NSDictionary* config = self.mutableTemplateCopy; + [config setValue:@{@"name" : @"TextInputType.none"} forKey:@"inputType"]; + [self setClientId:123 configuration:config]; + + // Verify the view's inputViewController is not nil; + XCTAssertNotNil(textInputPlugin.activeView.inputViewController); + + [config setValue:@{@"name" : @"TextInputType.url"} forKey:@"inputType"]; + [self setClientId:124 configuration:config]; + XCTAssertNotNil(textInputPlugin.activeView); + XCTAssertNil(textInputPlugin.activeView.inputViewController); +} + +- (void)testAutocorrectionPromptRectAppearsBeforeIOS17AndDoesNotAppearAfterIOS17 { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [inputView firstRectForRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]]; + + if (@available(iOS 17.0, *)) { + // Auto-correction prompt is disabled in iOS 17+. + OCMVerify(never(), [engine flutterTextInputView:inputView + showAutocorrectionPromptRectForStart:0 + end:1 + withClient:0]); + } else { + OCMVerify([engine flutterTextInputView:inputView + showAutocorrectionPromptRectForStart:0 + end:1 + withClient:0]); + } +} + +- (void)testIgnoresSelectionChangeIfSelectionIsDisabled { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + __block int updateCount = 0; + OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withState:[OCMArg isNotNil]]) + .andDo(^(NSInvocation* invocation) { + updateCount++; + }); + + [inputView.text setString:@"Some initial text"]; + XCTAssertEqual(updateCount, 0); + + FlutterTextRange* textRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]; + [inputView setSelectedTextRange:textRange]; + XCTAssertEqual(updateCount, 1); + + // Disable the interactive selection. + NSDictionary* config = self.mutableTemplateCopy; + [config setValue:@(NO) forKey:@"enableInteractiveSelection"]; + [config setValue:@(NO) forKey:@"obscureText"]; + [config setValue:@(NO) forKey:@"enableDeltaModel"]; + [inputView configureWithDictionary:config]; + + textRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(2, 3)]; + [inputView setSelectedTextRange:textRange]; + // The update count does not change. + XCTAssertEqual(updateCount, 1); +} + +- (void)testAutocorrectionPromptRectDoesNotAppearDuringScribble { + // Auto-correction prompt is disabled in iOS 17+. + if (@available(iOS 17.0, *)) { + return; + } + + if (@available(iOS 14.0, *)) { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + + __block int callCount = 0; + OCMStub([engine flutterTextInputView:inputView + showAutocorrectionPromptRectForStart:0 + end:1 + withClient:0]) + .andDo(^(NSInvocation* invocation) { + callCount++; + }); + + [inputView firstRectForRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]]; + // showAutocorrectionPromptRectForStart fires in response to firstRectForRange + XCTAssertEqual(callCount, 1); + + UIScribbleInteraction* scribbleInteraction = + [[UIScribbleInteraction alloc] initWithDelegate:inputView]; + + [inputView scribbleInteractionWillBeginWriting:scribbleInteraction]; + [inputView firstRectForRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]]; + // showAutocorrectionPromptRectForStart does not fire in response to setMarkedText during a + // scribble interaction.firstRectForRange + XCTAssertEqual(callCount, 1); + + [inputView scribbleInteractionDidFinishWriting:scribbleInteraction]; + [inputView resetScribbleInteractionStatusIfEnding]; + [inputView firstRectForRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]]; + // showAutocorrectionPromptRectForStart fires in response to firstRectForRange. + XCTAssertEqual(callCount, 2); + + inputView.scribbleFocusStatus = FlutterScribbleFocusStatusFocusing; + [inputView firstRectForRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]]; + // showAutocorrectionPromptRectForStart does not fire in response to firstRectForRange during a + // scribble-initiated focus. + XCTAssertEqual(callCount, 2); + + inputView.scribbleFocusStatus = FlutterScribbleFocusStatusFocused; + [inputView firstRectForRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]]; + // showAutocorrectionPromptRectForStart does not fire in response to firstRectForRange after a + // scribble-initiated focus. + XCTAssertEqual(callCount, 2); + + inputView.scribbleFocusStatus = FlutterScribbleFocusStatusUnfocused; + [inputView firstRectForRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]]; + // showAutocorrectionPromptRectForStart fires in response to firstRectForRange. + XCTAssertEqual(callCount, 3); + } +} + +- (void)testInputHiderOverlapWithTextWhenScribbleIsDisabledAfterIOS17AndDoesNotOverlapBeforeIOS17 { + FlutterTextInputPlugin* myInputPlugin = + [[FlutterTextInputPlugin alloc] initWithDelegate:OCMClassMock([FlutterEngine class])]; + + FlutterMethodCall* setClientCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(123), self.mutableTemplateCopy ]]; + [myInputPlugin handleMethodCall:setClientCall + result:^(id _Nullable result){ + }]; + + FlutterTextInputView* mockInputView = OCMPartialMock(myInputPlugin.activeView); + OCMStub([mockInputView isScribbleAvailable]).andReturn(NO); + + // yOffset = 200. + NSArray* yOffsetMatrix = @[ @1, @0, @0, @0, @0, @1, @0, @0, @0, @0, @1, @0, @0, @200, @0, @1 ]; + + FlutterMethodCall* setPlatformViewClientCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditableSizeAndTransform" + arguments:@{@"transform" : yOffsetMatrix}]; + [myInputPlugin handleMethodCall:setPlatformViewClientCall + result:^(id _Nullable result){ + }]; + + if (@available(iOS 17, *)) { + XCTAssert(CGRectEqualToRect(myInputPlugin.inputHider.frame, CGRectMake(0, 200, 0, 0)), + @"The input hider should overlap with the text on and after iOS 17"); + + } else { + XCTAssert(CGRectEqualToRect(myInputPlugin.inputHider.frame, CGRectZero), + @"The input hider should be on the origin of screen on and before iOS 16."); + } +} + +- (void)testTextRangeFromPositionMatchesUITextViewBehavior { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + FlutterTextPosition* fromPosition = [FlutterTextPosition positionWithIndex:2]; + FlutterTextPosition* toPosition = [FlutterTextPosition positionWithIndex:0]; + + FlutterTextRange* flutterRange = (FlutterTextRange*)[inputView textRangeFromPosition:fromPosition + toPosition:toPosition]; + NSRange range = flutterRange.range; + + XCTAssertEqual(range.location, 0ul); + XCTAssertEqual(range.length, 2ul); +} + +- (void)testTextInRange { + NSDictionary* config = self.mutableTemplateCopy; + [config setValue:@{@"name" : @"TextInputType.url"} forKey:@"inputType"]; + [self setClientId:123 configuration:config]; + NSArray* inputFields = self.installedInputViews; + FlutterTextInputView* inputView = inputFields[0]; + + [inputView insertText:@"test"]; + + UITextRange* range = [FlutterTextRange rangeWithNSRange:NSMakeRange(0, 20)]; + NSString* substring = [inputView textInRange:range]; + XCTAssertEqual(substring.length, 4ul); + + range = [FlutterTextRange rangeWithNSRange:NSMakeRange(10, 20)]; + substring = [inputView textInRange:range]; + XCTAssertEqual(substring.length, 0ul); +} + +- (void)testTextInRangeAcceptsNSNotFoundLocationGracefully { + NSDictionary* config = self.mutableTemplateCopy; + [self setClientId:123 configuration:config]; + NSArray* inputFields = self.installedInputViews; + FlutterTextInputView* inputView = inputFields[0]; + + [inputView insertText:@"text"]; + UITextRange* range = [FlutterTextRange rangeWithNSRange:NSMakeRange(NSNotFound, 0)]; + + NSString* substring = [inputView textInRange:range]; + XCTAssertNil(substring); +} + +- (void)testStandardEditActions { + NSDictionary* config = self.mutableTemplateCopy; + [self setClientId:123 configuration:config]; + NSArray* inputFields = self.installedInputViews; + FlutterTextInputView* inputView = inputFields[0]; + + [inputView insertText:@"aaaa"]; + [inputView selectAll:nil]; + [inputView cut:nil]; + [inputView insertText:@"bbbb"]; + XCTAssertTrue([inputView canPerformAction:@selector(paste:) withSender:nil]); + [inputView paste:nil]; + [inputView selectAll:nil]; + [inputView copy:nil]; + [inputView paste:nil]; + [inputView selectAll:nil]; + [inputView delete:nil]; + [inputView paste:nil]; + [inputView paste:nil]; + + UITextRange* range = [FlutterTextRange rangeWithNSRange:NSMakeRange(0, 30)]; + NSString* substring = [inputView textInRange:range]; + XCTAssertEqualObjects(substring, @"bbbbaaaabbbbaaaa"); +} + +- (void)testCanPerformActionForSelectActions { + NSDictionary* config = self.mutableTemplateCopy; + [self setClientId:123 configuration:config]; + NSArray* inputFields = self.installedInputViews; + FlutterTextInputView* inputView = inputFields[0]; + + XCTAssertFalse([inputView canPerformAction:@selector(selectAll:) withSender:nil]); + + [inputView insertText:@"aaaa"]; + + XCTAssertTrue([inputView canPerformAction:@selector(selectAll:) withSender:nil]); +} + +- (void)testDeletingBackward { + NSDictionary* config = self.mutableTemplateCopy; + [self setClientId:123 configuration:config]; + NSArray* inputFields = self.installedInputViews; + FlutterTextInputView* inputView = inputFields[0]; + + [inputView insertText:@"ឹ😀 text 🥰👨‍👩‍👧‍👦🇺🇳ดี "]; + [inputView deleteBackward]; + [inputView deleteBackward]; + + // Thai vowel is removed. + XCTAssertEqualObjects(inputView.text, @"ឹ😀 text 🥰👨‍👩‍👧‍👦🇺🇳ด"); + [inputView deleteBackward]; + XCTAssertEqualObjects(inputView.text, @"ឹ😀 text 🥰👨‍👩‍👧‍👦🇺🇳"); + [inputView deleteBackward]; + XCTAssertEqualObjects(inputView.text, @"ឹ😀 text 🥰👨‍👩‍👧‍👦"); + [inputView deleteBackward]; + XCTAssertEqualObjects(inputView.text, @"ឹ😀 text 🥰"); + [inputView deleteBackward]; + + XCTAssertEqualObjects(inputView.text, @"ឹ😀 text "); + [inputView deleteBackward]; + [inputView deleteBackward]; + [inputView deleteBackward]; + [inputView deleteBackward]; + [inputView deleteBackward]; + [inputView deleteBackward]; + + XCTAssertEqualObjects(inputView.text, @"ឹ😀"); + [inputView deleteBackward]; + XCTAssertEqualObjects(inputView.text, @"ឹ"); + [inputView deleteBackward]; + XCTAssertEqualObjects(inputView.text, @""); +} + +// This tests the workaround to fix an iOS 16 bug +// See: https://github.com/flutter/flutter/issues/111494 +- (void)testSystemOnlyAddingPartialComposedCharacter { + NSDictionary* config = self.mutableTemplateCopy; + [self setClientId:123 configuration:config]; + NSArray* inputFields = self.installedInputViews; + FlutterTextInputView* inputView = inputFields[0]; + + [inputView insertText:@"👨‍👩‍👧‍👦"]; + [inputView deleteBackward]; + + // Insert the first unichar in the emoji. + [inputView insertText:[@"👨‍👩‍👧‍👦" substringWithRange:NSMakeRange(0, 1)]]; + [inputView insertText:@"아"]; + + XCTAssertEqualObjects(inputView.text, @"👨‍👩‍👧‍👦아"); + + // Deleting 아. + [inputView deleteBackward]; + // 👨‍👩‍👧‍👦 should be the current string. + + [inputView insertText:@"😀"]; + [inputView deleteBackward]; + // Insert the first unichar in the emoji. + [inputView insertText:[@"😀" substringWithRange:NSMakeRange(0, 1)]]; + [inputView insertText:@"아"]; + XCTAssertEqualObjects(inputView.text, @"👨‍👩‍👧‍👦😀아"); + + // Deleting 아. + [inputView deleteBackward]; + // 👨‍👩‍👧‍👦😀 should be the current string. + + [inputView deleteBackward]; + // Insert the first unichar in the emoji. + [inputView insertText:[@"😀" substringWithRange:NSMakeRange(0, 1)]]; + [inputView insertText:@"아"]; + + XCTAssertEqualObjects(inputView.text, @"👨‍👩‍👧‍👦😀아"); +} + +- (void)testCachedComposedCharacterClearedAtKeyboardInteraction { + NSDictionary* config = self.mutableTemplateCopy; + [self setClientId:123 configuration:config]; + NSArray* inputFields = self.installedInputViews; + FlutterTextInputView* inputView = inputFields[0]; + + [inputView insertText:@"👨‍👩‍👧‍👦"]; + [inputView deleteBackward]; + [inputView shouldChangeTextInRange:OCMClassMock([UITextRange class]) replacementText:@""]; + + // Insert the first unichar in the emoji. + NSString* brokenEmoji = [@"👨‍👩‍👧‍👦" substringWithRange:NSMakeRange(0, 1)]; + [inputView insertText:brokenEmoji]; + [inputView insertText:@"아"]; + + NSString* finalText = [NSString stringWithFormat:@"%@아", brokenEmoji]; + XCTAssertEqualObjects(inputView.text, finalText); +} + +- (void)testPastingNonTextDisallowed { + NSDictionary* config = self.mutableTemplateCopy; + [self setClientId:123 configuration:config]; + NSArray* inputFields = self.installedInputViews; + FlutterTextInputView* inputView = inputFields[0]; + + UIPasteboard.generalPasteboard.color = UIColor.redColor; + XCTAssertNil(UIPasteboard.generalPasteboard.string); + XCTAssertFalse([inputView canPerformAction:@selector(paste:) withSender:nil]); + [inputView paste:nil]; + + XCTAssertEqualObjects(inputView.text, @""); +} + +- (void)testNoZombies { + // Regression test for https://github.com/flutter/flutter/issues/62501. + FlutterSecureTextInputView* passwordView = + [[FlutterSecureTextInputView alloc] initWithOwner:textInputPlugin]; + + @autoreleasepool { + // Initialize the lazy textField. + [passwordView.textField description]; + } + XCTAssert([[passwordView.textField description] containsString:@"TextField"]); +} + +- (void)testInputViewCrash { + FlutterTextInputView* activeView = nil; + @autoreleasepool { + FlutterEngine* flutterEngine = [[FlutterEngine alloc] init]; + FlutterTextInputPlugin* inputPlugin = [[FlutterTextInputPlugin alloc] + initWithDelegate:(id)flutterEngine]; + activeView = inputPlugin.activeView; + } + [activeView updateEditingState]; +} + +- (void)testDoNotReuseInputViews { + NSDictionary* config = self.mutableTemplateCopy; + [self setClientId:123 configuration:config]; + FlutterTextInputView* currentView = textInputPlugin.activeView; + [self setClientId:456 configuration:config]; + + XCTAssertNotNil(currentView); + XCTAssertNotNil(textInputPlugin.activeView); + XCTAssertNotEqual(currentView, textInputPlugin.activeView); +} + +- (void)ensureOnlyActiveViewCanBecomeFirstResponder { + for (FlutterTextInputView* inputView in self.installedInputViews) { + XCTAssertEqual(inputView.canBecomeFirstResponder, inputView == textInputPlugin.activeView); + } +} + +- (void)testPropagatePressEventsToViewController { + FlutterViewController* mockViewController = OCMPartialMock(viewController); + OCMStub([mockViewController pressesBegan:[OCMArg isNotNil] withEvent:[OCMArg isNotNil]]); + OCMStub([mockViewController pressesEnded:[OCMArg isNotNil] withEvent:[OCMArg isNotNil]]); + + textInputPlugin.viewController = mockViewController; + + NSDictionary* config = self.mutableTemplateCopy; + [self setClientId:123 configuration:config]; + FlutterTextInputView* currentView = textInputPlugin.activeView; + [self setTextInputShow]; + + [currentView pressesBegan:[NSSet setWithObjects:OCMClassMock([UIPress class]), nil] + withEvent:OCMClassMock([UIPressesEvent class])]; + + OCMVerify(times(1), [mockViewController pressesBegan:[OCMArg isNotNil] + withEvent:[OCMArg isNotNil]]); + OCMVerify(times(0), [mockViewController pressesEnded:[OCMArg isNotNil] + withEvent:[OCMArg isNotNil]]); + + [currentView pressesEnded:[NSSet setWithObjects:OCMClassMock([UIPress class]), nil] + withEvent:OCMClassMock([UIPressesEvent class])]; + + OCMVerify(times(1), [mockViewController pressesBegan:[OCMArg isNotNil] + withEvent:[OCMArg isNotNil]]); + OCMVerify(times(1), [mockViewController pressesEnded:[OCMArg isNotNil] + withEvent:[OCMArg isNotNil]]); +} + +- (void)testPropagatePressEventsToViewController2 { + FlutterViewController* mockViewController = OCMPartialMock(viewController); + OCMStub([mockViewController pressesBegan:[OCMArg isNotNil] withEvent:[OCMArg isNotNil]]); + OCMStub([mockViewController pressesEnded:[OCMArg isNotNil] withEvent:[OCMArg isNotNil]]); + + textInputPlugin.viewController = mockViewController; + + NSDictionary* config = self.mutableTemplateCopy; + [self setClientId:123 configuration:config]; + [self setTextInputShow]; + FlutterTextInputView* currentView = textInputPlugin.activeView; + + [currentView pressesBegan:[NSSet setWithObjects:OCMClassMock([UIPress class]), nil] + withEvent:OCMClassMock([UIPressesEvent class])]; + + OCMVerify(times(1), [mockViewController pressesBegan:[OCMArg isNotNil] + withEvent:[OCMArg isNotNil]]); + OCMVerify(times(0), [mockViewController pressesEnded:[OCMArg isNotNil] + withEvent:[OCMArg isNotNil]]); + + // Switch focus to a different view. + [self setClientId:321 configuration:config]; + [self setTextInputShow]; + NSAssert(textInputPlugin.activeView, @"active view must not be nil"); + NSAssert(textInputPlugin.activeView != currentView, @"active view must change"); + currentView = textInputPlugin.activeView; + [currentView pressesEnded:[NSSet setWithObjects:OCMClassMock([UIPress class]), nil] + withEvent:OCMClassMock([UIPressesEvent class])]; + + OCMVerify(times(1), [mockViewController pressesBegan:[OCMArg isNotNil] + withEvent:[OCMArg isNotNil]]); + OCMVerify(times(1), [mockViewController pressesEnded:[OCMArg isNotNil] + withEvent:[OCMArg isNotNil]]); +} + +- (void)testUpdateSecureTextEntry { + NSDictionary* config = self.mutableTemplateCopy; + [config setValue:@"YES" forKey:@"obscureText"]; + [self setClientId:123 configuration:config]; + + NSArray* inputFields = self.installedInputViews; + FlutterTextInputView* inputView = OCMPartialMock(inputFields[0]); + + __block int callCount = 0; + OCMStub([inputView reloadInputViews]).andDo(^(NSInvocation* invocation) { + callCount++; + }); + + XCTAssertTrue(inputView.isSecureTextEntry); + + config = self.mutableTemplateCopy; + [config setValue:@"NO" forKey:@"obscureText"]; + [self updateConfig:config]; + + XCTAssertEqual(callCount, 1); + XCTAssertFalse(inputView.isSecureTextEntry); +} + +- (void)testInputActionContinueAction { + id mockBinaryMessenger = OCMClassMock([FlutterBinaryMessengerRelay class]); + FlutterEngine* testEngine = [[FlutterEngine alloc] init]; + [testEngine setBinaryMessenger:mockBinaryMessenger]; + [testEngine runWithEntrypoint:FlutterDefaultDartEntrypoint initialRoute:@"test"]; + + FlutterTextInputPlugin* inputPlugin = + [[FlutterTextInputPlugin alloc] initWithDelegate:(id)testEngine]; + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:inputPlugin]; + + [testEngine flutterTextInputView:inputView + performAction:FlutterTextInputActionContinue + withClient:123]; + + FlutterMethodCall* methodCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInputClient.performAction" + arguments:@[ @(123), @"TextInputAction.continueAction" ]]; + NSData* encodedMethodCall = [[FlutterJSONMethodCodec sharedInstance] encodeMethodCall:methodCall]; + OCMVerify([mockBinaryMessenger sendOnChannel:@"flutter/textinput" message:encodedMethodCall]); +} + +- (void)testDisablingAutocorrectDisablesSpellChecking { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + + // Disable the interactive selection. + NSDictionary* config = self.mutableTemplateCopy; + [inputView configureWithDictionary:config]; + + XCTAssertEqual(inputView.autocorrectionType, UITextAutocorrectionTypeDefault); + XCTAssertEqual(inputView.spellCheckingType, UITextSpellCheckingTypeDefault); + + [config setValue:@(NO) forKey:@"autocorrect"]; + [inputView configureWithDictionary:config]; + + XCTAssertEqual(inputView.autocorrectionType, UITextAutocorrectionTypeNo); + XCTAssertEqual(inputView.spellCheckingType, UITextSpellCheckingTypeNo); +} + +- (void)testReplaceTestLocalAdjustSelectionAndMarkedTextRange { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [inputView setMarkedText:@"test text" selectedRange:NSMakeRange(0, 5)]; + NSRange selectedTextRange = ((FlutterTextRange*)inputView.selectedTextRange).range; + const NSRange markedTextRange = ((FlutterTextRange*)inputView.markedTextRange).range; + XCTAssertEqual(selectedTextRange.location, 0ul); + XCTAssertEqual(selectedTextRange.length, 5ul); + XCTAssertEqual(markedTextRange.location, 0ul); + XCTAssertEqual(markedTextRange.length, 9ul); + + // Replaces space with space. + [inputView replaceRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(4, 1)] withText:@" "]; + selectedTextRange = ((FlutterTextRange*)inputView.selectedTextRange).range; + + XCTAssertEqual(selectedTextRange.location, 5ul); + XCTAssertEqual(selectedTextRange.length, 0ul); + XCTAssertEqual(inputView.markedTextRange, nil); +} + +- (void)testFlutterTextInputViewOnlyRespondsToInsertionPointColorBelowIOS17 { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + // [UITextInputTraits insertionPointColor] is non-public API, so @selector(insertionPointColor) + // would generate a compile-time warning. + SEL insertionPointColor = NSSelectorFromString(@"insertionPointColor"); + BOOL respondsToInsertionPointColor = [inputView respondsToSelector:insertionPointColor]; + if (@available(iOS 17, *)) { + XCTAssertFalse(respondsToInsertionPointColor); + } else { + XCTAssertTrue(respondsToInsertionPointColor); + } +} + +#pragma mark - TextEditingDelta tests +- (void)testTextEditingDeltasAreGeneratedOnTextInput { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + inputView.enableDeltaModel = YES; + + __block int updateCount = 0; + + [inputView insertText:@"text to insert"]; + OCMExpect( + [engine + flutterTextInputView:inputView + updateEditingClient:0 + withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { + return ([[state[@"deltas"] objectAtIndex:0][@"oldText"] + isEqualToString:@""]) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaText"] + isEqualToString:@"text to insert"]) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"] intValue] == 0) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"] intValue] == 0); + }]]) + .andDo(^(NSInvocation* invocation) { + updateCount++; + }); + XCTAssertEqual(updateCount, 0); + + [self flushScheduledAsyncBlocks]; + + // Update the framework exactly once. + XCTAssertEqual(updateCount, 1); + + [inputView deleteBackward]; + OCMExpect([engine flutterTextInputView:inputView + updateEditingClient:0 + withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { + return ([[state[@"deltas"] objectAtIndex:0][@"oldText"] + isEqualToString:@"text to insert"]) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaText"] + isEqualToString:@""]) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"] + intValue] == 13) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"] + intValue] == 14); + }]]) + .andDo(^(NSInvocation* invocation) { + updateCount++; + }); + [self flushScheduledAsyncBlocks]; + XCTAssertEqual(updateCount, 2); + + inputView.selectedTextRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]; + OCMExpect([engine flutterTextInputView:inputView + updateEditingClient:0 + withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { + return ([[state[@"deltas"] objectAtIndex:0][@"oldText"] + isEqualToString:@"text to inser"]) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaText"] + isEqualToString:@""]) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"] + intValue] == -1) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"] + intValue] == -1); + }]]) + .andDo(^(NSInvocation* invocation) { + updateCount++; + }); + [self flushScheduledAsyncBlocks]; + XCTAssertEqual(updateCount, 3); + + [inputView replaceRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)] + withText:@"replace text"]; + OCMExpect( + [engine + flutterTextInputView:inputView + updateEditingClient:0 + withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { + return ([[state[@"deltas"] objectAtIndex:0][@"oldText"] + isEqualToString:@"text to inser"]) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaText"] + isEqualToString:@"replace text"]) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"] intValue] == 0) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"] intValue] == 1); + }]]) + .andDo(^(NSInvocation* invocation) { + updateCount++; + }); + [self flushScheduledAsyncBlocks]; + XCTAssertEqual(updateCount, 4); + + [inputView setMarkedText:@"marked text" selectedRange:NSMakeRange(0, 1)]; + OCMExpect([engine flutterTextInputView:inputView + updateEditingClient:0 + withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { + return ([[state[@"deltas"] objectAtIndex:0][@"oldText"] + isEqualToString:@"replace textext to inser"]) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaText"] + isEqualToString:@"marked text"]) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"] + intValue] == 12) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"] + intValue] == 12); + }]]) + .andDo(^(NSInvocation* invocation) { + updateCount++; + }); + [self flushScheduledAsyncBlocks]; + XCTAssertEqual(updateCount, 5); + + [inputView unmarkText]; + OCMExpect([engine + flutterTextInputView:inputView + updateEditingClient:0 + withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { + return ([[state[@"deltas"] objectAtIndex:0][@"oldText"] + isEqualToString:@"replace textmarked textext to inser"]) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaText"] + isEqualToString:@""]) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"] intValue] == + -1) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"] intValue] == + -1); + }]]) + .andDo(^(NSInvocation* invocation) { + updateCount++; + }); + [self flushScheduledAsyncBlocks]; + + XCTAssertEqual(updateCount, 6); + OCMVerifyAll(engine); +} + +- (void)testTextEditingDeltasAreBatchedAndForwardedToFramework { + // Setup + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + inputView.enableDeltaModel = YES; + + // Expected call. + OCMExpect([engine flutterTextInputView:inputView + updateEditingClient:0 + withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { + NSArray* deltas = state[@"deltas"]; + NSDictionary* firstDelta = deltas[0]; + NSDictionary* secondDelta = deltas[1]; + NSDictionary* thirdDelta = deltas[2]; + return [firstDelta[@"oldText"] isEqualToString:@""] && + [firstDelta[@"deltaText"] isEqualToString:@"-"] && + [firstDelta[@"deltaStart"] intValue] == 0 && + [firstDelta[@"deltaEnd"] intValue] == 0 && + [secondDelta[@"oldText"] isEqualToString:@"-"] && + [secondDelta[@"deltaText"] isEqualToString:@""] && + [secondDelta[@"deltaStart"] intValue] == 0 && + [secondDelta[@"deltaEnd"] intValue] == 1 && + [thirdDelta[@"oldText"] isEqualToString:@""] && + [thirdDelta[@"deltaText"] isEqualToString:@"—"] && + [thirdDelta[@"deltaStart"] intValue] == 0 && + [thirdDelta[@"deltaEnd"] intValue] == 0; + }]]); + + // Simulate user input. + [inputView insertText:@"-"]; + [inputView deleteBackward]; + [inputView insertText:@"—"]; + + [self flushScheduledAsyncBlocks]; + OCMVerifyAll(engine); +} + +- (void)testTextEditingDeltasAreGeneratedOnSetMarkedTextReplacement { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + inputView.enableDeltaModel = YES; + + __block int updateCount = 0; + OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withDelta:[OCMArg isNotNil]]) + .andDo(^(NSInvocation* invocation) { + updateCount++; + }); + + [inputView.text setString:@"Some initial text"]; + XCTAssertEqual(updateCount, 0); + + UITextRange* range = [FlutterTextRange rangeWithNSRange:NSMakeRange(13, 4)]; + inputView.markedTextRange = range; + inputView.selectedTextRange = nil; + [self flushScheduledAsyncBlocks]; + XCTAssertEqual(updateCount, 1); + + [inputView setMarkedText:@"new marked text." selectedRange:NSMakeRange(0, 1)]; + OCMVerify([engine + flutterTextInputView:inputView + updateEditingClient:0 + withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { + return ([[state[@"deltas"] objectAtIndex:0][@"oldText"] + isEqualToString:@"Some initial text"]) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaText"] + isEqualToString:@"new marked text."]) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"] intValue] == 13) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"] intValue] == 17); + }]]); + [self flushScheduledAsyncBlocks]; + XCTAssertEqual(updateCount, 2); +} + +- (void)testTextEditingDeltasAreGeneratedOnSetMarkedTextInsertion { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + inputView.enableDeltaModel = YES; + + __block int updateCount = 0; + OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withDelta:[OCMArg isNotNil]]) + .andDo(^(NSInvocation* invocation) { + updateCount++; + }); + + [inputView.text setString:@"Some initial text"]; + [self flushScheduledAsyncBlocks]; + XCTAssertEqual(updateCount, 0); + + UITextRange* range = [FlutterTextRange rangeWithNSRange:NSMakeRange(13, 4)]; + inputView.markedTextRange = range; + inputView.selectedTextRange = nil; + [self flushScheduledAsyncBlocks]; + XCTAssertEqual(updateCount, 1); + + [inputView setMarkedText:@"text." selectedRange:NSMakeRange(0, 1)]; + OCMVerify([engine + flutterTextInputView:inputView + updateEditingClient:0 + withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { + return ([[state[@"deltas"] objectAtIndex:0][@"oldText"] + isEqualToString:@"Some initial text"]) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaText"] + isEqualToString:@"text."]) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"] intValue] == 13) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"] intValue] == 17); + }]]); + [self flushScheduledAsyncBlocks]; + XCTAssertEqual(updateCount, 2); +} + +- (void)testTextEditingDeltasAreGeneratedOnSetMarkedTextDeletion { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + inputView.enableDeltaModel = YES; + + __block int updateCount = 0; + OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withDelta:[OCMArg isNotNil]]) + .andDo(^(NSInvocation* invocation) { + updateCount++; + }); + + [inputView.text setString:@"Some initial text"]; + [self flushScheduledAsyncBlocks]; + XCTAssertEqual(updateCount, 0); + + UITextRange* range = [FlutterTextRange rangeWithNSRange:NSMakeRange(13, 4)]; + inputView.markedTextRange = range; + inputView.selectedTextRange = nil; + [self flushScheduledAsyncBlocks]; + XCTAssertEqual(updateCount, 1); + + [inputView setMarkedText:@"tex" selectedRange:NSMakeRange(0, 1)]; + OCMVerify([engine + flutterTextInputView:inputView + updateEditingClient:0 + withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { + return ([[state[@"deltas"] objectAtIndex:0][@"oldText"] + isEqualToString:@"Some initial text"]) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaText"] + isEqualToString:@"tex"]) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"] intValue] == 13) && + ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"] intValue] == 17); + }]]); + [self flushScheduledAsyncBlocks]; + XCTAssertEqual(updateCount, 2); +} + +#pragma mark - EditingState tests + +- (void)testUITextInputCallsUpdateEditingStateOnce { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + + __block int updateCount = 0; + OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withState:[OCMArg isNotNil]]) + .andDo(^(NSInvocation* invocation) { + updateCount++; + }); + + [inputView insertText:@"text to insert"]; + // Update the framework exactly once. + XCTAssertEqual(updateCount, 1); + + [inputView deleteBackward]; + XCTAssertEqual(updateCount, 2); + + inputView.selectedTextRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]; + XCTAssertEqual(updateCount, 3); + + [inputView replaceRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)] + withText:@"replace text"]; + XCTAssertEqual(updateCount, 4); + + [inputView setMarkedText:@"marked text" selectedRange:NSMakeRange(0, 1)]; + XCTAssertEqual(updateCount, 5); + + [inputView unmarkText]; + XCTAssertEqual(updateCount, 6); +} + +- (void)testUITextInputCallsUpdateEditingStateWithDeltaOnce { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + inputView.enableDeltaModel = YES; + + __block int updateCount = 0; + OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withDelta:[OCMArg isNotNil]]) + .andDo(^(NSInvocation* invocation) { + updateCount++; + }); + + [inputView insertText:@"text to insert"]; + [self flushScheduledAsyncBlocks]; + // Update the framework exactly once. + XCTAssertEqual(updateCount, 1); + + [inputView deleteBackward]; + [self flushScheduledAsyncBlocks]; + XCTAssertEqual(updateCount, 2); + + inputView.selectedTextRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]; + [self flushScheduledAsyncBlocks]; + XCTAssertEqual(updateCount, 3); + + [inputView replaceRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)] + withText:@"replace text"]; + [self flushScheduledAsyncBlocks]; + XCTAssertEqual(updateCount, 4); + + [inputView setMarkedText:@"marked text" selectedRange:NSMakeRange(0, 1)]; + [self flushScheduledAsyncBlocks]; + XCTAssertEqual(updateCount, 5); + + [inputView unmarkText]; + [self flushScheduledAsyncBlocks]; + XCTAssertEqual(updateCount, 6); +} + +- (void)testTextChangesDoNotTriggerUpdateEditingClient { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + + __block int updateCount = 0; + OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withState:[OCMArg isNotNil]]) + .andDo(^(NSInvocation* invocation) { + updateCount++; + }); + + [inputView.text setString:@"BEFORE"]; + XCTAssertEqual(updateCount, 0); + + inputView.markedTextRange = nil; + inputView.selectedTextRange = nil; + XCTAssertEqual(updateCount, 1); + + // Text changes don't trigger an update. + XCTAssertEqual(updateCount, 1); + [inputView setTextInputState:@{@"text" : @"AFTER"}]; + XCTAssertEqual(updateCount, 1); + [inputView setTextInputState:@{@"text" : @"AFTER"}]; + XCTAssertEqual(updateCount, 1); + + // Selection changes don't trigger an update. + [inputView + setTextInputState:@{@"text" : @"SELECTION", @"selectionBase" : @0, @"selectionExtent" : @3}]; + XCTAssertEqual(updateCount, 1); + [inputView + setTextInputState:@{@"text" : @"SELECTION", @"selectionBase" : @1, @"selectionExtent" : @3}]; + XCTAssertEqual(updateCount, 1); + + // Composing region changes don't trigger an update. + [inputView + setTextInputState:@{@"text" : @"COMPOSING", @"composingBase" : @1, @"composingExtent" : @2}]; + XCTAssertEqual(updateCount, 1); + [inputView + setTextInputState:@{@"text" : @"COMPOSING", @"composingBase" : @1, @"composingExtent" : @3}]; + XCTAssertEqual(updateCount, 1); +} + +- (void)testTextChangesDoNotTriggerUpdateEditingClientWithDelta { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + inputView.enableDeltaModel = YES; + + __block int updateCount = 0; + OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withDelta:[OCMArg isNotNil]]) + .andDo(^(NSInvocation* invocation) { + updateCount++; + }); + + [inputView.text setString:@"BEFORE"]; + [self flushScheduledAsyncBlocks]; + XCTAssertEqual(updateCount, 0); + + inputView.markedTextRange = nil; + inputView.selectedTextRange = nil; + [self flushScheduledAsyncBlocks]; + XCTAssertEqual(updateCount, 1); + + // Text changes don't trigger an update. + XCTAssertEqual(updateCount, 1); + [inputView setTextInputState:@{@"text" : @"AFTER"}]; + [self flushScheduledAsyncBlocks]; + XCTAssertEqual(updateCount, 1); + + [inputView setTextInputState:@{@"text" : @"AFTER"}]; + [self flushScheduledAsyncBlocks]; + XCTAssertEqual(updateCount, 1); + + // Selection changes don't trigger an update. + [inputView + setTextInputState:@{@"text" : @"SELECTION", @"selectionBase" : @0, @"selectionExtent" : @3}]; + [self flushScheduledAsyncBlocks]; + XCTAssertEqual(updateCount, 1); + + [inputView + setTextInputState:@{@"text" : @"SELECTION", @"selectionBase" : @1, @"selectionExtent" : @3}]; + [self flushScheduledAsyncBlocks]; + XCTAssertEqual(updateCount, 1); + + // Composing region changes don't trigger an update. + [inputView + setTextInputState:@{@"text" : @"COMPOSING", @"composingBase" : @1, @"composingExtent" : @2}]; + [self flushScheduledAsyncBlocks]; + XCTAssertEqual(updateCount, 1); + + [inputView + setTextInputState:@{@"text" : @"COMPOSING", @"composingBase" : @1, @"composingExtent" : @3}]; + [self flushScheduledAsyncBlocks]; + XCTAssertEqual(updateCount, 1); +} + +- (void)testUITextInputAvoidUnnecessaryUndateEditingClientCalls { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + + __block int updateCount = 0; + OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withState:[OCMArg isNotNil]]) + .andDo(^(NSInvocation* invocation) { + updateCount++; + }); + + [inputView unmarkText]; + // updateEditingClient shouldn't fire as the text is already unmarked. + XCTAssertEqual(updateCount, 0); + + [inputView setMarkedText:@"marked text" selectedRange:NSMakeRange(0, 1)]; + // updateEditingClient fires in response to setMarkedText. + XCTAssertEqual(updateCount, 1); + + [inputView unmarkText]; + // updateEditingClient fires in response to unmarkText. + XCTAssertEqual(updateCount, 2); +} + +- (void)testCanCopyPasteWithScribbleEnabled { + if (@available(iOS 14.0, *)) { + NSDictionary* config = self.mutableTemplateCopy; + [self setClientId:123 configuration:config]; + NSArray* inputFields = self.installedInputViews; + FlutterTextInputView* inputView = inputFields[0]; + + FlutterTextInputView* mockInputView = OCMPartialMock(inputView); + OCMStub([mockInputView isScribbleAvailable]).andReturn(YES); + + [mockInputView insertText:@"aaaa"]; + [mockInputView selectAll:nil]; + + XCTAssertTrue([mockInputView canPerformAction:@selector(copy:) withSender:NULL]); + XCTAssertTrue([mockInputView canPerformAction:@selector(copy:) withSender:@"sender"]); + XCTAssertFalse([mockInputView canPerformAction:@selector(paste:) withSender:NULL]); + XCTAssertFalse([mockInputView canPerformAction:@selector(paste:) withSender:@"sender"]); + + [mockInputView copy:NULL]; + XCTAssertTrue([mockInputView canPerformAction:@selector(copy:) withSender:NULL]); + XCTAssertTrue([mockInputView canPerformAction:@selector(copy:) withSender:@"sender"]); + XCTAssertTrue([mockInputView canPerformAction:@selector(paste:) withSender:NULL]); + XCTAssertTrue([mockInputView canPerformAction:@selector(paste:) withSender:@"sender"]); + } +} + +- (void)testSetMarkedTextDuringScribbleDoesNotTriggerUpdateEditingClient { + if (@available(iOS 14.0, *)) { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + + __block int updateCount = 0; + OCMStub([engine flutterTextInputView:inputView + updateEditingClient:0 + withState:[OCMArg isNotNil]]) + .andDo(^(NSInvocation* invocation) { + updateCount++; + }); + + [inputView setMarkedText:@"marked text" selectedRange:NSMakeRange(0, 1)]; + // updateEditingClient fires in response to setMarkedText. + XCTAssertEqual(updateCount, 1); + + UIScribbleInteraction* scribbleInteraction = + [[UIScribbleInteraction alloc] initWithDelegate:inputView]; + + [inputView scribbleInteractionWillBeginWriting:scribbleInteraction]; + [inputView setMarkedText:@"during writing" selectedRange:NSMakeRange(1, 2)]; + // updateEditingClient does not fire in response to setMarkedText during a scribble interaction. + XCTAssertEqual(updateCount, 1); + + [inputView scribbleInteractionDidFinishWriting:scribbleInteraction]; + [inputView resetScribbleInteractionStatusIfEnding]; + [inputView setMarkedText:@"marked text" selectedRange:NSMakeRange(0, 1)]; + // updateEditingClient fires in response to setMarkedText. + XCTAssertEqual(updateCount, 2); + + inputView.scribbleFocusStatus = FlutterScribbleFocusStatusFocusing; + [inputView setMarkedText:@"during focus" selectedRange:NSMakeRange(1, 2)]; + // updateEditingClient does not fire in response to setMarkedText during a scribble-initiated + // focus. + XCTAssertEqual(updateCount, 2); + + inputView.scribbleFocusStatus = FlutterScribbleFocusStatusFocused; + [inputView setMarkedText:@"after focus" selectedRange:NSMakeRange(2, 3)]; + // updateEditingClient does not fire in response to setMarkedText after a scribble-initiated + // focus. + XCTAssertEqual(updateCount, 2); + + inputView.scribbleFocusStatus = FlutterScribbleFocusStatusUnfocused; + [inputView setMarkedText:@"marked text" selectedRange:NSMakeRange(0, 1)]; + // updateEditingClient fires in response to setMarkedText. + XCTAssertEqual(updateCount, 3); + } +} + +- (void)testUpdateEditingClientNegativeSelection { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + + [inputView.text setString:@"SELECTION"]; + inputView.markedTextRange = nil; + inputView.selectedTextRange = nil; + + [inputView setTextInputState:@{ + @"text" : @"SELECTION", + @"selectionBase" : @-1, + @"selectionExtent" : @-1 + }]; + [inputView updateEditingState]; + OCMVerify([engine flutterTextInputView:inputView + updateEditingClient:0 + withState:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { + return ([state[@"selectionBase"] intValue]) == 0 && + ([state[@"selectionExtent"] intValue] == 0); + }]]); + + // Returns (0, 0) when either end goes below 0. + [inputView + setTextInputState:@{@"text" : @"SELECTION", @"selectionBase" : @-1, @"selectionExtent" : @1}]; + [inputView updateEditingState]; + OCMVerify([engine flutterTextInputView:inputView + updateEditingClient:0 + withState:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { + return ([state[@"selectionBase"] intValue]) == 0 && + ([state[@"selectionExtent"] intValue] == 0); + }]]); + + [inputView + setTextInputState:@{@"text" : @"SELECTION", @"selectionBase" : @1, @"selectionExtent" : @-1}]; + [inputView updateEditingState]; + OCMVerify([engine flutterTextInputView:inputView + updateEditingClient:0 + withState:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { + return ([state[@"selectionBase"] intValue]) == 0 && + ([state[@"selectionExtent"] intValue] == 0); + }]]); +} + +- (void)testUpdateEditingClientSelectionClamping { + // Regression test for https://github.com/flutter/flutter/issues/62992. + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + + [inputView.text setString:@"SELECTION"]; + inputView.markedTextRange = nil; + inputView.selectedTextRange = nil; + + [inputView + setTextInputState:@{@"text" : @"SELECTION", @"selectionBase" : @0, @"selectionExtent" : @0}]; + [inputView updateEditingState]; + OCMVerify([engine flutterTextInputView:inputView + updateEditingClient:0 + withState:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { + return ([state[@"selectionBase"] intValue]) == 0 && + ([state[@"selectionExtent"] intValue] == 0); + }]]); + + // Needs clamping. + [inputView setTextInputState:@{ + @"text" : @"SELECTION", + @"selectionBase" : @0, + @"selectionExtent" : @9999 + }]; + [inputView updateEditingState]; + + OCMVerify([engine flutterTextInputView:inputView + updateEditingClient:0 + withState:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { + return ([state[@"selectionBase"] intValue]) == 0 && + ([state[@"selectionExtent"] intValue] == 9); + }]]); + + // No clamping needed, but in reverse direction. + [inputView + setTextInputState:@{@"text" : @"SELECTION", @"selectionBase" : @1, @"selectionExtent" : @0}]; + [inputView updateEditingState]; + OCMVerify([engine flutterTextInputView:inputView + updateEditingClient:0 + withState:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { + return ([state[@"selectionBase"] intValue]) == 0 && + ([state[@"selectionExtent"] intValue] == 1); + }]]); + + // Both ends need clamping. + [inputView setTextInputState:@{ + @"text" : @"SELECTION", + @"selectionBase" : @9999, + @"selectionExtent" : @9999 + }]; + [inputView updateEditingState]; + OCMVerify([engine flutterTextInputView:inputView + updateEditingClient:0 + withState:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { + return ([state[@"selectionBase"] intValue]) == 9 && + ([state[@"selectionExtent"] intValue] == 9); + }]]); +} + +- (void)testInputViewsHasNonNilInputDelegate { + if (@available(iOS 13.0, *)) { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [UIApplication.sharedApplication.keyWindow addSubview:inputView]; + + [inputView setTextInputClient:123]; + [inputView reloadInputViews]; + [inputView becomeFirstResponder]; + NSAssert(inputView.isFirstResponder, @"inputView is not first responder"); + inputView.inputDelegate = nil; + + FlutterTextInputView* mockInputView = OCMPartialMock(inputView); + [mockInputView setTextInputState:@{ + @"text" : @"COMPOSING", + @"composingBase" : @1, + @"composingExtent" : @3 + }]; + OCMVerify([mockInputView setInputDelegate:[OCMArg isNotNil]]); + [inputView removeFromSuperview]; + } +} + +- (void)testInputViewsDoNotHaveUITextInteractions { + if (@available(iOS 13.0, *)) { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + BOOL hasTextInteraction = NO; + for (id interaction in inputView.interactions) { + hasTextInteraction = [interaction isKindOfClass:[UITextInteraction class]]; + if (hasTextInteraction) { + break; + } + } + XCTAssertFalse(hasTextInteraction); + } +} + +#pragma mark - UITextInput methods - Tests + +- (void)testUpdateFirstRectForRange { + [self setClientId:123 configuration:self.mutableTemplateCopy]; + + FlutterTextInputView* inputView = textInputPlugin.activeView; + textInputPlugin.viewController.view.frame = CGRectMake(0, 0, 0, 0); + + [inputView + setTextInputState:@{@"text" : @"COMPOSING", @"composingBase" : @1, @"composingExtent" : @3}]; + + CGRect kInvalidFirstRect = CGRectMake(-1, -1, 9999, 9999); + FlutterTextRange* range = [FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]; + // yOffset = 200. + NSArray* yOffsetMatrix = @[ @1, @0, @0, @0, @0, @1, @0, @0, @0, @0, @1, @0, @0, @200, @0, @1 ]; + NSArray* zeroMatrix = @[ @0, @0, @0, @0, @0, @0, @0, @0, @0, @0, @0, @0, @0, @0, @0, @0 ]; + // This matrix can be generated by running this dart code snippet: + // Matrix4.identity()..scale(3.0)..rotateZ(math.pi/2)..translate(1.0, 2.0, + // 3.0); + NSArray* affineMatrix = @[ + @(0.0), @(3.0), @(0.0), @(0.0), @(-3.0), @(0.0), @(0.0), @(0.0), @(0.0), @(0.0), @(3.0), @(0.0), + @(-6.0), @(3.0), @(9.0), @(1.0) + ]; + + // Invalid since we don't have the transform or the rect. + XCTAssertTrue(CGRectEqualToRect(kInvalidFirstRect, [inputView firstRectForRange:range])); + + [inputView setEditableTransform:yOffsetMatrix]; + // Invalid since we don't have the rect. + XCTAssertTrue(CGRectEqualToRect(kInvalidFirstRect, [inputView firstRectForRange:range])); + + // Valid rect and transform. + CGRect testRect = CGRectMake(0, 0, 100, 100); + [inputView setMarkedRect:testRect]; + + CGRect finalRect = CGRectOffset(testRect, 0, 200); + XCTAssertTrue(CGRectEqualToRect(finalRect, [inputView firstRectForRange:range])); + // Idempotent. + XCTAssertTrue(CGRectEqualToRect(finalRect, [inputView firstRectForRange:range])); + + // Use an invalid matrix: + [inputView setEditableTransform:zeroMatrix]; + // Invalid matrix is invalid. + XCTAssertTrue(CGRectEqualToRect(kInvalidFirstRect, [inputView firstRectForRange:range])); + XCTAssertTrue(CGRectEqualToRect(kInvalidFirstRect, [inputView firstRectForRange:range])); + + // Revert the invalid matrix change. + [inputView setEditableTransform:yOffsetMatrix]; + [inputView setMarkedRect:testRect]; + XCTAssertTrue(CGRectEqualToRect(finalRect, [inputView firstRectForRange:range])); + + // Use an invalid rect: + [inputView setMarkedRect:kInvalidFirstRect]; + // Invalid marked rect is invalid. + XCTAssertTrue(CGRectEqualToRect(kInvalidFirstRect, [inputView firstRectForRange:range])); + XCTAssertTrue(CGRectEqualToRect(kInvalidFirstRect, [inputView firstRectForRange:range])); + + // Use a 3d affine transform that does 3d-scaling, z-index rotating and 3d translation. + [inputView setEditableTransform:affineMatrix]; + [inputView setMarkedRect:testRect]; + XCTAssertTrue( + CGRectEqualToRect(CGRectMake(-306, 3, 300, 300), [inputView firstRectForRange:range])); + + NSAssert(inputView.superview, @"inputView is not in the view hierarchy!"); + const CGPoint offset = CGPointMake(113, 119); + CGRect currentFrame = inputView.frame; + currentFrame.origin = offset; + inputView.frame = currentFrame; + // Moving the input view within the FlutterView shouldn't affect the coordinates, + // since the framework sends us global coordinates. + XCTAssertTrue(CGRectEqualToRect(CGRectMake(-306 - 113, 3 - 119, 300, 300), + [inputView firstRectForRange:range])); +} + +- (void)testFirstRectForRangeReturnsNoneZeroRectWhenScribbleIsEnabled { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; + + FlutterTextInputView* mockInputView = OCMPartialMock(inputView); + OCMStub([mockInputView isScribbleAvailable]).andReturn(YES); + + [inputView setSelectionRects:@[ + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:1U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:2U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:3U], + ]]; + + FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 3)]; + + if (@available(iOS 17, *)) { + XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, 0, 300, 100), + [inputView firstRectForRange:multiRectRange])); + } else { + XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, 0, 100, 100), + [inputView firstRectForRange:multiRectRange])); + } +} + +- (void)testFirstRectForRangeReturnsCorrectRectOnASingleLineLeftToRight { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; + + [inputView setSelectionRects:@[ + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:1U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:2U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:3U], + ]]; + FlutterTextRange* singleRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 1)]; + if (@available(iOS 17, *)) { + XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, 0, 100, 100), + [inputView firstRectForRange:singleRectRange])); + } else { + XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:singleRectRange])); + } + + FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 3)]; + + if (@available(iOS 17, *)) { + XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, 0, 300, 100), + [inputView firstRectForRange:multiRectRange])); + } else { + XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange])); + } + + [inputView setTextInputState:@{@"text" : @"COM"}]; + FlutterTextRange* rangeOutsideBounds = [FlutterTextRange rangeWithNSRange:NSMakeRange(3, 1)]; + XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:rangeOutsideBounds])); +} + +- (void)testFirstRectForRangeReturnsCorrectRectOnASingleLineRightToLeft { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; + + [inputView setSelectionRects:@[ + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:0U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:1U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:2U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:3U], + ]]; + FlutterTextRange* singleRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 1)]; + if (@available(iOS 17, *)) { + XCTAssertTrue(CGRectEqualToRect(CGRectMake(200, 0, 100, 100), + [inputView firstRectForRange:singleRectRange])); + } else { + XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:singleRectRange])); + } + + FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 3)]; + if (@available(iOS 17, *)) { + XCTAssertTrue(CGRectEqualToRect(CGRectMake(0, 0, 300, 100), + [inputView firstRectForRange:multiRectRange])); + } else { + XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange])); + } + + [inputView setTextInputState:@{@"text" : @"COM"}]; + FlutterTextRange* rangeOutsideBounds = [FlutterTextRange rangeWithNSRange:NSMakeRange(3, 1)]; + XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:rangeOutsideBounds])); +} + +- (void)testFirstRectForRangeReturnsCorrectRectOnMultipleLinesLeftToRight { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; + + [inputView setSelectionRects:@[ + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:1U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:2U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:3U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) position:4U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:5U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 100, 100, 100) position:6U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 100, 100, 100) position:7U], + ]]; + FlutterTextRange* singleRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 1)]; + if (@available(iOS 17, *)) { + XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, 0, 100, 100), + [inputView firstRectForRange:singleRectRange])); + } else { + XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:singleRectRange])); + } + + FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 4)]; + + if (@available(iOS 17, *)) { + XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, 0, 300, 100), + [inputView firstRectForRange:multiRectRange])); + } else { + XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange])); + } +} + +- (void)testFirstRectForRangeReturnsCorrectRectOnMultipleLinesRightToLeft { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; + + [inputView setSelectionRects:@[ + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:0U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:1U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:2U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:3U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 100, 100, 100) position:4U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 100, 100, 100) position:5U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:6U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) position:7U], + ]]; + FlutterTextRange* singleRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 1)]; + if (@available(iOS 17, *)) { + XCTAssertTrue(CGRectEqualToRect(CGRectMake(200, 0, 100, 100), + [inputView firstRectForRange:singleRectRange])); + } else { + XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:singleRectRange])); + } + + FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 4)]; + if (@available(iOS 17, *)) { + XCTAssertTrue(CGRectEqualToRect(CGRectMake(0, 0, 300, 100), + [inputView firstRectForRange:multiRectRange])); + } else { + XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange])); + } +} + +- (void)testFirstRectForRangeReturnsCorrectRectOnSingleLineWithVaryingMinYAndMaxYLeftToRight { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; + + [inputView setSelectionRects:@[ + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 10, 100, 80) + position:1U], // shorter + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, -10, 100, 120) + position:2U], // taller + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:3U], + ]]; + + FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 3)]; + + if (@available(iOS 17, *)) { + XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, -10, 300, 120), + [inputView firstRectForRange:multiRectRange])); + } else { + XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange])); + } +} + +- (void)testFirstRectForRangeReturnsCorrectRectOnSingleLineWithVaryingMinYAndMaxYRightToLeft { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; + + [inputView setSelectionRects:@[ + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:0U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, -10, 100, 120) + position:1U], // taller + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 10, 100, 80) + position:2U], // shorter + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:3U], + ]]; + + FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 3)]; + + if (@available(iOS 17, *)) { + XCTAssertTrue(CGRectEqualToRect(CGRectMake(0, -10, 300, 120), + [inputView firstRectForRange:multiRectRange])); + } else { + XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange])); + } +} + +- (void)testFirstRectForRangeReturnsCorrectRectWithOverlappingRectsExceedingThresholdLeftToRight { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; + + [inputView setSelectionRects:@[ + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:1U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:2U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:3U], + // y=60 exceeds threshold, so treat it as a new line. + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 60, 100, 100) position:4U], + ]]; + + FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 4)]; + + if (@available(iOS 17, *)) { + XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, 0, 300, 100), + [inputView firstRectForRange:multiRectRange])); + } else { + XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange])); + } +} + +- (void)testFirstRectForRangeReturnsCorrectRectWithOverlappingRectsExceedingThresholdRightToLeft { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; + + [inputView setSelectionRects:@[ + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:0U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:1U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:2U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:3U], + // y=60 exceeds threshold, so treat it as a new line. + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 60, 100, 100) position:4U], + ]]; + + FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 4)]; + + if (@available(iOS 17, *)) { + XCTAssertTrue(CGRectEqualToRect(CGRectMake(0, 0, 300, 100), + [inputView firstRectForRange:multiRectRange])); + } else { + XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange])); + } +} + +- (void)testFirstRectForRangeReturnsCorrectRectWithOverlappingRectsWithinThresholdLeftToRight { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; + + [inputView setSelectionRects:@[ + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:1U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:2U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:3U], + // y=40 is within line threshold, so treat it as the same line + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(400, 40, 100, 100) position:4U], + ]]; + + FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 4)]; + + if (@available(iOS 17, *)) { + XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, 0, 400, 140), + [inputView firstRectForRange:multiRectRange])); + } else { + XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange])); + } +} + +- (void)testFirstRectForRangeReturnsCorrectRectWithOverlappingRectsWithinThresholdRightToLeft { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; + + [inputView setSelectionRects:@[ + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(400, 0, 100, 100) position:0U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:1U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:2U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:3U], + // y=40 is within line threshold, so treat it as the same line + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 40, 100, 100) position:4U], + ]]; + + FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 4)]; + + if (@available(iOS 17, *)) { + XCTAssertTrue(CGRectEqualToRect(CGRectMake(0, 0, 400, 140), + [inputView firstRectForRange:multiRectRange])); + } else { + XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange])); + } +} + +- (void)testClosestPositionToPoint { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; + + // Minimize the vertical distance from the center of the rects first + [inputView setSelectionRects:@[ + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) position:1U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 200, 100, 100) position:2U], + ]]; + CGPoint point = CGPointMake(150, 150); + XCTAssertEqual(2U, ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).index); + XCTAssertEqual(UITextStorageDirectionBackward, + ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).affinity); + + // Then, if the point is above the bottom of the closest rects vertically, get the closest x + // origin + [inputView setSelectionRects:@[ + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) position:1U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:2U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 100, 100, 100) position:3U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 200, 100, 100) position:4U], + ]]; + point = CGPointMake(125, 150); + XCTAssertEqual(2U, ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).index); + XCTAssertEqual(UITextStorageDirectionForward, + ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).affinity); + + // However, if the point is below the bottom of the closest rects vertically, get the position + // farthest to the right + [inputView setSelectionRects:@[ + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) position:1U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:2U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 100, 100, 100) position:3U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 300, 100, 100) position:4U], + ]]; + point = CGPointMake(125, 201); + XCTAssertEqual(4U, ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).index); + XCTAssertEqual(UITextStorageDirectionBackward, + ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).affinity); + + // Also check a point at the right edge of the last selection rect + [inputView setSelectionRects:@[ + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) position:1U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:2U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 100, 100, 100) position:3U], + ]]; + point = CGPointMake(125, 250); + XCTAssertEqual(4U, ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).index); + XCTAssertEqual(UITextStorageDirectionBackward, + ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).affinity); + + // Minimize vertical distance if the difference is more than 1 point. + [inputView setSelectionRects:@[ + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 2, 100, 100) position:0U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 2, 100, 100) position:1U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:2U], + ]]; + point = CGPointMake(110, 50); + XCTAssertEqual(2U, ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).index); + XCTAssertEqual(UITextStorageDirectionForward, + ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).affinity); + + // In floating cursor mode, the vertical difference is allowed to be 10 points. + // The closest horizontal position will now win. + [inputView beginFloatingCursorAtPoint:CGPointZero]; + XCTAssertEqual(1U, ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).index); + XCTAssertEqual(UITextStorageDirectionForward, + ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).affinity); + [inputView endFloatingCursor]; +} + +- (void)testClosestPositionToPointRTL { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; + + [inputView setSelectionRects:@[ + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) + position:0U + writingDirection:NSWritingDirectionRightToLeft], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) + position:1U + writingDirection:NSWritingDirectionRightToLeft], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) + position:2U + writingDirection:NSWritingDirectionRightToLeft], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) + position:3U + writingDirection:NSWritingDirectionRightToLeft], + ]]; + FlutterTextPosition* position = + (FlutterTextPosition*)[inputView closestPositionToPoint:CGPointMake(275, 50)]; + XCTAssertEqual(0U, position.index); + XCTAssertEqual(UITextStorageDirectionForward, position.affinity); + position = (FlutterTextPosition*)[inputView closestPositionToPoint:CGPointMake(225, 50)]; + XCTAssertEqual(1U, position.index); + XCTAssertEqual(UITextStorageDirectionBackward, position.affinity); + position = (FlutterTextPosition*)[inputView closestPositionToPoint:CGPointMake(175, 50)]; + XCTAssertEqual(1U, position.index); + XCTAssertEqual(UITextStorageDirectionForward, position.affinity); + position = (FlutterTextPosition*)[inputView closestPositionToPoint:CGPointMake(125, 50)]; + XCTAssertEqual(2U, position.index); + XCTAssertEqual(UITextStorageDirectionBackward, position.affinity); + position = (FlutterTextPosition*)[inputView closestPositionToPoint:CGPointMake(75, 50)]; + XCTAssertEqual(2U, position.index); + XCTAssertEqual(UITextStorageDirectionForward, position.affinity); + position = (FlutterTextPosition*)[inputView closestPositionToPoint:CGPointMake(25, 50)]; + XCTAssertEqual(3U, position.index); + XCTAssertEqual(UITextStorageDirectionBackward, position.affinity); + position = (FlutterTextPosition*)[inputView closestPositionToPoint:CGPointMake(-25, 50)]; + XCTAssertEqual(3U, position.index); + XCTAssertEqual(UITextStorageDirectionBackward, position.affinity); +} + +- (void)testSelectionRectsForRange { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; + + CGRect testRect0 = CGRectMake(100, 100, 100, 100); + CGRect testRect1 = CGRectMake(200, 200, 100, 100); + [inputView setSelectionRects:@[ + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], + [FlutterTextSelectionRect selectionRectWithRect:testRect0 position:1U], + [FlutterTextSelectionRect selectionRectWithRect:testRect1 position:2U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 300, 100, 100) position:3U], + ]]; + + // Returns the matching rects within a range + FlutterTextRange* range = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 2)]; + XCTAssertTrue(CGRectEqualToRect(testRect0, [inputView selectionRectsForRange:range][0].rect)); + XCTAssertTrue(CGRectEqualToRect(testRect1, [inputView selectionRectsForRange:range][1].rect)); + XCTAssertEqual(2U, [[inputView selectionRectsForRange:range] count]); + + // Returns a 0 width rect for a 0-length range + range = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 0)]; + XCTAssertEqual(1U, [[inputView selectionRectsForRange:range] count]); + XCTAssertTrue(CGRectEqualToRect( + CGRectMake(testRect0.origin.x, testRect0.origin.y, 0, testRect0.size.height), + [inputView selectionRectsForRange:range][0].rect)); +} + +- (void)testClosestPositionToPointWithinRange { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; + + // Do not return a position before the start of the range + [inputView setSelectionRects:@[ + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) position:1U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:2U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 100, 100, 100) position:3U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 200, 100, 100) position:4U], + ]]; + CGPoint point = CGPointMake(125, 150); + FlutterTextRange* range = [[FlutterTextRange rangeWithNSRange:NSMakeRange(3, 2)] copy]; + XCTAssertEqual( + 3U, ((FlutterTextPosition*)[inputView closestPositionToPoint:point withinRange:range]).index); + XCTAssertEqual( + UITextStorageDirectionForward, + ((FlutterTextPosition*)[inputView closestPositionToPoint:point withinRange:range]).affinity); + + // Do not return a position after the end of the range + [inputView setSelectionRects:@[ + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) position:1U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:2U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 100, 100, 100) position:3U], + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 200, 100, 100) position:4U], + ]]; + point = CGPointMake(125, 150); + range = [[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)] copy]; + XCTAssertEqual( + 1U, ((FlutterTextPosition*)[inputView closestPositionToPoint:point withinRange:range]).index); + XCTAssertEqual( + UITextStorageDirectionForward, + ((FlutterTextPosition*)[inputView closestPositionToPoint:point withinRange:range]).affinity); +} + +- (void)testClosestPositionToPointWithPartialSelectionRects { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [inputView setTextInputState:@{@"text" : @"COMPOSING"}]; + + [inputView setSelectionRects:@[ [FlutterTextSelectionRect + selectionRectWithRect:CGRectMake(0, 0, 100, 100) + position:0U] ]]; + // Asking with a position at the end of selection rects should give you the trailing edge of + // the last rect. + XCTAssertTrue(CGRectEqualToRect( + [inputView caretRectForPosition:[FlutterTextPosition + positionWithIndex:1 + affinity:UITextStorageDirectionForward]], + CGRectMake(100, 0, 0, 100))); + // Asking with a position beyond the end of selection rects should return CGRectZero without + // crashing. + XCTAssertTrue(CGRectEqualToRect( + [inputView caretRectForPosition:[FlutterTextPosition + positionWithIndex:2 + affinity:UITextStorageDirectionForward]], + CGRectZero)); +} + +#pragma mark - Floating Cursor - Tests + +- (void)testFloatingCursorDoesNotThrow { + // The keyboard implementation may send unbalanced calls to the input view. + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [inputView beginFloatingCursorAtPoint:CGPointMake(123, 321)]; + [inputView beginFloatingCursorAtPoint:CGPointMake(123, 321)]; + [inputView endFloatingCursor]; + [inputView beginFloatingCursorAtPoint:CGPointMake(123, 321)]; + [inputView endFloatingCursor]; +} + +- (void)testFloatingCursor { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [inputView setTextInputState:@{ + @"text" : @"test", + @"selectionBase" : @1, + @"selectionExtent" : @1, + }]; + + FlutterTextSelectionRect* first = + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U]; + FlutterTextSelectionRect* second = + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:1U]; + FlutterTextSelectionRect* third = + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 200, 100, 100) position:2U]; + FlutterTextSelectionRect* fourth = + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 300, 100, 100) position:3U]; + [inputView setSelectionRects:@[ first, second, third, fourth ]]; + + // Verify zeroth caret rect is based on left edge of first character. + XCTAssertTrue(CGRectEqualToRect( + [inputView caretRectForPosition:[FlutterTextPosition + positionWithIndex:0 + affinity:UITextStorageDirectionForward]], + CGRectMake(0, 0, 0, 100))); + // Since the textAffinity is downstream, the caret rect will be based on the + // left edge of the succeeding character. + XCTAssertTrue(CGRectEqualToRect( + [inputView caretRectForPosition:[FlutterTextPosition + positionWithIndex:1 + affinity:UITextStorageDirectionForward]], + CGRectMake(100, 100, 0, 100))); + XCTAssertTrue(CGRectEqualToRect( + [inputView caretRectForPosition:[FlutterTextPosition + positionWithIndex:2 + affinity:UITextStorageDirectionForward]], + CGRectMake(200, 200, 0, 100))); + XCTAssertTrue(CGRectEqualToRect( + [inputView caretRectForPosition:[FlutterTextPosition + positionWithIndex:3 + affinity:UITextStorageDirectionForward]], + CGRectMake(300, 300, 0, 100))); + // There is no subsequent character for the last position, so the caret rect + // will be based on the right edge of the preceding character. + XCTAssertTrue(CGRectEqualToRect( + [inputView caretRectForPosition:[FlutterTextPosition + positionWithIndex:4 + affinity:UITextStorageDirectionForward]], + CGRectMake(400, 300, 0, 100))); + // Verify no caret rect for out-of-range character. + XCTAssertTrue(CGRectEqualToRect( + [inputView caretRectForPosition:[FlutterTextPosition + positionWithIndex:5 + affinity:UITextStorageDirectionForward]], + CGRectZero)); + + // Check caret rects again again when text affinity is upstream. + [inputView setTextInputState:@{ + @"text" : @"test", + @"selectionBase" : @2, + @"selectionExtent" : @2, + }]; + // Verify zeroth caret rect is based on left edge of first character. + XCTAssertTrue(CGRectEqualToRect( + [inputView caretRectForPosition:[FlutterTextPosition + positionWithIndex:0 + affinity:UITextStorageDirectionBackward]], + CGRectMake(0, 0, 0, 100))); + // Since the textAffinity is upstream, all below caret rects will be based on + // the right edge of the preceding character. + XCTAssertTrue(CGRectEqualToRect( + [inputView caretRectForPosition:[FlutterTextPosition + positionWithIndex:1 + affinity:UITextStorageDirectionBackward]], + CGRectMake(100, 0, 0, 100))); + XCTAssertTrue(CGRectEqualToRect( + [inputView caretRectForPosition:[FlutterTextPosition + positionWithIndex:2 + affinity:UITextStorageDirectionBackward]], + CGRectMake(200, 100, 0, 100))); + XCTAssertTrue(CGRectEqualToRect( + [inputView caretRectForPosition:[FlutterTextPosition + positionWithIndex:3 + affinity:UITextStorageDirectionBackward]], + CGRectMake(300, 200, 0, 100))); + XCTAssertTrue(CGRectEqualToRect( + [inputView caretRectForPosition:[FlutterTextPosition + positionWithIndex:4 + affinity:UITextStorageDirectionBackward]], + CGRectMake(400, 300, 0, 100))); + // Verify no caret rect for out-of-range character. + XCTAssertTrue(CGRectEqualToRect( + [inputView caretRectForPosition:[FlutterTextPosition + positionWithIndex:5 + affinity:UITextStorageDirectionBackward]], + CGRectZero)); + + // Verify floating cursor updates are relative to original position, and that there is no bounds + // change. + CGRect initialBounds = inputView.bounds; + [inputView beginFloatingCursorAtPoint:CGPointMake(123, 321)]; + XCTAssertTrue(CGRectEqualToRect(initialBounds, inputView.bounds)); + OCMVerify([engine flutterTextInputView:inputView + updateFloatingCursor:FlutterFloatingCursorDragStateStart + withClient:0 + withPosition:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { + return ([state[@"X"] isEqualToNumber:@(0)]) && + ([state[@"Y"] isEqualToNumber:@(0)]); + }]]); + + [inputView updateFloatingCursorAtPoint:CGPointMake(456, 654)]; + XCTAssertTrue(CGRectEqualToRect(initialBounds, inputView.bounds)); + OCMVerify([engine flutterTextInputView:inputView + updateFloatingCursor:FlutterFloatingCursorDragStateUpdate + withClient:0 + withPosition:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { + return ([state[@"X"] isEqualToNumber:@(333)]) && + ([state[@"Y"] isEqualToNumber:@(333)]); + }]]); + + [inputView endFloatingCursor]; + XCTAssertTrue(CGRectEqualToRect(initialBounds, inputView.bounds)); + OCMVerify([engine flutterTextInputView:inputView + updateFloatingCursor:FlutterFloatingCursorDragStateEnd + withClient:0 + withPosition:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) { + return ([state[@"X"] isEqualToNumber:@(0)]) && + ([state[@"Y"] isEqualToNumber:@(0)]); + }]]); +} + +#pragma mark - UIKeyInput Overrides - Tests + +- (void)testInsertTextAddsPlaceholderSelectionRects { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [inputView + setTextInputState:@{@"text" : @"test", @"selectionBase" : @1, @"selectionExtent" : @1}]; + + FlutterTextSelectionRect* first = + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U]; + FlutterTextSelectionRect* second = + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:1U]; + FlutterTextSelectionRect* third = + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 200, 100, 100) position:2U]; + FlutterTextSelectionRect* fourth = + [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 300, 100, 100) position:3U]; + [inputView setSelectionRects:@[ first, second, third, fourth ]]; + + // Inserts additional selection rects at the selection start + [inputView insertText:@"in"]; + NSArray* selectionRects = + [inputView selectionRectsForRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 6)]]; + XCTAssertEqual(6U, [selectionRects count]); + + XCTAssertEqual(first.position, ((FlutterTextSelectionRect*)selectionRects[0]).position); + XCTAssertTrue(CGRectEqualToRect(first.rect, ((FlutterTextSelectionRect*)selectionRects[0]).rect)); + + XCTAssertEqual(second.position, ((FlutterTextSelectionRect*)selectionRects[1]).position); + XCTAssertTrue( + CGRectEqualToRect(second.rect, ((FlutterTextSelectionRect*)selectionRects[1]).rect)); + + XCTAssertEqual(second.position + 1, ((FlutterTextSelectionRect*)selectionRects[2]).position); + XCTAssertTrue( + CGRectEqualToRect(second.rect, ((FlutterTextSelectionRect*)selectionRects[2]).rect)); + + XCTAssertEqual(second.position + 2, ((FlutterTextSelectionRect*)selectionRects[3]).position); + XCTAssertTrue( + CGRectEqualToRect(second.rect, ((FlutterTextSelectionRect*)selectionRects[3]).rect)); + + XCTAssertEqual(third.position + 2, ((FlutterTextSelectionRect*)selectionRects[4]).position); + XCTAssertTrue(CGRectEqualToRect(third.rect, ((FlutterTextSelectionRect*)selectionRects[4]).rect)); + + XCTAssertEqual(fourth.position + 2, ((FlutterTextSelectionRect*)selectionRects[5]).position); + XCTAssertTrue( + CGRectEqualToRect(fourth.rect, ((FlutterTextSelectionRect*)selectionRects[5]).rect)); +} + +#pragma mark - Autofill - Utilities + +- (NSMutableDictionary*)mutablePasswordTemplateCopy { + if (!_passwordTemplate) { + _passwordTemplate = @{ + @"inputType" : @{@"name" : @"TextInuptType.text"}, + @"keyboardAppearance" : @"Brightness.light", + @"obscureText" : @YES, + @"inputAction" : @"TextInputAction.unspecified", + @"smartDashesType" : @"0", + @"smartQuotesType" : @"0", + @"autocorrect" : @YES + }; + } + + return [_passwordTemplate mutableCopy]; +} + +- (NSArray*)viewsVisibleToAutofill { + return [self.installedInputViews + filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"isVisibleToAutofill == YES"]]; +} + +- (void)commitAutofillContextAndVerify { + FlutterMethodCall* methodCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.finishAutofillContext" + arguments:@YES]; + [textInputPlugin handleMethodCall:methodCall + result:^(id _Nullable result){ + }]; + + XCTAssertEqual(self.viewsVisibleToAutofill.count, + [textInputPlugin.activeView isVisibleToAutofill] ? 1ul : 0ul); + XCTAssertNotEqual(textInputPlugin.textInputView, nil); + // The active view should still be installed so it doesn't get + // deallocated. + XCTAssertEqual(self.installedInputViews.count, 1ul); + XCTAssertEqual(textInputPlugin.autofillContext.count, 0ul); +} + +#pragma mark - Autofill - Tests + +- (void)testDisablingAutofillOnInputClient { + NSDictionary* config = self.mutableTemplateCopy; + [config setValue:@"YES" forKey:@"obscureText"]; + + [self setClientId:123 configuration:config]; + + FlutterTextInputView* inputView = self.installedInputViews[0]; + XCTAssertEqualObjects(inputView.textContentType, @""); +} + +- (void)testAutofillEnabledByDefault { + NSDictionary* config = self.mutableTemplateCopy; + [config setValue:@"NO" forKey:@"obscureText"]; + [config setValue:@{@"uniqueIdentifier" : @"field1", @"editingValue" : @{@"text" : @""}} + forKey:@"autofill"]; + + [self setClientId:123 configuration:config]; + + FlutterTextInputView* inputView = self.installedInputViews[0]; + XCTAssertNil(inputView.textContentType); +} + +- (void)testAutofillContext { + NSMutableDictionary* field1 = self.mutableTemplateCopy; + + [field1 setValue:@{ + @"uniqueIdentifier" : @"field1", + @"hints" : @[ @"hint1" ], + @"editingValue" : @{@"text" : @""} + } + forKey:@"autofill"]; + + NSMutableDictionary* field2 = self.mutablePasswordTemplateCopy; + [field2 setValue:@{ + @"uniqueIdentifier" : @"field2", + @"hints" : @[ @"hint2" ], + @"editingValue" : @{@"text" : @""} + } + forKey:@"autofill"]; + + NSMutableDictionary* config = [field1 mutableCopy]; + [config setValue:@[ field1, field2 ] forKey:@"fields"]; + + [self setClientId:123 configuration:config]; + XCTAssertEqual(self.viewsVisibleToAutofill.count, 2ul); + + XCTAssertEqual(textInputPlugin.autofillContext.count, 2ul); + + [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO]; + XCTAssertEqual(self.installedInputViews.count, 2ul); + XCTAssertEqual(textInputPlugin.textInputView, textInputPlugin.autofillContext[@"field1"]); + [self ensureOnlyActiveViewCanBecomeFirstResponder]; + + // The configuration changes. + NSMutableDictionary* field3 = self.mutablePasswordTemplateCopy; + [field3 setValue:@{ + @"uniqueIdentifier" : @"field3", + @"hints" : @[ @"hint3" ], + @"editingValue" : @{@"text" : @""} + } + forKey:@"autofill"]; + + NSMutableDictionary* oldContext = textInputPlugin.autofillContext; + // Replace field2 with field3. + [config setValue:@[ field1, field3 ] forKey:@"fields"]; + + [self setClientId:123 configuration:config]; + + XCTAssertEqual(self.viewsVisibleToAutofill.count, 2ul); + XCTAssertEqual(textInputPlugin.autofillContext.count, 3ul); + + [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO]; + XCTAssertEqual(self.installedInputViews.count, 3ul); + XCTAssertEqual(textInputPlugin.textInputView, textInputPlugin.autofillContext[@"field1"]); + [self ensureOnlyActiveViewCanBecomeFirstResponder]; + + // Old autofill input fields are still installed and reused. + for (NSString* key in oldContext.allKeys) { + XCTAssertEqual(oldContext[key], textInputPlugin.autofillContext[key]); + } + + // Switch to a password field that has no contentType and is not in an AutofillGroup. + config = self.mutablePasswordTemplateCopy; + + oldContext = textInputPlugin.autofillContext; + [self setClientId:124 configuration:config]; + [self ensureOnlyActiveViewCanBecomeFirstResponder]; + + XCTAssertEqual(self.viewsVisibleToAutofill.count, 1ul); + XCTAssertEqual(textInputPlugin.autofillContext.count, 3ul); + + [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO]; + XCTAssertEqual(self.installedInputViews.count, 4ul); + + // Old autofill input fields are still installed and reused. + for (NSString* key in oldContext.allKeys) { + XCTAssertEqual(oldContext[key], textInputPlugin.autofillContext[key]); + } + // The active view should change. + XCTAssertNotEqual(textInputPlugin.textInputView, textInputPlugin.autofillContext[@"field1"]); + [self ensureOnlyActiveViewCanBecomeFirstResponder]; + + // Switch to a similar password field, the previous field should be reused. + oldContext = textInputPlugin.autofillContext; + [self setClientId:200 configuration:config]; + + // Reuse the input view instance from the last time. + XCTAssertEqual(self.viewsVisibleToAutofill.count, 1ul); + XCTAssertEqual(textInputPlugin.autofillContext.count, 3ul); + + [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO]; + XCTAssertEqual(self.installedInputViews.count, 4ul); + + // Old autofill input fields are still installed and reused. + for (NSString* key in oldContext.allKeys) { + XCTAssertEqual(oldContext[key], textInputPlugin.autofillContext[key]); + } + XCTAssertNotEqual(textInputPlugin.textInputView, textInputPlugin.autofillContext[@"field1"]); + [self ensureOnlyActiveViewCanBecomeFirstResponder]; +} + +- (void)testCommitAutofillContext { + NSMutableDictionary* field1 = self.mutableTemplateCopy; + [field1 setValue:@{ + @"uniqueIdentifier" : @"field1", + @"hints" : @[ @"hint1" ], + @"editingValue" : @{@"text" : @""} + } + forKey:@"autofill"]; + + NSMutableDictionary* field2 = self.mutablePasswordTemplateCopy; + [field2 setValue:@{ + @"uniqueIdentifier" : @"field2", + @"hints" : @[ @"hint2" ], + @"editingValue" : @{@"text" : @""} + } + forKey:@"autofill"]; + + NSMutableDictionary* field3 = self.mutableTemplateCopy; + [field3 setValue:@{ + @"uniqueIdentifier" : @"field3", + @"hints" : @[ @"hint3" ], + @"editingValue" : @{@"text" : @""} + } + forKey:@"autofill"]; + + NSMutableDictionary* config = [field1 mutableCopy]; + [config setValue:@[ field1, field2 ] forKey:@"fields"]; + + [self setClientId:123 configuration:config]; + XCTAssertEqual(self.viewsVisibleToAutofill.count, 2ul); + XCTAssertEqual(textInputPlugin.autofillContext.count, 2ul); + [self ensureOnlyActiveViewCanBecomeFirstResponder]; + + [self commitAutofillContextAndVerify]; + [self ensureOnlyActiveViewCanBecomeFirstResponder]; + + // Install the password field again. + [self setClientId:123 configuration:config]; + // Switch to a regular autofill group. + [self setClientId:124 configuration:field3]; + XCTAssertEqual(self.viewsVisibleToAutofill.count, 1ul); + + [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO]; + XCTAssertEqual(self.installedInputViews.count, 3ul); + XCTAssertEqual(textInputPlugin.autofillContext.count, 2ul); + XCTAssertNotEqual(textInputPlugin.textInputView, nil); + [self ensureOnlyActiveViewCanBecomeFirstResponder]; + + [self commitAutofillContextAndVerify]; + [self ensureOnlyActiveViewCanBecomeFirstResponder]; + + // Now switch to an input field that does not autofill. + [self setClientId:125 configuration:self.mutableTemplateCopy]; + + XCTAssertEqual(self.viewsVisibleToAutofill.count, 0ul); + // The active view should still be installed so it doesn't get + // deallocated. + + [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO]; + XCTAssertEqual(self.installedInputViews.count, 1ul); + XCTAssertEqual(textInputPlugin.autofillContext.count, 0ul); + [self ensureOnlyActiveViewCanBecomeFirstResponder]; + + [self commitAutofillContextAndVerify]; + [self ensureOnlyActiveViewCanBecomeFirstResponder]; +} + +- (void)testAutofillInputViews { + NSMutableDictionary* field1 = self.mutableTemplateCopy; + [field1 setValue:@{ + @"uniqueIdentifier" : @"field1", + @"hints" : @[ @"hint1" ], + @"editingValue" : @{@"text" : @""} + } + forKey:@"autofill"]; + + NSMutableDictionary* field2 = self.mutablePasswordTemplateCopy; + [field2 setValue:@{ + @"uniqueIdentifier" : @"field2", + @"hints" : @[ @"hint2" ], + @"editingValue" : @{@"text" : @""} + } + forKey:@"autofill"]; + + NSMutableDictionary* config = [field1 mutableCopy]; + [config setValue:@[ field1, field2 ] forKey:@"fields"]; + + [self setClientId:123 configuration:config]; + [self ensureOnlyActiveViewCanBecomeFirstResponder]; + + // Find all the FlutterTextInputViews we created. + NSArray* inputFields = self.installedInputViews; + + // Both fields are installed and visible because it's a password group. + XCTAssertEqual(inputFields.count, 2ul); + XCTAssertEqual(self.viewsVisibleToAutofill.count, 2ul); + + // Find the inactive autofillable input field. + FlutterTextInputView* inactiveView = inputFields[1]; + [inactiveView replaceRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 0)] + withText:@"Autofilled!"]; + [self ensureOnlyActiveViewCanBecomeFirstResponder]; + + // Verify behavior. + OCMVerify([engine flutterTextInputView:inactiveView + updateEditingClient:0 + withState:[OCMArg isNotNil] + withTag:@"field2"]); +} + +- (void)testPasswordAutofillHack { + NSDictionary* config = self.mutableTemplateCopy; + [config setValue:@"YES" forKey:@"obscureText"]; + [self setClientId:123 configuration:config]; + + // Find all the FlutterTextInputViews we created. + NSArray* inputFields = self.installedInputViews; + + FlutterTextInputView* inputView = inputFields[0]; + + XCTAssert([inputView isKindOfClass:[UITextField class]]); + // FlutterSecureTextInputView does not respond to font, + // but it should return the default UITextField.font. + XCTAssertNotEqual([inputView performSelector:@selector(font)], nil); +} + +- (void)testClearAutofillContextClearsSelection { + NSMutableDictionary* regularField = self.mutableTemplateCopy; + NSDictionary* editingValue = @{ + @"text" : @"REGULAR_TEXT_FIELD", + @"composingBase" : @0, + @"composingExtent" : @3, + @"selectionBase" : @1, + @"selectionExtent" : @4 + }; + [regularField setValue:@{ + @"uniqueIdentifier" : @"field2", + @"hints" : @[ @"hint2" ], + @"editingValue" : editingValue, + } + forKey:@"autofill"]; + [regularField addEntriesFromDictionary:editingValue]; + [self setClientId:123 configuration:regularField]; + [self ensureOnlyActiveViewCanBecomeFirstResponder]; + XCTAssertEqual(self.installedInputViews.count, 1ul); + + FlutterTextInputView* oldInputView = self.installedInputViews[0]; + XCTAssert([oldInputView.text isEqualToString:@"REGULAR_TEXT_FIELD"]); + FlutterTextRange* selectionRange = (FlutterTextRange*)oldInputView.selectedTextRange; + XCTAssert(NSEqualRanges(selectionRange.range, NSMakeRange(1, 3))); + + // Replace the original password field with new one. This should remove + // the old password field, but not immediately. + [self setClientId:124 configuration:self.mutablePasswordTemplateCopy]; + [self ensureOnlyActiveViewCanBecomeFirstResponder]; + + XCTAssertEqual(self.installedInputViews.count, 2ul); + + [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO]; + XCTAssertEqual(self.installedInputViews.count, 1ul); + + // Verify the old input view is properly cleaned up. + XCTAssert([oldInputView.text isEqualToString:@""]); + selectionRange = (FlutterTextRange*)oldInputView.selectedTextRange; + XCTAssert(NSEqualRanges(selectionRange.range, NSMakeRange(0, 0))); +} + +- (void)testGarbageInputViewsAreNotRemovedImmediately { + // Add a password field that should autofill. + [self setClientId:123 configuration:self.mutablePasswordTemplateCopy]; + [self ensureOnlyActiveViewCanBecomeFirstResponder]; + + XCTAssertEqual(self.installedInputViews.count, 1ul); + // Add an input field that doesn't autofill. This should remove the password + // field, but not immediately. + [self setClientId:124 configuration:self.mutableTemplateCopy]; + [self ensureOnlyActiveViewCanBecomeFirstResponder]; + + XCTAssertEqual(self.installedInputViews.count, 2ul); + + [self commitAutofillContextAndVerify]; +} + +- (void)testScribbleSetSelectionRects { + NSMutableDictionary* regularField = self.mutableTemplateCopy; + NSDictionary* editingValue = @{ + @"text" : @"REGULAR_TEXT_FIELD", + @"composingBase" : @0, + @"composingExtent" : @3, + @"selectionBase" : @1, + @"selectionExtent" : @4 + }; + [regularField setValue:@{ + @"uniqueIdentifier" : @"field1", + @"hints" : @[ @"hint2" ], + @"editingValue" : editingValue, + } + forKey:@"autofill"]; + [regularField addEntriesFromDictionary:editingValue]; + [self setClientId:123 configuration:regularField]; + XCTAssertEqual(self.installedInputViews.count, 1ul); + XCTAssertEqual([textInputPlugin.activeView.selectionRects count], 0u); + + NSArray* selectionRect = [NSArray arrayWithObjects:@0, @0, @100, @100, @0, @1, nil]; + NSArray* selectionRects = [NSArray arrayWithObjects:selectionRect, nil]; + FlutterMethodCall* methodCall = + [FlutterMethodCall methodCallWithMethodName:@"Scribble.setSelectionRects" + arguments:selectionRects]; + [textInputPlugin handleMethodCall:methodCall + result:^(id _Nullable result){ + }]; + + XCTAssertEqual([textInputPlugin.activeView.selectionRects count], 1u); +} + +- (void)testDecommissionedViewAreNotReusedByAutofill { + // Regression test for https://github.com/flutter/flutter/issues/84407. + NSMutableDictionary* configuration = self.mutableTemplateCopy; + [configuration setValue:@{ + @"uniqueIdentifier" : @"field1", + @"hints" : @[ UITextContentTypePassword ], + @"editingValue" : @{@"text" : @""} + } + forKey:@"autofill"]; + [configuration setValue:@[ [configuration copy] ] forKey:@"fields"]; + + [self setClientId:123 configuration:configuration]; + + [self setTextInputHide]; + UIView* previousActiveView = textInputPlugin.activeView; + + [self setClientId:124 configuration:configuration]; + + // Make sure the autofillable view is reused. + XCTAssertEqual(previousActiveView, textInputPlugin.activeView); + XCTAssertNotNil(previousActiveView); + // Does not crash. +} + +- (void)testInitialActiveViewCantAccessTextInputDelegate { + // Before the framework sends the first text input configuration, + // the dummy "activeView" we use should never have access to + // its textInputDelegate. + XCTAssertNil(textInputPlugin.activeView.textInputDelegate); +} + +#pragma mark - Accessibility - Tests + +- (void)testUITextInputAccessibilityNotHiddenWhenShowed { + [self setClientId:123 configuration:self.mutableTemplateCopy]; + + // Send show text input method call. + [self setTextInputShow]; + // Find all the FlutterTextInputViews we created. + NSArray* inputFields = self.installedInputViews; + + // The input view should not be hidden. + XCTAssertEqual([inputFields count], 1u); + + // Send hide text input method call. + [self setTextInputHide]; + + inputFields = self.installedInputViews; + + // The input view should be hidden. + XCTAssertEqual([inputFields count], 0u); +} + +- (void)testFlutterTextInputViewDirectFocusToBackingTextInput { + FlutterTextInputViewSpy* inputView = + [[FlutterTextInputViewSpy alloc] initWithOwner:textInputPlugin]; + UIView* container = [[UIView alloc] init]; + UIAccessibilityElement* backing = + [[UIAccessibilityElement alloc] initWithAccessibilityContainer:container]; + inputView.backingTextInputAccessibilityObject = backing; + // Simulate accessibility focus. + inputView.isAccessibilityFocused = YES; + [inputView accessibilityElementDidBecomeFocused]; + + XCTAssertEqual(inputView.receivedNotification, UIAccessibilityScreenChangedNotification); + XCTAssertEqual(inputView.receivedNotificationTarget, backing); +} + +- (void)testFlutterTokenizerCanParseLines { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + id tokenizer = [inputView tokenizer]; + + // The tokenizer returns zero range When text is empty. + FlutterTextRange* range = [self getLineRangeFromTokenizer:tokenizer atIndex:0]; + XCTAssertEqual(range.range.location, 0u); + XCTAssertEqual(range.range.length, 0u); + + [inputView insertText:@"how are you\nI am fine, Thank you"]; + + range = [self getLineRangeFromTokenizer:tokenizer atIndex:0]; + XCTAssertEqual(range.range.location, 0u); + XCTAssertEqual(range.range.length, 11u); + + range = [self getLineRangeFromTokenizer:tokenizer atIndex:2]; + XCTAssertEqual(range.range.location, 0u); + XCTAssertEqual(range.range.length, 11u); + + range = [self getLineRangeFromTokenizer:tokenizer atIndex:11]; + XCTAssertEqual(range.range.location, 0u); + XCTAssertEqual(range.range.length, 11u); + + range = [self getLineRangeFromTokenizer:tokenizer atIndex:12]; + XCTAssertEqual(range.range.location, 12u); + XCTAssertEqual(range.range.length, 20u); + + range = [self getLineRangeFromTokenizer:tokenizer atIndex:15]; + XCTAssertEqual(range.range.location, 12u); + XCTAssertEqual(range.range.length, 20u); + + range = [self getLineRangeFromTokenizer:tokenizer atIndex:32]; + XCTAssertEqual(range.range.location, 12u); + XCTAssertEqual(range.range.length, 20u); +} + +- (void)testFlutterTokenizerLineEnclosingEndOfDocumentInBackwardDirectionShouldNotReturnNil { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [inputView insertText:@"0123456789\n012345"]; + id tokenizer = [inputView tokenizer]; + + FlutterTextRange* range = + (FlutterTextRange*)[tokenizer rangeEnclosingPosition:[inputView endOfDocument] + withGranularity:UITextGranularityLine + inDirection:UITextStorageDirectionBackward]; + XCTAssertEqual(range.range.location, 11u); + XCTAssertEqual(range.range.length, 6u); +} + +- (void)testFlutterTokenizerLineEnclosingEndOfDocumentInForwardDirectionShouldReturnNilOnIOS17 { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [inputView insertText:@"0123456789\n012345"]; + id tokenizer = [inputView tokenizer]; + + FlutterTextRange* range = + (FlutterTextRange*)[tokenizer rangeEnclosingPosition:[inputView endOfDocument] + withGranularity:UITextGranularityLine + inDirection:UITextStorageDirectionForward]; + if (@available(iOS 17.0, *)) { + XCTAssertNil(range); + } else { + XCTAssertEqual(range.range.location, 11u); + XCTAssertEqual(range.range.length, 6u); + } +} + +- (void)testFlutterTokenizerLineEnclosingOutOfRangePositionShouldReturnNilOnIOS17 { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [inputView insertText:@"0123456789\n012345"]; + id tokenizer = [inputView tokenizer]; + + FlutterTextPosition* position = [FlutterTextPosition positionWithIndex:100]; + FlutterTextRange* range = + (FlutterTextRange*)[tokenizer rangeEnclosingPosition:position + withGranularity:UITextGranularityLine + inDirection:UITextStorageDirectionForward]; + if (@available(iOS 17.0, *)) { + XCTAssertNil(range); + } else { + XCTAssertEqual(range.range.location, 0u); + XCTAssertEqual(range.range.length, 0u); + } +} + +- (void)testFlutterTextInputPluginRetainsFlutterTextInputView { + FlutterViewController* flutterViewController = [[FlutterViewController alloc] init]; + FlutterTextInputPlugin* myInputPlugin = [[FlutterTextInputPlugin alloc] initWithDelegate:engine]; + myInputPlugin.viewController = flutterViewController; + + __weak UIView* activeView; + @autoreleasepool { + FlutterMethodCall* setClientCall = [FlutterMethodCall + methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ + [NSNumber numberWithInt:123], self.mutablePasswordTemplateCopy + ]]; + [myInputPlugin handleMethodCall:setClientCall + result:^(id _Nullable result){ + }]; + activeView = myInputPlugin.textInputView; + FlutterMethodCall* hideCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.hide" + arguments:@[]]; + [myInputPlugin handleMethodCall:hideCall + result:^(id _Nullable result){ + }]; + XCTAssertNotNil(activeView); + } + // This assert proves the myInputPlugin.textInputView is not deallocated. + XCTAssertNotNil(activeView); +} + +- (void)testFlutterTextInputPluginHostViewNilCrash { + FlutterTextInputPlugin* myInputPlugin = [[FlutterTextInputPlugin alloc] initWithDelegate:engine]; + myInputPlugin.viewController = nil; + XCTAssertThrows([myInputPlugin hostView], @"Throws exception if host view is nil"); +} + +- (void)testFlutterTextInputPluginHostViewNotNil { + FlutterViewController* flutterViewController = [[FlutterViewController alloc] init]; + FlutterEngine* flutterEngine = [[FlutterEngine alloc] init]; + [flutterEngine runWithEntrypoint:nil]; + flutterEngine.viewController = flutterViewController; + XCTAssertNotNil(flutterEngine.textInputPlugin.viewController); + XCTAssertNotNil([flutterEngine.textInputPlugin hostView]); +} + +- (void)testSetPlatformViewClient { + FlutterViewController* flutterViewController = [[FlutterViewController alloc] init]; + FlutterTextInputPlugin* myInputPlugin = [[FlutterTextInputPlugin alloc] initWithDelegate:engine]; + myInputPlugin.viewController = flutterViewController; + + FlutterMethodCall* setClientCall = [FlutterMethodCall + methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ [NSNumber numberWithInt:123], self.mutablePasswordTemplateCopy ]]; + [myInputPlugin handleMethodCall:setClientCall + result:^(id _Nullable result){ + }]; + UIView* activeView = myInputPlugin.textInputView; + XCTAssertNotNil(activeView.superview, @"activeView must be added to the view hierarchy."); + FlutterMethodCall* setPlatformViewClientCall = [FlutterMethodCall + methodCallWithMethodName:@"TextInput.setPlatformViewClient" + arguments:@{@"platformViewId" : [NSNumber numberWithLong:456]}]; + [myInputPlugin handleMethodCall:setPlatformViewClientCall + result:^(id _Nullable result){ + }]; + XCTAssertNil(activeView.superview, @"activeView must be removed from view hierarchy."); +} + +- (void)testEditMenu_shouldSetupEditMenuDelegateCorrectly { + if (@available(iOS 16.0, *)) { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [UIApplication.sharedApplication.keyWindow addSubview:inputView]; + XCTAssertEqual(inputView.editMenuInteraction.delegate, inputView, + @"editMenuInteraction setup delegate correctly"); + } +} + +- (void)testEditMenu_shouldNotPresentEditMenuIfNotFirstResponder { + if (@available(iOS 16.0, *)) { + FlutterTextInputPlugin* myInputPlugin = + [[FlutterTextInputPlugin alloc] initWithDelegate:OCMClassMock([FlutterEngine class])]; + BOOL shownEditMenu = [myInputPlugin showEditMenu:@{}]; + XCTAssertFalse(shownEditMenu, @"Should not show edit menu if not first responder."); + } +} + +- (void)testEditMenu_shouldPresentEditMenuWithCorrectConfiguration { + if (@available(iOS 16.0, *)) { + FlutterTextInputPlugin* myInputPlugin = + [[FlutterTextInputPlugin alloc] initWithDelegate:OCMClassMock([FlutterEngine class])]; + FlutterViewController* myViewController = [[FlutterViewController alloc] init]; + myInputPlugin.viewController = myViewController; + [myViewController loadView]; + FlutterMethodCall* setClientCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(123), self.mutableTemplateCopy ]]; + [myInputPlugin handleMethodCall:setClientCall + result:^(id _Nullable result){ + }]; + + FlutterTextInputView* myInputView = myInputPlugin.activeView; + FlutterTextInputView* mockInputView = OCMPartialMock(myInputView); + + OCMStub([mockInputView isFirstResponder]).andReturn(YES); + + XCTestExpectation* expectation = [[XCTestExpectation alloc] + initWithDescription:@"presentEditMenuWithConfiguration must be called."]; + + id mockInteraction = OCMClassMock([UIEditMenuInteraction class]); + OCMStub([mockInputView editMenuInteraction]).andReturn(mockInteraction); + OCMStub([mockInteraction presentEditMenuWithConfiguration:[OCMArg any]]) + .andDo(^(NSInvocation* invocation) { + // arguments are released once invocation is released. + [invocation retainArguments]; + UIEditMenuConfiguration* config; + [invocation getArgument:&config atIndex:2]; + XCTAssertEqual(config.preferredArrowDirection, UIEditMenuArrowDirectionAutomatic, + @"UIEditMenuConfiguration must use automatic arrow direction."); + XCTAssert(CGPointEqualToPoint(config.sourcePoint, CGPointZero), + @"UIEditMenuConfiguration must have the correct point."); + [expectation fulfill]; + }); + + NSDictionary* encodedTargetRect = + @{@"x" : @(0), @"y" : @(0), @"width" : @(0), @"height" : @(0)}; + + BOOL shownEditMenu = [myInputPlugin showEditMenu:@{@"targetRect" : encodedTargetRect}]; + XCTAssertTrue(shownEditMenu, @"Should show edit menu with correct configuration."); + [self waitForExpectations:@[ expectation ] timeout:1.0]; + } +} + +- (void)testEditMenu_shouldPresentEditMenuWithCorectTargetRect { + if (@available(iOS 16.0, *)) { + FlutterTextInputPlugin* myInputPlugin = + [[FlutterTextInputPlugin alloc] initWithDelegate:OCMClassMock([FlutterEngine class])]; + FlutterViewController* myViewController = [[FlutterViewController alloc] init]; + myInputPlugin.viewController = myViewController; + [myViewController loadView]; + + FlutterMethodCall* setClientCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(123), self.mutableTemplateCopy ]]; + [myInputPlugin handleMethodCall:setClientCall + result:^(id _Nullable result){ + }]; + + FlutterTextInputView* myInputView = myInputPlugin.activeView; + + FlutterTextInputView* mockInputView = OCMPartialMock(myInputView); + OCMStub([mockInputView isFirstResponder]).andReturn(YES); + + XCTestExpectation* expectation = [[XCTestExpectation alloc] + initWithDescription:@"presentEditMenuWithConfiguration must be called."]; + + id mockInteraction = OCMClassMock([UIEditMenuInteraction class]); + OCMStub([mockInputView editMenuInteraction]).andReturn(mockInteraction); + OCMStub([mockInteraction presentEditMenuWithConfiguration:[OCMArg any]]) + .andDo(^(NSInvocation* invocation) { + [expectation fulfill]; + }); + + myInputView.frame = CGRectMake(10, 20, 30, 40); + NSDictionary* encodedTargetRect = + @{@"x" : @(100), @"y" : @(200), @"width" : @(300), @"height" : @(400)}; + + BOOL shownEditMenu = [myInputPlugin showEditMenu:@{@"targetRect" : encodedTargetRect}]; + XCTAssertTrue(shownEditMenu, @"Should show edit menu with correct configuration."); + [self waitForExpectations:@[ expectation ] timeout:1.0]; + + CGRect targetRect = + [myInputView editMenuInteraction:mockInteraction + targetRectForConfiguration:OCMClassMock([UIEditMenuConfiguration class])]; + // the encoded target rect is in global coordinate space. + XCTAssert(CGRectEqualToRect(targetRect, CGRectMake(90, 180, 300, 400)), + @"targetRectForConfiguration must return the correct target rect."); + } +} + +- (void)testEditMenu_shouldPresentEditMenuWithSuggestedItemsByDefaultIfNoFrameworkData { + if (@available(iOS 16.0, *)) { + FlutterTextInputPlugin* myInputPlugin = + [[FlutterTextInputPlugin alloc] initWithDelegate:OCMClassMock([FlutterEngine class])]; + FlutterViewController* myViewController = [[FlutterViewController alloc] init]; + myInputPlugin.viewController = myViewController; + [myViewController loadView]; + + FlutterMethodCall* setClientCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(123), self.mutableTemplateCopy ]]; + [myInputPlugin handleMethodCall:setClientCall + result:^(id _Nullable result){ + }]; + + FlutterTextInputView* myInputView = myInputPlugin.activeView; + + FlutterTextInputView* mockInputView = OCMPartialMock(myInputView); + OCMStub([mockInputView isFirstResponder]).andReturn(YES); + + XCTestExpectation* expectation = [[XCTestExpectation alloc] + initWithDescription:@"presentEditMenuWithConfiguration must be called."]; + + id mockInteraction = OCMClassMock([UIEditMenuInteraction class]); + OCMStub([mockInputView editMenuInteraction]).andReturn(mockInteraction); + OCMStub([mockInteraction presentEditMenuWithConfiguration:[OCMArg any]]) + .andDo(^(NSInvocation* invocation) { + [expectation fulfill]; + }); + + myInputView.frame = CGRectMake(10, 20, 30, 40); + NSDictionary* encodedTargetRect = + @{@"x" : @(100), @"y" : @(200), @"width" : @(300), @"height" : @(400)}; + // No items provided from framework. Show the suggested items by default. + BOOL shownEditMenu = [myInputPlugin showEditMenu:@{@"targetRect" : encodedTargetRect}]; + XCTAssertTrue(shownEditMenu, @"Should show edit menu with correct configuration."); + [self waitForExpectations:@[ expectation ] timeout:1.0]; + + UICommand* copyItem = [UICommand commandWithTitle:@"Copy" + image:nil + action:@selector(copy:) + propertyList:nil]; + UICommand* pasteItem = [UICommand commandWithTitle:@"Paste" + image:nil + action:@selector(paste:) + propertyList:nil]; + NSArray* suggestedActions = @[ copyItem, pasteItem ]; + + UIMenu* menu = [myInputView editMenuInteraction:mockInteraction + menuForConfiguration:OCMClassMock([UIEditMenuConfiguration class]) + suggestedActions:suggestedActions]; + XCTAssertEqualObjects(menu.children, suggestedActions, + @"Must show suggested items by default."); + } +} + +- (void)testEditMenu_shouldPresentEditMenuWithCorectItemsAndCorrectOrderingForBasicEditingActions { + if (@available(iOS 16.0, *)) { + FlutterTextInputPlugin* myInputPlugin = + [[FlutterTextInputPlugin alloc] initWithDelegate:OCMClassMock([FlutterEngine class])]; + FlutterViewController* myViewController = [[FlutterViewController alloc] init]; + myInputPlugin.viewController = myViewController; + [myViewController loadView]; + + FlutterMethodCall* setClientCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(123), self.mutableTemplateCopy ]]; + [myInputPlugin handleMethodCall:setClientCall + result:^(id _Nullable result){ + }]; + + FlutterTextInputView* myInputView = myInputPlugin.activeView; + + FlutterTextInputView* mockInputView = OCMPartialMock(myInputView); + OCMStub([mockInputView isFirstResponder]).andReturn(YES); + + XCTestExpectation* expectation = [[XCTestExpectation alloc] + initWithDescription:@"presentEditMenuWithConfiguration must be called."]; + + id mockInteraction = OCMClassMock([UIEditMenuInteraction class]); + OCMStub([mockInputView editMenuInteraction]).andReturn(mockInteraction); + OCMStub([mockInteraction presentEditMenuWithConfiguration:[OCMArg any]]) + .andDo(^(NSInvocation* invocation) { + [expectation fulfill]; + }); + + myInputView.frame = CGRectMake(10, 20, 30, 40); + NSDictionary* encodedTargetRect = + @{@"x" : @(100), @"y" : @(200), @"width" : @(300), @"height" : @(400)}; + + NSArray*>* encodedItems = + @[ @{@"type" : @"paste"}, @{@"type" : @"copy"} ]; + + BOOL shownEditMenu = + [myInputPlugin showEditMenu:@{@"targetRect" : encodedTargetRect, @"items" : encodedItems}]; + XCTAssertTrue(shownEditMenu, @"Should show edit menu with correct configuration."); + [self waitForExpectations:@[ expectation ] timeout:1.0]; + + UICommand* copyItem = [UICommand commandWithTitle:@"Copy" + image:nil + action:@selector(copy:) + propertyList:nil]; + UICommand* pasteItem = [UICommand commandWithTitle:@"Paste" + image:nil + action:@selector(paste:) + propertyList:nil]; + NSArray* suggestedActions = @[ copyItem, pasteItem ]; + + UIMenu* menu = [myInputView editMenuInteraction:mockInteraction + menuForConfiguration:OCMClassMock([UIEditMenuConfiguration class]) + suggestedActions:suggestedActions]; + // The item ordering should follow the encoded data sent from the framework. + NSArray* expectedChildren = @[ pasteItem, copyItem ]; + XCTAssertEqualObjects(menu.children, expectedChildren); + } +} + +- (void)testEditMenu_shouldPresentEditMenuWithCorectItemsUnderNestedSubtreeForBasicEditingActions { + if (@available(iOS 16.0, *)) { + FlutterTextInputPlugin* myInputPlugin = + [[FlutterTextInputPlugin alloc] initWithDelegate:OCMClassMock([FlutterEngine class])]; + FlutterViewController* myViewController = [[FlutterViewController alloc] init]; + myInputPlugin.viewController = myViewController; + [myViewController loadView]; + + FlutterMethodCall* setClientCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(123), self.mutableTemplateCopy ]]; + [myInputPlugin handleMethodCall:setClientCall + result:^(id _Nullable result){ + }]; + + FlutterTextInputView* myInputView = myInputPlugin.activeView; + + FlutterTextInputView* mockInputView = OCMPartialMock(myInputView); + OCMStub([mockInputView isFirstResponder]).andReturn(YES); + + XCTestExpectation* expectation = [[XCTestExpectation alloc] + initWithDescription:@"presentEditMenuWithConfiguration must be called."]; + + id mockInteraction = OCMClassMock([UIEditMenuInteraction class]); + OCMStub([mockInputView editMenuInteraction]).andReturn(mockInteraction); + OCMStub([mockInteraction presentEditMenuWithConfiguration:[OCMArg any]]) + .andDo(^(NSInvocation* invocation) { + [expectation fulfill]; + }); + + myInputView.frame = CGRectMake(10, 20, 30, 40); + NSDictionary* encodedTargetRect = + @{@"x" : @(100), @"y" : @(200), @"width" : @(300), @"height" : @(400)}; + + NSArray*>* encodedItems = + @[ @{@"type" : @"cut"}, @{@"type" : @"paste"}, @{@"type" : @"copy"} ]; + + BOOL shownEditMenu = + [myInputPlugin showEditMenu:@{@"targetRect" : encodedTargetRect, @"items" : encodedItems}]; + XCTAssertTrue(shownEditMenu, @"Should show edit menu with correct configuration."); + [self waitForExpectations:@[ expectation ] timeout:1.0]; + + UICommand* copyItem = [UICommand commandWithTitle:@"Copy" + image:nil + action:@selector(copy:) + propertyList:nil]; + UICommand* cutItem = [UICommand commandWithTitle:@"Cut" + image:nil + action:@selector(cut:) + propertyList:nil]; + UICommand* pasteItem = [UICommand commandWithTitle:@"Paste" + image:nil + action:@selector(paste:) + propertyList:nil]; + /* + A more complex menu hierarchy for DFS: + + menu + / | \ + copy menu menu + | \ + paste menu + | + cut + */ + NSArray* suggestedActions = @[ + copyItem, [UIMenu menuWithChildren:@[ pasteItem ]], + [UIMenu menuWithChildren:@[ [UIMenu menuWithChildren:@[ cutItem ]] ]] + ]; + + UIMenu* menu = [myInputView editMenuInteraction:mockInteraction + menuForConfiguration:OCMClassMock([UIEditMenuConfiguration class]) + suggestedActions:suggestedActions]; + // The item ordering should follow the encoded data sent from the framework. + NSArray* expectedActions = @[ cutItem, pasteItem, copyItem ]; + XCTAssertEqualObjects(menu.children, expectedActions); + } +} + +- (void)testEditMenu_shouldPresentEditMenuWithCorectItemsForMoreAdditionalItems { + if (@available(iOS 16.0, *)) { + FlutterTextInputPlugin* myInputPlugin = + [[FlutterTextInputPlugin alloc] initWithDelegate:OCMClassMock([FlutterEngine class])]; + FlutterViewController* myViewController = [[FlutterViewController alloc] init]; + myInputPlugin.viewController = myViewController; + [myViewController loadView]; + + FlutterMethodCall* setClientCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(123), self.mutableTemplateCopy ]]; + [myInputPlugin handleMethodCall:setClientCall + result:^(id _Nullable result){ + }]; + + FlutterTextInputView* myInputView = myInputPlugin.activeView; + + FlutterTextInputView* mockInputView = OCMPartialMock(myInputView); + OCMStub([mockInputView isFirstResponder]).andReturn(YES); + + XCTestExpectation* expectation = [[XCTestExpectation alloc] + initWithDescription:@"presentEditMenuWithConfiguration must be called."]; + + id mockInteraction = OCMClassMock([UIEditMenuInteraction class]); + OCMStub([mockInputView editMenuInteraction]).andReturn(mockInteraction); + OCMStub([mockInteraction presentEditMenuWithConfiguration:[OCMArg any]]) + .andDo(^(NSInvocation* invocation) { + [expectation fulfill]; + }); + + myInputView.frame = CGRectMake(10, 20, 30, 40); + NSDictionary* encodedTargetRect = + @{@"x" : @(100), @"y" : @(200), @"width" : @(300), @"height" : @(400)}; + + NSArray*>* encodedItems = @[ + @{@"type" : @"searchWeb", @"title" : @"Search Web"}, + @{@"type" : @"lookUp", @"title" : @"Look Up"}, @{@"type" : @"share", @"title" : @"Share"} + ]; + + BOOL shownEditMenu = + [myInputPlugin showEditMenu:@{@"targetRect" : encodedTargetRect, @"items" : encodedItems}]; + XCTAssertTrue(shownEditMenu, @"Should show edit menu with correct configuration."); + [self waitForExpectations:@[ expectation ] timeout:1.0]; + + NSArray* suggestedActions = @[ + [UICommand commandWithTitle:@"copy" image:nil action:@selector(copy:) propertyList:nil], + ]; + + UIMenu* menu = [myInputView editMenuInteraction:mockInteraction + menuForConfiguration:OCMClassMock([UIEditMenuConfiguration class]) + suggestedActions:suggestedActions]; + XCTAssert(menu.children.count == 3, @"There must be 3 menu items"); + + XCTAssert(((UICommand*)menu.children[0]).action == @selector(handleSearchWebAction), + @"Must create search web item in the tree."); + XCTAssert(((UICommand*)menu.children[1]).action == @selector(handleLookUpAction), + @"Must create look up item in the tree."); + XCTAssert(((UICommand*)menu.children[2]).action == @selector(handleShareAction), + @"Must create share item in the tree."); + } +} + +- (void)testInteractiveKeyboardAfterUserScrollWillResignFirstResponder { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [UIApplication.sharedApplication.keyWindow addSubview:inputView]; + + [inputView setTextInputClient:123]; + [inputView reloadInputViews]; + [inputView becomeFirstResponder]; + XCTAssert(inputView.isFirstResponder); + + CGRect keyboardFrame = CGRectMake(0, 500, 500, 500); + [NSNotificationCenter.defaultCenter + postNotificationName:UIKeyboardWillShowNotification + object:nil + userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}]; + FlutterMethodCall* onPointerMoveCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" + arguments:@{@"pointerY" : @(500)}]; + [textInputPlugin handleMethodCall:onPointerMoveCall + result:^(id _Nullable result){ + }]; + XCTAssertFalse(inputView.isFirstResponder); + textInputPlugin.cachedFirstResponder = nil; +} + +- (void)testInteractiveKeyboardAfterUserScrollToTopOfKeyboardWillTakeScreenshot { + NSSet* scenes = UIApplication.sharedApplication.connectedScenes; + XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test"); + UIScene* scene = scenes.anyObject; + XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test"); + UIWindowScene* windowScene = (UIWindowScene*)scene; + XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test"); + UIWindow* window = windowScene.windows[0]; + [window addSubview:viewController.view]; + + [viewController loadView]; + + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [UIApplication.sharedApplication.keyWindow addSubview:inputView]; + + [inputView setTextInputClient:123]; + [inputView reloadInputViews]; + [inputView becomeFirstResponder]; + + if (textInputPlugin.keyboardView.superview != nil) { + for (UIView* subView in textInputPlugin.keyboardViewContainer.subviews) { + [subView removeFromSuperview]; + } + } + XCTAssert(textInputPlugin.keyboardView.superview == nil); + CGRect keyboardFrame = CGRectMake(0, 500, 500, 500); + [NSNotificationCenter.defaultCenter + postNotificationName:UIKeyboardWillShowNotification + object:nil + userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}]; + FlutterMethodCall* onPointerMoveCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" + arguments:@{@"pointerY" : @(510)}]; + [textInputPlugin handleMethodCall:onPointerMoveCall + result:^(id _Nullable result){ + }]; + XCTAssertFalse(textInputPlugin.keyboardView.superview == nil); + for (UIView* subView in textInputPlugin.keyboardViewContainer.subviews) { + [subView removeFromSuperview]; + } + textInputPlugin.cachedFirstResponder = nil; +} + +- (void)testInteractiveKeyboardScreenshotWillBeMovedDownAfterUserScroll { + NSSet* scenes = UIApplication.sharedApplication.connectedScenes; + XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test"); + UIScene* scene = scenes.anyObject; + XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test"); + UIWindowScene* windowScene = (UIWindowScene*)scene; + XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test"); + UIWindow* window = windowScene.windows[0]; + [window addSubview:viewController.view]; + + [viewController loadView]; + + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [UIApplication.sharedApplication.keyWindow addSubview:inputView]; + + [inputView setTextInputClient:123]; + [inputView reloadInputViews]; + [inputView becomeFirstResponder]; + + CGRect keyboardFrame = CGRectMake(0, 500, 500, 500); + [NSNotificationCenter.defaultCenter + postNotificationName:UIKeyboardWillShowNotification + object:nil + userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}]; + FlutterMethodCall* onPointerMoveCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" + arguments:@{@"pointerY" : @(510)}]; + [textInputPlugin handleMethodCall:onPointerMoveCall + result:^(id _Nullable result){ + }]; + XCTAssert(textInputPlugin.keyboardView.superview != nil); + + XCTAssertEqual(textInputPlugin.keyboardViewContainer.frame.origin.y, keyboardFrame.origin.y); + + FlutterMethodCall* onPointerMoveCallMove = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" + arguments:@{@"pointerY" : @(600)}]; + [textInputPlugin handleMethodCall:onPointerMoveCallMove + result:^(id _Nullable result){ + }]; + XCTAssert(textInputPlugin.keyboardView.superview != nil); + + XCTAssertEqual(textInputPlugin.keyboardViewContainer.frame.origin.y, 600.0); + + for (UIView* subView in textInputPlugin.keyboardViewContainer.subviews) { + [subView removeFromSuperview]; + } + textInputPlugin.cachedFirstResponder = nil; +} + +- (void)testInteractiveKeyboardScreenshotWillBeMovedToOrginalPositionAfterUserScroll { + NSSet* scenes = UIApplication.sharedApplication.connectedScenes; + XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test"); + UIScene* scene = scenes.anyObject; + XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test"); + UIWindowScene* windowScene = (UIWindowScene*)scene; + XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test"); + UIWindow* window = windowScene.windows[0]; + [window addSubview:viewController.view]; + + [viewController loadView]; + + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [UIApplication.sharedApplication.keyWindow addSubview:inputView]; + + [inputView setTextInputClient:123]; + [inputView reloadInputViews]; + [inputView becomeFirstResponder]; + + CGRect keyboardFrame = CGRectMake(0, 500, 500, 500); + [NSNotificationCenter.defaultCenter + postNotificationName:UIKeyboardWillShowNotification + object:nil + userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}]; + FlutterMethodCall* onPointerMoveCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" + arguments:@{@"pointerY" : @(500)}]; + [textInputPlugin handleMethodCall:onPointerMoveCall + result:^(id _Nullable result){ + }]; + XCTAssert(textInputPlugin.keyboardView.superview != nil); + XCTAssertEqual(textInputPlugin.keyboardViewContainer.frame.origin.y, keyboardFrame.origin.y); + + FlutterMethodCall* onPointerMoveCallMove = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" + arguments:@{@"pointerY" : @(600)}]; + [textInputPlugin handleMethodCall:onPointerMoveCallMove + result:^(id _Nullable result){ + }]; + XCTAssert(textInputPlugin.keyboardView.superview != nil); + XCTAssertEqual(textInputPlugin.keyboardViewContainer.frame.origin.y, 600.0); + + FlutterMethodCall* onPointerMoveCallBackUp = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" + arguments:@{@"pointerY" : @(10)}]; + [textInputPlugin handleMethodCall:onPointerMoveCallBackUp + result:^(id _Nullable result){ + }]; + XCTAssert(textInputPlugin.keyboardView.superview != nil); + XCTAssertEqual(textInputPlugin.keyboardViewContainer.frame.origin.y, keyboardFrame.origin.y); + for (UIView* subView in textInputPlugin.keyboardViewContainer.subviews) { + [subView removeFromSuperview]; + } + textInputPlugin.cachedFirstResponder = nil; +} + +- (void)testInteractiveKeyboardFindFirstResponderRecursive { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [UIApplication.sharedApplication.keyWindow addSubview:inputView]; + [inputView setTextInputClient:123]; + [inputView reloadInputViews]; + [inputView becomeFirstResponder]; + + UIView* firstResponder = UIApplication.sharedApplication.keyWindow.flutterFirstResponder; + XCTAssertEqualObjects(inputView, firstResponder); + textInputPlugin.cachedFirstResponder = nil; +} + +- (void)testInteractiveKeyboardFindFirstResponderRecursiveInMultipleSubviews { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + FlutterTextInputView* subInputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + FlutterTextInputView* otherSubInputView = + [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + FlutterTextInputView* subFirstResponderInputView = + [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [subInputView addSubview:subFirstResponderInputView]; + [inputView addSubview:subInputView]; + [inputView addSubview:otherSubInputView]; + [UIApplication.sharedApplication.keyWindow addSubview:inputView]; + [inputView setTextInputClient:123]; + [inputView reloadInputViews]; + [subInputView setTextInputClient:123]; + [subInputView reloadInputViews]; + [otherSubInputView setTextInputClient:123]; + [otherSubInputView reloadInputViews]; + [subFirstResponderInputView setTextInputClient:123]; + [subFirstResponderInputView reloadInputViews]; + [subFirstResponderInputView becomeFirstResponder]; + + UIView* firstResponder = UIApplication.sharedApplication.keyWindow.flutterFirstResponder; + XCTAssertEqualObjects(subFirstResponderInputView, firstResponder); + textInputPlugin.cachedFirstResponder = nil; +} + +- (void)testInteractiveKeyboardFindFirstResponderIsNilRecursive { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [UIApplication.sharedApplication.keyWindow addSubview:inputView]; + [inputView setTextInputClient:123]; + [inputView reloadInputViews]; + + UIView* firstResponder = UIApplication.sharedApplication.keyWindow.flutterFirstResponder; + XCTAssertNil(firstResponder); + textInputPlugin.cachedFirstResponder = nil; +} + +- (void)testInteractiveKeyboardDidResignFirstResponderDelegateisCalledAfterDismissedKeyboard { + NSSet* scenes = UIApplication.sharedApplication.connectedScenes; + XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test"); + UIScene* scene = scenes.anyObject; + XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test"); + UIWindowScene* windowScene = (UIWindowScene*)scene; + XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test"); + UIWindow* window = windowScene.windows[0]; + [window addSubview:viewController.view]; + + [viewController loadView]; + + XCTestExpectation* expectation = [[XCTestExpectation alloc] + initWithDescription: + @"didResignFirstResponder is called after screenshot keyboard dismissed."]; + OCMStub([engine flutterTextInputView:[OCMArg any] didResignFirstResponderWithTextInputClient:0]) + .andDo(^(NSInvocation* invocation) { + [expectation fulfill]; + }); + CGRect keyboardFrame = CGRectMake(0, 500, 500, 500); + [NSNotificationCenter.defaultCenter + postNotificationName:UIKeyboardWillShowNotification + object:nil + userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}]; + FlutterMethodCall* initialMoveCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" + arguments:@{@"pointerY" : @(500)}]; + [textInputPlugin handleMethodCall:initialMoveCall + result:^(id _Nullable result){ + }]; + FlutterMethodCall* subsequentMoveCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" + arguments:@{@"pointerY" : @(1000)}]; + [textInputPlugin handleMethodCall:subsequentMoveCall + result:^(id _Nullable result){ + }]; + + FlutterMethodCall* pointerUpCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerUpForInteractiveKeyboard" + arguments:@{@"pointerY" : @(1000)}]; + [textInputPlugin handleMethodCall:pointerUpCall + result:^(id _Nullable result){ + }]; + + [self waitForExpectations:@[ expectation ] timeout:2.0]; + textInputPlugin.cachedFirstResponder = nil; +} + +- (void)testInteractiveKeyboardScreenshotDismissedAfterPointerLiftedAboveMiddleYOfKeyboard { + NSSet* scenes = UIApplication.sharedApplication.connectedScenes; + XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test"); + UIScene* scene = scenes.anyObject; + XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test"); + UIWindowScene* windowScene = (UIWindowScene*)scene; + XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test"); + UIWindow* window = windowScene.windows[0]; + [window addSubview:viewController.view]; + + [viewController loadView]; + + CGRect keyboardFrame = CGRectMake(0, 500, 500, 500); + [NSNotificationCenter.defaultCenter + postNotificationName:UIKeyboardWillShowNotification + object:nil + userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}]; + FlutterMethodCall* initialMoveCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" + arguments:@{@"pointerY" : @(500)}]; + [textInputPlugin handleMethodCall:initialMoveCall + result:^(id _Nullable result){ + }]; + FlutterMethodCall* subsequentMoveCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" + arguments:@{@"pointerY" : @(1000)}]; + [textInputPlugin handleMethodCall:subsequentMoveCall + result:^(id _Nullable result){ + }]; + + FlutterMethodCall* subsequentMoveBackUpCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" + arguments:@{@"pointerY" : @(0)}]; + [textInputPlugin handleMethodCall:subsequentMoveBackUpCall + result:^(id _Nullable result){ + }]; + + FlutterMethodCall* pointerUpCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerUpForInteractiveKeyboard" + arguments:@{@"pointerY" : @(0)}]; + [textInputPlugin handleMethodCall:pointerUpCall + result:^(id _Nullable result){ + }]; + NSPredicate* predicate = [NSPredicate predicateWithBlock:^BOOL(id item, NSDictionary* bindings) { + return textInputPlugin.keyboardViewContainer.subviews.count == 0; + }]; + XCTNSPredicateExpectation* expectation = + [[XCTNSPredicateExpectation alloc] initWithPredicate:predicate object:nil]; + [self waitForExpectations:@[ expectation ] timeout:10.0]; + textInputPlugin.cachedFirstResponder = nil; +} + +- (void)testInteractiveKeyboardKeyboardReappearsAfterPointerLiftedAboveMiddleYOfKeyboard { + NSSet* scenes = UIApplication.sharedApplication.connectedScenes; + XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test"); + UIScene* scene = scenes.anyObject; + XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test"); + UIWindowScene* windowScene = (UIWindowScene*)scene; + XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test"); + UIWindow* window = windowScene.windows[0]; + [window addSubview:viewController.view]; + + [viewController loadView]; + + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin]; + [UIApplication.sharedApplication.keyWindow addSubview:inputView]; + + [inputView setTextInputClient:123]; + [inputView reloadInputViews]; + [inputView becomeFirstResponder]; + + CGRect keyboardFrame = CGRectMake(0, 500, 500, 500); + [NSNotificationCenter.defaultCenter + postNotificationName:UIKeyboardWillShowNotification + object:nil + userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}]; + FlutterMethodCall* initialMoveCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" + arguments:@{@"pointerY" : @(500)}]; + [textInputPlugin handleMethodCall:initialMoveCall + result:^(id _Nullable result){ + }]; + FlutterMethodCall* subsequentMoveCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" + arguments:@{@"pointerY" : @(1000)}]; + [textInputPlugin handleMethodCall:subsequentMoveCall + result:^(id _Nullable result){ + }]; + + FlutterMethodCall* subsequentMoveBackUpCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" + arguments:@{@"pointerY" : @(0)}]; + [textInputPlugin handleMethodCall:subsequentMoveBackUpCall + result:^(id _Nullable result){ + }]; + + FlutterMethodCall* pointerUpCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerUpForInteractiveKeyboard" + arguments:@{@"pointerY" : @(0)}]; + [textInputPlugin handleMethodCall:pointerUpCall + result:^(id _Nullable result){ + }]; + NSPredicate* predicate = [NSPredicate predicateWithBlock:^BOOL(id item, NSDictionary* bindings) { + return textInputPlugin.cachedFirstResponder.isFirstResponder; + }]; + XCTNSPredicateExpectation* expectation = + [[XCTNSPredicateExpectation alloc] initWithPredicate:predicate object:nil]; + [self waitForExpectations:@[ expectation ] timeout:10.0]; + textInputPlugin.cachedFirstResponder = nil; +} + +- (void)testInteractiveKeyboardKeyboardAnimatesToOriginalPositionalOnPointerUp { + NSSet* scenes = UIApplication.sharedApplication.connectedScenes; + XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test"); + UIScene* scene = scenes.anyObject; + XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test"); + UIWindowScene* windowScene = (UIWindowScene*)scene; + XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test"); + UIWindow* window = windowScene.windows[0]; + [window addSubview:viewController.view]; + + [viewController loadView]; + + XCTestExpectation* expectation = + [[XCTestExpectation alloc] initWithDescription:@"Keyboard animates to proper position."]; + CGRect keyboardFrame = CGRectMake(0, 500, 500, 500); + [NSNotificationCenter.defaultCenter + postNotificationName:UIKeyboardWillShowNotification + object:nil + userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}]; + FlutterMethodCall* initialMoveCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" + arguments:@{@"pointerY" : @(500)}]; + [textInputPlugin handleMethodCall:initialMoveCall + result:^(id _Nullable result){ + }]; + FlutterMethodCall* subsequentMoveCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" + arguments:@{@"pointerY" : @(1000)}]; + [textInputPlugin handleMethodCall:subsequentMoveCall + result:^(id _Nullable result){ + }]; + FlutterMethodCall* upwardVelocityMoveCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" + arguments:@{@"pointerY" : @(500)}]; + [textInputPlugin handleMethodCall:upwardVelocityMoveCall + result:^(id _Nullable result){ + }]; + + FlutterMethodCall* pointerUpCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerUpForInteractiveKeyboard" + arguments:@{@"pointerY" : @(0)}]; + [textInputPlugin + handleMethodCall:pointerUpCall + result:^(id _Nullable result) { + XCTAssertEqual(textInputPlugin.keyboardViewContainer.frame.origin.y, + viewController.flutterScreenIfViewLoaded.bounds.size.height - + keyboardFrame.origin.y); + [expectation fulfill]; + }]; + textInputPlugin.cachedFirstResponder = nil; +} + +- (void)testInteractiveKeyboardKeyboardAnimatesToDismissalPositionalOnPointerUp { + NSSet* scenes = UIApplication.sharedApplication.connectedScenes; + XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test"); + UIScene* scene = scenes.anyObject; + XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test"); + UIWindowScene* windowScene = (UIWindowScene*)scene; + XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test"); + UIWindow* window = windowScene.windows[0]; + [window addSubview:viewController.view]; + + [viewController loadView]; + + XCTestExpectation* expectation = + [[XCTestExpectation alloc] initWithDescription:@"Keyboard animates to proper position."]; + CGRect keyboardFrame = CGRectMake(0, 500, 500, 500); + [NSNotificationCenter.defaultCenter + postNotificationName:UIKeyboardWillShowNotification + object:nil + userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}]; + FlutterMethodCall* initialMoveCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" + arguments:@{@"pointerY" : @(500)}]; + [textInputPlugin handleMethodCall:initialMoveCall + result:^(id _Nullable result){ + }]; + FlutterMethodCall* subsequentMoveCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard" + arguments:@{@"pointerY" : @(1000)}]; + [textInputPlugin handleMethodCall:subsequentMoveCall + result:^(id _Nullable result){ + }]; + + FlutterMethodCall* pointerUpCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerUpForInteractiveKeyboard" + arguments:@{@"pointerY" : @(1000)}]; + [textInputPlugin + handleMethodCall:pointerUpCall + result:^(id _Nullable result) { + XCTAssertEqual(textInputPlugin.keyboardViewContainer.frame.origin.y, + viewController.flutterScreenIfViewLoaded.bounds.size.height); + [expectation fulfill]; + }]; + textInputPlugin.cachedFirstResponder = nil; +} +- (void)testInteractiveKeyboardShowKeyboardAndRemoveScreenshotAnimationIsNotImmediatelyEnable { + [UIView setAnimationsEnabled:YES]; + [textInputPlugin showKeyboardAndRemoveScreenshot]; + XCTAssertFalse( + UIView.areAnimationsEnabled, + @"The animation should still be disabled following showKeyboardAndRemoveScreenshot"); +} + +- (void)testInteractiveKeyboardShowKeyboardAndRemoveScreenshotAnimationIsReenabledAfterDelay { + [UIView setAnimationsEnabled:YES]; + [textInputPlugin showKeyboardAndRemoveScreenshot]; + + NSPredicate* predicate = [NSPredicate predicateWithBlock:^BOOL(id item, NSDictionary* bindings) { + // This will be enabled after a delay + return UIView.areAnimationsEnabled; + }]; + XCTNSPredicateExpectation* expectation = + [[XCTNSPredicateExpectation alloc] initWithPredicate:predicate object:nil]; + [self waitForExpectations:@[ expectation ] timeout:10.0]; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextureRegistryRelay.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextureRegistryRelay.h new file mode 100644 index 0000000000000000000000000000000000000000..2152ac55a370e4fd698b7a09cd219e56ec14291b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextureRegistryRelay.h @@ -0,0 +1,29 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERTEXTUREREGISTRYRELAY_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERTEXTUREREGISTRYRELAY_H_ + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterTexture.h" + +#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG +FLUTTER_DARWIN_EXPORT +#endif + +/** + * Wrapper around a weakly held collection of registered textures. + * + * Avoids a retain cycle between plugins and the engine. + */ +@interface FlutterTextureRegistryRelay : NSObject + +/** + * A weak reference to a FlutterEngine that will be passed texture registration. + */ +@property(nonatomic, weak) NSObject* parent; +- (instancetype)initWithParent:(NSObject*)parent; +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERTEXTUREREGISTRYRELAY_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextureRegistryRelay.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextureRegistryRelay.mm new file mode 100644 index 0000000000000000000000000000000000000000..1df2b05c4575d753a1c0274515121b8286a315ab --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextureRegistryRelay.mm @@ -0,0 +1,44 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextureRegistryRelay.h" + +#include "flutter/fml/logging.h" + +FLUTTER_ASSERT_ARC + +@implementation FlutterTextureRegistryRelay : NSObject + +#pragma mark - FlutterTextureRegistry + +- (instancetype)initWithParent:(NSObject*)parent { + if (self = [super init]) { + _parent = parent; + } + return self; +} + +- (int64_t)registerTexture:(NSObject*)texture { + if (!self.parent) { + FML_LOG(WARNING) << "Using on an empty registry."; + return 0; + } + return [self.parent registerTexture:texture]; +} + +- (void)textureFrameAvailable:(int64_t)textureId { + if (!self.parent) { + FML_LOG(WARNING) << "Using on an empty registry."; + } + return [self.parent textureFrameAvailable:textureId]; +} + +- (void)unregisterTexture:(int64_t)textureId { + if (!self.parent) { + FML_LOG(WARNING) << "Using on an empty registry."; + } + return [self.parent unregisterTexture:textureId]; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextureRegistryRelayTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextureRegistryRelayTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..790b484075e3fa5651a76142493bec6a2f6a1fa9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextureRegistryRelayTest.mm @@ -0,0 +1,67 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterEngine.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextureRegistryRelay.h" + +#import +#import + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterTexture.h" + +FLUTTER_ASSERT_ARC + +@interface FlutterTextureRegistryRelayTest : XCTestCase +@end + +@implementation FlutterTextureRegistryRelayTest + +- (void)testCreate { + id textureRegistry = OCMProtocolMock(@protocol(FlutterTextureRegistry)); + FlutterTextureRegistryRelay* relay = + [[FlutterTextureRegistryRelay alloc] initWithParent:textureRegistry]; + XCTAssertNotNil(relay); + XCTAssertEqual(textureRegistry, relay.parent); +} + +- (void)testRegisterTexture { + id textureRegistry = OCMProtocolMock(@protocol(FlutterTextureRegistry)); + FlutterTextureRegistryRelay* relay = + [[FlutterTextureRegistryRelay alloc] initWithParent:textureRegistry]; + id texture = OCMProtocolMock(@protocol(FlutterTexture)); + [relay registerTexture:texture]; + OCMVerify([textureRegistry registerTexture:texture]); +} + +- (void)testTextureFrameAvailable { + id textureRegistry = OCMProtocolMock(@protocol(FlutterTextureRegistry)); + FlutterTextureRegistryRelay* relay = + [[FlutterTextureRegistryRelay alloc] initWithParent:textureRegistry]; + [relay textureFrameAvailable:0]; + OCMVerify([textureRegistry textureFrameAvailable:0]); +} + +- (void)testUnregisterTexture { + id textureRegistry = OCMProtocolMock(@protocol(FlutterTextureRegistry)); + FlutterTextureRegistryRelay* relay = + [[FlutterTextureRegistryRelay alloc] initWithParent:textureRegistry]; + [relay unregisterTexture:0]; + OCMVerify([textureRegistry unregisterTexture:0]); +} + +- (void)testRetainCycle { + __weak FlutterEngine* weakEngine; + NSObject* strongRelay; + @autoreleasepool { + FlutterDartProject* project = [[FlutterDartProject alloc] init]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project]; + strongRelay = [engine textureRegistry]; + weakEngine = engine; + } + XCTAssertNil(weakEngine); + XCTAssertNotNil(strongRelay); +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTouchInterceptingView_Test.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTouchInterceptingView_Test.h new file mode 100644 index 0000000000000000000000000000000000000000..5d0eae76aedcacb85cde4da302ea89ac90e4cd15 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTouchInterceptingView_Test.h @@ -0,0 +1,14 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h" + +#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERTOUCHINTERCEPTINGVIEW_TEST_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERTOUCHINTERCEPTINGVIEW_TEST_H_ + +@interface FlutterTouchInterceptingView (Tests) +- (id)accessibilityContainer; +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERTOUCHINTERCEPTINGVIEW_TEST_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h new file mode 100644 index 0000000000000000000000000000000000000000..9aeb4d7a517cb165d91a34c4069742c89836ff75 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h @@ -0,0 +1,28 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERUIPRESSPROXY_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERUIPRESSPROXY_H_ + +#import +#include + +/** + * A event class that is a wrapper around a UIPress and a UIEvent to allow + * overidding for testing purposes, since UIKit doesn't allow creation of + * UIEvent or UIPress directly. + */ +API_AVAILABLE(ios(13.4)) +@interface FlutterUIPressProxy : NSObject + +- (instancetype)initWithPress:(UIPress*)press withEvent:(UIEvent*)event API_AVAILABLE(ios(13.4)); + +- (UIPressPhase)phase API_AVAILABLE(ios(13.4)); +- (UIKey*)key API_AVAILABLE(ios(13.4)); +- (UIEventType)type API_AVAILABLE(ios(13.4)); +- (NSTimeInterval)timestamp API_AVAILABLE(ios(13.4)); + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERUIPRESSPROXY_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.mm new file mode 100644 index 0000000000000000000000000000000000000000..540b6ae0beb99ab4975072564a00f1b9a64bf899 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.mm @@ -0,0 +1,45 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h" + +#import + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" + +FLUTTER_ASSERT_ARC + +@interface FlutterUIPressProxy () +@property(nonatomic, readonly) UIPress* press; +@property(nonatomic, readonly) UIEvent* event; +@end + +@implementation FlutterUIPressProxy + +- (instancetype)initWithPress:(UIPress*)press withEvent:(UIEvent*)event API_AVAILABLE(ios(13.4)) { + self = [super init]; + if (self) { + _press = press; + _event = event; + } + return self; +} + +- (UIPressPhase)phase API_AVAILABLE(ios(13.4)) { + return _press.phase; +} + +- (UIKey*)key API_AVAILABLE(ios(13.4)) { + return _press.key; +} + +- (UIEventType)type API_AVAILABLE(ios(13.4)) { + return _event.type; +} + +- (NSTimeInterval)timestamp API_AVAILABLE(ios(13.4)) { + return _event.timestamp; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUmbrellaImport.m b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUmbrellaImport.m new file mode 100644 index 0000000000000000000000000000000000000000..849a05e5a052a23f22937673f816d77090632f98 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUmbrellaImport.m @@ -0,0 +1,11 @@ +// 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. + +// FLUTTER_NOLINT: https://github.com/flutter/flutter/issues/93360 + +// The only point of this file is to ensure that the Flutter framework umbrella header can be +// cleanly imported from an Objective-C translation unit. The target that uses this file copies the +// headers to a path that simulates how users would actually import the framework outside of the +// engine source root. +#import diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerDelegate.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerDelegate.h new file mode 100644 index 0000000000000000000000000000000000000000..bcfd609dd185cf8021511007037a060c373ed786 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerDelegate.h @@ -0,0 +1,45 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERUNDOMANAGERDELEGATE_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERUNDOMANAGERDELEGATE_H_ + +#import + +NS_ASSUME_NONNULL_BEGIN + +typedef NS_ENUM(NSInteger, FlutterUndoRedoDirection) { + // NOLINTBEGIN(readability-identifier-naming) + FlutterUndoRedoDirectionUndo, + FlutterUndoRedoDirectionRedo, + // NOLINTEND(readability-identifier-naming) +}; + +/** + * Protocol for undo manager changes from the `FlutterUndoManagerPlugin`, typically a + * `FlutterEngine`. + */ +@protocol FlutterUndoManagerDelegate + +/** + * The `NSUndoManager` that should be managed by the `FlutterUndoManagerPlugin`. + * When the delegate is `FlutterEngine` this will be the `FlutterViewController`'s undo manager. + */ +@property(nonatomic, readonly, nullable) NSUndoManager* undoManager; + +/** + * Used to notify the active view when undo manager state (can redo/can undo) + * changes, in order to force keyboards to update undo/redo buttons. + */ +@property(nonatomic, readonly, nullable) UIView* activeTextInputView; + +/** + * Pass changes to the framework through the undo manager channel. + */ +- (void)handleUndoWithDirection:(FlutterUndoRedoDirection)direction; + +@end +NS_ASSUME_NONNULL_END + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERUNDOMANAGERDELEGATE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerPlugin.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerPlugin.h new file mode 100644 index 0000000000000000000000000000000000000000..3a3271f7b360d52d25e194c3bb5d141f476286be --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerPlugin.h @@ -0,0 +1,25 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERUNDOMANAGERPLUGIN_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERUNDOMANAGERPLUGIN_H_ + +#import + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerDelegate.h" + +@interface FlutterUndoManagerPlugin : NSObject + +- (instancetype)init NS_UNAVAILABLE; ++ (instancetype)new NS_UNAVAILABLE; + +- (instancetype)initWithDelegate:(id)undoManagerDelegate + NS_DESIGNATED_INITIALIZER; + +- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERUNDOMANAGERPLUGIN_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerPlugin.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerPlugin.mm new file mode 100644 index 0000000000000000000000000000000000000000..32810dcacc9c18695a5e61edad99ca7b0d935bf0 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerPlugin.mm @@ -0,0 +1,109 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerPlugin.h" + +#pragma mark - UndoManager channel method names. +static NSString* const kSetUndoStateMethod = @"UndoManager.setUndoState"; + +#pragma mark - Undo State field names +static NSString* const kCanUndo = @"canUndo"; +static NSString* const kCanRedo = @"canRedo"; + +@interface FlutterUndoManagerPlugin () +@property(nonatomic, weak, readonly) id undoManagerDelegate; + +// When the delegate is `FlutterEngine` this will be the `FlutterViewController`'s undo manager. +// Strongly retain to ensure this target's actions are completely removed during dealloc. +@property(nonatomic) NSUndoManager* undoManager; +@end + +@implementation FlutterUndoManagerPlugin + +- (instancetype)initWithDelegate:(id)undoManagerDelegate { + self = [super init]; + + if (self) { + _undoManagerDelegate = undoManagerDelegate; + } + + return self; +} + +- (void)dealloc { + [_undoManager removeAllActionsWithTarget:self]; +} + +- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { + NSString* method = call.method; + id args = call.arguments; + if ([method isEqualToString:kSetUndoStateMethod]) { + self.undoManager = self.undoManagerDelegate.undoManager; + [self setUndoState:args]; + result(nil); + } else { + result(FlutterMethodNotImplemented); + } +} + +- (void)resetUndoManager { + [self.undoManager removeAllActionsWithTarget:self]; +} + +- (void)registerUndoWithDirection:(FlutterUndoRedoDirection)direction { + NSUndoManager* undoManager = self.undoManager; + [undoManager beginUndoGrouping]; + [undoManager registerUndoWithTarget:self + handler:^(FlutterUndoManagerPlugin* target) { + // Register undo with opposite direction. + FlutterUndoRedoDirection newDirection = + (direction == FlutterUndoRedoDirectionRedo) + ? FlutterUndoRedoDirectionUndo + : FlutterUndoRedoDirectionRedo; + [target registerUndoWithDirection:newDirection]; + // Invoke method on delegate. + [target.undoManagerDelegate handleUndoWithDirection:direction]; + }]; + [undoManager endUndoGrouping]; +} + +- (void)registerRedo { + NSUndoManager* undoManager = self.undoManager; + [undoManager beginUndoGrouping]; + [undoManager registerUndoWithTarget:self + handler:^(id target) { + // Register undo with opposite direction. + [target registerUndoWithDirection:FlutterUndoRedoDirectionRedo]; + }]; + [undoManager endUndoGrouping]; + [undoManager undo]; +} + +- (void)setUndoState:(NSDictionary*)dictionary { + NSUndoManager* undoManager = self.undoManager; + BOOL groupsByEvent = undoManager.groupsByEvent; + undoManager.groupsByEvent = NO; + BOOL canUndo = [dictionary[kCanUndo] boolValue]; + BOOL canRedo = [dictionary[kCanRedo] boolValue]; + + [self resetUndoManager]; + + if (canUndo) { + [self registerUndoWithDirection:FlutterUndoRedoDirectionUndo]; + } + if (canRedo) { + [self registerRedo]; + } + UIView* textInputView = self.undoManagerDelegate.activeTextInputView; + if (textInputView != nil) { + // This is needed to notify the iPadOS keyboard that it needs to update the + // state of the UIBarButtons. Otherwise, the state changes to NSUndoManager + // will not show up until the next keystroke (or other trigger). + UITextInputAssistantItem* assistantItem = textInputView.inputAssistantItem; + assistantItem.leadingBarButtonGroups = assistantItem.leadingBarButtonGroups; + } + undoManager.groupsByEvent = groupsByEvent; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerPluginTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerPluginTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..261b421b17722352aeba7a92646890c6590d93cf --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerPluginTest.mm @@ -0,0 +1,189 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerPlugin.h" + +#import +#import + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h" + +FLUTTER_ASSERT_ARC + +@interface FakeFlutterUndoManagerDelegate : NSObject + +@property(readonly) NSUInteger undoCount; +@property(readonly) NSUInteger redoCount; +@property(nonatomic, nullable) NSUndoManager* undoManager; +@property(nonatomic, nullable) UIView* activeTextInputView; + +- (instancetype)initWithUndoManager:(NSUndoManager*)undoManager + activeTextInputView:(UIView*)activeTextInputView; + +@end + +@implementation FakeFlutterUndoManagerDelegate + +- (instancetype)initWithUndoManager:(NSUndoManager*)undoManager + activeTextInputView:(UIView*)activeTextInputView { + self = [super init]; + if (self) { + _undoManager = undoManager; + _activeTextInputView = activeTextInputView; + } + return self; +} + +- (void)handleUndoWithDirection:(FlutterUndoRedoDirection)direction { + if (direction == FlutterUndoRedoDirectionUndo) { + _undoCount++; + } else { + _redoCount++; + } +} + +@end + +@interface FlutterUndoManagerPluginTest : XCTestCase +@property(nonatomic) FakeFlutterUndoManagerDelegate* undoManagerDelegate; +@property(nonatomic) FlutterUndoManagerPlugin* undoManagerPlugin; +@property(nonatomic) UIView* activeTextInputView; +@property(nonatomic) NSUndoManager* undoManager; +@end + +@implementation FlutterUndoManagerPluginTest + +- (void)setUp { + [super setUp]; + + self.undoManager = OCMClassMock([NSUndoManager class]); + self.activeTextInputView = OCMClassMock([FlutterTextInputView class]); + + self.undoManagerDelegate = + [[FakeFlutterUndoManagerDelegate alloc] initWithUndoManager:self.undoManager + activeTextInputView:self.activeTextInputView]; + + self.undoManagerPlugin = + [[FlutterUndoManagerPlugin alloc] initWithDelegate:self.undoManagerDelegate]; +} + +- (void)testSetUndoState { + __block int registerUndoCount = 0; + __block void (^undoHandler)(id target); + OCMStub([self.undoManager registerUndoWithTarget:self.undoManagerPlugin handler:[OCMArg any]]) + .andDo(^(NSInvocation* invocation) { + registerUndoCount++; + __weak void (^handler)(id target); + [invocation retainArguments]; + [invocation getArgument:&handler atIndex:3]; + undoHandler = handler; + }); + __block int removeAllActionsCount = 0; + OCMStub([self.undoManager removeAllActionsWithTarget:self.undoManagerPlugin]) + .andDo(^(NSInvocation* invocation) { + removeAllActionsCount++; + }); + __block int undoCount = 0; + OCMStub([self.undoManager undo]).andDo(^(NSInvocation* invocation) { + undoCount++; + undoHandler(self.undoManagerPlugin); + }); + + // If canUndo and canRedo are false, only removeAllActionsWithTarget is called. + FlutterMethodCall* setUndoStateCall = + [FlutterMethodCall methodCallWithMethodName:@"UndoManager.setUndoState" + arguments:@{@"canUndo" : @NO, @"canRedo" : @NO}]; + [self.undoManagerPlugin handleMethodCall:setUndoStateCall + result:^(id _Nullable result){ + }]; + XCTAssertEqual(1, removeAllActionsCount); + XCTAssertEqual(0, registerUndoCount); + + // If canUndo is true, an undo will be registered. + setUndoStateCall = + [FlutterMethodCall methodCallWithMethodName:@"UndoManager.setUndoState" + arguments:@{@"canUndo" : @YES, @"canRedo" : @NO}]; + [self.undoManagerPlugin handleMethodCall:setUndoStateCall + result:^(id _Nullable result){ + }]; + XCTAssertEqual(2, removeAllActionsCount); + XCTAssertEqual(1, registerUndoCount); + + // Invoking the undo handler will invoke the handleUndo delegate method with "undo". + undoHandler(self.undoManagerPlugin); + XCTAssertEqual(1UL, self.undoManagerDelegate.undoCount); + XCTAssertEqual(0UL, self.undoManagerDelegate.redoCount); + XCTAssertEqual(2, registerUndoCount); + + // Invoking the redo handler will invoke the handleUndo delegate method with "redo". + undoHandler(self.undoManagerPlugin); + XCTAssertEqual(1UL, self.undoManagerDelegate.undoCount); + XCTAssertEqual(1UL, self.undoManagerDelegate.redoCount); + XCTAssertEqual(3, registerUndoCount); + + // If canRedo is true, an undo will be registered and undo will be called. + setUndoStateCall = + [FlutterMethodCall methodCallWithMethodName:@"UndoManager.setUndoState" + arguments:@{@"canUndo" : @NO, @"canRedo" : @YES}]; + [self.undoManagerPlugin handleMethodCall:setUndoStateCall + result:^(id _Nullable result){ + }]; + XCTAssertEqual(3, removeAllActionsCount); + XCTAssertEqual(5, registerUndoCount); + XCTAssertEqual(1, undoCount); + + // Invoking the redo handler will invoke the handleUndo delegate method with "redo". + undoHandler(self.undoManagerPlugin); + XCTAssertEqual(1UL, self.undoManagerDelegate.undoCount); + XCTAssertEqual(2UL, self.undoManagerDelegate.redoCount); +} + +- (void)testSetUndoStateDoesInteractWithInputDelegate { + // Regression test for https://github.com/flutter/flutter/issues/133424 + FlutterMethodCall* setUndoStateCall = + [FlutterMethodCall methodCallWithMethodName:@"UndoManager.setUndoState" + arguments:@{@"canUndo" : @NO, @"canRedo" : @NO}]; + [self.undoManagerPlugin handleMethodCall:setUndoStateCall + result:^(id _Nullable result){ + }]; + + OCMVerify(never(), [self.activeTextInputView inputDelegate]); +} + +- (void)testDeallocRemovesAllUndoManagerActions { + __weak FlutterUndoManagerPlugin* weakUndoManagerPlugin; + // Use a real undo manager. + NSUndoManager* undoManager = [[NSUndoManager alloc] init]; + @autoreleasepool { + id activeTextInputView = OCMClassMock([FlutterTextInputView class]); + + FakeFlutterUndoManagerDelegate* undoManagerDelegate = + [[FakeFlutterUndoManagerDelegate alloc] initWithUndoManager:undoManager + activeTextInputView:activeTextInputView]; + + FlutterUndoManagerPlugin* undoManagerPlugin = + [[FlutterUndoManagerPlugin alloc] initWithDelegate:undoManagerDelegate]; + weakUndoManagerPlugin = undoManagerPlugin; + + FlutterMethodCall* setUndoStateCall = + [FlutterMethodCall methodCallWithMethodName:@"UndoManager.setUndoState" + arguments:@{@"canUndo" : @YES, @"canRedo" : @YES}]; + [undoManagerPlugin handleMethodCall:setUndoStateCall + result:^(id _Nullable result){ + }]; + XCTAssertTrue(undoManager.canUndo); + XCTAssertTrue(undoManager.canRedo); + // Fake out the undoManager being nil, which happens when the FlutterViewController deallocs and + // the undo manager can't be fetched from the FlutterEngine delegate. + undoManagerDelegate.undoManager = nil; + } + XCTAssertNil(weakUndoManagerPlugin); + // Regression test for https://github.com/flutter/flutter/issues/150408. + // Undo manager undo and redo stack should be empty after the plugin deallocs. + XCTAssertFalse(undoManager.canUndo); + XCTAssertFalse(undoManager.canRedo); +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h new file mode 100644 index 0000000000000000000000000000000000000000..7f3a32ed63f6f6d2355e49a654627735838a9aae --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h @@ -0,0 +1,48 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERVIEW_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERVIEW_H_ + +#import +#import + +#include "flutter/shell/common/rasterizer.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h" + +@protocol FlutterViewEngineDelegate + +@property(nonatomic, readonly) FlutterPlatformViewsController* platformViewsController; + +- (flutter::Rasterizer::Screenshot)takeScreenshot:(flutter::Rasterizer::ScreenshotType)type + asBase64Encoded:(BOOL)base64Encode; + +/** + * A callback that is called when iOS queries accessibility information of the Flutter view. + * + * This is useful to predict the current iOS accessibility status. For example, there is + * no API to listen whether voice control is turned on or off. The Flutter engine uses + * this callback to enable semantics in order to catch the case that voice control is + * on. + */ +- (void)flutterViewAccessibilityDidCall; +@end + +@interface FlutterView : UIView + +- (instancetype)init NS_UNAVAILABLE; ++ (instancetype)new NS_UNAVAILABLE; +- (instancetype)initWithFrame:(CGRect)frame NS_UNAVAILABLE; +- (instancetype)initWithCoder:(NSCoder*)aDecoder NS_UNAVAILABLE; + +- (instancetype)initWithDelegate:(id)delegate + opaque:(BOOL)opaque + enableWideGamut:(BOOL)isWideGamutEnabled NS_DESIGNATED_INITIALIZER; + +- (UIScreen*)screen; +- (MTLPixelFormat)pixelFormat; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERVIEW_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.mm new file mode 100644 index 0000000000000000000000000000000000000000..d1f813b13a0131384535e3c489c66911d8194986 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.mm @@ -0,0 +1,247 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h" + +#include "flutter/fml/platform/darwin/cf_utils.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterSharedApplication.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h" + +FLUTTER_ASSERT_ARC + +@interface FlutterView () +@property(nonatomic, weak) id delegate; +@end + +@implementation FlutterView { + BOOL _isWideGamutEnabled; +} + +- (instancetype)init { + NSAssert(NO, @"FlutterView must initWithDelegate"); + return nil; +} + +- (instancetype)initWithFrame:(CGRect)frame { + NSAssert(NO, @"FlutterView must initWithDelegate"); + return nil; +} + +- (instancetype)initWithCoder:(NSCoder*)aDecoder { + NSAssert(NO, @"FlutterView must initWithDelegate"); + return nil; +} + +- (UIScreen*)screen { + if (@available(iOS 13.0, *)) { + return self.window.windowScene.screen; + } + return UIScreen.mainScreen; +} + +- (MTLPixelFormat)pixelFormat { + if ([self.layer isKindOfClass:[CAMetalLayer class]]) { +// It is a known Apple bug that CAMetalLayer incorrectly reports its supported +// SDKs. It is, in fact, available since iOS 8. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability-new" + CAMetalLayer* layer = (CAMetalLayer*)self.layer; + return layer.pixelFormat; + } + return MTLPixelFormatBGRA8Unorm; +} +- (BOOL)isWideGamutSupported { + FML_DCHECK(self.screen); + + // Wide Gamut is not supported for iOS Extensions due to memory limitations + // (see https://github.com/flutter/flutter/issues/165086). + if (FlutterSharedApplication.isAppExtension) { + return NO; + } + + // This predicates the decision on the capabilities of the iOS device's + // display. This means external displays will not support wide gamut if the + // device's display doesn't support it. It practice that should be never. + return self.screen.traitCollection.displayGamut != UIDisplayGamutSRGB; +} + +- (instancetype)initWithDelegate:(id)delegate + opaque:(BOOL)opaque + enableWideGamut:(BOOL)isWideGamutEnabled { + if (delegate == nil) { + NSLog(@"FlutterView delegate was nil."); + return nil; + } + + self = [super initWithFrame:CGRectNull]; + + if (self) { + _delegate = delegate; + _isWideGamutEnabled = isWideGamutEnabled; + self.layer.opaque = opaque; + } + + return self; +} + +static void PrintWideGamutWarningOnce() { + static BOOL did_print = NO; + if (did_print) { + return; + } + FML_DLOG(WARNING) << "Rendering wide gamut colors is turned on but isn't " + "supported, downgrading the color gamut to sRGB."; + did_print = YES; +} + +- (void)layoutSubviews { + if ([self.layer isKindOfClass:[CAMetalLayer class]]) { +// It is a known Apple bug that CAMetalLayer incorrectly reports its supported +// SDKs. It is, in fact, available since iOS 8. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability-new" + CAMetalLayer* layer = (CAMetalLayer*)self.layer; +#pragma clang diagnostic pop + CGFloat screenScale = self.screen.scale; + layer.allowsGroupOpacity = YES; + layer.contentsScale = screenScale; + layer.rasterizationScale = screenScale; + layer.framebufferOnly = flutter::Settings::kSurfaceDataAccessible ? NO : YES; + if (_isWideGamutEnabled && self.isWideGamutSupported) { + fml::CFRef srgb(CGColorSpaceCreateWithName(kCGColorSpaceExtendedSRGB)); + layer.colorspace = srgb; + layer.pixelFormat = MTLPixelFormatBGRA10_XR; + } else if (_isWideGamutEnabled && !self.isWideGamutSupported) { + PrintWideGamutWarningOnce(); + } + } + + [super layoutSubviews]; +} + ++ (Class)layerClass { + return flutter::GetCoreAnimationLayerClassForRenderingAPI( + flutter::GetRenderingAPIForProcess(/*force_software=*/false)); +} + +- (void)drawLayer:(CALayer*)layer inContext:(CGContextRef)context { + TRACE_EVENT0("flutter", "SnapshotFlutterView"); + + if (layer != self.layer || context == nullptr) { + return; + } + + auto screenshot = [_delegate takeScreenshot:flutter::Rasterizer::ScreenshotType::UncompressedImage + asBase64Encoded:NO]; + + if (!screenshot.data || screenshot.data->isEmpty() || screenshot.frame_size.isEmpty()) { + return; + } + + NSData* data = [NSData dataWithBytes:const_cast(screenshot.data->data()) + length:screenshot.data->size()]; + + fml::CFRef image_data_provider( + CGDataProviderCreateWithCFData(reinterpret_cast(data))); + + fml::CFRef colorspace(CGColorSpaceCreateDeviceRGB()); + + // Defaults for RGBA8888. + size_t bits_per_component = 8u; + size_t bits_per_pixel = 32u; + size_t bytes_per_row_multiplier = 4u; + CGBitmapInfo bitmap_info = + static_cast(static_cast(kCGImageAlphaPremultipliedLast) | + static_cast(kCGBitmapByteOrder32Big)); + + switch (screenshot.pixel_format) { + case flutter::Rasterizer::ScreenshotFormat::kUnknown: + case flutter::Rasterizer::ScreenshotFormat::kR8G8B8A8UNormInt: + // Assume unknown is Skia and is RGBA8888. Keep defaults. + break; + case flutter::Rasterizer::ScreenshotFormat::kB8G8R8A8UNormInt: + // Treat this as little endian with the alpha first so that it's read backwards. + bitmap_info = + static_cast(static_cast(kCGImageAlphaPremultipliedFirst) | + static_cast(kCGBitmapByteOrder32Little)); + break; + case flutter::Rasterizer::ScreenshotFormat::kR16G16B16A16Float: + bits_per_component = 16u; + bits_per_pixel = 64u; + bytes_per_row_multiplier = 8u; + bitmap_info = + static_cast(static_cast(kCGImageAlphaPremultipliedLast) | + static_cast(kCGBitmapFloatComponents) | + static_cast(kCGBitmapByteOrder16Little)); + break; + } + + fml::CFRef image(CGImageCreate( + screenshot.frame_size.width(), // size_t width + screenshot.frame_size.height(), // size_t height + bits_per_component, // size_t bitsPerComponent + bits_per_pixel, // size_t bitsPerPixel, + bytes_per_row_multiplier * screenshot.frame_size.width(), // size_t bytesPerRow + colorspace, // CGColorSpaceRef space + bitmap_info, // CGBitmapInfo bitmapInfo + image_data_provider, // CGDataProviderRef provider + nullptr, // const CGFloat* decode + false, // bool shouldInterpolate + kCGRenderingIntentDefault // CGColorRenderingIntent intent + )); + + const CGRect frame_rect = + CGRectMake(0.0, 0.0, screenshot.frame_size.width(), screenshot.frame_size.height()); + CGContextSaveGState(context); + // If the CGContext is not a bitmap based context, this returns zero. + CGFloat height = CGBitmapContextGetHeight(context); + if (height == 0) { + height = CGFloat(screenshot.frame_size.height()); + } + CGContextTranslateCTM(context, 0.0, height); + CGContextScaleCTM(context, 1.0, -1.0); + CGContextDrawImage(context, frame_rect, image); + CGContextRestoreGState(context); +} + +- (BOOL)isAccessibilityElement { + // iOS does not provide an API to query whether the voice control + // is turned on or off. It is likely at least one of the assitive + // technologies is turned on if this method is called. If we do + // not catch it in notification center, we will catch it here. + // + // TODO(chunhtai): Remove this workaround once iOS provides an + // API to query whether voice control is enabled. + // https://github.com/flutter/flutter/issues/76808. + [self.delegate flutterViewAccessibilityDidCall]; + return NO; +} + +// Enables keyboard-based navigation when the user turns on +// full keyboard access (FKA), using existing accessibility information. +// +// iOS does not provide any API for monitoring or querying whether FKA is on, +// but it does call isAccessibilityElement if FKA is on, +// so the isAccessibilityElement implementation above will be called +// when the view appears and the accessibility information will most likely +// be available by the time the user starts to interact with the app using FKA. +// +// See SemanticsObject+UIFocusSystem.mm for more details. +- (NSArray>*)focusItemsInRect:(CGRect)rect { + NSObject* rootAccessibilityElement = + [self.accessibilityElements count] > 0 ? self.accessibilityElements[0] : nil; + return [rootAccessibilityElement isKindOfClass:[SemanticsObjectContainer class]] + ? @[ [rootAccessibilityElement accessibilityElementAtIndex:0] ] + : nil; +} + +- (NSArray>*)preferredFocusEnvironments { + // Occasionally we add subviews to FlutterView (text fields for example). + // These views shouldn't be directly visible to the iOS focus engine, instead + // the focus engine should only interact with the designated focus items + // (SemanticsObjects). + return nil; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm new file mode 100644 index 0000000000000000000000000000000000000000..22cd3061a38cc5e44309900bb489593100bef3cf --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm @@ -0,0 +1,2712 @@ +// 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. + +#define FML_USED_ON_EMBEDDER + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h" + +#import +#include + +#include "flutter/common/constants.h" +#include "flutter/fml/memory/weak_ptr.h" +#include "flutter/fml/message_loop.h" +#include "flutter/fml/platform/darwin/platform_version.h" +#include "flutter/runtime/ptrace_check.h" +#include "flutter/shell/common/thread_host.h" +#import "flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponder.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyPrimaryResponder.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPlugin.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterSharedApplication.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/UIViewController+FlutterScreenAndSceneIfLoaded.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/platform_message_response_darwin.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.h" +#import "flutter/shell/platform/darwin/ios/platform_view_ios.h" +#import "flutter/shell/platform/embedder/embedder.h" +#import "flutter/third_party/spring_animation/spring_animation.h" + +FLUTTER_ASSERT_ARC + +static constexpr int kMicrosecondsPerSecond = 1000 * 1000; +static constexpr CGFloat kScrollViewContentSize = 2.0; + +static NSString* const kFlutterRestorationStateAppData = @"FlutterRestorationStateAppData"; + +NSNotificationName const FlutterSemanticsUpdateNotification = @"FlutterSemanticsUpdate"; +NSNotificationName const FlutterViewControllerWillDealloc = @"FlutterViewControllerWillDealloc"; +NSNotificationName const FlutterViewControllerHideHomeIndicator = + @"FlutterViewControllerHideHomeIndicator"; +NSNotificationName const FlutterViewControllerShowHomeIndicator = + @"FlutterViewControllerShowHomeIndicator"; + +// Struct holding data to help adapt system mouse/trackpad events to embedder events. +typedef struct MouseState { + // Current coordinate of the mouse cursor in physical device pixels. + CGPoint location = CGPointZero; + + // Last reported translation for an in-flight pan gesture in physical device pixels. + CGPoint last_translation = CGPointZero; +} MouseState; + +// This is left a FlutterBinaryMessenger privately for now to give people a chance to notice the +// change. Unfortunately unless you have Werror turned on, incompatible pointers as arguments are +// just a warning. +@interface FlutterViewController () +// TODO(dkwingsmt): Make the view ID property public once the iOS shell +// supports multiple views. +// https://github.com/flutter/flutter/issues/138168 +@property(nonatomic, readonly) int64_t viewIdentifier; + +// We keep a separate reference to this and create it ahead of time because we want to be able to +// set up a shell along with its platform view before the view has to appear. +@property(nonatomic, strong) FlutterView* flutterView; +@property(nonatomic, strong) void (^flutterViewRenderedCallback)(void); + +@property(nonatomic, assign) UIInterfaceOrientationMask orientationPreferences; +@property(nonatomic, assign) UIStatusBarStyle statusBarStyle; +@property(nonatomic, assign) BOOL initialized; +@property(nonatomic, assign) BOOL engineNeedsLaunch; + +@property(nonatomic, readwrite, getter=isDisplayingFlutterUI) BOOL displayingFlutterUI; +@property(nonatomic, assign) BOOL isHomeIndicatorHidden; +@property(nonatomic, assign) BOOL isPresentingViewControllerAnimating; + +// Internal state backing override of UIView.prefersStatusBarHidden. +@property(nonatomic, assign) BOOL flutterPrefersStatusBarHidden; + +@property(nonatomic, strong) NSMutableSet* ongoingTouches; +// This scroll view is a workaround to accommodate iOS 13 and higher. There isn't a way to get +// touches on the status bar to trigger scrolling to the top of a scroll view. We place a +// UIScrollView with height zero and a content offset so we can get those events. See also: +// https://github.com/flutter/flutter/issues/35050 +@property(nonatomic, strong) UIScrollView* scrollView; +@property(nonatomic, strong) UIView* keyboardAnimationView; +@property(nonatomic, strong) SpringAnimation* keyboardSpringAnimation; + +/** + * Whether we should ignore viewport metrics updates during rotation transition. + */ +@property(nonatomic, assign) BOOL shouldIgnoreViewportMetricsUpdatesDuringRotation; + +/** + * Keyboard animation properties + */ +@property(nonatomic, assign) CGFloat targetViewInsetBottom; +@property(nonatomic, assign) CGFloat originalViewInsetBottom; +@property(nonatomic, strong) VSyncClient* keyboardAnimationVSyncClient; +@property(nonatomic, assign) BOOL keyboardAnimationIsShowing; +@property(nonatomic, assign) fml::TimePoint keyboardAnimationStartTime; +@property(nonatomic, assign) BOOL isKeyboardInOrTransitioningFromBackground; + +/// Timestamp after which a scroll inertia cancel event should be inferred. +@property(nonatomic, assign) NSTimeInterval scrollInertiaEventStartline; + +/// When an iOS app is running in emulation on an Apple Silicon Mac, trackpad input goes through +/// a translation layer, and events are not received with precise deltas. Due to this, we can't +/// rely on checking for a stationary trackpad event. Fortunately, AppKit will send an event of +/// type UIEventTypeScroll following a scroll when inertia should stop. This field is needed to +/// estimate if such an event represents the natural end of scrolling inertia or a user-initiated +/// cancellation. +@property(nonatomic, assign) NSTimeInterval scrollInertiaEventAppKitDeadline; + +/// VSyncClient for touch events delivery frame rate correction. +/// +/// On promotion devices(eg: iPhone13 Pro), the delivery frame rate of touch events is 60HZ +/// but the frame rate of rendering is 120HZ, which is different and will leads jitter and laggy. +/// With this VSyncClient, it can correct the delivery frame rate of touch events to let it keep +/// the same with frame rate of rendering. +@property(nonatomic, strong) VSyncClient* touchRateCorrectionVSyncClient; + +/* + * Mouse and trackpad gesture recognizers + */ +// Mouse and trackpad hover +@property(nonatomic, strong) + UIHoverGestureRecognizer* hoverGestureRecognizer API_AVAILABLE(ios(13.4)); +// Mouse wheel scrolling +@property(nonatomic, strong) + UIPanGestureRecognizer* discreteScrollingPanGestureRecognizer API_AVAILABLE(ios(13.4)); +// Trackpad and Magic Mouse scrolling +@property(nonatomic, strong) + UIPanGestureRecognizer* continuousScrollingPanGestureRecognizer API_AVAILABLE(ios(13.4)); +// Trackpad pinching +@property(nonatomic, strong) + UIPinchGestureRecognizer* pinchGestureRecognizer API_AVAILABLE(ios(13.4)); +// Trackpad rotating +@property(nonatomic, strong) + UIRotationGestureRecognizer* rotationGestureRecognizer API_AVAILABLE(ios(13.4)); + +/// Creates and registers plugins used by this view controller. +- (void)addInternalPlugins; +- (void)deregisterNotifications; + +/// Called when the first frame has been rendered. Invokes any registered first-frame callback. +- (void)onFirstFrameRendered; + +/// Handles updating viewport metrics on keyboard animation. +- (void)handleKeyboardAnimationCallbackWithTargetTime:(fml::TimePoint)targetTime; +@end + +@implementation FlutterViewController { + flutter::ViewportMetrics _viewportMetrics; + MouseState _mouseState; +} + +// Synthesize properties with an overridden getter/setter. +@synthesize viewOpaque = _viewOpaque; +@synthesize displayingFlutterUI = _displayingFlutterUI; + +// TODO(dkwingsmt): https://github.com/flutter/flutter/issues/138168 +// No backing ivar is currently required; when multiple views are supported, we'll need to +// synthesize the ivar and store the view identifier. +@dynamic viewIdentifier; + +#pragma mark - Manage and override all designated initializers + +- (instancetype)initWithEngine:(FlutterEngine*)engine + nibName:(nullable NSString*)nibName + bundle:(nullable NSBundle*)nibBundle { + FML_CHECK(engine) << "initWithEngine:nibName:bundle: must be called with non-nil engine"; + self = [super initWithNibName:nibName bundle:nibBundle]; + if (self) { + _viewOpaque = YES; + if (engine.viewController) { + FML_LOG(ERROR) << "The supplied FlutterEngine " << [[engine description] UTF8String] + << " is already used with FlutterViewController instance " + << [[engine.viewController description] UTF8String] + << ". One instance of the FlutterEngine can only be attached to one " + "FlutterViewController at a time. Set FlutterEngine.viewController " + "to nil before attaching it to another FlutterViewController."; + } + _engine = engine; + _engineNeedsLaunch = NO; + _flutterView = [[FlutterView alloc] initWithDelegate:_engine + opaque:self.isViewOpaque + enableWideGamut:engine.project.isWideGamutEnabled]; + _ongoingTouches = [[NSMutableSet alloc] init]; + + // TODO(cbracken): https://github.com/flutter/flutter/issues/157140 + // Eliminate method calls in initializers and dealloc. + [self performCommonViewControllerInitialization]; + [engine setViewController:self]; + } + + return self; +} + +- (instancetype)initWithProject:(FlutterDartProject*)project + nibName:(NSString*)nibName + bundle:(NSBundle*)nibBundle { + self = [super initWithNibName:nibName bundle:nibBundle]; + if (self) { + // TODO(cbracken): https://github.com/flutter/flutter/issues/157140 + // Eliminate method calls in initializers and dealloc. + [self sharedSetupWithProject:project initialRoute:nil]; + } + + return self; +} + +- (instancetype)initWithProject:(FlutterDartProject*)project + initialRoute:(NSString*)initialRoute + nibName:(NSString*)nibName + bundle:(NSBundle*)nibBundle { + self = [super initWithNibName:nibName bundle:nibBundle]; + if (self) { + // TODO(cbracken): https://github.com/flutter/flutter/issues/157140 + // Eliminate method calls in initializers and dealloc. + [self sharedSetupWithProject:project initialRoute:initialRoute]; + } + + return self; +} + +- (instancetype)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil { + return [self initWithProject:nil nibName:nil bundle:nil]; +} + +- (instancetype)initWithCoder:(NSCoder*)aDecoder { + self = [super initWithCoder:aDecoder]; + return self; +} + +- (void)awakeFromNib { + [super awakeFromNib]; + if (!self.engine) { + [self sharedSetupWithProject:nil initialRoute:nil]; + } +} + +- (instancetype)init { + return [self initWithProject:nil nibName:nil bundle:nil]; +} + +- (void)sharedSetupWithProject:(nullable FlutterDartProject*)project + initialRoute:(nullable NSString*)initialRoute { + // Need the project to get settings for the view. Initializing it here means + // the Engine class won't initialize it later. + if (!project) { + project = [[FlutterDartProject alloc] init]; + } + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"io.flutter" + project:project + allowHeadlessExecution:self.engineAllowHeadlessExecution + restorationEnabled:self.restorationIdentifier != nil]; + if (!engine) { + return; + } + + _viewOpaque = YES; + _engine = engine; + _flutterView = [[FlutterView alloc] initWithDelegate:_engine + opaque:_viewOpaque + enableWideGamut:project.isWideGamutEnabled]; + [_engine createShell:nil libraryURI:nil initialRoute:initialRoute]; + _engineNeedsLaunch = YES; + _ongoingTouches = [[NSMutableSet alloc] init]; + + // TODO(cbracken): https://github.com/flutter/flutter/issues/157140 + // Eliminate method calls in initializers and dealloc. + [self loadDefaultSplashScreenView]; + [self performCommonViewControllerInitialization]; +} + +- (BOOL)isViewOpaque { + return _viewOpaque; +} + +- (void)setViewOpaque:(BOOL)value { + _viewOpaque = value; + if (self.flutterView.layer.opaque != value) { + self.flutterView.layer.opaque = value; + [self.flutterView.layer setNeedsLayout]; + } +} + +#pragma mark - Common view controller initialization tasks + +- (void)performCommonViewControllerInitialization { + if (_initialized) { + return; + } + + _initialized = YES; + _orientationPreferences = UIInterfaceOrientationMaskAll; + _statusBarStyle = UIStatusBarStyleDefault; + + // TODO(cbracken): https://github.com/flutter/flutter/issues/157140 + // Eliminate method calls in initializers and dealloc. + [self setUpNotificationCenterObservers]; +} + +- (void)setUpNotificationCenterObservers { + NSNotificationCenter* center = [NSNotificationCenter defaultCenter]; + [center addObserver:self + selector:@selector(onOrientationPreferencesUpdated:) + name:@(flutter::kOrientationUpdateNotificationName) + object:nil]; + + [center addObserver:self + selector:@selector(onPreferredStatusBarStyleUpdated:) + name:@(flutter::kOverlayStyleUpdateNotificationName) + object:nil]; + + if (FlutterSharedApplication.isAvailable) { + [self setUpApplicationLifecycleNotifications:center]; + } else { + if (@available(iOS 13.0, *)) { + [self setUpSceneLifecycleNotifications:center]; + } else { + [self setUpApplicationLifecycleNotifications:center]; + } + } + + [center addObserver:self + selector:@selector(keyboardWillChangeFrame:) + name:UIKeyboardWillChangeFrameNotification + object:nil]; + + [center addObserver:self + selector:@selector(keyboardWillShowNotification:) + name:UIKeyboardWillShowNotification + object:nil]; + + [center addObserver:self + selector:@selector(keyboardWillBeHidden:) + name:UIKeyboardWillHideNotification + object:nil]; + + [center addObserver:self + selector:@selector(onAccessibilityStatusChanged:) + name:UIAccessibilityVoiceOverStatusDidChangeNotification + object:nil]; + + [center addObserver:self + selector:@selector(onAccessibilityStatusChanged:) + name:UIAccessibilitySwitchControlStatusDidChangeNotification + object:nil]; + + [center addObserver:self + selector:@selector(onAccessibilityStatusChanged:) + name:UIAccessibilitySpeakScreenStatusDidChangeNotification + object:nil]; + + [center addObserver:self + selector:@selector(onAccessibilityStatusChanged:) + name:UIAccessibilityInvertColorsStatusDidChangeNotification + object:nil]; + + [center addObserver:self + selector:@selector(onAccessibilityStatusChanged:) + name:UIAccessibilityReduceMotionStatusDidChangeNotification + object:nil]; + + [center addObserver:self + selector:@selector(onAccessibilityStatusChanged:) + name:UIAccessibilityBoldTextStatusDidChangeNotification + object:nil]; + + [center addObserver:self + selector:@selector(onAccessibilityStatusChanged:) + name:UIAccessibilityDarkerSystemColorsStatusDidChangeNotification + object:nil]; + + if (@available(iOS 13.0, *)) { + [center addObserver:self + selector:@selector(onAccessibilityStatusChanged:) + name:UIAccessibilityOnOffSwitchLabelsDidChangeNotification + object:nil]; + } + + [center addObserver:self + selector:@selector(onUserSettingsChanged:) + name:UIContentSizeCategoryDidChangeNotification + object:nil]; + + [center addObserver:self + selector:@selector(onHideHomeIndicatorNotification:) + name:FlutterViewControllerHideHomeIndicator + object:nil]; + + [center addObserver:self + selector:@selector(onShowHomeIndicatorNotification:) + name:FlutterViewControllerShowHomeIndicator + object:nil]; +} + +- (void)setUpSceneLifecycleNotifications:(NSNotificationCenter*)center API_AVAILABLE(ios(13.0)) { + [center addObserver:self + selector:@selector(sceneBecameActive:) + name:UISceneDidActivateNotification + object:nil]; + + [center addObserver:self + selector:@selector(sceneWillResignActive:) + name:UISceneWillDeactivateNotification + object:nil]; + + [center addObserver:self + selector:@selector(sceneWillDisconnect:) + name:UISceneDidDisconnectNotification + object:nil]; + + [center addObserver:self + selector:@selector(sceneDidEnterBackground:) + name:UISceneDidEnterBackgroundNotification + object:nil]; + + [center addObserver:self + selector:@selector(sceneWillEnterForeground:) + name:UISceneWillEnterForegroundNotification + object:nil]; +} + +- (void)setUpApplicationLifecycleNotifications:(NSNotificationCenter*)center { + [center addObserver:self + selector:@selector(applicationBecameActive:) + name:UIApplicationDidBecomeActiveNotification + object:nil]; + + [center addObserver:self + selector:@selector(applicationWillResignActive:) + name:UIApplicationWillResignActiveNotification + object:nil]; + + [center addObserver:self + selector:@selector(applicationWillTerminate:) + name:UIApplicationWillTerminateNotification + object:nil]; + + [center addObserver:self + selector:@selector(applicationDidEnterBackground:) + name:UIApplicationDidEnterBackgroundNotification + object:nil]; + + [center addObserver:self + selector:@selector(applicationWillEnterForeground:) + name:UIApplicationWillEnterForegroundNotification + object:nil]; +} + +- (void)setInitialRoute:(NSString*)route { + [self.engine.navigationChannel invokeMethod:@"setInitialRoute" arguments:route]; +} + +- (void)popRoute { + [self.engine.navigationChannel invokeMethod:@"popRoute" arguments:nil]; +} + +- (void)pushRoute:(NSString*)route { + [self.engine.navigationChannel invokeMethod:@"pushRoute" arguments:route]; +} + +#pragma mark - Loading the view + +static UIView* GetViewOrPlaceholder(UIView* existing_view) { + if (existing_view) { + return existing_view; + } + + auto placeholder = [[UIView alloc] init]; + + placeholder.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; + if (@available(iOS 13.0, *)) { + placeholder.backgroundColor = UIColor.systemBackgroundColor; + } else { + placeholder.backgroundColor = UIColor.whiteColor; + } + placeholder.autoresizesSubviews = YES; + + // Only add the label when we know we have failed to enable tracing (and it was necessary). + // Otherwise, a spurious warning will be shown in cases where an engine cannot be initialized for + // other reasons. + if (flutter::GetTracingResult() == flutter::TracingResult::kDisabled) { + auto messageLabel = [[UILabel alloc] init]; + messageLabel.numberOfLines = 0u; + messageLabel.textAlignment = NSTextAlignmentCenter; + messageLabel.autoresizingMask = + UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; + messageLabel.text = + @"In iOS 14+, debug mode Flutter apps can only be launched from Flutter tooling, " + @"IDEs with Flutter plugins or from Xcode.\n\nAlternatively, build in profile or release " + @"modes to enable launching from the home screen."; + [placeholder addSubview:messageLabel]; + } + + return placeholder; +} + +- (void)loadView { + self.view = GetViewOrPlaceholder(self.flutterView); + self.view.multipleTouchEnabled = YES; + self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; + + [self installSplashScreenViewIfNecessary]; + + // Create and set up the scroll view. + UIScrollView* scrollView = [[UIScrollView alloc] init]; + scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth; + // The color shouldn't matter since it is offscreen. + scrollView.backgroundColor = UIColor.whiteColor; + scrollView.delegate = self; + // This is an arbitrary small size. + scrollView.contentSize = CGSizeMake(kScrollViewContentSize, kScrollViewContentSize); + // This is an arbitrary offset that is not CGPointZero. + scrollView.contentOffset = CGPointMake(kScrollViewContentSize, kScrollViewContentSize); + + [self.view addSubview:scrollView]; + self.scrollView = scrollView; +} + +- (flutter::PointerData)generatePointerDataForFake { + flutter::PointerData pointer_data; + pointer_data.Clear(); + pointer_data.kind = flutter::PointerData::DeviceKind::kTouch; + // `UITouch.timestamp` is defined as seconds since system startup. Synthesized events can get this + // time with `NSProcessInfo.systemUptime`. See + // https://developer.apple.com/documentation/uikit/uitouch/1618144-timestamp?language=objc + pointer_data.time_stamp = [[NSProcessInfo processInfo] systemUptime] * kMicrosecondsPerSecond; + return pointer_data; +} + +static void SendFakeTouchEvent(UIScreen* screen, + FlutterEngine* engine, + CGPoint location, + flutter::PointerData::Change change) { + const CGFloat scale = screen.scale; + flutter::PointerData pointer_data = [[engine viewController] generatePointerDataForFake]; + pointer_data.physical_x = location.x * scale; + pointer_data.physical_y = location.y * scale; + auto packet = std::make_unique(/*count=*/1); + pointer_data.change = change; + packet->SetPointerData(0, pointer_data); + [engine dispatchPointerDataPacket:std::move(packet)]; +} + +- (BOOL)scrollViewShouldScrollToTop:(UIScrollView*)scrollView { + if (!self.engine) { + return NO; + } + CGPoint statusBarPoint = CGPointZero; + UIScreen* screen = self.flutterScreenIfViewLoaded; + if (screen) { + SendFakeTouchEvent(screen, self.engine, statusBarPoint, flutter::PointerData::Change::kDown); + SendFakeTouchEvent(screen, self.engine, statusBarPoint, flutter::PointerData::Change::kUp); + } + return NO; +} + +#pragma mark - Managing launch views + +- (void)installSplashScreenViewIfNecessary { + // Show the launch screen view again on top of the FlutterView if available. + // This launch screen view will be removed once the first Flutter frame is rendered. + if (self.splashScreenView && (self.isBeingPresented || self.isMovingToParentViewController)) { + [self.splashScreenView removeFromSuperview]; + self.splashScreenView = nil; + return; + } + + // Use the property getter to initialize the default value. + UIView* splashScreenView = self.splashScreenView; + if (splashScreenView == nil) { + return; + } + splashScreenView.frame = self.view.bounds; + [self.view addSubview:splashScreenView]; +} + ++ (BOOL)automaticallyNotifiesObserversOfDisplayingFlutterUI { + return NO; +} + +- (void)setDisplayingFlutterUI:(BOOL)displayingFlutterUI { + if (_displayingFlutterUI != displayingFlutterUI) { + if (displayingFlutterUI == YES) { + if (!self.viewIfLoaded.window) { + return; + } + } + [self willChangeValueForKey:@"displayingFlutterUI"]; + _displayingFlutterUI = displayingFlutterUI; + [self didChangeValueForKey:@"displayingFlutterUI"]; + } +} + +- (void)callViewRenderedCallback { + self.displayingFlutterUI = YES; + if (self.flutterViewRenderedCallback) { + self.flutterViewRenderedCallback(); + self.flutterViewRenderedCallback = nil; + } +} + +- (void)removeSplashScreenWithCompletion:(dispatch_block_t _Nullable)onComplete { + NSAssert(self.splashScreenView, @"The splash screen view must not be nil"); + UIView* splashScreen = self.splashScreenView; + // setSplashScreenView calls this method. Assign directly to ivar to avoid an infinite loop. + _splashScreenView = nil; + [UIView animateWithDuration:0.2 + animations:^{ + splashScreen.alpha = 0; + } + completion:^(BOOL finished) { + [splashScreen removeFromSuperview]; + if (onComplete) { + onComplete(); + } + }]; +} + +- (void)onFirstFrameRendered { + if (self.splashScreenView) { + __weak FlutterViewController* weakSelf = self; + [self removeSplashScreenWithCompletion:^{ + [weakSelf callViewRenderedCallback]; + }]; + } else { + [self callViewRenderedCallback]; + } +} + +- (void)installFirstFrameCallback { + if (!self.engine) { + return; + } + __weak FlutterViewController* weakSelf = self; + [self.engine installFirstFrameCallback:^{ + [weakSelf onFirstFrameRendered]; + }]; +} + +#pragma mark - Properties + +- (int64_t)viewIdentifier { + // TODO(dkwingsmt): Fill the view ID property with the correct value once the + // iOS shell supports multiple views. + return flutter::kFlutterImplicitViewId; +} + +- (BOOL)loadDefaultSplashScreenView { + NSString* launchscreenName = + [[[NSBundle mainBundle] infoDictionary] objectForKey:@"UILaunchStoryboardName"]; + if (launchscreenName == nil) { + return NO; + } + UIView* splashView = [self splashScreenFromStoryboard:launchscreenName]; + if (!splashView) { + splashView = [self splashScreenFromXib:launchscreenName]; + } + if (!splashView) { + return NO; + } + self.splashScreenView = splashView; + return YES; +} + +- (UIView*)splashScreenFromStoryboard:(NSString*)name { + UIStoryboard* storyboard = nil; + @try { + storyboard = [UIStoryboard storyboardWithName:name bundle:nil]; + } @catch (NSException* exception) { + return nil; + } + if (storyboard) { + UIViewController* splashScreenViewController = [storyboard instantiateInitialViewController]; + return splashScreenViewController.view; + } + return nil; +} + +- (UIView*)splashScreenFromXib:(NSString*)name { + NSArray* objects = nil; + @try { + objects = [[NSBundle mainBundle] loadNibNamed:name owner:self options:nil]; + } @catch (NSException* exception) { + return nil; + } + if ([objects count] != 0) { + UIView* view = [objects objectAtIndex:0]; + return view; + } + return nil; +} + +- (void)setSplashScreenView:(UIView*)view { + if (view == _splashScreenView) { + return; + } + + // Special case: user wants to remove the splash screen view. + if (!view) { + if (_splashScreenView) { + [self removeSplashScreenWithCompletion:nil]; + } + return; + } + + _splashScreenView = view; + _splashScreenView.autoresizingMask = + UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; +} + +- (void)setFlutterViewDidRenderCallback:(void (^)(void))callback { + _flutterViewRenderedCallback = callback; +} + +- (UISceneActivationState)activationState { + return self.flutterWindowSceneIfViewLoaded.activationState; +} + +- (BOOL)stateIsActive { + BOOL isActive = YES; + + UIApplication* flutterApplication = FlutterSharedApplication.application; + if (flutterApplication) { + isActive = [self isApplicationStateMatching:UIApplicationStateActive + withApplication:flutterApplication]; + } else if (@available(iOS 13.0, *)) { + isActive = [self isSceneStateMatching:UISceneActivationStateForegroundActive]; + } + return isActive; +} + +- (BOOL)stateIsBackground { + // [UIApplication sharedApplication API is not available for app extension. + // Assume the app is not in the background if we're unable to get the state. + BOOL isBackground = NO; + + UIApplication* flutterApplication = FlutterSharedApplication.application; + if (flutterApplication) { + isBackground = [self isApplicationStateMatching:UIApplicationStateBackground + withApplication:flutterApplication]; + } else if (@available(iOS 13.0, *)) { + isBackground = [self isSceneStateMatching:UISceneActivationStateBackground]; + } + return isBackground; +} + +- (BOOL)isApplicationStateMatching:(UIApplicationState)match + withApplication:(UIApplication*)application { + switch (application.applicationState) { + case UIApplicationStateActive: + case UIApplicationStateInactive: + case UIApplicationStateBackground: + return application.applicationState == match; + } +} + +- (BOOL)isSceneStateMatching:(UISceneActivationState)match API_AVAILABLE(ios(13.0)) { + switch (self.activationState) { + case UISceneActivationStateForegroundActive: + case UISceneActivationStateUnattached: + case UISceneActivationStateForegroundInactive: + case UISceneActivationStateBackground: + return self.activationState == match; + } +} + +#pragma mark - Surface creation and teardown updates + +- (void)surfaceUpdated:(BOOL)appeared { + if (!self.engine) { + return; + } + + // NotifyCreated/NotifyDestroyed are synchronous and require hops between the UI and raster + // thread. + if (appeared) { + [self installFirstFrameCallback]; + self.platformViewsController.flutterView = self.flutterView; + self.platformViewsController.flutterViewController = self; + [self.engine notifyViewCreated]; + } else { + self.displayingFlutterUI = NO; + [self.engine notifyViewDestroyed]; + self.platformViewsController.flutterView = nil; + self.platformViewsController.flutterViewController = nil; + } +} + +#pragma mark - UIViewController lifecycle notifications + +- (void)viewDidLoad { + TRACE_EVENT0("flutter", "viewDidLoad"); + + if (self.engine && self.engineNeedsLaunch) { + [self.engine launchEngine:nil libraryURI:nil entrypointArgs:nil]; + [self.engine setViewController:self]; + self.engineNeedsLaunch = NO; + } else if (self.engine.viewController == self) { + [self.engine attachView]; + } + + // Register internal plugins. + [self addInternalPlugins]; + + // Create a vsync client to correct delivery frame rate of touch events if needed. + [self createTouchRateCorrectionVSyncClientIfNeeded]; + + if (@available(iOS 13.4, *)) { + _hoverGestureRecognizer = + [[UIHoverGestureRecognizer alloc] initWithTarget:self action:@selector(hoverEvent:)]; + _hoverGestureRecognizer.delegate = self; + [self.flutterView addGestureRecognizer:_hoverGestureRecognizer]; + + _discreteScrollingPanGestureRecognizer = + [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(discreteScrollEvent:)]; + _discreteScrollingPanGestureRecognizer.allowedScrollTypesMask = UIScrollTypeMaskDiscrete; + // Disallowing all touch types. If touch events are allowed here, touches to the screen will be + // consumed by the UIGestureRecognizer instead of being passed through to flutter via + // touchesBegan. Trackpad and mouse scrolls are sent by the platform as scroll events rather + // than touch events, so they will still be received. + _discreteScrollingPanGestureRecognizer.allowedTouchTypes = @[]; + _discreteScrollingPanGestureRecognizer.delegate = self; + [self.flutterView addGestureRecognizer:_discreteScrollingPanGestureRecognizer]; + _continuousScrollingPanGestureRecognizer = + [[UIPanGestureRecognizer alloc] initWithTarget:self + action:@selector(continuousScrollEvent:)]; + _continuousScrollingPanGestureRecognizer.allowedScrollTypesMask = UIScrollTypeMaskContinuous; + _continuousScrollingPanGestureRecognizer.allowedTouchTypes = @[]; + _continuousScrollingPanGestureRecognizer.delegate = self; + [self.flutterView addGestureRecognizer:_continuousScrollingPanGestureRecognizer]; + _pinchGestureRecognizer = + [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchEvent:)]; + _pinchGestureRecognizer.allowedTouchTypes = @[]; + _pinchGestureRecognizer.delegate = self; + [self.flutterView addGestureRecognizer:_pinchGestureRecognizer]; + _rotationGestureRecognizer = [[UIRotationGestureRecognizer alloc] init]; + _rotationGestureRecognizer.allowedTouchTypes = @[]; + _rotationGestureRecognizer.delegate = self; + [self.flutterView addGestureRecognizer:_rotationGestureRecognizer]; + } + + [super viewDidLoad]; +} + +- (void)addInternalPlugins { + self.keyboardManager = [[FlutterKeyboardManager alloc] init]; + __weak FlutterViewController* weakSelf = self; + FlutterSendKeyEvent sendEvent = + ^(const FlutterKeyEvent& event, FlutterKeyEventCallback callback, void* userData) { + [weakSelf.engine sendKeyEvent:event callback:callback userData:userData]; + }; + [self.keyboardManager + addPrimaryResponder:[[FlutterEmbedderKeyResponder alloc] initWithSendEvent:sendEvent]]; + FlutterChannelKeyResponder* responder = + [[FlutterChannelKeyResponder alloc] initWithChannel:self.engine.keyEventChannel]; + [self.keyboardManager addPrimaryResponder:responder]; + FlutterTextInputPlugin* textInputPlugin = self.engine.textInputPlugin; + if (textInputPlugin != nil) { + [self.keyboardManager addSecondaryResponder:textInputPlugin]; + } + if (self.engine.viewController == self) { + [textInputPlugin setUpIndirectScribbleInteraction:self]; + } +} + +- (void)removeInternalPlugins { + self.keyboardManager = nil; +} + +- (void)viewWillAppear:(BOOL)animated { + TRACE_EVENT0("flutter", "viewWillAppear"); + if (self.engine.viewController == self) { + // Send platform settings to Flutter, e.g., platform brightness. + [self onUserSettingsChanged:nil]; + + // Only recreate surface on subsequent appearances when viewport metrics are known. + // First time surface creation is done on viewDidLayoutSubviews. + if (_viewportMetrics.physical_width) { + [self surfaceUpdated:YES]; + } + [self.engine.lifecycleChannel sendMessage:@"AppLifecycleState.inactive"]; + [self.engine.restorationPlugin markRestorationComplete]; + } + + [super viewWillAppear:animated]; +} + +- (void)viewDidAppear:(BOOL)animated { + TRACE_EVENT0("flutter", "viewDidAppear"); + if (self.engine.viewController == self) { + [self onUserSettingsChanged:nil]; + [self onAccessibilityStatusChanged:nil]; + + if (self.stateIsActive) { + [self.engine.lifecycleChannel sendMessage:@"AppLifecycleState.resumed"]; + } + } + [super viewDidAppear:animated]; +} + +- (void)viewWillDisappear:(BOOL)animated { + TRACE_EVENT0("flutter", "viewWillDisappear"); + if (self.engine.viewController == self) { + [self.engine.lifecycleChannel sendMessage:@"AppLifecycleState.inactive"]; + } + [super viewWillDisappear:animated]; +} + +- (void)viewDidDisappear:(BOOL)animated { + TRACE_EVENT0("flutter", "viewDidDisappear"); + if (self.engine.viewController == self) { + [self invalidateKeyboardAnimationVSyncClient]; + [self ensureViewportMetricsIsCorrect]; + [self surfaceUpdated:NO]; + [self.engine.lifecycleChannel sendMessage:@"AppLifecycleState.paused"]; + [self flushOngoingTouches]; + [self.engine notifyLowMemory]; + } + + [super viewDidDisappear:animated]; +} + +- (void)viewWillTransitionToSize:(CGSize)size + withTransitionCoordinator:(id)coordinator { + [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator]; + + // We delay the viewport metrics update for half of rotation transition duration, to address + // a bug with distorted aspect ratio. + // See: https://github.com/flutter/flutter/issues/16322 + // + // This approach does not fully resolve all distortion problem. But instead, it reduces the + // rotation distortion roughly from 4x to 2x. The most distorted frames occur in the middle + // of the transition when it is rotating the fastest, making it hard to notice. + + NSTimeInterval transitionDuration = coordinator.transitionDuration; + // Do not delay viewport metrics update if zero transition duration. + if (transitionDuration == 0) { + return; + } + + __weak FlutterViewController* weakSelf = self; + _shouldIgnoreViewportMetricsUpdatesDuringRotation = YES; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, + static_cast(transitionDuration / 2.0 * NSEC_PER_SEC)), + dispatch_get_main_queue(), ^{ + FlutterViewController* strongSelf = weakSelf; + if (!strongSelf) { + return; + } + + // `viewWillTransitionToSize` is only called after the previous rotation is + // complete. So there won't be race condition for this flag. + strongSelf.shouldIgnoreViewportMetricsUpdatesDuringRotation = NO; + [strongSelf updateViewportMetricsIfNeeded]; + }); +} + +- (void)flushOngoingTouches { + if (self.engine && self.ongoingTouches.count > 0) { + auto packet = std::make_unique(self.ongoingTouches.count); + size_t pointer_index = 0; + // If the view controller is going away, we want to flush cancel all the ongoing + // touches to the framework so nothing gets orphaned. + for (NSNumber* device in self.ongoingTouches) { + // Create fake PointerData to balance out each previously started one for the framework. + flutter::PointerData pointer_data = [self generatePointerDataForFake]; + + pointer_data.change = flutter::PointerData::Change::kCancel; + pointer_data.device = device.longLongValue; + pointer_data.pointer_identifier = 0; + pointer_data.view_id = self.viewIdentifier; + + // Anything we put here will be arbitrary since there are no touches. + pointer_data.physical_x = 0; + pointer_data.physical_y = 0; + pointer_data.physical_delta_x = 0.0; + pointer_data.physical_delta_y = 0.0; + pointer_data.pressure = 1.0; + pointer_data.pressure_max = 1.0; + + packet->SetPointerData(pointer_index++, pointer_data); + } + + [self.ongoingTouches removeAllObjects]; + [self.engine dispatchPointerDataPacket:std::move(packet)]; + } +} + +- (void)deregisterNotifications { + [[NSNotificationCenter defaultCenter] postNotificationName:FlutterViewControllerWillDealloc + object:self + userInfo:nil]; + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +- (void)dealloc { + // TODO(cbracken): https://github.com/flutter/flutter/issues/157140 + // Eliminate method calls in initializers and dealloc. + [self removeInternalPlugins]; + [self deregisterNotifications]; + + [self invalidateKeyboardAnimationVSyncClient]; + [self invalidateTouchRateCorrectionVSyncClient]; + + // TODO(cbracken): https://github.com/flutter/flutter/issues/156222 + // Ensure all delegates are weak and remove this. + _scrollView.delegate = nil; + _hoverGestureRecognizer.delegate = nil; + _discreteScrollingPanGestureRecognizer.delegate = nil; + _continuousScrollingPanGestureRecognizer.delegate = nil; + _pinchGestureRecognizer.delegate = nil; + _rotationGestureRecognizer.delegate = nil; +} + +#pragma mark - Application lifecycle notifications + +- (void)applicationBecameActive:(NSNotification*)notification { + TRACE_EVENT0("flutter", "applicationBecameActive"); + [self appOrSceneBecameActive]; +} + +- (void)applicationWillResignActive:(NSNotification*)notification { + TRACE_EVENT0("flutter", "applicationWillResignActive"); + [self appOrSceneWillResignActive]; +} + +- (void)applicationWillTerminate:(NSNotification*)notification { + [self appOrSceneWillTerminate]; +} + +- (void)applicationDidEnterBackground:(NSNotification*)notification { + TRACE_EVENT0("flutter", "applicationDidEnterBackground"); + [self appOrSceneDidEnterBackground]; +} + +- (void)applicationWillEnterForeground:(NSNotification*)notification { + TRACE_EVENT0("flutter", "applicationWillEnterForeground"); + [self appOrSceneWillEnterForeground]; +} + +#pragma mark - Scene lifecycle notifications + +- (void)sceneBecameActive:(NSNotification*)notification API_AVAILABLE(ios(13.0)) { + TRACE_EVENT0("flutter", "sceneBecameActive"); + [self appOrSceneBecameActive]; +} + +- (void)sceneWillResignActive:(NSNotification*)notification API_AVAILABLE(ios(13.0)) { + TRACE_EVENT0("flutter", "sceneWillResignActive"); + [self appOrSceneWillResignActive]; +} + +- (void)sceneWillDisconnect:(NSNotification*)notification API_AVAILABLE(ios(13.0)) { + [self appOrSceneWillTerminate]; +} + +- (void)sceneDidEnterBackground:(NSNotification*)notification API_AVAILABLE(ios(13.0)) { + TRACE_EVENT0("flutter", "sceneDidEnterBackground"); + [self appOrSceneDidEnterBackground]; +} + +- (void)sceneWillEnterForeground:(NSNotification*)notification API_AVAILABLE(ios(13.0)) { + TRACE_EVENT0("flutter", "sceneWillEnterForeground"); + [self appOrSceneWillEnterForeground]; +} + +#pragma mark - Lifecycle shared + +- (void)appOrSceneBecameActive { + self.isKeyboardInOrTransitioningFromBackground = NO; + if (_viewportMetrics.physical_width) { + [self surfaceUpdated:YES]; + } + [self performSelector:@selector(goToApplicationLifecycle:) + withObject:@"AppLifecycleState.resumed" + afterDelay:0.0f]; +} + +- (void)appOrSceneWillResignActive { + [NSObject cancelPreviousPerformRequestsWithTarget:self + selector:@selector(goToApplicationLifecycle:) + object:@"AppLifecycleState.resumed"]; + [self goToApplicationLifecycle:@"AppLifecycleState.inactive"]; +} + +- (void)appOrSceneWillTerminate { + [self goToApplicationLifecycle:@"AppLifecycleState.detached"]; + [self.engine destroyContext]; +} + +- (void)appOrSceneDidEnterBackground { + self.isKeyboardInOrTransitioningFromBackground = YES; + [self surfaceUpdated:NO]; + [self goToApplicationLifecycle:@"AppLifecycleState.paused"]; +} + +- (void)appOrSceneWillEnterForeground { + [self goToApplicationLifecycle:@"AppLifecycleState.inactive"]; +} + +// Make this transition only while this current view controller is visible. +- (void)goToApplicationLifecycle:(nonnull NSString*)state { + // Accessing self.view will create the view. Instead use viewIfLoaded + // to check whether the view is attached to window. + if (self.viewIfLoaded.window) { + [self.engine.lifecycleChannel sendMessage:state]; + } +} + +#pragma mark - Touch event handling + +static flutter::PointerData::Change PointerDataChangeFromUITouchPhase(UITouchPhase phase) { + switch (phase) { + case UITouchPhaseBegan: + return flutter::PointerData::Change::kDown; + case UITouchPhaseMoved: + case UITouchPhaseStationary: + // There is no EVENT_TYPE_POINTER_STATIONARY. So we just pass a move type + // with the same coordinates + return flutter::PointerData::Change::kMove; + case UITouchPhaseEnded: + return flutter::PointerData::Change::kUp; + case UITouchPhaseCancelled: + return flutter::PointerData::Change::kCancel; + default: + // TODO(53695): Handle the `UITouchPhaseRegion`... enum values. + FML_DLOG(INFO) << "Unhandled touch phase: " << phase; + break; + } + + return flutter::PointerData::Change::kCancel; +} + +static flutter::PointerData::DeviceKind DeviceKindFromTouchType(UITouch* touch) { + switch (touch.type) { + case UITouchTypeDirect: + case UITouchTypeIndirect: + return flutter::PointerData::DeviceKind::kTouch; + case UITouchTypeStylus: + return flutter::PointerData::DeviceKind::kStylus; + case UITouchTypeIndirectPointer: + return flutter::PointerData::DeviceKind::kMouse; + default: + FML_DLOG(INFO) << "Unhandled touch type: " << touch.type; + break; + } + + return flutter::PointerData::DeviceKind::kTouch; +} + +// Dispatches the UITouches to the engine. Usually, the type of change of the touch is determined +// from the UITouch's phase. However, FlutterAppDelegate fakes touches to ensure that touch events +// in the status bar area are available to framework code. The change type (optional) of the faked +// touch is specified in the second argument. +- (void)dispatchTouches:(NSSet*)touches + pointerDataChangeOverride:(flutter::PointerData::Change*)overridden_change + event:(UIEvent*)event { + if (!self.engine) { + return; + } + + // If the UIApplicationSupportsIndirectInputEvents in Info.plist returns YES, then the platform + // dispatches indirect pointer touches (trackpad clicks) as UITouch with a type of + // UITouchTypeIndirectPointer and different identifiers for each click. They are translated into + // Flutter pointer events with type of kMouse and different device IDs. These devices must be + // terminated with kRemove events when the touches end, otherwise they will keep triggering hover + // events. + // + // If the UIApplicationSupportsIndirectInputEvents in Info.plist returns NO, then the platform + // dispatches indirect pointer touches (trackpad clicks) as UITouch with a type of + // UITouchTypeIndirectPointer and different identifiers for each click. They are translated into + // Flutter pointer events with type of kTouch and different device IDs. Removing these devices is + // neither necessary nor harmful. + // + // Therefore Flutter always removes these devices. The touches_to_remove_count tracks how many + // remove events are needed in this group of touches to properly allocate space for the packet. + // The remove event of a touch is synthesized immediately after its normal event. + // + // See also: + // https://developer.apple.com/documentation/uikit/pointer_interactions?language=objc + // https://developer.apple.com/documentation/bundleresources/information_property_list/uiapplicationsupportsindirectinputevents?language=objc + NSUInteger touches_to_remove_count = 0; + for (UITouch* touch in touches) { + if (touch.phase == UITouchPhaseEnded || touch.phase == UITouchPhaseCancelled) { + touches_to_remove_count++; + } + } + + // Activate or pause the correction of delivery frame rate of touch events. + [self triggerTouchRateCorrectionIfNeeded:touches]; + + const CGFloat scale = self.flutterScreenIfViewLoaded.scale; + auto packet = + std::make_unique(touches.count + touches_to_remove_count); + + size_t pointer_index = 0; + + for (UITouch* touch in touches) { + CGPoint windowCoordinates = [touch locationInView:self.view]; + + flutter::PointerData pointer_data; + pointer_data.Clear(); + + constexpr int kMicrosecondsPerSecond = 1000 * 1000; + pointer_data.time_stamp = touch.timestamp * kMicrosecondsPerSecond; + + pointer_data.change = overridden_change != nullptr + ? *overridden_change + : PointerDataChangeFromUITouchPhase(touch.phase); + + pointer_data.kind = DeviceKindFromTouchType(touch); + + pointer_data.device = reinterpret_cast(touch); + + pointer_data.view_id = self.viewIdentifier; + + // Pointer will be generated in pointer_data_packet_converter.cc. + pointer_data.pointer_identifier = 0; + + pointer_data.physical_x = windowCoordinates.x * scale; + pointer_data.physical_y = windowCoordinates.y * scale; + + // Delta will be generated in pointer_data_packet_converter.cc. + pointer_data.physical_delta_x = 0.0; + pointer_data.physical_delta_y = 0.0; + + NSNumber* deviceKey = [NSNumber numberWithLongLong:pointer_data.device]; + // Track touches that began and not yet stopped so we can flush them + // if the view controller goes away. + switch (pointer_data.change) { + case flutter::PointerData::Change::kDown: + [self.ongoingTouches addObject:deviceKey]; + break; + case flutter::PointerData::Change::kCancel: + case flutter::PointerData::Change::kUp: + [self.ongoingTouches removeObject:deviceKey]; + break; + case flutter::PointerData::Change::kHover: + case flutter::PointerData::Change::kMove: + // We're only tracking starts and stops. + break; + case flutter::PointerData::Change::kAdd: + case flutter::PointerData::Change::kRemove: + // We don't use kAdd/kRemove. + break; + case flutter::PointerData::Change::kPanZoomStart: + case flutter::PointerData::Change::kPanZoomUpdate: + case flutter::PointerData::Change::kPanZoomEnd: + // We don't send pan/zoom events here + break; + } + + // pressure_min is always 0.0 + pointer_data.pressure = touch.force; + pointer_data.pressure_max = touch.maximumPossibleForce; + pointer_data.radius_major = touch.majorRadius; + pointer_data.radius_min = touch.majorRadius - touch.majorRadiusTolerance; + pointer_data.radius_max = touch.majorRadius + touch.majorRadiusTolerance; + + // iOS Documentation: altitudeAngle + // A value of 0 radians indicates that the stylus is parallel to the surface. The value of + // this property is Pi/2 when the stylus is perpendicular to the surface. + // + // PointerData Documentation: tilt + // The angle of the stylus, in radians in the range: + // 0 <= tilt <= pi/2 + // giving the angle of the axis of the stylus, relative to the axis perpendicular to the input + // surface (thus 0.0 indicates the stylus is orthogonal to the plane of the input surface, + // while pi/2 indicates that the stylus is flat on that surface). + // + // Discussion: + // The ranges are the same. Origins are swapped. + pointer_data.tilt = M_PI_2 - touch.altitudeAngle; + + // iOS Documentation: azimuthAngleInView: + // With the tip of the stylus touching the screen, the value of this property is 0 radians + // when the cap end of the stylus (that is, the end opposite of the tip) points along the + // positive x axis of the device's screen. The azimuth angle increases as the user swings the + // cap end of the stylus in a clockwise direction around the tip. + // + // PointerData Documentation: orientation + // The angle of the stylus, in radians in the range: + // -pi < orientation <= pi + // giving the angle of the axis of the stylus projected onto the input surface, relative to + // the positive y-axis of that surface (thus 0.0 indicates the stylus, if projected onto that + // surface, would go from the contact point vertically up in the positive y-axis direction, pi + // would indicate that the stylus would go down in the negative y-axis direction; pi/4 would + // indicate that the stylus goes up and to the right, -pi/2 would indicate that the stylus + // goes to the left, etc). + // + // Discussion: + // Sweep direction is the same. Phase of M_PI_2. + pointer_data.orientation = [touch azimuthAngleInView:nil] - M_PI_2; + + if (@available(iOS 13.4, *)) { + if (event != nullptr) { + pointer_data.buttons = (((event.buttonMask & UIEventButtonMaskPrimary) > 0) + ? flutter::PointerButtonMouse::kPointerButtonMousePrimary + : 0) | + (((event.buttonMask & UIEventButtonMaskSecondary) > 0) + ? flutter::PointerButtonMouse::kPointerButtonMouseSecondary + : 0); + } + } + + packet->SetPointerData(pointer_index++, pointer_data); + + if (touch.phase == UITouchPhaseEnded || touch.phase == UITouchPhaseCancelled) { + flutter::PointerData remove_pointer_data = pointer_data; + remove_pointer_data.change = flutter::PointerData::Change::kRemove; + packet->SetPointerData(pointer_index++, remove_pointer_data); + } + } + + [self.engine dispatchPointerDataPacket:std::move(packet)]; +} + +- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event { + [self dispatchTouches:touches pointerDataChangeOverride:nullptr event:event]; +} + +- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event { + [self dispatchTouches:touches pointerDataChangeOverride:nullptr event:event]; +} + +- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event { + [self dispatchTouches:touches pointerDataChangeOverride:nullptr event:event]; +} + +- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event { + [self dispatchTouches:touches pointerDataChangeOverride:nullptr event:event]; +} + +- (void)forceTouchesCancelled:(NSSet*)touches { + flutter::PointerData::Change cancel = flutter::PointerData::Change::kCancel; + [self dispatchTouches:touches pointerDataChangeOverride:&cancel event:nullptr]; +} + +#pragma mark - Touch events rate correction + +- (void)createTouchRateCorrectionVSyncClientIfNeeded { + if (_touchRateCorrectionVSyncClient != nil) { + return; + } + + double displayRefreshRate = DisplayLinkManager.displayRefreshRate; + const double epsilon = 0.1; + if (displayRefreshRate < 60.0 + epsilon) { // displayRefreshRate <= 60.0 + + // If current device's max frame rate is not larger than 60HZ, the delivery rate of touch events + // is the same with render vsync rate. So it is unnecessary to create + // _touchRateCorrectionVSyncClient to correct touch callback's rate. + return; + } + + auto callback = [](std::unique_ptr recorder) { + // Do nothing in this block. Just trigger system to callback touch events with correct rate. + }; + _touchRateCorrectionVSyncClient = + [[VSyncClient alloc] initWithTaskRunner:self.engine.platformTaskRunner callback:callback]; + _touchRateCorrectionVSyncClient.allowPauseAfterVsync = NO; +} + +- (void)triggerTouchRateCorrectionIfNeeded:(NSSet*)touches { + if (_touchRateCorrectionVSyncClient == nil) { + // If the _touchRateCorrectionVSyncClient is not created, means current devices doesn't + // need to correct the touch rate. So just return. + return; + } + + // As long as there is a touch's phase is UITouchPhaseBegan or UITouchPhaseMoved, + // activate the correction. Otherwise pause the correction. + BOOL isUserInteracting = NO; + for (UITouch* touch in touches) { + if (touch.phase == UITouchPhaseBegan || touch.phase == UITouchPhaseMoved) { + isUserInteracting = YES; + break; + } + } + + if (isUserInteracting && self.engine.viewController == self) { + [_touchRateCorrectionVSyncClient await]; + } else { + [_touchRateCorrectionVSyncClient pause]; + } +} + +- (void)invalidateTouchRateCorrectionVSyncClient { + [_touchRateCorrectionVSyncClient invalidate]; + _touchRateCorrectionVSyncClient = nil; +} + +#pragma mark - Handle view resizing + +- (void)updateViewportMetricsIfNeeded { + if (_shouldIgnoreViewportMetricsUpdatesDuringRotation) { + return; + } + if (self.engine.viewController == self) { + [self.engine updateViewportMetrics:_viewportMetrics]; + } +} + +- (void)viewDidLayoutSubviews { + CGRect viewBounds = self.view.bounds; + CGFloat scale = self.flutterScreenIfViewLoaded.scale; + + // Purposefully place this not visible. + self.scrollView.frame = CGRectMake(0.0, 0.0, viewBounds.size.width, 0.0); + self.scrollView.contentOffset = CGPointMake(kScrollViewContentSize, kScrollViewContentSize); + + // First time since creation that the dimensions of its view is known. + bool firstViewBoundsUpdate = !_viewportMetrics.physical_width; + _viewportMetrics.device_pixel_ratio = scale; + [self setViewportMetricsSize]; + [self setViewportMetricsPaddings]; + [self updateViewportMetricsIfNeeded]; + + // There is no guarantee that UIKit will layout subviews when the application/scene is active. + // Creating the surface when inactive will cause GPU accesses from the background. Only wait for + // the first frame to render when the application/scene is actually active. + // This must run after updateViewportMetrics so that the surface creation tasks are queued after + // the viewport metrics update tasks. + if (firstViewBoundsUpdate && self.stateIsActive && self.engine) { + [self surfaceUpdated:YES]; +#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG + NSTimeInterval timeout = 0.2; +#else + NSTimeInterval timeout = 0.1; +#endif + [self.engine + waitForFirstFrameSync:timeout + callback:^(BOOL didTimeout) { + if (didTimeout) { + FML_LOG(INFO) + << "Timeout waiting for the first frame to render. This may happen in " + "unoptimized builds. If this is a release build, you should load a " + "less complex frame to avoid the timeout."; + } + }]; + } +} + +- (void)viewSafeAreaInsetsDidChange { + [self setViewportMetricsPaddings]; + [self updateViewportMetricsIfNeeded]; + [super viewSafeAreaInsetsDidChange]; +} + +// Set _viewportMetrics physical size. +- (void)setViewportMetricsSize { + UIScreen* screen = self.flutterScreenIfViewLoaded; + if (!screen) { + return; + } + + CGFloat scale = screen.scale; + _viewportMetrics.physical_width = self.view.bounds.size.width * scale; + _viewportMetrics.physical_height = self.view.bounds.size.height * scale; +} + +// Set _viewportMetrics physical paddings. +// +// Viewport paddings represent the iOS safe area insets. +- (void)setViewportMetricsPaddings { + UIScreen* screen = self.flutterScreenIfViewLoaded; + if (!screen) { + return; + } + + CGFloat scale = screen.scale; + _viewportMetrics.physical_padding_top = self.view.safeAreaInsets.top * scale; + _viewportMetrics.physical_padding_left = self.view.safeAreaInsets.left * scale; + _viewportMetrics.physical_padding_right = self.view.safeAreaInsets.right * scale; + _viewportMetrics.physical_padding_bottom = self.view.safeAreaInsets.bottom * scale; +} + +#pragma mark - Keyboard events + +- (void)keyboardWillShowNotification:(NSNotification*)notification { + // Immediately prior to a docked keyboard being shown or when a keyboard goes from + // undocked/floating to docked, this notification is triggered. This notification also happens + // when Minimized/Expanded Shortcuts bar is dropped after dragging (the keyboard's end frame will + // be CGRectZero). + [self handleKeyboardNotification:notification]; +} + +- (void)keyboardWillChangeFrame:(NSNotification*)notification { + // Immediately prior to a change in keyboard frame, this notification is triggered. + // Sometimes when the keyboard is being hidden or undocked, this notification's keyboard's end + // frame is not yet entirely out of screen, which is why we also use + // UIKeyboardWillHideNotification. + [self handleKeyboardNotification:notification]; +} + +- (void)keyboardWillBeHidden:(NSNotification*)notification { + // When keyboard is hidden or undocked, this notification will be triggered. + // This notification might not occur when the keyboard is changed from docked to floating, which + // is why we also use UIKeyboardWillChangeFrameNotification. + [self handleKeyboardNotification:notification]; +} + +- (void)handleKeyboardNotification:(NSNotification*)notification { + // See https://flutter.dev/go/ios-keyboard-calculating-inset for more details + // on why notifications are used and how things are calculated. + if ([self shouldIgnoreKeyboardNotification:notification]) { + return; + } + + NSDictionary* info = notification.userInfo; + CGRect beginKeyboardFrame = [info[UIKeyboardFrameBeginUserInfoKey] CGRectValue]; + CGRect keyboardFrame = [info[UIKeyboardFrameEndUserInfoKey] CGRectValue]; + FlutterKeyboardMode keyboardMode = [self calculateKeyboardAttachMode:notification]; + CGFloat calculatedInset = [self calculateKeyboardInset:keyboardFrame keyboardMode:keyboardMode]; + NSTimeInterval duration = [info[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; + + // If the software keyboard is displayed before displaying the PasswordManager prompt, + // UIKeyboardWillHideNotification will occur immediately after UIKeyboardWillShowNotification. + // The duration of the animation will be 0.0, and the calculated inset will be 0.0. + // In this case, it is necessary to cancel the animation and hide the keyboard immediately. + // https://github.com/flutter/flutter/pull/164884 + if (keyboardMode == FlutterKeyboardModeHidden && calculatedInset == 0.0 && duration == 0.0) { + [self hideKeyboardImmediately]; + return; + } + + // Avoid double triggering startKeyBoardAnimation. + if (self.targetViewInsetBottom == calculatedInset) { + return; + } + + self.targetViewInsetBottom = calculatedInset; + + // Flag for simultaneous compounding animation calls. + // This captures animation calls made while the keyboard animation is currently animating. If the + // new animation is in the same direction as the current animation, this flag lets the current + // animation continue with an updated targetViewInsetBottom instead of starting a new keyboard + // animation. This allows for smoother keyboard animation interpolation. + BOOL keyboardWillShow = beginKeyboardFrame.origin.y > keyboardFrame.origin.y; + BOOL keyboardAnimationIsCompounding = + self.keyboardAnimationIsShowing == keyboardWillShow && _keyboardAnimationVSyncClient != nil; + + // Mark keyboard as showing or hiding. + self.keyboardAnimationIsShowing = keyboardWillShow; + + if (!keyboardAnimationIsCompounding) { + [self startKeyBoardAnimation:duration]; + } else if (self.keyboardSpringAnimation) { + self.keyboardSpringAnimation.toValue = self.targetViewInsetBottom; + } +} + +- (BOOL)shouldIgnoreKeyboardNotification:(NSNotification*)notification { + // Don't ignore UIKeyboardWillHideNotification notifications. + // Even if the notification is triggered in the background or by a different app/view controller, + // we want to always handle this notification to avoid inaccurate inset when in a mulitasking mode + // or when switching between apps. + if (notification.name == UIKeyboardWillHideNotification) { + return NO; + } + + // Ignore notification when keyboard's dimensions and position are all zeroes for + // UIKeyboardWillChangeFrameNotification. This happens when keyboard is dragged. Do not ignore if + // the notification is UIKeyboardWillShowNotification, as CGRectZero for that notfication only + // occurs when Minimized/Expanded Shortcuts Bar is dropped after dragging, which we later use to + // categorize it as floating. + NSDictionary* info = notification.userInfo; + CGRect keyboardFrame = [info[UIKeyboardFrameEndUserInfoKey] CGRectValue]; + if (notification.name == UIKeyboardWillChangeFrameNotification && + CGRectEqualToRect(keyboardFrame, CGRectZero)) { + return YES; + } + + // When keyboard's height or width is set to 0, don't ignore. This does not happen + // often but can happen sometimes when switching between multitasking modes. + if (CGRectIsEmpty(keyboardFrame)) { + return NO; + } + + // Ignore keyboard notifications related to other apps or view controllers. + if ([self isKeyboardNotificationForDifferentView:notification]) { + return YES; + } + + if (@available(iOS 13.0, *)) { + // noop + } else { + // If OS version is less than 13, ignore notification if the app is in the background + // or is transitioning from the background. In older versions, when switching between + // apps with the keyboard open in the secondary app, notifications are sent when + // the app is in the background/transitioning from background as if they belong + // to the app and as if the keyboard is showing even though it is not. + if (self.isKeyboardInOrTransitioningFromBackground) { + return YES; + } + } + + return NO; +} + +- (BOOL)isKeyboardNotificationForDifferentView:(NSNotification*)notification { + NSDictionary* info = notification.userInfo; + // Keyboard notifications related to other apps. + // If the UIKeyboardIsLocalUserInfoKey key doesn't exist (this should not happen after iOS 8), + // proceed as if it was local so that the notification is not ignored. + id isLocal = info[UIKeyboardIsLocalUserInfoKey]; + if (isLocal && ![isLocal boolValue]) { + return YES; + } + return self.engine.viewController != self; +} + +- (FlutterKeyboardMode)calculateKeyboardAttachMode:(NSNotification*)notification { + // There are multiple types of keyboard: docked, undocked, split, split docked, + // floating, expanded shortcuts bar, minimized shortcuts bar. This function will categorize + // the keyboard as one of the following modes: docked, floating, or hidden. + // Docked mode includes docked, split docked, expanded shortcuts bar (when opening via click), + // and minimized shortcuts bar (when opened via click). + // Floating includes undocked, split, floating, expanded shortcuts bar (when dragged and dropped), + // and minimized shortcuts bar (when dragged and dropped). + NSDictionary* info = notification.userInfo; + CGRect keyboardFrame = [info[UIKeyboardFrameEndUserInfoKey] CGRectValue]; + + if (notification.name == UIKeyboardWillHideNotification) { + return FlutterKeyboardModeHidden; + } + + // If keyboard's dimensions and position are all zeroes, that means it's a Minimized/Expanded + // Shortcuts Bar that has been dropped after dragging, which we categorize as floating. + if (CGRectEqualToRect(keyboardFrame, CGRectZero)) { + return FlutterKeyboardModeFloating; + } + // If keyboard's width or height are 0, it's hidden. + if (CGRectIsEmpty(keyboardFrame)) { + return FlutterKeyboardModeHidden; + } + + CGRect screenRect = self.flutterScreenIfViewLoaded.bounds; + CGRect adjustedKeyboardFrame = keyboardFrame; + adjustedKeyboardFrame.origin.y += [self calculateMultitaskingAdjustment:screenRect + keyboardFrame:keyboardFrame]; + + // If the keyboard is partially or fully showing within the screen, it's either docked or + // floating. Sometimes with custom keyboard extensions, the keyboard's position may be off by a + // small decimal amount (which is why CGRectIntersectRect can't be used). Round to compare. + CGRect intersection = CGRectIntersection(adjustedKeyboardFrame, screenRect); + CGFloat intersectionHeight = CGRectGetHeight(intersection); + CGFloat intersectionWidth = CGRectGetWidth(intersection); + if (round(intersectionHeight) > 0 && intersectionWidth > 0) { + // If the keyboard is above the bottom of the screen, it's floating. + CGFloat screenHeight = CGRectGetHeight(screenRect); + CGFloat adjustedKeyboardBottom = CGRectGetMaxY(adjustedKeyboardFrame); + if (round(adjustedKeyboardBottom) < screenHeight) { + return FlutterKeyboardModeFloating; + } + return FlutterKeyboardModeDocked; + } + return FlutterKeyboardModeHidden; +} + +- (CGFloat)calculateMultitaskingAdjustment:(CGRect)screenRect keyboardFrame:(CGRect)keyboardFrame { + // In Slide Over mode, the keyboard's frame does not include the space + // below the app, even though the keyboard may be at the bottom of the screen. + // To handle, shift the Y origin by the amount of space below the app. + if (self.viewIfLoaded.traitCollection.userInterfaceIdiom == UIUserInterfaceIdiomPad && + self.viewIfLoaded.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassCompact && + self.viewIfLoaded.traitCollection.verticalSizeClass == UIUserInterfaceSizeClassRegular) { + CGFloat screenHeight = CGRectGetHeight(screenRect); + CGFloat keyboardBottom = CGRectGetMaxY(keyboardFrame); + + // Stage Manager mode will also meet the above parameters, but it does not handle + // the keyboard positioning the same way, so skip if keyboard is at bottom of page. + if (screenHeight == keyboardBottom) { + return 0; + } + CGRect viewRectRelativeToScreen = + [self.viewIfLoaded convertRect:self.viewIfLoaded.frame + toCoordinateSpace:self.flutterScreenIfViewLoaded.coordinateSpace]; + CGFloat viewBottom = CGRectGetMaxY(viewRectRelativeToScreen); + CGFloat offset = screenHeight - viewBottom; + if (offset > 0) { + return offset; + } + } + return 0; +} + +- (CGFloat)calculateKeyboardInset:(CGRect)keyboardFrame keyboardMode:(NSInteger)keyboardMode { + // Only docked keyboards will have an inset. + if (keyboardMode == FlutterKeyboardModeDocked) { + // Calculate how much of the keyboard intersects with the view. + CGRect viewRectRelativeToScreen = + [self.viewIfLoaded convertRect:self.viewIfLoaded.frame + toCoordinateSpace:self.flutterScreenIfViewLoaded.coordinateSpace]; + CGRect intersection = CGRectIntersection(keyboardFrame, viewRectRelativeToScreen); + CGFloat portionOfKeyboardInView = CGRectGetHeight(intersection); + + // The keyboard is treated as an inset since we want to effectively reduce the window size by + // the keyboard height. The Dart side will compute a value accounting for the keyboard-consuming + // bottom padding. + CGFloat scale = self.flutterScreenIfViewLoaded.scale; + return portionOfKeyboardInView * scale; + } + return 0; +} + +- (void)startKeyBoardAnimation:(NSTimeInterval)duration { + // If current physical_view_inset_bottom == targetViewInsetBottom, do nothing. + if (_viewportMetrics.physical_view_inset_bottom == self.targetViewInsetBottom) { + return; + } + + // When this method is called for the first time, + // initialize the keyboardAnimationView to get animation interpolation during animation. + if (!self.keyboardAnimationView) { + UIView* keyboardAnimationView = [[UIView alloc] init]; + keyboardAnimationView.hidden = YES; + self.keyboardAnimationView = keyboardAnimationView; + } + + if (!self.keyboardAnimationView.superview) { + [self.view addSubview:self.keyboardAnimationView]; + } + + // Remove running animation when start another animation. + [self.keyboardAnimationView.layer removeAllAnimations]; + + // Set animation begin value and DisplayLink tracking values. + self.keyboardAnimationView.frame = + CGRectMake(0, _viewportMetrics.physical_view_inset_bottom, 0, 0); + self.keyboardAnimationStartTime = fml::TimePoint().Now(); + self.originalViewInsetBottom = _viewportMetrics.physical_view_inset_bottom; + + // Invalidate old vsync client if old animation is not completed. + [self invalidateKeyboardAnimationVSyncClient]; + + __weak FlutterViewController* weakSelf = self; + [self setUpKeyboardAnimationVsyncClient:^(fml::TimePoint targetTime) { + [weakSelf handleKeyboardAnimationCallbackWithTargetTime:targetTime]; + }]; + VSyncClient* currentVsyncClient = _keyboardAnimationVSyncClient; + + [UIView animateWithDuration:duration + animations:^{ + FlutterViewController* strongSelf = weakSelf; + if (!strongSelf) { + return; + } + + // Set end value. + strongSelf.keyboardAnimationView.frame = CGRectMake(0, self.targetViewInsetBottom, 0, 0); + + // Setup keyboard animation interpolation. + CAAnimation* keyboardAnimation = + [strongSelf.keyboardAnimationView.layer animationForKey:@"position"]; + [strongSelf setUpKeyboardSpringAnimationIfNeeded:keyboardAnimation]; + } + completion:^(BOOL finished) { + if (_keyboardAnimationVSyncClient == currentVsyncClient) { + FlutterViewController* strongSelf = weakSelf; + if (!strongSelf) { + return; + } + + // Indicates the vsync client captured by this block is the original one, which also + // indicates the animation has not been interrupted from its beginning. Moreover, + // indicates the animation is over and there is no more to execute. + [strongSelf invalidateKeyboardAnimationVSyncClient]; + [strongSelf removeKeyboardAnimationView]; + [strongSelf ensureViewportMetricsIsCorrect]; + } + }]; +} + +- (void)hideKeyboardImmediately { + [self invalidateKeyboardAnimationVSyncClient]; + if (self.keyboardAnimationView) { + [self.keyboardAnimationView.layer removeAllAnimations]; + [self removeKeyboardAnimationView]; + self.keyboardAnimationView = nil; + } + if (self.keyboardSpringAnimation) { + self.keyboardSpringAnimation = nil; + } + // Reset targetViewInsetBottom to 0.0. + self.targetViewInsetBottom = 0.0; + [self ensureViewportMetricsIsCorrect]; +} + +- (void)setUpKeyboardSpringAnimationIfNeeded:(CAAnimation*)keyboardAnimation { + // If keyboard animation is null or not a spring animation, fallback to DisplayLink tracking. + if (keyboardAnimation == nil || ![keyboardAnimation isKindOfClass:[CASpringAnimation class]]) { + _keyboardSpringAnimation = nil; + return; + } + + // Setup keyboard spring animation details for spring curve animation calculation. + CASpringAnimation* keyboardCASpringAnimation = (CASpringAnimation*)keyboardAnimation; + _keyboardSpringAnimation = + [[SpringAnimation alloc] initWithStiffness:keyboardCASpringAnimation.stiffness + damping:keyboardCASpringAnimation.damping + mass:keyboardCASpringAnimation.mass + initialVelocity:keyboardCASpringAnimation.initialVelocity + fromValue:self.originalViewInsetBottom + toValue:self.targetViewInsetBottom]; +} + +- (void)handleKeyboardAnimationCallbackWithTargetTime:(fml::TimePoint)targetTime { + // If the view controller's view is not loaded, bail out. + if (!self.isViewLoaded) { + return; + } + // If the view for tracking keyboard animation is nil, means it is not + // created, bail out. + if (!self.keyboardAnimationView) { + return; + } + // If keyboardAnimationVSyncClient is nil, means the animation ends. + // And should bail out. + if (!self.keyboardAnimationVSyncClient) { + return; + } + + if (!self.keyboardAnimationView.superview) { + // Ensure the keyboardAnimationView is in view hierarchy when animation running. + [self.view addSubview:self.keyboardAnimationView]; + } + + if (!self.keyboardSpringAnimation) { + if (self.keyboardAnimationView.layer.presentationLayer) { + self->_viewportMetrics.physical_view_inset_bottom = + self.keyboardAnimationView.layer.presentationLayer.frame.origin.y; + [self updateViewportMetricsIfNeeded]; + } + } else { + fml::TimeDelta timeElapsed = targetTime - self.keyboardAnimationStartTime; + self->_viewportMetrics.physical_view_inset_bottom = + [self.keyboardSpringAnimation curveFunction:timeElapsed.ToSecondsF()]; + [self updateViewportMetricsIfNeeded]; + } +} + +- (void)setUpKeyboardAnimationVsyncClient: + (FlutterKeyboardAnimationCallback)keyboardAnimationCallback { + if (!keyboardAnimationCallback) { + return; + } + NSAssert(_keyboardAnimationVSyncClient == nil, + @"_keyboardAnimationVSyncClient must be nil when setting up."); + + // Make sure the new viewport metrics get sent after the begin frame event has processed. + FlutterKeyboardAnimationCallback animationCallback = [keyboardAnimationCallback copy]; + auto uiCallback = [animationCallback](std::unique_ptr recorder) { + fml::TimeDelta frameInterval = recorder->GetVsyncTargetTime() - recorder->GetVsyncStartTime(); + fml::TimePoint targetTime = recorder->GetVsyncTargetTime() + frameInterval; + dispatch_async(dispatch_get_main_queue(), ^(void) { + animationCallback(targetTime); + }); + }; + + _keyboardAnimationVSyncClient = [[VSyncClient alloc] initWithTaskRunner:self.engine.uiTaskRunner + callback:uiCallback]; + _keyboardAnimationVSyncClient.allowPauseAfterVsync = NO; + [_keyboardAnimationVSyncClient await]; +} + +- (void)invalidateKeyboardAnimationVSyncClient { + [_keyboardAnimationVSyncClient invalidate]; + _keyboardAnimationVSyncClient = nil; +} + +- (void)removeKeyboardAnimationView { + if (self.keyboardAnimationView.superview != nil) { + [self.keyboardAnimationView removeFromSuperview]; + } +} + +- (void)ensureViewportMetricsIsCorrect { + if (_viewportMetrics.physical_view_inset_bottom != self.targetViewInsetBottom) { + // Make sure the `physical_view_inset_bottom` is the target value. + _viewportMetrics.physical_view_inset_bottom = self.targetViewInsetBottom; + [self updateViewportMetricsIfNeeded]; + } +} + +- (void)handlePressEvent:(FlutterUIPressProxy*)press + nextAction:(void (^)())next API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + } else { + next(); + return; + } + [self.keyboardManager handlePress:press nextAction:next]; +} + +- (void)sendDeepLinkToFramework:(NSURL*)url completionHandler:(void (^)(BOOL success))completion { + __weak FlutterViewController* weakSelf = self; + [self.engine + waitForFirstFrame:3.0 + callback:^(BOOL didTimeout) { + if (didTimeout) { + FML_LOG(ERROR) << "Timeout waiting for the first frame when launching an URL."; + completion(NO); + } else { + // invove the method and get the result + [weakSelf.engine.navigationChannel + invokeMethod:@"pushRouteInformation" + arguments:@{ + @"location" : url.absoluteString ?: [NSNull null], + } + result:^(id _Nullable result) { + BOOL success = + [result isKindOfClass:[NSNumber class]] && [result boolValue]; + if (!success) { + // Logging the error if the result is not successful + FML_LOG(ERROR) << "Failed to handle route information in Flutter."; + } + completion(success); + }]; + } + }]; +} + +// The documentation for presses* handlers (implemented below) is entirely +// unclear about how to handle the case where some, but not all, of the presses +// are handled here. I've elected to call super separately for each of the +// presses that aren't handled, but it's not clear if this is correct. It may be +// that iOS intends for us to either handle all or none of the presses, and pass +// the original set to super. I have not yet seen multiple presses in the set in +// the wild, however, so I suspect that the API is built for a tvOS remote or +// something, and perhaps only one ever appears in the set on iOS from a +// keyboard. +// +// We define separate superPresses* overrides to avoid implicitly capturing self in the blocks +// passed to the presses* methods below. + +- (void)superPressesBegan:(NSSet*)presses withEvent:(UIPressesEvent*)event { + [super pressesBegan:presses withEvent:event]; +} + +- (void)superPressesChanged:(NSSet*)presses withEvent:(UIPressesEvent*)event { + [super pressesChanged:presses withEvent:event]; +} + +- (void)superPressesEnded:(NSSet*)presses withEvent:(UIPressesEvent*)event { + [super pressesEnded:presses withEvent:event]; +} + +- (void)superPressesCancelled:(NSSet*)presses withEvent:(UIPressesEvent*)event { + [super pressesCancelled:presses withEvent:event]; +} + +// If you substantially change these presses overrides, consider also changing +// the similar ones in FlutterTextInputPlugin. They need to be overridden in +// both places to capture keys both inside and outside of a text field, but have +// slightly different implementations. + +- (void)pressesBegan:(NSSet*)presses + withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) { + if (@available(iOS 13.4, *)) { + __weak FlutterViewController* weakSelf = self; + for (UIPress* press in presses) { + [self handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press withEvent:event] + nextAction:^() { + [weakSelf superPressesBegan:[NSSet setWithObject:press] withEvent:event]; + }]; + } + } else { + [super pressesBegan:presses withEvent:event]; + } +} + +- (void)pressesChanged:(NSSet*)presses + withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) { + if (@available(iOS 13.4, *)) { + __weak FlutterViewController* weakSelf = self; + for (UIPress* press in presses) { + [self handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press withEvent:event] + nextAction:^() { + [weakSelf superPressesChanged:[NSSet setWithObject:press] withEvent:event]; + }]; + } + } else { + [super pressesChanged:presses withEvent:event]; + } +} + +- (void)pressesEnded:(NSSet*)presses + withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) { + if (@available(iOS 13.4, *)) { + __weak FlutterViewController* weakSelf = self; + for (UIPress* press in presses) { + [self handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press withEvent:event] + nextAction:^() { + [weakSelf superPressesEnded:[NSSet setWithObject:press] withEvent:event]; + }]; + } + } else { + [super pressesEnded:presses withEvent:event]; + } +} + +- (void)pressesCancelled:(NSSet*)presses + withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) { + if (@available(iOS 13.4, *)) { + __weak FlutterViewController* weakSelf = self; + for (UIPress* press in presses) { + [self handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press withEvent:event] + nextAction:^() { + [weakSelf superPressesCancelled:[NSSet setWithObject:press] withEvent:event]; + }]; + } + } else { + [super pressesCancelled:presses withEvent:event]; + } +} + +#pragma mark - Orientation updates + +- (void)onOrientationPreferencesUpdated:(NSNotification*)notification { + // Notifications may not be on the iOS UI thread + __weak FlutterViewController* weakSelf = self; + dispatch_async(dispatch_get_main_queue(), ^{ + NSDictionary* info = notification.userInfo; + NSNumber* update = info[@(flutter::kOrientationUpdateNotificationKey)]; + if (update == nil) { + return; + } + [weakSelf performOrientationUpdate:update.unsignedIntegerValue]; + }); +} + +- (void)requestGeometryUpdateForWindowScenes:(NSSet*)windowScenes + API_AVAILABLE(ios(16.0)) { + for (UIScene* windowScene in windowScenes) { + FML_DCHECK([windowScene isKindOfClass:[UIWindowScene class]]); + UIWindowSceneGeometryPreferencesIOS* preference = [[UIWindowSceneGeometryPreferencesIOS alloc] + initWithInterfaceOrientations:self.orientationPreferences]; + [(UIWindowScene*)windowScene + requestGeometryUpdateWithPreferences:preference + errorHandler:^(NSError* error) { + os_log_error(OS_LOG_DEFAULT, + "Failed to change device orientation: %@", error); + }]; + [self setNeedsUpdateOfSupportedInterfaceOrientations]; + } +} + +- (void)performOrientationUpdate:(UIInterfaceOrientationMask)new_preferences { + if (new_preferences != self.orientationPreferences) { + self.orientationPreferences = new_preferences; + + if (@available(iOS 16.0, *)) { + UIApplication* flutterApplication = FlutterSharedApplication.application; + NSSet* scenes = [NSSet set]; + if (flutterApplication) { + scenes = [flutterApplication.connectedScenes + filteredSetUsingPredicate:[NSPredicate predicateWithBlock:^BOOL( + id scene, NSDictionary* bindings) { + return [scene isKindOfClass:[UIWindowScene class]]; + }]]; + } else if (self.flutterWindowSceneIfViewLoaded) { + scenes = [NSSet setWithObject:self.flutterWindowSceneIfViewLoaded]; + } + [self requestGeometryUpdateForWindowScenes:scenes]; + } else { + UIInterfaceOrientationMask currentInterfaceOrientation = 0; + if (@available(iOS 13.0, *)) { + UIWindowScene* windowScene = self.flutterWindowSceneIfViewLoaded; + if (!windowScene) { + FML_LOG(WARNING) + << "Accessing the interface orientation when the window scene is unavailable."; + return; + } + currentInterfaceOrientation = 1 << windowScene.interfaceOrientation; + } else { + UIApplication* flutterApplication = FlutterSharedApplication.application; + if (flutterApplication) { + currentInterfaceOrientation = 1 << [flutterApplication statusBarOrientation]; + } else { + FML_LOG(ERROR) << "Application based status bar orentiation update is not supported in " + "app extension. Orientation: " + << currentInterfaceOrientation; + } + } + if (!(self.orientationPreferences & currentInterfaceOrientation)) { + [UIViewController attemptRotationToDeviceOrientation]; + // Force orientation switch if the current orientation is not allowed + if (self.orientationPreferences & UIInterfaceOrientationMaskPortrait) { + // This is no official API but more like a workaround / hack (using + // key-value coding on a read-only property). This might break in + // the future, but currently it´s the only way to force an orientation change + [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationPortrait) + forKey:@"orientation"]; + } else if (self.orientationPreferences & UIInterfaceOrientationMaskPortraitUpsideDown) { + [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationPortraitUpsideDown) + forKey:@"orientation"]; + } else if (self.orientationPreferences & UIInterfaceOrientationMaskLandscapeLeft) { + [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeLeft) + forKey:@"orientation"]; + } else if (self.orientationPreferences & UIInterfaceOrientationMaskLandscapeRight) { + [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeRight) + forKey:@"orientation"]; + } + } + } + } +} + +- (void)onHideHomeIndicatorNotification:(NSNotification*)notification { + self.isHomeIndicatorHidden = YES; +} + +- (void)onShowHomeIndicatorNotification:(NSNotification*)notification { + self.isHomeIndicatorHidden = NO; +} + +- (void)setIsHomeIndicatorHidden:(BOOL)hideHomeIndicator { + if (hideHomeIndicator != _isHomeIndicatorHidden) { + _isHomeIndicatorHidden = hideHomeIndicator; + [self setNeedsUpdateOfHomeIndicatorAutoHidden]; + } +} + +- (BOOL)prefersHomeIndicatorAutoHidden { + return self.isHomeIndicatorHidden; +} + +- (BOOL)shouldAutorotate { + return YES; +} + +- (NSUInteger)supportedInterfaceOrientations { + return self.orientationPreferences; +} + +#pragma mark - Accessibility + +- (void)onAccessibilityStatusChanged:(NSNotification*)notification { + if (!self.engine) { + return; + } + BOOL enabled = NO; + int32_t flags = self.accessibilityFlags; +#if TARGET_OS_SIMULATOR + // There doesn't appear to be any way to determine whether the accessibility + // inspector is enabled on the simulator. We conservatively always turn on the + // accessibility bridge in the simulator, but never assistive technology. + enabled = YES; +#else + _isVoiceOverRunning = UIAccessibilityIsVoiceOverRunning(); + enabled = _isVoiceOverRunning || UIAccessibilityIsSwitchControlRunning(); + if (enabled) { + flags |= static_cast(flutter::AccessibilityFeatureFlag::kAccessibleNavigation); + } + enabled |= UIAccessibilityIsSpeakScreenEnabled(); +#endif + [self.engine enableSemantics:enabled withFlags:flags]; +} + +- (int32_t)accessibilityFlags { + int32_t flags = 0; + if (UIAccessibilityIsInvertColorsEnabled()) { + flags |= static_cast(flutter::AccessibilityFeatureFlag::kInvertColors); + } + if (UIAccessibilityIsReduceMotionEnabled()) { + flags |= static_cast(flutter::AccessibilityFeatureFlag::kReduceMotion); + } + if (UIAccessibilityIsBoldTextEnabled()) { + flags |= static_cast(flutter::AccessibilityFeatureFlag::kBoldText); + } + if (UIAccessibilityDarkerSystemColorsEnabled()) { + flags |= static_cast(flutter::AccessibilityFeatureFlag::kHighContrast); + } + if ([FlutterViewController accessibilityIsOnOffSwitchLabelsEnabled]) { + flags |= static_cast(flutter::AccessibilityFeatureFlag::kOnOffSwitchLabels); + } + + return flags; +} + +- (BOOL)accessibilityPerformEscape { + FlutterMethodChannel* navigationChannel = self.engine.navigationChannel; + if (navigationChannel) { + [self popRoute]; + return YES; + } + return NO; +} + ++ (BOOL)accessibilityIsOnOffSwitchLabelsEnabled { + if (@available(iOS 13, *)) { + return UIAccessibilityIsOnOffSwitchLabelsEnabled(); + } else { + return NO; + } +} + +#pragma mark - Set user settings + +- (void)traitCollectionDidChange:(UITraitCollection*)previousTraitCollection { + [super traitCollectionDidChange:previousTraitCollection]; + [self onUserSettingsChanged:nil]; +} + +- (void)onUserSettingsChanged:(NSNotification*)notification { + [self.engine.settingsChannel sendMessage:@{ + @"textScaleFactor" : @(self.textScaleFactor), + @"alwaysUse24HourFormat" : @(FlutterHourFormat.isAlwaysUse24HourFormat), + @"platformBrightness" : self.brightnessMode, + @"platformContrast" : self.contrastMode, + @"nativeSpellCheckServiceDefined" : @YES, + @"supportsShowingSystemContextMenu" : @(self.supportsShowingSystemContextMenu) + }]; +} + +- (CGFloat)textScaleFactor { + UIApplication* flutterApplication = FlutterSharedApplication.application; + if (flutterApplication == nil) { + FML_LOG(WARNING) << "Dynamic content size update is not supported in app extension."; + return 1.0; + } + + UIContentSizeCategory category = flutterApplication.preferredContentSizeCategory; + // The delta is computed by approximating Apple's typography guidelines: + // https://developer.apple.com/ios/human-interface-guidelines/visual-design/typography/ + // + // Specifically: + // Non-accessibility sizes for "body" text are: + const CGFloat xs = 14; + const CGFloat s = 15; + const CGFloat m = 16; + const CGFloat l = 17; + const CGFloat xl = 19; + const CGFloat xxl = 21; + const CGFloat xxxl = 23; + + // Accessibility sizes for "body" text are: + const CGFloat ax1 = 28; + const CGFloat ax2 = 33; + const CGFloat ax3 = 40; + const CGFloat ax4 = 47; + const CGFloat ax5 = 53; + + // We compute the scale as relative difference from size L (large, the default size), where + // L is assumed to have scale 1.0. + if ([category isEqualToString:UIContentSizeCategoryExtraSmall]) { + return xs / l; + } else if ([category isEqualToString:UIContentSizeCategorySmall]) { + return s / l; + } else if ([category isEqualToString:UIContentSizeCategoryMedium]) { + return m / l; + } else if ([category isEqualToString:UIContentSizeCategoryLarge]) { + return 1.0; + } else if ([category isEqualToString:UIContentSizeCategoryExtraLarge]) { + return xl / l; + } else if ([category isEqualToString:UIContentSizeCategoryExtraExtraLarge]) { + return xxl / l; + } else if ([category isEqualToString:UIContentSizeCategoryExtraExtraExtraLarge]) { + return xxxl / l; + } else if ([category isEqualToString:UIContentSizeCategoryAccessibilityMedium]) { + return ax1 / l; + } else if ([category isEqualToString:UIContentSizeCategoryAccessibilityLarge]) { + return ax2 / l; + } else if ([category isEqualToString:UIContentSizeCategoryAccessibilityExtraLarge]) { + return ax3 / l; + } else if ([category isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraLarge]) { + return ax4 / l; + } else if ([category isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraExtraLarge]) { + return ax5 / l; + } else { + return 1.0; + } +} + +- (BOOL)supportsShowingSystemContextMenu { + if (@available(iOS 16.0, *)) { + return YES; + } else { + return NO; + } +} + +// The brightness mode of the platform, e.g., light or dark, expressed as a string that +// is understood by the Flutter framework. See the settings +// system channel for more information. +- (NSString*)brightnessMode { + if (@available(iOS 13, *)) { + UIUserInterfaceStyle style = self.traitCollection.userInterfaceStyle; + + if (style == UIUserInterfaceStyleDark) { + return @"dark"; + } else { + return @"light"; + } + } else { + return @"light"; + } +} + +// The contrast mode of the platform, e.g., normal or high, expressed as a string that is +// understood by the Flutter framework. See the settings system channel for more +// information. +- (NSString*)contrastMode { + if (@available(iOS 13, *)) { + UIAccessibilityContrast contrast = self.traitCollection.accessibilityContrast; + + if (contrast == UIAccessibilityContrastHigh) { + return @"high"; + } else { + return @"normal"; + } + } else { + return @"normal"; + } +} + +#pragma mark - Status bar style + +- (UIStatusBarStyle)preferredStatusBarStyle { + return self.statusBarStyle; +} + +- (void)onPreferredStatusBarStyleUpdated:(NSNotification*)notification { + // Notifications may not be on the iOS UI thread + __weak FlutterViewController* weakSelf = self; + dispatch_async(dispatch_get_main_queue(), ^{ + FlutterViewController* strongSelf = weakSelf; + if (!strongSelf) { + return; + } + + NSDictionary* info = notification.userInfo; + NSNumber* update = info[@(flutter::kOverlayStyleUpdateNotificationKey)]; + if (update == nil) { + return; + } + + UIStatusBarStyle style = static_cast(update.integerValue); + if (style != strongSelf.statusBarStyle) { + strongSelf.statusBarStyle = style; + [strongSelf setNeedsStatusBarAppearanceUpdate]; + } + }); +} + +- (void)setPrefersStatusBarHidden:(BOOL)hidden { + if (hidden != self.flutterPrefersStatusBarHidden) { + self.flutterPrefersStatusBarHidden = hidden; + [self setNeedsStatusBarAppearanceUpdate]; + } +} + +- (BOOL)prefersStatusBarHidden { + return self.flutterPrefersStatusBarHidden; +} + +#pragma mark - Platform views + +- (FlutterPlatformViewsController*)platformViewsController { + return self.engine.platformViewsController; +} + +- (NSObject*)binaryMessenger { + return self.engine.binaryMessenger; +} + +#pragma mark - FlutterBinaryMessenger + +- (void)sendOnChannel:(NSString*)channel message:(NSData*)message { + [self.engine.binaryMessenger sendOnChannel:channel message:message]; +} + +- (void)sendOnChannel:(NSString*)channel + message:(NSData*)message + binaryReply:(FlutterBinaryReply)callback { + NSAssert(channel, @"The channel must not be null"); + [self.engine.binaryMessenger sendOnChannel:channel message:message binaryReply:callback]; +} + +- (NSObject*)makeBackgroundTaskQueue { + return [self.engine.binaryMessenger makeBackgroundTaskQueue]; +} + +- (FlutterBinaryMessengerConnection)setMessageHandlerOnChannel:(NSString*)channel + binaryMessageHandler: + (FlutterBinaryMessageHandler)handler { + return [self setMessageHandlerOnChannel:channel binaryMessageHandler:handler taskQueue:nil]; +} + +- (FlutterBinaryMessengerConnection) + setMessageHandlerOnChannel:(NSString*)channel + binaryMessageHandler:(FlutterBinaryMessageHandler _Nullable)handler + taskQueue:(NSObject* _Nullable)taskQueue { + NSAssert(channel, @"The channel must not be null"); + return [self.engine.binaryMessenger setMessageHandlerOnChannel:channel + binaryMessageHandler:handler + taskQueue:taskQueue]; +} + +- (void)cleanUpConnection:(FlutterBinaryMessengerConnection)connection { + [self.engine.binaryMessenger cleanUpConnection:connection]; +} + +#pragma mark - FlutterTextureRegistry + +- (int64_t)registerTexture:(NSObject*)texture { + return [self.engine.textureRegistry registerTexture:texture]; +} + +- (void)unregisterTexture:(int64_t)textureId { + [self.engine.textureRegistry unregisterTexture:textureId]; +} + +- (void)textureFrameAvailable:(int64_t)textureId { + [self.engine.textureRegistry textureFrameAvailable:textureId]; +} + +- (NSString*)lookupKeyForAsset:(NSString*)asset { + return [FlutterDartProject lookupKeyForAsset:asset]; +} + +- (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package { + return [FlutterDartProject lookupKeyForAsset:asset fromPackage:package]; +} + +- (id)pluginRegistry { + return self.engine; +} + ++ (BOOL)isUIAccessibilityIsVoiceOverRunning { + return UIAccessibilityIsVoiceOverRunning(); +} + +#pragma mark - FlutterPluginRegistry + +- (NSObject*)registrarForPlugin:(NSString*)pluginKey { + return [self.engine registrarForPlugin:pluginKey]; +} + +- (BOOL)hasPlugin:(NSString*)pluginKey { + return [self.engine hasPlugin:pluginKey]; +} + +- (NSObject*)valuePublishedByPlugin:(NSString*)pluginKey { + return [self.engine valuePublishedByPlugin:pluginKey]; +} + +- (void)presentViewController:(UIViewController*)viewControllerToPresent + animated:(BOOL)flag + completion:(void (^)(void))completion { + self.isPresentingViewControllerAnimating = YES; + __weak FlutterViewController* weakSelf = self; + [super presentViewController:viewControllerToPresent + animated:flag + completion:^{ + weakSelf.isPresentingViewControllerAnimating = NO; + if (completion) { + completion(); + } + }]; +} + +- (BOOL)isPresentingViewController { + return self.presentedViewController != nil || self.isPresentingViewControllerAnimating; +} + +- (flutter::PointerData)updateMousePointerDataFrom:(UIGestureRecognizer*)gestureRecognizer + API_AVAILABLE(ios(13.4)) { + CGPoint location = [gestureRecognizer locationInView:self.view]; + CGFloat scale = self.flutterScreenIfViewLoaded.scale; + _mouseState.location = {location.x * scale, location.y * scale}; + flutter::PointerData pointer_data; + pointer_data.Clear(); + pointer_data.time_stamp = [[NSProcessInfo processInfo] systemUptime] * kMicrosecondsPerSecond; + pointer_data.physical_x = _mouseState.location.x; + pointer_data.physical_y = _mouseState.location.y; + return pointer_data; +} + +- (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer + shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer*)otherGestureRecognizer + API_AVAILABLE(ios(13.4)) { + return YES; +} + +- (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer + shouldReceiveEvent:(UIEvent*)event API_AVAILABLE(ios(13.4)) { + if (gestureRecognizer == _continuousScrollingPanGestureRecognizer && + event.type == UIEventTypeScroll) { + // Events with type UIEventTypeScroll are only received when running on macOS under emulation. + flutter::PointerData pointer_data = [self updateMousePointerDataFrom:gestureRecognizer]; + pointer_data.device = reinterpret_cast(_continuousScrollingPanGestureRecognizer); + pointer_data.kind = flutter::PointerData::DeviceKind::kTrackpad; + pointer_data.signal_kind = flutter::PointerData::SignalKind::kScrollInertiaCancel; + pointer_data.view_id = self.viewIdentifier; + + if (event.timestamp < self.scrollInertiaEventAppKitDeadline) { + // Only send the event if it occured before the expected natural end of gesture momentum. + // If received after the deadline, it's not likely the event is from a user-initiated cancel. + auto packet = std::make_unique(1); + packet->SetPointerData(/*i=*/0, pointer_data); + [self.engine dispatchPointerDataPacket:std::move(packet)]; + self.scrollInertiaEventAppKitDeadline = 0; + } + } + // This method is also called for UITouches, should return YES to process all touches. + return YES; +} + +- (void)hoverEvent:(UIHoverGestureRecognizer*)recognizer API_AVAILABLE(ios(13.4)) { + CGPoint oldLocation = _mouseState.location; + + flutter::PointerData pointer_data = [self updateMousePointerDataFrom:recognizer]; + pointer_data.device = reinterpret_cast(recognizer); + pointer_data.kind = flutter::PointerData::DeviceKind::kMouse; + pointer_data.view_id = self.viewIdentifier; + + switch (_hoverGestureRecognizer.state) { + case UIGestureRecognizerStateBegan: + pointer_data.change = flutter::PointerData::Change::kAdd; + break; + case UIGestureRecognizerStateChanged: + pointer_data.change = flutter::PointerData::Change::kHover; + break; + case UIGestureRecognizerStateEnded: + case UIGestureRecognizerStateCancelled: + pointer_data.change = flutter::PointerData::Change::kRemove; + break; + default: + // Sending kHover is the least harmful thing to do here + // But this state is not expected to ever be reached. + pointer_data.change = flutter::PointerData::Change::kHover; + break; + } + + NSTimeInterval time = [NSProcessInfo processInfo].systemUptime; + BOOL isRunningOnMac = NO; + if (@available(iOS 14.0, *)) { + // This "stationary pointer" heuristic is not reliable when running within macOS. + // We instead receive a scroll cancel event directly from AppKit. + // See gestureRecognizer:shouldReceiveEvent: + isRunningOnMac = [NSProcessInfo processInfo].iOSAppOnMac; + } + if (!isRunningOnMac && CGPointEqualToPoint(oldLocation, _mouseState.location) && + time > self.scrollInertiaEventStartline) { + // iPadOS reports trackpad movements events with high (sub-pixel) precision. When an event + // is received with the same position as the previous one, it can only be from a finger + // making or breaking contact with the trackpad surface. + auto packet = std::make_unique(2); + packet->SetPointerData(/*i=*/0, pointer_data); + flutter::PointerData inertia_cancel = pointer_data; + inertia_cancel.device = reinterpret_cast(_continuousScrollingPanGestureRecognizer); + inertia_cancel.kind = flutter::PointerData::DeviceKind::kTrackpad; + inertia_cancel.signal_kind = flutter::PointerData::SignalKind::kScrollInertiaCancel; + inertia_cancel.view_id = self.viewIdentifier; + packet->SetPointerData(/*i=*/1, inertia_cancel); + [self.engine dispatchPointerDataPacket:std::move(packet)]; + self.scrollInertiaEventStartline = DBL_MAX; + } else { + auto packet = std::make_unique(1); + packet->SetPointerData(/*i=*/0, pointer_data); + [self.engine dispatchPointerDataPacket:std::move(packet)]; + } +} + +- (void)discreteScrollEvent:(UIPanGestureRecognizer*)recognizer API_AVAILABLE(ios(13.4)) { + CGPoint translation = [recognizer translationInView:self.view]; + const CGFloat scale = self.flutterScreenIfViewLoaded.scale; + + translation.x *= scale; + translation.y *= scale; + + flutter::PointerData pointer_data = [self updateMousePointerDataFrom:recognizer]; + pointer_data.device = reinterpret_cast(recognizer); + pointer_data.kind = flutter::PointerData::DeviceKind::kMouse; + pointer_data.signal_kind = flutter::PointerData::SignalKind::kScroll; + pointer_data.scroll_delta_x = (translation.x - _mouseState.last_translation.x); + pointer_data.scroll_delta_y = -(translation.y - _mouseState.last_translation.y); + pointer_data.view_id = self.viewIdentifier; + + // The translation reported by UIPanGestureRecognizer is the total translation + // generated by the pan gesture since the gesture began. We need to be able + // to keep track of the last translation value in order to generate the deltaX + // and deltaY coordinates for each subsequent scroll event. + if (recognizer.state != UIGestureRecognizerStateEnded) { + _mouseState.last_translation = translation; + } else { + _mouseState.last_translation = CGPointZero; + } + + auto packet = std::make_unique(1); + packet->SetPointerData(/*i=*/0, pointer_data); + [self.engine dispatchPointerDataPacket:std::move(packet)]; +} + +- (void)continuousScrollEvent:(UIPanGestureRecognizer*)recognizer API_AVAILABLE(ios(13.4)) { + CGPoint translation = [recognizer translationInView:self.view]; + const CGFloat scale = self.flutterScreenIfViewLoaded.scale; + + flutter::PointerData pointer_data = [self updateMousePointerDataFrom:recognizer]; + pointer_data.device = reinterpret_cast(recognizer); + pointer_data.kind = flutter::PointerData::DeviceKind::kTrackpad; + pointer_data.view_id = self.viewIdentifier; + switch (recognizer.state) { + case UIGestureRecognizerStateBegan: + pointer_data.change = flutter::PointerData::Change::kPanZoomStart; + break; + case UIGestureRecognizerStateChanged: + pointer_data.change = flutter::PointerData::Change::kPanZoomUpdate; + pointer_data.pan_x = translation.x * scale; + pointer_data.pan_y = translation.y * scale; + pointer_data.pan_delta_x = 0; // Delta will be generated in pointer_data_packet_converter.cc. + pointer_data.pan_delta_y = 0; // Delta will be generated in pointer_data_packet_converter.cc. + pointer_data.scale = 1; + break; + case UIGestureRecognizerStateEnded: + case UIGestureRecognizerStateCancelled: + self.scrollInertiaEventStartline = + [[NSProcessInfo processInfo] systemUptime] + + 0.1; // Time to lift fingers off trackpad (experimentally determined) + // When running an iOS app on an Apple Silicon Mac, AppKit will send an event + // of type UIEventTypeScroll when trackpad scroll momentum has ended. This event + // is sent whether the momentum ended normally or was cancelled by a trackpad touch. + // Since Flutter scrolling inertia will likely not match the system inertia, we should + // only send a PointerScrollInertiaCancel event for user-initiated cancellations. + // The following (curve-fitted) calculation provides a cutoff point after which any + // UIEventTypeScroll event will likely be from the system instead of the user. + // See https://github.com/flutter/engine/pull/34929. + self.scrollInertiaEventAppKitDeadline = + [[NSProcessInfo processInfo] systemUptime] + + (0.1821 * log(fmax([recognizer velocityInView:self.view].x, + [recognizer velocityInView:self.view].y))) - + 0.4825; + pointer_data.change = flutter::PointerData::Change::kPanZoomEnd; + break; + default: + // continuousScrollEvent: should only ever be triggered with the above phases + NSAssert(NO, @"Trackpad pan event occured with unexpected phase 0x%lx", + (long)recognizer.state); + break; + } + + auto packet = std::make_unique(1); + packet->SetPointerData(/*i=*/0, pointer_data); + [self.engine dispatchPointerDataPacket:std::move(packet)]; +} + +- (void)pinchEvent:(UIPinchGestureRecognizer*)recognizer API_AVAILABLE(ios(13.4)) { + flutter::PointerData pointer_data = [self updateMousePointerDataFrom:recognizer]; + pointer_data.device = reinterpret_cast(recognizer); + pointer_data.kind = flutter::PointerData::DeviceKind::kTrackpad; + pointer_data.view_id = self.viewIdentifier; + switch (recognizer.state) { + case UIGestureRecognizerStateBegan: + pointer_data.change = flutter::PointerData::Change::kPanZoomStart; + break; + case UIGestureRecognizerStateChanged: + pointer_data.change = flutter::PointerData::Change::kPanZoomUpdate; + pointer_data.scale = recognizer.scale; + pointer_data.rotation = _rotationGestureRecognizer.rotation; + break; + case UIGestureRecognizerStateEnded: + case UIGestureRecognizerStateCancelled: + pointer_data.change = flutter::PointerData::Change::kPanZoomEnd; + break; + default: + // pinchEvent: should only ever be triggered with the above phases + NSAssert(NO, @"Trackpad pinch event occured with unexpected phase 0x%lx", + (long)recognizer.state); + break; + } + + auto packet = std::make_unique(1); + packet->SetPointerData(/*i=*/0, pointer_data); + [self.engine dispatchPointerDataPacket:std::move(packet)]; +} + +#pragma mark - State Restoration + +- (void)encodeRestorableStateWithCoder:(NSCoder*)coder { + NSData* restorationData = [self.engine.restorationPlugin restorationData]; + [coder encodeBytes:(const unsigned char*)restorationData.bytes + length:restorationData.length + forKey:kFlutterRestorationStateAppData]; + [super encodeRestorableStateWithCoder:coder]; +} + +- (void)decodeRestorableStateWithCoder:(NSCoder*)coder { + NSUInteger restorationDataLength; + const unsigned char* restorationBytes = [coder decodeBytesForKey:kFlutterRestorationStateAppData + returnedLength:&restorationDataLength]; + NSData* restorationData = [NSData dataWithBytes:restorationBytes length:restorationDataLength]; + [self.engine.restorationPlugin setRestorationData:restorationData]; +} + +- (FlutterRestorationPlugin*)restorationPlugin { + return self.engine.restorationPlugin; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewControllerTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewControllerTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..c98b3e2b82482fd76e6316a7f3ca3d38c19b71a6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewControllerTest.mm @@ -0,0 +1,2533 @@ +// 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. + +#import +#import + +#include "flutter/fml/platform/darwin/message_loop_darwin.h" +#import "flutter/lib/ui/window/platform_configuration.h" +#include "flutter/lib/ui/window/pointer_data.h" +#import "flutter/lib/ui/window/viewport_metrics.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterHourFormat.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/UIViewController+FlutterScreenAndSceneIfLoaded.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.h" +#import "flutter/shell/platform/embedder/embedder.h" +#import "flutter/third_party/spring_animation/spring_animation.h" + +FLUTTER_ASSERT_ARC + +using namespace flutter::testing; + +/// Sometimes we have to use a custom mock to avoid retain cycles in OCMock. +/// Used for testing low memory notification. +@interface FlutterEnginePartialMock : FlutterEngine + +@property(nonatomic, strong) FlutterBasicMessageChannel* lifecycleChannel; +@property(nonatomic, strong) FlutterBasicMessageChannel* keyEventChannel; +@property(nonatomic, weak) FlutterViewController* viewController; +@property(nonatomic, strong) FlutterTextInputPlugin* textInputPlugin; +@property(nonatomic, assign) BOOL didCallNotifyLowMemory; + +- (FlutterTextInputPlugin*)textInputPlugin; + +- (void)sendKeyEvent:(const FlutterKeyEvent&)event + callback:(nullable FlutterKeyEventCallback)callback + userData:(nullable void*)userData; +@end + +@implementation FlutterEnginePartialMock + +// Synthesize properties declared readonly in FlutterEngine. +@synthesize lifecycleChannel; +@synthesize keyEventChannel; +@synthesize viewController; +@synthesize textInputPlugin; + +- (void)notifyLowMemory { + _didCallNotifyLowMemory = YES; +} + +- (void)sendKeyEvent:(const FlutterKeyEvent&)event + callback:(FlutterKeyEventCallback)callback + userData:(void*)userData API_AVAILABLE(ios(9.0)) { + if (callback == nil) { + return; + } + // NSAssert(callback != nullptr, @"Invalid callback"); + // Response is async, so we have to post it to the run loop instead of calling + // it directly. + CFRunLoopPerformBlock(CFRunLoopGetCurrent(), fml::MessageLoopDarwin::kMessageLoopCFRunLoopMode, + ^() { + callback(true, userData); + }); +} +@end + +@interface FlutterEngine () +- (BOOL)createShell:(NSString*)entrypoint + libraryURI:(NSString*)libraryURI + initialRoute:(NSString*)initialRoute; +- (void)dispatchPointerDataPacket:(std::unique_ptr)packet; +- (void)updateViewportMetrics:(flutter::ViewportMetrics)viewportMetrics; +- (void)attachView; +@end + +@interface FlutterEngine (TestLowMemory) +- (void)notifyLowMemory; +@end + +extern NSNotificationName const FlutterViewControllerWillDealloc; + +/// A simple mock class for FlutterEngine. +/// +/// OCMClassMock can't be used for FlutterEngine sometimes because OCMock retains arguments to +/// invocations and since the init for FlutterViewController calls a method on the +/// FlutterEngine it creates a retain cycle that stops us from testing behaviors related to +/// deleting FlutterViewControllers. +/// +/// Used for testing deallocation. +@interface MockEngine : NSObject +@property(nonatomic, strong) FlutterDartProject* project; +@end + +@implementation MockEngine +- (FlutterViewController*)viewController { + return nil; +} +- (void)setViewController:(FlutterViewController*)viewController { + // noop +} +@end + +@interface FlutterKeyboardManager (Tests) +@property(nonatomic, retain, readonly) + NSMutableArray>* primaryResponders; +@end + +@interface FlutterEmbedderKeyResponder (Tests) +@property(nonatomic, copy, readonly) FlutterSendKeyEvent sendEvent; +@end + +@interface FlutterViewController (Tests) + +@property(nonatomic, assign) double targetViewInsetBottom; +@property(nonatomic, assign) BOOL isKeyboardInOrTransitioningFromBackground; +@property(nonatomic, assign) BOOL keyboardAnimationIsShowing; +@property(nonatomic, strong) VSyncClient* keyboardAnimationVSyncClient; +@property(nonatomic, strong) VSyncClient* touchRateCorrectionVSyncClient; + +- (void)createTouchRateCorrectionVSyncClientIfNeeded; +- (void)surfaceUpdated:(BOOL)appeared; +- (void)performOrientationUpdate:(UIInterfaceOrientationMask)new_preferences; +- (void)handlePressEvent:(FlutterUIPressProxy*)press + nextAction:(void (^)())next API_AVAILABLE(ios(13.4)); +- (void)discreteScrollEvent:(UIPanGestureRecognizer*)recognizer; +- (void)updateViewportMetricsIfNeeded; +- (void)onUserSettingsChanged:(NSNotification*)notification; +- (void)applicationWillTerminate:(NSNotification*)notification; +- (void)goToApplicationLifecycle:(nonnull NSString*)state; +- (void)handleKeyboardNotification:(NSNotification*)notification; +- (CGFloat)calculateKeyboardInset:(CGRect)keyboardFrame keyboardMode:(int)keyboardMode; +- (BOOL)shouldIgnoreKeyboardNotification:(NSNotification*)notification; +- (FlutterKeyboardMode)calculateKeyboardAttachMode:(NSNotification*)notification; +- (CGFloat)calculateMultitaskingAdjustment:(CGRect)screenRect keyboardFrame:(CGRect)keyboardFrame; +- (void)startKeyBoardAnimation:(NSTimeInterval)duration; +- (void)hideKeyboardImmediately; +- (UIView*)keyboardAnimationView; +- (SpringAnimation*)keyboardSpringAnimation; +- (void)setUpKeyboardSpringAnimationIfNeeded:(CAAnimation*)keyboardAnimation; +- (void)setUpKeyboardAnimationVsyncClient: + (FlutterKeyboardAnimationCallback)keyboardAnimationCallback; +- (void)ensureViewportMetricsIsCorrect; +- (void)invalidateKeyboardAnimationVSyncClient; +- (void)addInternalPlugins; +- (flutter::PointerData)generatePointerDataForFake; +- (void)sharedSetupWithProject:(nullable FlutterDartProject*)project + initialRoute:(nullable NSString*)initialRoute; +- (void)applicationBecameActive:(NSNotification*)notification; +- (void)applicationWillResignActive:(NSNotification*)notification; +- (void)applicationWillTerminate:(NSNotification*)notification; +- (void)applicationDidEnterBackground:(NSNotification*)notification; +- (void)applicationWillEnterForeground:(NSNotification*)notification; +- (void)sceneBecameActive:(NSNotification*)notification API_AVAILABLE(ios(13.0)); +- (void)sceneWillResignActive:(NSNotification*)notification API_AVAILABLE(ios(13.0)); +- (void)sceneWillDisconnect:(NSNotification*)notification API_AVAILABLE(ios(13.0)); +- (void)sceneDidEnterBackground:(NSNotification*)notification API_AVAILABLE(ios(13.0)); +- (void)sceneWillEnterForeground:(NSNotification*)notification API_AVAILABLE(ios(13.0)); +- (void)triggerTouchRateCorrectionIfNeeded:(NSSet*)touches; +@end + +@interface FlutterViewControllerTest : XCTestCase +@property(nonatomic, strong) id mockEngine; +@property(nonatomic, strong) id mockTextInputPlugin; +@property(nonatomic, strong) id messageSent; +- (void)sendMessage:(id _Nullable)message reply:(FlutterReply _Nullable)callback; +@end + +@interface UITouch () + +@property(nonatomic, readwrite) UITouchPhase phase; + +@end + +@interface VSyncClient (Testing) + +- (CADisplayLink*)getDisplayLink; + +@end + +@implementation FlutterViewControllerTest + +- (void)setUp { + self.mockEngine = OCMClassMock([FlutterEngine class]); + self.mockTextInputPlugin = OCMClassMock([FlutterTextInputPlugin class]); + OCMStub([self.mockEngine textInputPlugin]).andReturn(self.mockTextInputPlugin); + self.messageSent = nil; +} + +- (void)tearDown { + // We stop mocking here to avoid retain cycles that stop + // FlutterViewControllers from deallocing. + [self.mockEngine stopMocking]; + self.mockEngine = nil; + self.mockTextInputPlugin = nil; + self.messageSent = nil; +} + +- (id)setUpMockScreen { + UIScreen* mockScreen = OCMClassMock([UIScreen class]); + // iPhone 14 pixels + CGRect screenBounds = CGRectMake(0, 0, 1170, 2532); + OCMStub([mockScreen bounds]).andReturn(screenBounds); + CGFloat screenScale = 1; + OCMStub([mockScreen scale]).andReturn(screenScale); + + return mockScreen; +} + +- (id)setUpMockView:(FlutterViewController*)viewControllerMock + screen:(UIScreen*)screen + viewFrame:(CGRect)viewFrame + convertedFrame:(CGRect)convertedFrame { + OCMStub([viewControllerMock flutterScreenIfViewLoaded]).andReturn(screen); + id mockView = OCMClassMock([UIView class]); + OCMStub([mockView frame]).andReturn(viewFrame); + OCMStub([mockView convertRect:viewFrame toCoordinateSpace:[OCMArg any]]) + .andReturn(convertedFrame); + OCMStub([viewControllerMock viewIfLoaded]).andReturn(mockView); + + return mockView; +} + +- (void)testViewDidLoadWillInvokeCreateTouchRateCorrectionVSyncClient { + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + FlutterViewController* viewControllerMock = OCMPartialMock(viewController); + [viewControllerMock loadView]; + [viewControllerMock viewDidLoad]; + OCMVerify([viewControllerMock createTouchRateCorrectionVSyncClientIfNeeded]); +} + +- (void)testStartKeyboardAnimationWillInvokeSetupKeyboardSpringAnimationIfNeeded { + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + FlutterViewController* viewControllerMock = OCMPartialMock(viewController); + viewControllerMock.targetViewInsetBottom = 100; + [viewControllerMock startKeyBoardAnimation:0.25]; + + CAAnimation* keyboardAnimation = + [[viewControllerMock keyboardAnimationView].layer animationForKey:@"position"]; + + OCMVerify([viewControllerMock setUpKeyboardSpringAnimationIfNeeded:keyboardAnimation]); +} + +- (void)testSetupKeyboardSpringAnimationIfNeeded { + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + FlutterViewController* viewControllerMock = OCMPartialMock(viewController); + UIScreen* screen = [self setUpMockScreen]; + CGRect viewFrame = screen.bounds; + [self setUpMockView:viewControllerMock + screen:screen + viewFrame:viewFrame + convertedFrame:viewFrame]; + + // Null check. + [viewControllerMock setUpKeyboardSpringAnimationIfNeeded:nil]; + SpringAnimation* keyboardSpringAnimation = [viewControllerMock keyboardSpringAnimation]; + XCTAssertTrue(keyboardSpringAnimation == nil); + + // CAAnimation that is not a CASpringAnimation. + CABasicAnimation* nonSpringAnimation = [CABasicAnimation animation]; + nonSpringAnimation.duration = 1.0; + nonSpringAnimation.fromValue = [NSNumber numberWithFloat:0.0]; + nonSpringAnimation.toValue = [NSNumber numberWithFloat:1.0]; + nonSpringAnimation.keyPath = @"position"; + [viewControllerMock setUpKeyboardSpringAnimationIfNeeded:nonSpringAnimation]; + keyboardSpringAnimation = [viewControllerMock keyboardSpringAnimation]; + + XCTAssertTrue(keyboardSpringAnimation == nil); + + // CASpringAnimation. + CASpringAnimation* springAnimation = [CASpringAnimation animation]; + springAnimation.mass = 1.0; + springAnimation.stiffness = 100.0; + springAnimation.damping = 10.0; + springAnimation.keyPath = @"position"; + springAnimation.fromValue = [NSValue valueWithCGPoint:CGPointMake(0, 0)]; + springAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(100, 100)]; + [viewControllerMock setUpKeyboardSpringAnimationIfNeeded:springAnimation]; + keyboardSpringAnimation = [viewControllerMock keyboardSpringAnimation]; + XCTAssertTrue(keyboardSpringAnimation != nil); +} + +- (void)testKeyboardAnimationIsShowingAndCompounding { + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + FlutterViewController* viewControllerMock = OCMPartialMock(viewController); + UIScreen* screen = [self setUpMockScreen]; + CGRect viewFrame = screen.bounds; + [self setUpMockView:viewControllerMock + screen:screen + viewFrame:viewFrame + convertedFrame:viewFrame]; + + BOOL isLocal = YES; + CGFloat screenHeight = screen.bounds.size.height; + CGFloat screenWidth = screen.bounds.size.height; + + // Start show keyboard animation. + CGRect initialShowKeyboardBeginFrame = CGRectMake(0, screenHeight, screenWidth, 250); + CGRect initialShowKeyboardEndFrame = CGRectMake(0, screenHeight - 250, screenWidth, 500); + NSNotification* fakeNotification = [NSNotification + notificationWithName:UIKeyboardWillChangeFrameNotification + object:nil + userInfo:@{ + @"UIKeyboardFrameBeginUserInfoKey" : @(initialShowKeyboardBeginFrame), + @"UIKeyboardFrameEndUserInfoKey" : @(initialShowKeyboardEndFrame), + @"UIKeyboardAnimationDurationUserInfoKey" : @(0.25), + @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) + }]; + viewControllerMock.targetViewInsetBottom = 0; + [viewControllerMock handleKeyboardNotification:fakeNotification]; + BOOL isShowingAnimation1 = viewControllerMock.keyboardAnimationIsShowing; + XCTAssertTrue(isShowingAnimation1); + + // Start compounding show keyboard animation. + CGRect compoundingShowKeyboardBeginFrame = CGRectMake(0, screenHeight - 250, screenWidth, 250); + CGRect compoundingShowKeyboardEndFrame = CGRectMake(0, screenHeight - 500, screenWidth, 500); + fakeNotification = [NSNotification + notificationWithName:UIKeyboardWillChangeFrameNotification + object:nil + userInfo:@{ + @"UIKeyboardFrameBeginUserInfoKey" : @(compoundingShowKeyboardBeginFrame), + @"UIKeyboardFrameEndUserInfoKey" : @(compoundingShowKeyboardEndFrame), + @"UIKeyboardAnimationDurationUserInfoKey" : @(0.25), + @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) + }]; + + [viewControllerMock handleKeyboardNotification:fakeNotification]; + BOOL isShowingAnimation2 = viewControllerMock.keyboardAnimationIsShowing; + XCTAssertTrue(isShowingAnimation2); + XCTAssertTrue(isShowingAnimation1 == isShowingAnimation2); + + // Start hide keyboard animation. + CGRect initialHideKeyboardBeginFrame = CGRectMake(0, screenHeight - 500, screenWidth, 250); + CGRect initialHideKeyboardEndFrame = CGRectMake(0, screenHeight - 250, screenWidth, 500); + fakeNotification = [NSNotification + notificationWithName:UIKeyboardWillChangeFrameNotification + object:nil + userInfo:@{ + @"UIKeyboardFrameBeginUserInfoKey" : @(initialHideKeyboardBeginFrame), + @"UIKeyboardFrameEndUserInfoKey" : @(initialHideKeyboardEndFrame), + @"UIKeyboardAnimationDurationUserInfoKey" : @(0.25), + @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) + }]; + + [viewControllerMock handleKeyboardNotification:fakeNotification]; + BOOL isShowingAnimation3 = viewControllerMock.keyboardAnimationIsShowing; + XCTAssertFalse(isShowingAnimation3); + XCTAssertTrue(isShowingAnimation2 != isShowingAnimation3); + + // Start compounding hide keyboard animation. + CGRect compoundingHideKeyboardBeginFrame = CGRectMake(0, screenHeight - 250, screenWidth, 250); + CGRect compoundingHideKeyboardEndFrame = CGRectMake(0, screenHeight, screenWidth, 500); + fakeNotification = [NSNotification + notificationWithName:UIKeyboardWillChangeFrameNotification + object:nil + userInfo:@{ + @"UIKeyboardFrameBeginUserInfoKey" : @(compoundingHideKeyboardBeginFrame), + @"UIKeyboardFrameEndUserInfoKey" : @(compoundingHideKeyboardEndFrame), + @"UIKeyboardAnimationDurationUserInfoKey" : @(0.25), + @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) + }]; + + [viewControllerMock handleKeyboardNotification:fakeNotification]; + BOOL isShowingAnimation4 = viewControllerMock.keyboardAnimationIsShowing; + XCTAssertFalse(isShowingAnimation4); + XCTAssertTrue(isShowingAnimation3 == isShowingAnimation4); +} + +- (void)testShouldIgnoreKeyboardNotification { + FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); + [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + FlutterViewController* viewControllerMock = OCMPartialMock(viewController); + UIScreen* screen = [self setUpMockScreen]; + CGRect viewFrame = screen.bounds; + [self setUpMockView:viewControllerMock + screen:screen + viewFrame:viewFrame + convertedFrame:viewFrame]; + + CGFloat screenWidth = screen.bounds.size.width; + CGFloat screenHeight = screen.bounds.size.height; + CGRect emptyKeyboard = CGRectZero; + CGRect zeroHeightKeyboard = CGRectMake(0, 0, screenWidth, 0); + CGRect validKeyboardEndFrame = CGRectMake(0, screenHeight - 320, screenWidth, 320); + BOOL isLocal = NO; + + // Hide notification, valid keyboard + NSNotification* notification = + [NSNotification notificationWithName:UIKeyboardWillHideNotification + object:nil + userInfo:@{ + @"UIKeyboardFrameEndUserInfoKey" : @(validKeyboardEndFrame), + @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, + @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) + }]; + + BOOL shouldIgnore = [viewControllerMock shouldIgnoreKeyboardNotification:notification]; + XCTAssertTrue(shouldIgnore == NO); + + // All zero keyboard + isLocal = YES; + notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification + object:nil + userInfo:@{ + @"UIKeyboardFrameEndUserInfoKey" : @(emptyKeyboard), + @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, + @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) + }]; + shouldIgnore = [viewControllerMock shouldIgnoreKeyboardNotification:notification]; + XCTAssertTrue(shouldIgnore == YES); + + // Zero height keyboard + isLocal = NO; + notification = + [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification + object:nil + userInfo:@{ + @"UIKeyboardFrameEndUserInfoKey" : @(zeroHeightKeyboard), + @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, + @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) + }]; + shouldIgnore = [viewControllerMock shouldIgnoreKeyboardNotification:notification]; + XCTAssertTrue(shouldIgnore == NO); + + // Valid keyboard, triggered from another app + isLocal = NO; + notification = + [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification + object:nil + userInfo:@{ + @"UIKeyboardFrameEndUserInfoKey" : @(validKeyboardEndFrame), + @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, + @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) + }]; + shouldIgnore = [viewControllerMock shouldIgnoreKeyboardNotification:notification]; + XCTAssertTrue(shouldIgnore == YES); + + // Valid keyboard + isLocal = YES; + notification = + [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification + object:nil + userInfo:@{ + @"UIKeyboardFrameEndUserInfoKey" : @(validKeyboardEndFrame), + @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, + @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) + }]; + shouldIgnore = [viewControllerMock shouldIgnoreKeyboardNotification:notification]; + XCTAssertTrue(shouldIgnore == NO); + + if (@available(iOS 13.0, *)) { + // noop + } else { + // Valid keyboard, keyboard is in background + OCMStub([viewControllerMock isKeyboardInOrTransitioningFromBackground]).andReturn(YES); + + isLocal = YES; + notification = + [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification + object:nil + userInfo:@{ + @"UIKeyboardFrameEndUserInfoKey" : @(validKeyboardEndFrame), + @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, + @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) + }]; + shouldIgnore = [viewControllerMock shouldIgnoreKeyboardNotification:notification]; + XCTAssertTrue(shouldIgnore == YES); + } +} +- (void)testKeyboardAnimationWillNotCrashWhenEngineDestroyed { + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + [viewController setUpKeyboardAnimationVsyncClient:^(fml::TimePoint){ + }]; + [engine destroyContext]; +} + +- (void)testKeyboardAnimationWillWaitUIThreadVsync { + // We need to make sure the new viewport metrics get sent after the + // begin frame event has processed. And this test is to expect that the callback + // will sync with UI thread. So just simulate a lot of works on UI thread and + // test the keyboard animation callback will execute until UI task completed. + // Related issue: https://github.com/flutter/flutter/issues/120555. + + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + // Post a task to UI thread to block the thread. + const int delayTime = 1; + [engine uiTaskRunner]->PostTask([] { sleep(delayTime); }); + XCTestExpectation* expectation = [self expectationWithDescription:@"keyboard animation callback"]; + + __block CFTimeInterval fulfillTime; + FlutterKeyboardAnimationCallback callback = ^(fml::TimePoint targetTime) { + fulfillTime = CACurrentMediaTime(); + [expectation fulfill]; + }; + CFTimeInterval startTime = CACurrentMediaTime(); + [viewController setUpKeyboardAnimationVsyncClient:callback]; + [self waitForExpectationsWithTimeout:5.0 handler:nil]; + XCTAssertTrue(fulfillTime - startTime > delayTime); +} + +- (void)testCalculateKeyboardAttachMode { + FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); + [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + + FlutterViewController* viewControllerMock = OCMPartialMock(viewController); + UIScreen* screen = [self setUpMockScreen]; + CGRect viewFrame = screen.bounds; + [self setUpMockView:viewControllerMock + screen:screen + viewFrame:viewFrame + convertedFrame:viewFrame]; + + CGFloat screenWidth = screen.bounds.size.width; + CGFloat screenHeight = screen.bounds.size.height; + + // hide notification + CGRect keyboardFrame = CGRectZero; + NSNotification* notification = + [NSNotification notificationWithName:UIKeyboardWillHideNotification + object:nil + userInfo:@{ + @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame), + @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, + @"UIKeyboardIsLocalUserInfoKey" : @(YES) + }]; + FlutterKeyboardMode keyboardMode = [viewControllerMock calculateKeyboardAttachMode:notification]; + XCTAssertTrue(keyboardMode == FlutterKeyboardModeHidden); + + // all zeros + keyboardFrame = CGRectZero; + notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification + object:nil + userInfo:@{ + @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame), + @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, + @"UIKeyboardIsLocalUserInfoKey" : @(YES) + }]; + keyboardMode = [viewControllerMock calculateKeyboardAttachMode:notification]; + XCTAssertTrue(keyboardMode == FlutterKeyboardModeFloating); + + // 0 height + keyboardFrame = CGRectMake(0, 0, screenWidth, 0); + notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification + object:nil + userInfo:@{ + @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame), + @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, + @"UIKeyboardIsLocalUserInfoKey" : @(YES) + }]; + keyboardMode = [viewControllerMock calculateKeyboardAttachMode:notification]; + XCTAssertTrue(keyboardMode == FlutterKeyboardModeHidden); + + // floating + keyboardFrame = CGRectMake(0, 0, 320, 320); + notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification + object:nil + userInfo:@{ + @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame), + @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, + @"UIKeyboardIsLocalUserInfoKey" : @(YES) + }]; + keyboardMode = [viewControllerMock calculateKeyboardAttachMode:notification]; + XCTAssertTrue(keyboardMode == FlutterKeyboardModeFloating); + + // undocked + keyboardFrame = CGRectMake(0, 0, screenWidth, 320); + notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification + object:nil + userInfo:@{ + @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame), + @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, + @"UIKeyboardIsLocalUserInfoKey" : @(YES) + }]; + keyboardMode = [viewControllerMock calculateKeyboardAttachMode:notification]; + XCTAssertTrue(keyboardMode == FlutterKeyboardModeFloating); + + // docked + keyboardFrame = CGRectMake(0, screenHeight - 320, screenWidth, 320); + notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification + object:nil + userInfo:@{ + @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame), + @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, + @"UIKeyboardIsLocalUserInfoKey" : @(YES) + }]; + keyboardMode = [viewControllerMock calculateKeyboardAttachMode:notification]; + XCTAssertTrue(keyboardMode == FlutterKeyboardModeDocked); + + // docked - rounded values + CGFloat longDecimalHeight = 320.666666666666666; + keyboardFrame = CGRectMake(0, screenHeight - longDecimalHeight, screenWidth, longDecimalHeight); + notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification + object:nil + userInfo:@{ + @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame), + @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, + @"UIKeyboardIsLocalUserInfoKey" : @(YES) + }]; + keyboardMode = [viewControllerMock calculateKeyboardAttachMode:notification]; + XCTAssertTrue(keyboardMode == FlutterKeyboardModeDocked); + + // hidden - rounded values + keyboardFrame = CGRectMake(0, screenHeight - .0000001, screenWidth, longDecimalHeight); + notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification + object:nil + userInfo:@{ + @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame), + @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, + @"UIKeyboardIsLocalUserInfoKey" : @(YES) + }]; + keyboardMode = [viewControllerMock calculateKeyboardAttachMode:notification]; + XCTAssertTrue(keyboardMode == FlutterKeyboardModeHidden); + + // hidden + keyboardFrame = CGRectMake(0, screenHeight, screenWidth, 320); + notification = [NSNotification notificationWithName:UIKeyboardWillChangeFrameNotification + object:nil + userInfo:@{ + @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame), + @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, + @"UIKeyboardIsLocalUserInfoKey" : @(YES) + }]; + keyboardMode = [viewControllerMock calculateKeyboardAttachMode:notification]; + XCTAssertTrue(keyboardMode == FlutterKeyboardModeHidden); +} + +- (void)testCalculateMultitaskingAdjustment { + FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); + [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + FlutterViewController* viewControllerMock = OCMPartialMock(viewController); + + UIScreen* screen = [self setUpMockScreen]; + CGFloat screenWidth = screen.bounds.size.width; + CGFloat screenHeight = screen.bounds.size.height; + CGRect screenRect = screen.bounds; + CGRect viewOrigFrame = CGRectMake(0, 0, 320, screenHeight - 40); + CGRect convertedViewFrame = CGRectMake(20, 20, 320, screenHeight - 40); + CGRect keyboardFrame = CGRectMake(20, screenHeight - 320, screenWidth, 300); + id mockView = [self setUpMockView:viewControllerMock + screen:screen + viewFrame:viewOrigFrame + convertedFrame:convertedViewFrame]; + id mockTraitCollection = OCMClassMock([UITraitCollection class]); + OCMStub([mockTraitCollection userInterfaceIdiom]).andReturn(UIUserInterfaceIdiomPad); + OCMStub([mockTraitCollection horizontalSizeClass]).andReturn(UIUserInterfaceSizeClassCompact); + OCMStub([mockTraitCollection verticalSizeClass]).andReturn(UIUserInterfaceSizeClassRegular); + OCMStub([mockView traitCollection]).andReturn(mockTraitCollection); + + CGFloat adjustment = [viewControllerMock calculateMultitaskingAdjustment:screenRect + keyboardFrame:keyboardFrame]; + XCTAssertTrue(adjustment == 20); +} + +- (void)testCalculateKeyboardInset { + FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); + [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + FlutterViewController* viewControllerMock = OCMPartialMock(viewController); + UIScreen* screen = [self setUpMockScreen]; + OCMStub([viewControllerMock flutterScreenIfViewLoaded]).andReturn(screen); + + CGFloat screenWidth = screen.bounds.size.width; + CGFloat screenHeight = screen.bounds.size.height; + CGRect viewOrigFrame = CGRectMake(0, 0, 320, screenHeight - 40); + CGRect convertedViewFrame = CGRectMake(20, 20, 320, screenHeight - 40); + CGRect keyboardFrame = CGRectMake(20, screenHeight - 320, screenWidth, 300); + + [self setUpMockView:viewControllerMock + screen:screen + viewFrame:viewOrigFrame + convertedFrame:convertedViewFrame]; + + CGFloat inset = [viewControllerMock calculateKeyboardInset:keyboardFrame + keyboardMode:FlutterKeyboardModeDocked]; + XCTAssertTrue(inset == 300 * screen.scale); +} + +- (void)testHandleKeyboardNotification { + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + // keyboard is empty + UIScreen* screen = [self setUpMockScreen]; + CGFloat screenWidth = screen.bounds.size.width; + CGFloat screenHeight = screen.bounds.size.height; + CGRect keyboardFrame = CGRectMake(0, screenHeight - 320, screenWidth, 320); + CGRect viewFrame = screen.bounds; + BOOL isLocal = YES; + NSNotification* notification = + [NSNotification notificationWithName:UIKeyboardWillShowNotification + object:nil + userInfo:@{ + @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame), + @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, + @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) + }]; + FlutterViewController* viewControllerMock = OCMPartialMock(viewController); + [self setUpMockView:viewControllerMock + screen:screen + viewFrame:viewFrame + convertedFrame:viewFrame]; + viewControllerMock.targetViewInsetBottom = 0; + XCTestExpectation* expectation = [self expectationWithDescription:@"update viewport"]; + OCMStub([viewControllerMock updateViewportMetricsIfNeeded]).andDo(^(NSInvocation* invocation) { + [expectation fulfill]; + }); + + [viewControllerMock handleKeyboardNotification:notification]; + XCTAssertTrue(viewControllerMock.targetViewInsetBottom == 320 * screen.scale); + OCMVerify([viewControllerMock startKeyBoardAnimation:0.25]); + [self waitForExpectationsWithTimeout:5.0 handler:nil]; +} + +- (void)testEnsureBottomInsetIsZeroWhenKeyboardDismissed { + FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); + [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + + FlutterViewController* viewControllerMock = OCMPartialMock(viewController); + CGRect keyboardFrame = CGRectZero; + BOOL isLocal = YES; + NSNotification* fakeNotification = + [NSNotification notificationWithName:UIKeyboardWillHideNotification + object:nil + userInfo:@{ + @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame), + @"UIKeyboardAnimationDurationUserInfoKey" : @(0.25), + @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) + }]; + + viewControllerMock.targetViewInsetBottom = 10; + [viewControllerMock handleKeyboardNotification:fakeNotification]; + XCTAssertTrue(viewControllerMock.targetViewInsetBottom == 0); +} + +- (void)testStopKeyBoardAnimationWhenReceivedWillHideNotificationAfterWillShowNotification { + // see: https://github.com/flutter/flutter/issues/112281 + + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + FlutterViewController* viewControllerMock = OCMPartialMock(viewController); + UIScreen* screen = [self setUpMockScreen]; + CGRect viewFrame = screen.bounds; + [self setUpMockView:viewControllerMock + screen:screen + viewFrame:viewFrame + convertedFrame:viewFrame]; + viewControllerMock.targetViewInsetBottom = 0; + + CGFloat screenHeight = screen.bounds.size.height; + CGFloat screenWidth = screen.bounds.size.height; + CGRect keyboardFrame = CGRectMake(0, screenHeight - 320, screenWidth, 320); + BOOL isLocal = YES; + + // Receive will show notification + NSNotification* fakeShowNotification = + [NSNotification notificationWithName:UIKeyboardWillShowNotification + object:nil + userInfo:@{ + @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame), + @"UIKeyboardAnimationDurationUserInfoKey" : @0.25, + @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) + }]; + [viewControllerMock handleKeyboardNotification:fakeShowNotification]; + XCTAssertTrue(viewControllerMock.targetViewInsetBottom == 320 * screen.scale); + + // Receive will hide notification + NSNotification* fakeHideNotification = + [NSNotification notificationWithName:UIKeyboardWillHideNotification + object:nil + userInfo:@{ + @"UIKeyboardFrameEndUserInfoKey" : @(keyboardFrame), + @"UIKeyboardAnimationDurationUserInfoKey" : @(0.0), + @"UIKeyboardIsLocalUserInfoKey" : @(isLocal) + }]; + [viewControllerMock handleKeyboardNotification:fakeHideNotification]; + XCTAssertTrue(viewControllerMock.targetViewInsetBottom == 0); + + // Check if the keyboard animation is stopped. + XCTAssertNil(viewControllerMock.keyboardAnimationView); + XCTAssertNil(viewControllerMock.keyboardSpringAnimation); +} + +- (void)testEnsureViewportMetricsWillInvokeAndDisplayLinkWillInvalidateInViewDidDisappear { + FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); + [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + id viewControllerMock = OCMPartialMock(viewController); + [viewControllerMock viewDidDisappear:YES]; + OCMVerify([viewControllerMock ensureViewportMetricsIsCorrect]); + OCMVerify([viewControllerMock invalidateKeyboardAnimationVSyncClient]); +} + +- (void)testViewDidDisappearDoesntPauseEngineWhenNotTheViewController { + id lifecycleChannel = OCMClassMock([FlutterBasicMessageChannel class]); + FlutterEnginePartialMock* mockEngine = [[FlutterEnginePartialMock alloc] init]; + mockEngine.lifecycleChannel = lifecycleChannel; + FlutterViewController* viewControllerA = + [[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil]; + FlutterViewController* viewControllerB = + [[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil]; + id viewControllerMock = OCMPartialMock(viewControllerA); + OCMStub([viewControllerMock surfaceUpdated:NO]); + mockEngine.viewController = viewControllerB; + [viewControllerA viewDidDisappear:NO]; + OCMReject([lifecycleChannel sendMessage:@"AppLifecycleState.paused"]); + OCMReject([viewControllerMock surfaceUpdated:[OCMArg any]]); +} + +- (void)testAppWillTerminateViewDidDestroyTheEngine { + FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); + [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + id viewControllerMock = OCMPartialMock(viewController); + OCMStub([viewControllerMock goToApplicationLifecycle:@"AppLifecycleState.detached"]); + OCMStub([mockEngine destroyContext]); + [viewController applicationWillTerminate:nil]; + OCMVerify([viewControllerMock goToApplicationLifecycle:@"AppLifecycleState.detached"]); + OCMVerify([mockEngine destroyContext]); +} + +- (void)testViewDidDisappearDoesPauseEngineWhenIsTheViewController { + id lifecycleChannel = OCMClassMock([FlutterBasicMessageChannel class]); + FlutterEnginePartialMock* mockEngine = [[FlutterEnginePartialMock alloc] init]; + mockEngine.lifecycleChannel = lifecycleChannel; + __weak FlutterViewController* weakViewController; + @autoreleasepool { + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + weakViewController = viewController; + id viewControllerMock = OCMPartialMock(viewController); + OCMStub([viewControllerMock surfaceUpdated:NO]); + [viewController viewDidDisappear:NO]; + OCMVerify([lifecycleChannel sendMessage:@"AppLifecycleState.paused"]); + OCMVerify([viewControllerMock surfaceUpdated:NO]); + } + XCTAssertNil(weakViewController); +} + +- (void) + testEngineConfigSyncMethodWillExecuteWhenViewControllerInEngineIsCurrentViewControllerInViewWillAppear { + FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); + [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + [viewController viewWillAppear:YES]; + OCMVerify([viewController onUserSettingsChanged:nil]); +} + +- (void) + testEngineConfigSyncMethodWillNotExecuteWhenViewControllerInEngineIsNotCurrentViewControllerInViewWillAppear { + FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); + [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; + FlutterViewController* viewControllerA = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + mockEngine.viewController = nil; + FlutterViewController* viewControllerB = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + mockEngine.viewController = nil; + mockEngine.viewController = viewControllerB; + [viewControllerA viewWillAppear:YES]; + OCMVerify(never(), [viewControllerA onUserSettingsChanged:nil]); +} + +- (void) + testEngineConfigSyncMethodWillExecuteWhenViewControllerInEngineIsCurrentViewControllerInViewDidAppear { + FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); + [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + [viewController viewDidAppear:YES]; + OCMVerify([viewController onUserSettingsChanged:nil]); +} + +- (void) + testEngineConfigSyncMethodWillNotExecuteWhenViewControllerInEngineIsNotCurrentViewControllerInViewDidAppear { + FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); + [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; + FlutterViewController* viewControllerA = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + mockEngine.viewController = nil; + FlutterViewController* viewControllerB = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + mockEngine.viewController = nil; + mockEngine.viewController = viewControllerB; + [viewControllerA viewDidAppear:YES]; + OCMVerify(never(), [viewControllerA onUserSettingsChanged:nil]); +} + +- (void) + testEngineConfigSyncMethodWillExecuteWhenViewControllerInEngineIsCurrentViewControllerInViewWillDisappear { + id lifecycleChannel = OCMClassMock([FlutterBasicMessageChannel class]); + FlutterEnginePartialMock* mockEngine = [[FlutterEnginePartialMock alloc] init]; + mockEngine.lifecycleChannel = lifecycleChannel; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + mockEngine.viewController = viewController; + [viewController viewWillDisappear:NO]; + OCMVerify([lifecycleChannel sendMessage:@"AppLifecycleState.inactive"]); +} + +- (void) + testEngineConfigSyncMethodWillNotExecuteWhenViewControllerInEngineIsNotCurrentViewControllerInViewWillDisappear { + id lifecycleChannel = OCMClassMock([FlutterBasicMessageChannel class]); + FlutterEnginePartialMock* mockEngine = [[FlutterEnginePartialMock alloc] init]; + mockEngine.lifecycleChannel = lifecycleChannel; + FlutterViewController* viewControllerA = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + FlutterViewController* viewControllerB = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + mockEngine.viewController = viewControllerB; + [viewControllerA viewDidDisappear:NO]; + OCMReject([lifecycleChannel sendMessage:@"AppLifecycleState.inactive"]); +} + +- (void)testUpdateViewportMetricsIfNeeded_DoesntInvokeEngineWhenNotTheViewController { + FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); + [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; + FlutterViewController* viewControllerA = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + mockEngine.viewController = nil; + FlutterViewController* viewControllerB = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + mockEngine.viewController = viewControllerB; + [viewControllerA updateViewportMetricsIfNeeded]; + flutter::ViewportMetrics viewportMetrics; + OCMVerify(never(), [mockEngine updateViewportMetrics:viewportMetrics]); +} + +- (void)testUpdateViewportMetricsIfNeeded_DoesInvokeEngineWhenIsTheViewController { + FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); + [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + mockEngine.viewController = viewController; + flutter::ViewportMetrics viewportMetrics; + OCMExpect([mockEngine updateViewportMetrics:viewportMetrics]).ignoringNonObjectArgs(); + [viewController updateViewportMetricsIfNeeded]; + OCMVerifyAll(mockEngine); +} + +- (void)testUpdateViewportMetricsIfNeeded_DoesNotInvokeEngineWhenShouldBeIgnoredDuringRotation { + FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); + [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + FlutterViewController* viewControllerMock = OCMPartialMock(viewController); + UIScreen* screen = [self setUpMockScreen]; + OCMStub([viewControllerMock flutterScreenIfViewLoaded]).andReturn(screen); + mockEngine.viewController = viewController; + + id mockCoordinator = OCMProtocolMock(@protocol(UIViewControllerTransitionCoordinator)); + OCMStub([mockCoordinator transitionDuration]).andReturn(0.5); + + // Mimic the device rotation. + [viewController viewWillTransitionToSize:CGSizeZero withTransitionCoordinator:mockCoordinator]; + // Should not trigger the engine call when during rotation. + [viewController updateViewportMetricsIfNeeded]; + + OCMVerify(never(), [mockEngine updateViewportMetrics:flutter::ViewportMetrics()]); +} + +- (void)testViewWillTransitionToSize_DoesDelayEngineCallIfNonZeroDuration { + FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); + [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + FlutterViewController* viewControllerMock = OCMPartialMock(viewController); + UIScreen* screen = [self setUpMockScreen]; + OCMStub([viewControllerMock flutterScreenIfViewLoaded]).andReturn(screen); + mockEngine.viewController = viewController; + + // Mimic the device rotation with non-zero transition duration. + NSTimeInterval transitionDuration = 0.5; + id mockCoordinator = OCMProtocolMock(@protocol(UIViewControllerTransitionCoordinator)); + OCMStub([mockCoordinator transitionDuration]).andReturn(transitionDuration); + + flutter::ViewportMetrics viewportMetrics; + OCMExpect([mockEngine updateViewportMetrics:viewportMetrics]).ignoringNonObjectArgs(); + + [viewController viewWillTransitionToSize:CGSizeZero withTransitionCoordinator:mockCoordinator]; + // Should not immediately call the engine (this request should be ignored). + [viewController updateViewportMetricsIfNeeded]; + OCMVerify(never(), [mockEngine updateViewportMetrics:flutter::ViewportMetrics()]); + + // Should delay the engine call for half of the transition duration. + // Wait for additional transitionDuration to allow updateViewportMetrics calls if any. + XCTWaiterResult result = [XCTWaiter + waitForExpectations:@[ [self expectationWithDescription:@"Waiting for rotation duration"] ] + timeout:transitionDuration]; + XCTAssertEqual(result, XCTWaiterResultTimedOut); + + OCMVerifyAll(mockEngine); +} + +- (void)testViewWillTransitionToSize_DoesNotDelayEngineCallIfZeroDuration { + FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); + [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + FlutterViewController* viewControllerMock = OCMPartialMock(viewController); + UIScreen* screen = [self setUpMockScreen]; + OCMStub([viewControllerMock flutterScreenIfViewLoaded]).andReturn(screen); + mockEngine.viewController = viewController; + + // Mimic the device rotation with zero transition duration. + id mockCoordinator = OCMProtocolMock(@protocol(UIViewControllerTransitionCoordinator)); + OCMStub([mockCoordinator transitionDuration]).andReturn(0); + + flutter::ViewportMetrics viewportMetrics; + OCMExpect([mockEngine updateViewportMetrics:viewportMetrics]).ignoringNonObjectArgs(); + + // Should immediately trigger the engine call, without delay. + [viewController viewWillTransitionToSize:CGSizeZero withTransitionCoordinator:mockCoordinator]; + [viewController updateViewportMetricsIfNeeded]; + + OCMVerifyAll(mockEngine); +} + +- (void)testViewDidLoadDoesntInvokeEngineWhenNotTheViewController { + FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); + [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; + FlutterViewController* viewControllerA = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + mockEngine.viewController = nil; + FlutterViewController* viewControllerB = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + mockEngine.viewController = viewControllerB; + UIView* view = viewControllerA.view; + XCTAssertNotNil(view); + OCMVerify(never(), [mockEngine attachView]); +} + +- (void)testViewDidLoadDoesInvokeEngineWhenIsTheViewController { + FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); + [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; + mockEngine.viewController = nil; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + mockEngine.viewController = viewController; + UIView* view = viewController.view; + XCTAssertNotNil(view); + OCMVerify(times(1), [mockEngine attachView]); +} + +- (void)testViewDidLoadDoesntInvokeEngineAttachViewWhenEngineNeedsLaunch { + FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); + [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; + mockEngine.viewController = nil; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + // sharedSetupWithProject sets the engine needs to be launched. + [viewController sharedSetupWithProject:nil initialRoute:nil]; + mockEngine.viewController = viewController; + UIView* view = viewController.view; + XCTAssertNotNil(view); + OCMVerify(never(), [mockEngine attachView]); +} + +- (void)testSplashScreenViewRemoveNotCrash { + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"engine" project:nil]; + [engine runWithEntrypoint:nil]; + FlutterViewController* flutterViewController = + [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; + [flutterViewController setSplashScreenView:[[UIView alloc] init]]; + [flutterViewController setSplashScreenView:nil]; +} + +- (void)testInternalPluginsWeakPtrNotCrash { + FlutterSendKeyEvent sendEvent; + @autoreleasepool { + FlutterViewController* vc = [[FlutterViewController alloc] initWithProject:nil + nibName:nil + bundle:nil]; + [vc addInternalPlugins]; + FlutterKeyboardManager* keyboardManager = vc.keyboardManager; + FlutterEmbedderKeyResponder* keyPrimaryResponder = (FlutterEmbedderKeyResponder*) + [(NSArray>*)keyboardManager.primaryResponders firstObject]; + sendEvent = [keyPrimaryResponder sendEvent]; + } + + if (sendEvent) { + sendEvent({}, nil, nil); + } +} + +// Regression test for https://github.com/flutter/engine/pull/32098. +- (void)testInternalPluginsInvokeInViewDidLoad { + FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); + [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + UIView* view = viewController.view; + // The implementation in viewDidLoad requires the viewControllers.viewLoaded is true. + // Accessing the view to make sure the view loads in the memory, + // which makes viewControllers.viewLoaded true. + XCTAssertNotNil(view); + [viewController viewDidLoad]; + OCMVerify([viewController addInternalPlugins]); +} + +- (void)testBinaryMessenger { + FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine + nibName:nil + bundle:nil]; + XCTAssertNotNil(vc); + id messenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub([self.mockEngine binaryMessenger]).andReturn(messenger); + XCTAssertEqual(vc.binaryMessenger, messenger); + OCMVerify([self.mockEngine binaryMessenger]); +} + +- (void)testViewControllerIsReleased { + __weak FlutterViewController* weakViewController; + __weak UIView* weakView; + @autoreleasepool { + FlutterEngine* engine = [[FlutterEngine alloc] init]; + + [engine runWithEntrypoint:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + weakViewController = viewController; + [viewController loadView]; + [viewController viewDidLoad]; + weakView = viewController.view; + XCTAssertTrue([viewController.view isKindOfClass:[FlutterView class]]); + } + XCTAssertNil(weakViewController); + XCTAssertNil(weakView); +} + +#pragma mark - Platform Brightness + +- (void)testItReportsLightPlatformBrightnessByDefault { + // Setup test. + id settingsChannel = OCMClassMock([FlutterBasicMessageChannel class]); + OCMStub([self.mockEngine settingsChannel]).andReturn(settingsChannel); + + FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine + nibName:nil + bundle:nil]; + + // Exercise behavior under test. + [vc traitCollectionDidChange:nil]; + + // Verify behavior. + OCMVerify([settingsChannel sendMessage:[OCMArg checkWithBlock:^BOOL(id message) { + return [message[@"platformBrightness"] isEqualToString:@"light"]; + }]]); + + // Clean up mocks + [settingsChannel stopMocking]; +} + +- (void)testItReportsPlatformBrightnessWhenViewWillAppear { + // Setup test. + id settingsChannel = OCMClassMock([FlutterBasicMessageChannel class]); + FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); + [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; + OCMStub([mockEngine settingsChannel]).andReturn(settingsChannel); + FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + + // Exercise behavior under test. + [vc viewWillAppear:false]; + + // Verify behavior. + OCMVerify([settingsChannel sendMessage:[OCMArg checkWithBlock:^BOOL(id message) { + return [message[@"platformBrightness"] isEqualToString:@"light"]; + }]]); + + // Clean up mocks + [settingsChannel stopMocking]; +} + +- (void)testItReportsDarkPlatformBrightnessWhenTraitCollectionRequestsIt { + if (@available(iOS 13, *)) { + // noop + } else { + return; + } + + // Setup test. + id settingsChannel = OCMClassMock([FlutterBasicMessageChannel class]); + OCMStub([self.mockEngine settingsChannel]).andReturn(settingsChannel); + id mockTraitCollection = + [self fakeTraitCollectionWithUserInterfaceStyle:UIUserInterfaceStyleDark]; + + // We partially mock the real FlutterViewController to act as the OS and report + // the UITraitCollection of our choice. Mocking the object under test is not + // desirable, but given that the OS does not offer a DI approach to providing + // our own UITraitCollection, this seems to be the least bad option. + id partialMockVC = OCMPartialMock([[FlutterViewController alloc] initWithEngine:self.mockEngine + nibName:nil + bundle:nil]); + OCMStub([partialMockVC traitCollection]).andReturn(mockTraitCollection); + + // Exercise behavior under test. + [partialMockVC traitCollectionDidChange:nil]; + + // Verify behavior. + OCMVerify([settingsChannel sendMessage:[OCMArg checkWithBlock:^BOOL(id message) { + return [message[@"platformBrightness"] isEqualToString:@"dark"]; + }]]); + + // Clean up mocks + [partialMockVC stopMocking]; + [settingsChannel stopMocking]; + [mockTraitCollection stopMocking]; +} + +// Creates a mocked UITraitCollection with nil values for everything except userInterfaceStyle, +// which is set to the given "style". +- (UITraitCollection*)fakeTraitCollectionWithUserInterfaceStyle:(UIUserInterfaceStyle)style { + id mockTraitCollection = OCMClassMock([UITraitCollection class]); + OCMStub([mockTraitCollection userInterfaceStyle]).andReturn(style); + return mockTraitCollection; +} + +#pragma mark - Platform Contrast + +- (void)testItReportsNormalPlatformContrastByDefault { + if (@available(iOS 13, *)) { + // noop + } else { + return; + } + + // Setup test. + id settingsChannel = OCMClassMock([FlutterBasicMessageChannel class]); + OCMStub([self.mockEngine settingsChannel]).andReturn(settingsChannel); + + FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine + nibName:nil + bundle:nil]; + + // Exercise behavior under test. + [vc traitCollectionDidChange:nil]; + + // Verify behavior. + OCMVerify([settingsChannel sendMessage:[OCMArg checkWithBlock:^BOOL(id message) { + return [message[@"platformContrast"] isEqualToString:@"normal"]; + }]]); + + // Clean up mocks + [settingsChannel stopMocking]; +} + +- (void)testItReportsPlatformContrastWhenViewWillAppear { + if (@available(iOS 13, *)) { + // noop + } else { + return; + } + FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); + [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; + + // Setup test. + id settingsChannel = OCMClassMock([FlutterBasicMessageChannel class]); + OCMStub([mockEngine settingsChannel]).andReturn(settingsChannel); + FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + + // Exercise behavior under test. + [vc viewWillAppear:false]; + + // Verify behavior. + OCMVerify([settingsChannel sendMessage:[OCMArg checkWithBlock:^BOOL(id message) { + return [message[@"platformContrast"] isEqualToString:@"normal"]; + }]]); + + // Clean up mocks + [settingsChannel stopMocking]; +} + +- (void)testItReportsHighContrastWhenTraitCollectionRequestsIt { + if (@available(iOS 13, *)) { + // noop + } else { + return; + } + + // Setup test. + id settingsChannel = OCMClassMock([FlutterBasicMessageChannel class]); + OCMStub([self.mockEngine settingsChannel]).andReturn(settingsChannel); + + id mockTraitCollection = [self fakeTraitCollectionWithContrast:UIAccessibilityContrastHigh]; + + // We partially mock the real FlutterViewController to act as the OS and report + // the UITraitCollection of our choice. Mocking the object under test is not + // desirable, but given that the OS does not offer a DI approach to providing + // our own UITraitCollection, this seems to be the least bad option. + id partialMockVC = OCMPartialMock([[FlutterViewController alloc] initWithEngine:self.mockEngine + nibName:nil + bundle:nil]); + OCMStub([partialMockVC traitCollection]).andReturn(mockTraitCollection); + + // Exercise behavior under test. + [partialMockVC traitCollectionDidChange:mockTraitCollection]; + + // Verify behavior. + OCMVerify([settingsChannel sendMessage:[OCMArg checkWithBlock:^BOOL(id message) { + return [message[@"platformContrast"] isEqualToString:@"high"]; + }]]); + + // Clean up mocks + [partialMockVC stopMocking]; + [settingsChannel stopMocking]; + [mockTraitCollection stopMocking]; +} + +- (void)testItReportsAlwaysUsed24HourFormat { + // Setup test. + id settingsChannel = OCMStrictClassMock([FlutterBasicMessageChannel class]); + OCMStub([self.mockEngine settingsChannel]).andReturn(settingsChannel); + FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine + nibName:nil + bundle:nil]; + // Test the YES case. + id mockHourFormat = OCMClassMock([FlutterHourFormat class]); + OCMStub([mockHourFormat isAlwaysUse24HourFormat]).andReturn(YES); + OCMExpect([settingsChannel sendMessage:[OCMArg checkWithBlock:^BOOL(id message) { + return [message[@"alwaysUse24HourFormat"] isEqual:@(YES)]; + }]]); + [vc onUserSettingsChanged:nil]; + [mockHourFormat stopMocking]; + + // Test the NO case. + mockHourFormat = OCMClassMock([FlutterHourFormat class]); + OCMStub([mockHourFormat isAlwaysUse24HourFormat]).andReturn(NO); + OCMExpect([settingsChannel sendMessage:[OCMArg checkWithBlock:^BOOL(id message) { + return [message[@"alwaysUse24HourFormat"] isEqual:@(NO)]; + }]]); + [vc onUserSettingsChanged:nil]; + [mockHourFormat stopMocking]; + + // Clean up mocks. + [settingsChannel stopMocking]; +} + +- (void)testItReportsAccessibilityOnOffSwitchLabelsFlagNotSet { + if (@available(iOS 13, *)) { + // noop + } else { + return; + } + + // Setup test. + FlutterViewController* viewController = + [[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil]; + id partialMockViewController = OCMPartialMock(viewController); + OCMStub([partialMockViewController accessibilityIsOnOffSwitchLabelsEnabled]).andReturn(NO); + + // Exercise behavior under test. + int32_t flags = [partialMockViewController accessibilityFlags]; + + // Verify behavior. + XCTAssert((flags & (int32_t)flutter::AccessibilityFeatureFlag::kOnOffSwitchLabels) == 0); +} + +- (void)testItReportsAccessibilityOnOffSwitchLabelsFlagSet { + if (@available(iOS 13, *)) { + // noop + } else { + return; + } + + // Setup test. + FlutterViewController* viewController = + [[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil]; + id partialMockViewController = OCMPartialMock(viewController); + OCMStub([partialMockViewController accessibilityIsOnOffSwitchLabelsEnabled]).andReturn(YES); + + // Exercise behavior under test. + int32_t flags = [partialMockViewController accessibilityFlags]; + + // Verify behavior. + XCTAssert((flags & (int32_t)flutter::AccessibilityFeatureFlag::kOnOffSwitchLabels) != 0); +} + +- (void)testAccessibilityPerformEscapePopsRoute { + FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); + [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; + id mockNavigationChannel = OCMClassMock([FlutterMethodChannel class]); + OCMStub([mockEngine navigationChannel]).andReturn(mockNavigationChannel); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + XCTAssertTrue([viewController accessibilityPerformEscape]); + + OCMVerify([mockNavigationChannel invokeMethod:@"popRoute" arguments:nil]); + + [mockNavigationChannel stopMocking]; +} + +- (void)testPerformOrientationUpdateForcesOrientationChange { + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskPortrait + currentOrientation:UIInterfaceOrientationLandscapeLeft + didChangeOrientation:YES + resultingOrientation:UIInterfaceOrientationPortrait]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskPortrait + currentOrientation:UIInterfaceOrientationLandscapeRight + didChangeOrientation:YES + resultingOrientation:UIInterfaceOrientationPortrait]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskPortrait + currentOrientation:UIInterfaceOrientationPortraitUpsideDown + didChangeOrientation:YES + resultingOrientation:UIInterfaceOrientationPortrait]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskPortraitUpsideDown + currentOrientation:UIInterfaceOrientationLandscapeLeft + didChangeOrientation:YES + resultingOrientation:UIInterfaceOrientationPortraitUpsideDown]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskPortraitUpsideDown + currentOrientation:UIInterfaceOrientationLandscapeRight + didChangeOrientation:YES + resultingOrientation:UIInterfaceOrientationPortraitUpsideDown]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskPortraitUpsideDown + currentOrientation:UIInterfaceOrientationPortrait + didChangeOrientation:YES + resultingOrientation:UIInterfaceOrientationPortraitUpsideDown]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscape + currentOrientation:UIInterfaceOrientationPortrait + didChangeOrientation:YES + resultingOrientation:UIInterfaceOrientationLandscapeLeft]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscape + currentOrientation:UIInterfaceOrientationPortraitUpsideDown + didChangeOrientation:YES + resultingOrientation:UIInterfaceOrientationLandscapeLeft]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscapeLeft + currentOrientation:UIInterfaceOrientationPortrait + didChangeOrientation:YES + resultingOrientation:UIInterfaceOrientationLandscapeLeft]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscapeLeft + currentOrientation:UIInterfaceOrientationLandscapeRight + didChangeOrientation:YES + resultingOrientation:UIInterfaceOrientationLandscapeLeft]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscapeLeft + currentOrientation:UIInterfaceOrientationPortraitUpsideDown + didChangeOrientation:YES + resultingOrientation:UIInterfaceOrientationLandscapeLeft]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscapeRight + currentOrientation:UIInterfaceOrientationPortrait + didChangeOrientation:YES + resultingOrientation:UIInterfaceOrientationLandscapeRight]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscapeRight + currentOrientation:UIInterfaceOrientationLandscapeLeft + didChangeOrientation:YES + resultingOrientation:UIInterfaceOrientationLandscapeRight]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscapeRight + currentOrientation:UIInterfaceOrientationPortraitUpsideDown + didChangeOrientation:YES + resultingOrientation:UIInterfaceOrientationLandscapeRight]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskAllButUpsideDown + currentOrientation:UIInterfaceOrientationPortraitUpsideDown + didChangeOrientation:YES + resultingOrientation:UIInterfaceOrientationPortrait]; +} + +- (void)testPerformOrientationUpdateDoesNotForceOrientationChange { + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskAll + currentOrientation:UIInterfaceOrientationPortrait + didChangeOrientation:NO + resultingOrientation:static_cast(0)]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskAll + currentOrientation:UIInterfaceOrientationPortraitUpsideDown + didChangeOrientation:NO + resultingOrientation:static_cast(0)]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskAll + currentOrientation:UIInterfaceOrientationLandscapeLeft + didChangeOrientation:NO + resultingOrientation:static_cast(0)]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskAll + currentOrientation:UIInterfaceOrientationLandscapeRight + didChangeOrientation:NO + resultingOrientation:static_cast(0)]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskAllButUpsideDown + currentOrientation:UIInterfaceOrientationPortrait + didChangeOrientation:NO + resultingOrientation:static_cast(0)]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskAllButUpsideDown + currentOrientation:UIInterfaceOrientationLandscapeLeft + didChangeOrientation:NO + resultingOrientation:static_cast(0)]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskAllButUpsideDown + currentOrientation:UIInterfaceOrientationLandscapeRight + didChangeOrientation:NO + resultingOrientation:static_cast(0)]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskPortrait + currentOrientation:UIInterfaceOrientationPortrait + didChangeOrientation:NO + resultingOrientation:static_cast(0)]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskPortraitUpsideDown + currentOrientation:UIInterfaceOrientationPortraitUpsideDown + didChangeOrientation:NO + resultingOrientation:static_cast(0)]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscape + currentOrientation:UIInterfaceOrientationLandscapeLeft + didChangeOrientation:NO + resultingOrientation:static_cast(0)]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscape + currentOrientation:UIInterfaceOrientationLandscapeRight + didChangeOrientation:NO + resultingOrientation:static_cast(0)]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscapeLeft + currentOrientation:UIInterfaceOrientationLandscapeLeft + didChangeOrientation:NO + resultingOrientation:static_cast(0)]; + + [self orientationTestWithOrientationUpdate:UIInterfaceOrientationMaskLandscapeRight + currentOrientation:UIInterfaceOrientationLandscapeRight + didChangeOrientation:NO + resultingOrientation:static_cast(0)]; +} + +// Perform an orientation update test that fails when the expected outcome +// for an orientation update is not met +- (void)orientationTestWithOrientationUpdate:(UIInterfaceOrientationMask)mask + currentOrientation:(UIInterfaceOrientation)currentOrientation + didChangeOrientation:(BOOL)didChange + resultingOrientation:(UIInterfaceOrientation)resultingOrientation { + id mockApplication = OCMClassMock([UIApplication class]); + id mockWindowScene; + id deviceMock; + id mockVC; + __block __weak id weakPreferences; + @autoreleasepool { + FlutterViewController* realVC = [[FlutterViewController alloc] initWithEngine:self.mockEngine + nibName:nil + bundle:nil]; + + if (@available(iOS 16.0, *)) { + mockWindowScene = OCMClassMock([UIWindowScene class]); + mockVC = OCMPartialMock(realVC); + OCMStub([mockVC flutterWindowSceneIfViewLoaded]).andReturn(mockWindowScene); + if (realVC.supportedInterfaceOrientations == mask) { + OCMReject([mockWindowScene requestGeometryUpdateWithPreferences:[OCMArg any] + errorHandler:[OCMArg any]]); + } else { + // iOS 16 will decide whether to rotate based on the new preference, so always set it + // when it changes. + OCMExpect([mockWindowScene + requestGeometryUpdateWithPreferences:[OCMArg checkWithBlock:^BOOL( + UIWindowSceneGeometryPreferencesIOS* + preferences) { + weakPreferences = preferences; + return preferences.interfaceOrientations == mask; + }] + errorHandler:[OCMArg any]]); + } + OCMStub([mockApplication sharedApplication]).andReturn(mockApplication); + OCMStub([mockApplication connectedScenes]).andReturn([NSSet setWithObject:mockWindowScene]); + } else { + deviceMock = OCMPartialMock([UIDevice currentDevice]); + if (!didChange) { + OCMReject([deviceMock setValue:[OCMArg any] forKey:@"orientation"]); + } else { + OCMExpect([deviceMock setValue:@(resultingOrientation) forKey:@"orientation"]); + } + if (@available(iOS 13.0, *)) { + mockWindowScene = OCMClassMock([UIWindowScene class]); + mockVC = OCMPartialMock(realVC); + OCMStub([mockVC flutterWindowSceneIfViewLoaded]).andReturn(mockWindowScene); + OCMStub(((UIWindowScene*)mockWindowScene).interfaceOrientation) + .andReturn(currentOrientation); + } else { + OCMStub([mockApplication sharedApplication]).andReturn(mockApplication); + OCMStub([mockApplication statusBarOrientation]).andReturn(currentOrientation); + } + } + + [realVC performOrientationUpdate:mask]; + if (@available(iOS 16.0, *)) { + OCMVerifyAll(mockWindowScene); + } else { + OCMVerifyAll(deviceMock); + } + } + [mockWindowScene stopMocking]; + [deviceMock stopMocking]; + [mockApplication stopMocking]; + XCTAssertNil(weakPreferences); +} + +// Creates a mocked UITraitCollection with nil values for everything except accessibilityContrast, +// which is set to the given "contrast". +- (UITraitCollection*)fakeTraitCollectionWithContrast:(UIAccessibilityContrast)contrast { + id mockTraitCollection = OCMClassMock([UITraitCollection class]); + OCMStub([mockTraitCollection accessibilityContrast]).andReturn(contrast); + return mockTraitCollection; +} + +- (void)testWillDeallocNotification { + XCTestExpectation* expectation = + [[XCTestExpectation alloc] initWithDescription:@"notification called"]; + id engine = [[MockEngine alloc] init]; + @autoreleasepool { + // NOLINTNEXTLINE(clang-analyzer-deadcode.DeadStores) + FlutterViewController* realVC = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + [NSNotificationCenter.defaultCenter addObserverForName:FlutterViewControllerWillDealloc + object:nil + queue:[NSOperationQueue mainQueue] + usingBlock:^(NSNotification* _Nonnull note) { + [expectation fulfill]; + }]; + XCTAssertNotNil(realVC); + realVC = nil; + } + [self waitForExpectations:@[ expectation ] timeout:1.0]; +} + +- (void)testReleasesKeyboardManagerOnDealloc { + __weak FlutterKeyboardManager* weakKeyboardManager = nil; + @autoreleasepool { + FlutterViewController* viewController = [[FlutterViewController alloc] init]; + + [viewController addInternalPlugins]; + weakKeyboardManager = viewController.keyboardManager; + XCTAssertNotNil(weakKeyboardManager); + [viewController deregisterNotifications]; + viewController = nil; + } + // View controller has released the keyboard manager. + XCTAssertNil(weakKeyboardManager); +} + +- (void)testDoesntLoadViewInInit { + FlutterDartProject* project = [[FlutterDartProject alloc] init]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project]; + [engine createShell:@"" libraryURI:@"" initialRoute:nil]; + FlutterViewController* realVC = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + XCTAssertFalse([realVC isViewLoaded], @"shouldn't have loaded since it hasn't been shown"); + engine.viewController = nil; +} + +- (void)testHideOverlay { + FlutterDartProject* project = [[FlutterDartProject alloc] init]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project]; + [engine createShell:@"" libraryURI:@"" initialRoute:nil]; + FlutterViewController* realVC = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + XCTAssertFalse(realVC.prefersHomeIndicatorAutoHidden, @""); + [NSNotificationCenter.defaultCenter postNotificationName:FlutterViewControllerHideHomeIndicator + object:nil]; + XCTAssertTrue(realVC.prefersHomeIndicatorAutoHidden, @""); + engine.viewController = nil; +} + +- (void)testNotifyLowMemory { + FlutterEnginePartialMock* mockEngine = [[FlutterEnginePartialMock alloc] init]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + id viewControllerMock = OCMPartialMock(viewController); + OCMStub([viewControllerMock surfaceUpdated:NO]); + [viewController beginAppearanceTransition:NO animated:NO]; + [viewController endAppearanceTransition]; + XCTAssertTrue(mockEngine.didCallNotifyLowMemory); +} + +- (void)sendMessage:(id _Nullable)message reply:(FlutterReply _Nullable)callback { + NSMutableDictionary* replyMessage = [@{ + @"handled" : @YES, + } mutableCopy]; + // Response is async, so we have to post it to the run loop instead of calling + // it directly. + self.messageSent = message; + CFRunLoopPerformBlock(CFRunLoopGetCurrent(), fml::MessageLoopDarwin::kMessageLoopCFRunLoopMode, + ^() { + callback(replyMessage); + }); +} + +- (void)testValidKeyUpEvent API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + // noop + } else { + return; + } + FlutterEnginePartialMock* mockEngine = [[FlutterEnginePartialMock alloc] init]; + mockEngine.keyEventChannel = OCMClassMock([FlutterBasicMessageChannel class]); + OCMStub([mockEngine.keyEventChannel sendMessage:[OCMArg any] reply:[OCMArg any]]) + .andCall(self, @selector(sendMessage:reply:)); + OCMStub([self.mockTextInputPlugin handlePress:[OCMArg any]]).andReturn(YES); + mockEngine.textInputPlugin = self.mockTextInputPlugin; + + FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + + // Allocate the keyboard manager in the view controller by adding the internal + // plugins. + [vc addInternalPlugins]; + + [vc handlePressEvent:keyUpEvent(UIKeyboardHIDUsageKeyboardA, UIKeyModifierShift, 123.0) + nextAction:^(){ + }]; + + XCTAssert(self.messageSent != nil); + XCTAssert([self.messageSent[@"keymap"] isEqualToString:@"ios"]); + XCTAssert([self.messageSent[@"type"] isEqualToString:@"keyup"]); + XCTAssert([self.messageSent[@"keyCode"] isEqualToNumber:[NSNumber numberWithInt:4]]); + XCTAssert([self.messageSent[@"modifiers"] isEqualToNumber:[NSNumber numberWithInt:0]]); + XCTAssert([self.messageSent[@"characters"] isEqualToString:@""]); + XCTAssert([self.messageSent[@"charactersIgnoringModifiers"] isEqualToString:@""]); + [vc deregisterNotifications]; +} + +- (void)testValidKeyDownEvent API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + // noop + } else { + return; + } + + FlutterEnginePartialMock* mockEngine = [[FlutterEnginePartialMock alloc] init]; + mockEngine.keyEventChannel = OCMClassMock([FlutterBasicMessageChannel class]); + OCMStub([mockEngine.keyEventChannel sendMessage:[OCMArg any] reply:[OCMArg any]]) + .andCall(self, @selector(sendMessage:reply:)); + OCMStub([self.mockTextInputPlugin handlePress:[OCMArg any]]).andReturn(YES); + mockEngine.textInputPlugin = self.mockTextInputPlugin; + + __strong FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + // Allocate the keyboard manager in the view controller by adding the internal + // plugins. + [vc addInternalPlugins]; + + [vc handlePressEvent:keyDownEvent(UIKeyboardHIDUsageKeyboardA, UIKeyModifierShift, 123.0f, "A", + "a") + nextAction:^(){ + }]; + + XCTAssert(self.messageSent != nil); + XCTAssert([self.messageSent[@"keymap"] isEqualToString:@"ios"]); + XCTAssert([self.messageSent[@"type"] isEqualToString:@"keydown"]); + XCTAssert([self.messageSent[@"keyCode"] isEqualToNumber:[NSNumber numberWithInt:4]]); + XCTAssert([self.messageSent[@"modifiers"] isEqualToNumber:[NSNumber numberWithInt:0]]); + XCTAssert([self.messageSent[@"characters"] isEqualToString:@"A"]); + XCTAssert([self.messageSent[@"charactersIgnoringModifiers"] isEqualToString:@"a"]); + [vc deregisterNotifications]; + vc = nil; +} + +- (void)testIgnoredKeyEvents API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + // noop + } else { + return; + } + id keyEventChannel = OCMClassMock([FlutterBasicMessageChannel class]); + OCMStub([keyEventChannel sendMessage:[OCMArg any] reply:[OCMArg any]]) + .andCall(self, @selector(sendMessage:reply:)); + OCMStub([self.mockTextInputPlugin handlePress:[OCMArg any]]).andReturn(YES); + OCMStub([self.mockEngine keyEventChannel]).andReturn(keyEventChannel); + + FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine + nibName:nil + bundle:nil]; + + // Allocate the keyboard manager in the view controller by adding the internal + // plugins. + [vc addInternalPlugins]; + + [vc handlePressEvent:keyEventWithPhase(UIPressPhaseStationary, UIKeyboardHIDUsageKeyboardA, + UIKeyModifierShift, 123.0) + nextAction:^(){ + }]; + [vc handlePressEvent:keyEventWithPhase(UIPressPhaseCancelled, UIKeyboardHIDUsageKeyboardA, + UIKeyModifierShift, 123.0) + nextAction:^(){ + }]; + [vc handlePressEvent:keyEventWithPhase(UIPressPhaseChanged, UIKeyboardHIDUsageKeyboardA, + UIKeyModifierShift, 123.0) + nextAction:^(){ + }]; + + XCTAssert(self.messageSent == nil); + OCMVerify(never(), [keyEventChannel sendMessage:[OCMArg any]]); + [vc deregisterNotifications]; +} + +- (void)testPanGestureRecognizer API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + // noop + } else { + return; + } + + FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine + nibName:nil + bundle:nil]; + XCTAssertNotNil(vc); + UIView* view = vc.view; + XCTAssertNotNil(view); + NSArray* gestureRecognizers = view.gestureRecognizers; + XCTAssertNotNil(gestureRecognizers); + + BOOL found = NO; + for (id gesture in gestureRecognizers) { + if ([gesture isKindOfClass:[UIPanGestureRecognizer class]]) { + found = YES; + break; + } + } + XCTAssertTrue(found); +} + +- (void)testMouseSupport API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + // noop + } else { + return; + } + + FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine + nibName:nil + bundle:nil]; + XCTAssertNotNil(vc); + + id mockPanGestureRecognizer = OCMClassMock([UIPanGestureRecognizer class]); + XCTAssertNotNil(mockPanGestureRecognizer); + + [vc discreteScrollEvent:mockPanGestureRecognizer]; + + // The mouse position within panGestureRecognizer should be checked + [[mockPanGestureRecognizer verify] locationInView:[OCMArg any]]; + [[[self.mockEngine verify] ignoringNonObjectArgs] + dispatchPointerDataPacket:std::make_unique(0)]; +} + +- (void)testFakeEventTimeStamp { + FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine + nibName:nil + bundle:nil]; + XCTAssertNotNil(vc); + + flutter::PointerData pointer_data = [vc generatePointerDataForFake]; + int64_t current_micros = [[NSProcessInfo processInfo] systemUptime] * 1000 * 1000; + int64_t interval_micros = current_micros - pointer_data.time_stamp; + const int64_t tolerance_millis = 2; + XCTAssertTrue(interval_micros / 1000 < tolerance_millis, + @"PointerData.time_stamp should be equal to NSProcessInfo.systemUptime"); +} + +- (void)testSplashScreenViewCanSetNil { + FlutterViewController* flutterViewController = + [[FlutterViewController alloc] initWithProject:nil nibName:nil bundle:nil]; + [flutterViewController setSplashScreenView:nil]; +} + +- (void)testLifeCycleNotificationApplicationBecameActive { + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* flutterViewController = + [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; + UIWindow* window = [[UIWindow alloc] init]; + [window addSubview:flutterViewController.view]; + flutterViewController.view.bounds = CGRectMake(0, 0, 100, 100); + [flutterViewController viewDidLayoutSubviews]; + NSNotification* sceneNotification = + [NSNotification notificationWithName:UISceneDidActivateNotification object:nil userInfo:nil]; + NSNotification* applicationNotification = + [NSNotification notificationWithName:UIApplicationDidBecomeActiveNotification + object:nil + userInfo:nil]; + id mockVC = OCMPartialMock(flutterViewController); + [NSNotificationCenter.defaultCenter postNotification:sceneNotification]; + [NSNotificationCenter.defaultCenter postNotification:applicationNotification]; + OCMReject([mockVC sceneBecameActive:[OCMArg any]]); + OCMVerify([mockVC applicationBecameActive:[OCMArg any]]); + XCTAssertFalse(flutterViewController.isKeyboardInOrTransitioningFromBackground); + OCMVerify([mockVC surfaceUpdated:YES]); + XCTestExpectation* timeoutApplicationLifeCycle = + [self expectationWithDescription:@"timeoutApplicationLifeCycle"]; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), + dispatch_get_main_queue(), ^{ + [timeoutApplicationLifeCycle fulfill]; + OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.resumed"]); + [flutterViewController deregisterNotifications]; + }); + [self waitForExpectationsWithTimeout:5.0 handler:nil]; +} + +- (void)testLifeCycleNotificationSceneBecameActive { + id mockBundle = OCMPartialMock([NSBundle mainBundle]); + OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{ + @"NSExtensionPointIdentifier" : @"com.apple.share-services" + }); + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* flutterViewController = + [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; + UIWindow* window = [[UIWindow alloc] init]; + [window addSubview:flutterViewController.view]; + flutterViewController.view.bounds = CGRectMake(0, 0, 100, 100); + [flutterViewController viewDidLayoutSubviews]; + NSNotification* sceneNotification = + [NSNotification notificationWithName:UISceneDidActivateNotification object:nil userInfo:nil]; + NSNotification* applicationNotification = + [NSNotification notificationWithName:UIApplicationDidBecomeActiveNotification + object:nil + userInfo:nil]; + id mockVC = OCMPartialMock(flutterViewController); + [NSNotificationCenter.defaultCenter postNotification:sceneNotification]; + [NSNotificationCenter.defaultCenter postNotification:applicationNotification]; + OCMVerify([mockVC sceneBecameActive:[OCMArg any]]); + OCMReject([mockVC applicationBecameActive:[OCMArg any]]); + XCTAssertFalse(flutterViewController.isKeyboardInOrTransitioningFromBackground); + OCMVerify([mockVC surfaceUpdated:YES]); + XCTestExpectation* timeoutApplicationLifeCycle = + [self expectationWithDescription:@"timeoutApplicationLifeCycle"]; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), + dispatch_get_main_queue(), ^{ + [timeoutApplicationLifeCycle fulfill]; + OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.resumed"]); + [flutterViewController deregisterNotifications]; + }); + [self waitForExpectationsWithTimeout:5.0 handler:nil]; + [mockBundle stopMocking]; +} + +- (void)testLifeCycleNotificationApplicationWillResignActive { + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* flutterViewController = + [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; + NSNotification* sceneNotification = + [NSNotification notificationWithName:UISceneWillDeactivateNotification + object:nil + userInfo:nil]; + NSNotification* applicationNotification = + [NSNotification notificationWithName:UIApplicationWillResignActiveNotification + object:nil + userInfo:nil]; + id mockVC = OCMPartialMock(flutterViewController); + [NSNotificationCenter.defaultCenter postNotification:sceneNotification]; + [NSNotificationCenter.defaultCenter postNotification:applicationNotification]; + OCMReject([mockVC sceneWillResignActive:[OCMArg any]]); + OCMVerify([mockVC applicationWillResignActive:[OCMArg any]]); + OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.inactive"]); + [flutterViewController deregisterNotifications]; +} + +- (void)testLifeCycleNotificationSceneWillResignActive { + id mockBundle = OCMPartialMock([NSBundle mainBundle]); + OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{ + @"NSExtensionPointIdentifier" : @"com.apple.share-services" + }); + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* flutterViewController = + [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; + NSNotification* sceneNotification = + [NSNotification notificationWithName:UISceneWillDeactivateNotification + object:nil + userInfo:nil]; + NSNotification* applicationNotification = + [NSNotification notificationWithName:UIApplicationWillResignActiveNotification + object:nil + userInfo:nil]; + id mockVC = OCMPartialMock(flutterViewController); + [NSNotificationCenter.defaultCenter postNotification:sceneNotification]; + [NSNotificationCenter.defaultCenter postNotification:applicationNotification]; + OCMVerify([mockVC sceneWillResignActive:[OCMArg any]]); + OCMReject([mockVC applicationWillResignActive:[OCMArg any]]); + OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.inactive"]); + [flutterViewController deregisterNotifications]; + [mockBundle stopMocking]; +} + +- (void)testLifeCycleNotificationApplicationWillTerminate { + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* flutterViewController = + [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; + NSNotification* sceneNotification = + [NSNotification notificationWithName:UISceneDidDisconnectNotification + object:nil + userInfo:nil]; + NSNotification* applicationNotification = + [NSNotification notificationWithName:UIApplicationWillTerminateNotification + object:nil + userInfo:nil]; + id mockVC = OCMPartialMock(flutterViewController); + id mockEngine = OCMPartialMock(engine); + OCMStub([mockVC engine]).andReturn(mockEngine); + [NSNotificationCenter.defaultCenter postNotification:sceneNotification]; + [NSNotificationCenter.defaultCenter postNotification:applicationNotification]; + OCMReject([mockVC sceneWillDisconnect:[OCMArg any]]); + OCMVerify([mockVC applicationWillTerminate:[OCMArg any]]); + OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.detached"]); + OCMVerify([mockEngine destroyContext]); + [flutterViewController deregisterNotifications]; +} + +- (void)testLifeCycleNotificationSceneWillTerminate { + id mockBundle = OCMPartialMock([NSBundle mainBundle]); + OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{ + @"NSExtensionPointIdentifier" : @"com.apple.share-services" + }); + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* flutterViewController = + [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; + NSNotification* sceneNotification = + [NSNotification notificationWithName:UISceneDidDisconnectNotification + object:nil + userInfo:nil]; + NSNotification* applicationNotification = + [NSNotification notificationWithName:UIApplicationWillTerminateNotification + object:nil + userInfo:nil]; + id mockVC = OCMPartialMock(flutterViewController); + id mockEngine = OCMPartialMock(engine); + OCMStub([mockVC engine]).andReturn(mockEngine); + [NSNotificationCenter.defaultCenter postNotification:sceneNotification]; + [NSNotificationCenter.defaultCenter postNotification:applicationNotification]; + OCMVerify([mockVC sceneWillDisconnect:[OCMArg any]]); + OCMReject([mockVC applicationWillTerminate:[OCMArg any]]); + OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.detached"]); + OCMVerify([mockEngine destroyContext]); + [flutterViewController deregisterNotifications]; + [mockBundle stopMocking]; +} + +- (void)testLifeCycleNotificationApplicationDidEnterBackground { + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* flutterViewController = + [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; + NSNotification* sceneNotification = + [NSNotification notificationWithName:UISceneDidEnterBackgroundNotification + object:nil + userInfo:nil]; + NSNotification* applicationNotification = + [NSNotification notificationWithName:UIApplicationDidEnterBackgroundNotification + object:nil + userInfo:nil]; + id mockVC = OCMPartialMock(flutterViewController); + [NSNotificationCenter.defaultCenter postNotification:sceneNotification]; + [NSNotificationCenter.defaultCenter postNotification:applicationNotification]; + OCMReject([mockVC sceneDidEnterBackground:[OCMArg any]]); + OCMVerify([mockVC applicationDidEnterBackground:[OCMArg any]]); + XCTAssertTrue(flutterViewController.isKeyboardInOrTransitioningFromBackground); + OCMVerify([mockVC surfaceUpdated:NO]); + OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.paused"]); + [flutterViewController deregisterNotifications]; +} + +- (void)testLifeCycleNotificationSceneDidEnterBackground { + id mockBundle = OCMPartialMock([NSBundle mainBundle]); + OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{ + @"NSExtensionPointIdentifier" : @"com.apple.share-services" + }); + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* flutterViewController = + [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; + NSNotification* sceneNotification = + [NSNotification notificationWithName:UISceneDidEnterBackgroundNotification + object:nil + userInfo:nil]; + NSNotification* applicationNotification = + [NSNotification notificationWithName:UIApplicationDidEnterBackgroundNotification + object:nil + userInfo:nil]; + id mockVC = OCMPartialMock(flutterViewController); + [NSNotificationCenter.defaultCenter postNotification:sceneNotification]; + [NSNotificationCenter.defaultCenter postNotification:applicationNotification]; + OCMVerify([mockVC sceneDidEnterBackground:[OCMArg any]]); + OCMReject([mockVC applicationDidEnterBackground:[OCMArg any]]); + XCTAssertTrue(flutterViewController.isKeyboardInOrTransitioningFromBackground); + OCMVerify([mockVC surfaceUpdated:NO]); + OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.paused"]); + [flutterViewController deregisterNotifications]; + [mockBundle stopMocking]; +} + +- (void)testLifeCycleNotificationApplicationWillEnterForeground { + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* flutterViewController = + [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; + NSNotification* sceneNotification = + [NSNotification notificationWithName:UISceneWillEnterForegroundNotification + object:nil + userInfo:nil]; + NSNotification* applicationNotification = + [NSNotification notificationWithName:UIApplicationWillEnterForegroundNotification + object:nil + userInfo:nil]; + id mockVC = OCMPartialMock(flutterViewController); + [NSNotificationCenter.defaultCenter postNotification:sceneNotification]; + [NSNotificationCenter.defaultCenter postNotification:applicationNotification]; + OCMReject([mockVC sceneWillEnterForeground:[OCMArg any]]); + OCMVerify([mockVC applicationWillEnterForeground:[OCMArg any]]); + OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.inactive"]); + [flutterViewController deregisterNotifications]; +} + +- (void)testLifeCycleNotificationSceneWillEnterForeground { + id mockBundle = OCMPartialMock([NSBundle mainBundle]); + OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{ + @"NSExtensionPointIdentifier" : @"com.apple.share-services" + }); + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* flutterViewController = + [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; + NSNotification* sceneNotification = + [NSNotification notificationWithName:UISceneWillEnterForegroundNotification + object:nil + userInfo:nil]; + NSNotification* applicationNotification = + [NSNotification notificationWithName:UIApplicationWillEnterForegroundNotification + object:nil + userInfo:nil]; + id mockVC = OCMPartialMock(flutterViewController); + [NSNotificationCenter.defaultCenter postNotification:sceneNotification]; + [NSNotificationCenter.defaultCenter postNotification:applicationNotification]; + OCMVerify([mockVC sceneWillEnterForeground:[OCMArg any]]); + OCMReject([mockVC applicationWillEnterForeground:[OCMArg any]]); + OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.inactive"]); + [flutterViewController deregisterNotifications]; + [mockBundle stopMocking]; +} + +- (void)testLifeCycleNotificationCancelledInvalidResumed { + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* flutterViewController = + [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; + NSNotification* applicationDidBecomeActiveNotification = + [NSNotification notificationWithName:UIApplicationDidBecomeActiveNotification + object:nil + userInfo:nil]; + NSNotification* applicationWillResignActiveNotification = + [NSNotification notificationWithName:UIApplicationWillResignActiveNotification + object:nil + userInfo:nil]; + id mockVC = OCMPartialMock(flutterViewController); + [NSNotificationCenter.defaultCenter postNotification:applicationDidBecomeActiveNotification]; + [NSNotificationCenter.defaultCenter postNotification:applicationWillResignActiveNotification]; + OCMVerify([mockVC goToApplicationLifecycle:@"AppLifecycleState.inactive"]); + + XCTestExpectation* timeoutApplicationLifeCycle = + [self expectationWithDescription:@"timeoutApplicationLifeCycle"]; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), + dispatch_get_main_queue(), ^{ + OCMReject([mockVC goToApplicationLifecycle:@"AppLifecycleState.resumed"]); + [timeoutApplicationLifeCycle fulfill]; + [flutterViewController deregisterNotifications]; + }); + [self waitForExpectationsWithTimeout:5.0 handler:nil]; +} + +- (void)testSetupKeyboardAnimationVsyncClientWillCreateNewVsyncClientForFlutterViewController { + id bundleMock = OCMPartialMock([NSBundle mainBundle]); + OCMStub([bundleMock objectForInfoDictionaryKey:kCADisableMinimumFrameDurationOnPhoneKey]) + .andReturn(@YES); + id mockDisplayLinkManager = [OCMockObject mockForClass:[DisplayLinkManager class]]; + double maxFrameRate = 120; + [[[mockDisplayLinkManager stub] andReturnValue:@(maxFrameRate)] displayRefreshRate]; + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + FlutterKeyboardAnimationCallback callback = ^(fml::TimePoint targetTime) { + }; + [viewController setUpKeyboardAnimationVsyncClient:callback]; + XCTAssertNotNil(viewController.keyboardAnimationVSyncClient); + CADisplayLink* link = [viewController.keyboardAnimationVSyncClient getDisplayLink]; + XCTAssertNotNil(link); + if (@available(iOS 15.0, *)) { + XCTAssertEqual(link.preferredFrameRateRange.maximum, maxFrameRate); + XCTAssertEqual(link.preferredFrameRateRange.preferred, maxFrameRate); + XCTAssertEqual(link.preferredFrameRateRange.minimum, maxFrameRate / 2); + } else { + XCTAssertEqual(link.preferredFramesPerSecond, maxFrameRate); + } +} + +- (void) + testCreateTouchRateCorrectionVSyncClientWillCreateVsyncClientWhenRefreshRateIsLargerThan60HZ { + id mockDisplayLinkManager = [OCMockObject mockForClass:[DisplayLinkManager class]]; + double maxFrameRate = 120; + [[[mockDisplayLinkManager stub] andReturnValue:@(maxFrameRate)] displayRefreshRate]; + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + [viewController createTouchRateCorrectionVSyncClientIfNeeded]; + XCTAssertNotNil(viewController.touchRateCorrectionVSyncClient); +} + +- (void)testCreateTouchRateCorrectionVSyncClientWillNotCreateNewVSyncClientWhenClientAlreadyExists { + id mockDisplayLinkManager = [OCMockObject mockForClass:[DisplayLinkManager class]]; + double maxFrameRate = 120; + [[[mockDisplayLinkManager stub] andReturnValue:@(maxFrameRate)] displayRefreshRate]; + + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + [viewController createTouchRateCorrectionVSyncClientIfNeeded]; + VSyncClient* clientBefore = viewController.touchRateCorrectionVSyncClient; + XCTAssertNotNil(clientBefore); + + [viewController createTouchRateCorrectionVSyncClientIfNeeded]; + VSyncClient* clientAfter = viewController.touchRateCorrectionVSyncClient; + XCTAssertNotNil(clientAfter); + + XCTAssertTrue(clientBefore == clientAfter); +} + +- (void)testCreateTouchRateCorrectionVSyncClientWillNotCreateVsyncClientWhenRefreshRateIs60HZ { + id mockDisplayLinkManager = [OCMockObject mockForClass:[DisplayLinkManager class]]; + double maxFrameRate = 60; + [[[mockDisplayLinkManager stub] andReturnValue:@(maxFrameRate)] displayRefreshRate]; + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + [viewController createTouchRateCorrectionVSyncClientIfNeeded]; + XCTAssertNil(viewController.touchRateCorrectionVSyncClient); +} + +- (void)testTriggerTouchRateCorrectionVSyncClientCorrectly { + id mockDisplayLinkManager = [OCMockObject mockForClass:[DisplayLinkManager class]]; + double maxFrameRate = 120; + [[[mockDisplayLinkManager stub] andReturnValue:@(maxFrameRate)] displayRefreshRate]; + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + [viewController loadView]; + [viewController viewDidLoad]; + + VSyncClient* client = viewController.touchRateCorrectionVSyncClient; + CADisplayLink* link = [client getDisplayLink]; + + UITouch* fakeTouchBegan = [[UITouch alloc] init]; + fakeTouchBegan.phase = UITouchPhaseBegan; + + UITouch* fakeTouchMove = [[UITouch alloc] init]; + fakeTouchMove.phase = UITouchPhaseMoved; + + UITouch* fakeTouchEnd = [[UITouch alloc] init]; + fakeTouchEnd.phase = UITouchPhaseEnded; + + UITouch* fakeTouchCancelled = [[UITouch alloc] init]; + fakeTouchCancelled.phase = UITouchPhaseCancelled; + + [viewController + triggerTouchRateCorrectionIfNeeded:[[NSSet alloc] initWithObjects:fakeTouchBegan, nil]]; + XCTAssertFalse(link.isPaused); + + [viewController + triggerTouchRateCorrectionIfNeeded:[[NSSet alloc] initWithObjects:fakeTouchEnd, nil]]; + XCTAssertTrue(link.isPaused); + + [viewController + triggerTouchRateCorrectionIfNeeded:[[NSSet alloc] initWithObjects:fakeTouchMove, nil]]; + XCTAssertFalse(link.isPaused); + + [viewController + triggerTouchRateCorrectionIfNeeded:[[NSSet alloc] initWithObjects:fakeTouchCancelled, nil]]; + XCTAssertTrue(link.isPaused); + + [viewController + triggerTouchRateCorrectionIfNeeded:[[NSSet alloc] + initWithObjects:fakeTouchBegan, fakeTouchEnd, nil]]; + XCTAssertFalse(link.isPaused); + + [viewController + triggerTouchRateCorrectionIfNeeded:[[NSSet alloc] initWithObjects:fakeTouchEnd, + fakeTouchCancelled, nil]]; + XCTAssertTrue(link.isPaused); + + [viewController + triggerTouchRateCorrectionIfNeeded:[[NSSet alloc] + initWithObjects:fakeTouchMove, fakeTouchEnd, nil]]; + XCTAssertFalse(link.isPaused); +} + +- (void)testFlutterViewControllerStartKeyboardAnimationWillCreateVsyncClientCorrectly { + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + viewController.targetViewInsetBottom = 100; + [viewController startKeyBoardAnimation:0.25]; + XCTAssertNotNil(viewController.keyboardAnimationVSyncClient); +} + +- (void) + testSetupKeyboardAnimationVsyncClientWillNotCreateNewVsyncClientWhenKeyboardAnimationCallbackIsNil { + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + [viewController setUpKeyboardAnimationVsyncClient:nil]; + XCTAssertNil(viewController.keyboardAnimationVSyncClient); +} + +- (void)testSupportsShowingSystemContextMenuForIOS16AndAbove { + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + BOOL supportsShowingSystemContextMenu = [viewController supportsShowingSystemContextMenu]; + if (@available(iOS 16.0, *)) { + XCTAssertTrue(supportsShowingSystemContextMenu); + } else { + XCTAssertFalse(supportsShowingSystemContextMenu); + } +} + +- (void)testStateIsActiveAndBackgroundWhenApplicationStateIsActive { + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + id mockApplication = OCMClassMock([UIApplication class]); + OCMStub([mockApplication applicationState]).andReturn(UIApplicationStateActive); + OCMStub([mockApplication sharedApplication]).andReturn(mockApplication); + XCTAssertTrue(viewController.stateIsActive); + XCTAssertFalse(viewController.stateIsBackground); +} + +- (void)testStateIsActiveAndBackgroundWhenApplicationStateIsBackground { + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + id mockApplication = OCMClassMock([UIApplication class]); + OCMStub([mockApplication applicationState]).andReturn(UIApplicationStateBackground); + OCMStub([mockApplication sharedApplication]).andReturn(mockApplication); + XCTAssertFalse(viewController.stateIsActive); + XCTAssertTrue(viewController.stateIsBackground); +} + +- (void)testStateIsActiveAndBackgroundWhenApplicationStateIsInactive { + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + id mockApplication = OCMClassMock([UIApplication class]); + OCMStub([mockApplication applicationState]).andReturn(UIApplicationStateInactive); + OCMStub([mockApplication sharedApplication]).andReturn(mockApplication); + XCTAssertFalse(viewController.stateIsActive); + XCTAssertFalse(viewController.stateIsBackground); +} + +- (void)testStateIsActiveAndBackgroundWhenSceneStateIsActive { + id mockBundle = OCMPartialMock([NSBundle mainBundle]); + OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{ + @"NSExtensionPointIdentifier" : @"com.apple.share-services" + }); + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + id mockVC = OCMPartialMock(viewController); + OCMStub([mockVC activationState]).andReturn(UISceneActivationStateForegroundActive); + XCTAssertTrue(viewController.stateIsActive); + XCTAssertFalse(viewController.stateIsBackground); + + [mockBundle stopMocking]; + [mockVC stopMocking]; +} + +- (void)testStateIsActiveAndBackgroundWhenSceneStateIsBackground { + id mockBundle = OCMPartialMock([NSBundle mainBundle]); + OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{ + @"NSExtensionPointIdentifier" : @"com.apple.share-services" + }); + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + id mockVC = OCMPartialMock(viewController); + OCMStub([mockVC activationState]).andReturn(UISceneActivationStateBackground); + XCTAssertFalse(viewController.stateIsActive); + XCTAssertTrue(viewController.stateIsBackground); + + [mockBundle stopMocking]; + [mockVC stopMocking]; +} + +- (void)testStateIsActiveAndBackgroundWhenSceneStateIsInactive { + id mockBundle = OCMPartialMock([NSBundle mainBundle]); + OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{ + @"NSExtensionPointIdentifier" : @"com.apple.share-services" + }); + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + id mockVC = OCMPartialMock(viewController); + OCMStub([mockVC activationState]).andReturn(UISceneActivationStateForegroundInactive); + XCTAssertFalse(viewController.stateIsActive); + XCTAssertFalse(viewController.stateIsBackground); + + [mockBundle stopMocking]; + [mockVC stopMocking]; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h new file mode 100644 index 0000000000000000000000000000000000000000..f62eec2bb2bd297ec228ddfd3ea142ffe061d306 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h @@ -0,0 +1,78 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERVIEWCONTROLLER_INTERNAL_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERVIEWCONTROLLER_INTERNAL_H_ + +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h" + +#include "flutter/fml/time/time_point.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeySecondaryResponder.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViewsController.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterRestorationPlugin.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewResponder.h" + +namespace flutter { +class PlatformViewsController; +} + +FLUTTER_DARWIN_EXPORT +// NOLINTNEXTLINE(readability-identifier-naming) +extern NSNotificationName const FlutterViewControllerWillDealloc; + +FLUTTER_DARWIN_EXPORT +// NOLINTNEXTLINE(readability-identifier-naming) +extern NSNotificationName const FlutterViewControllerHideHomeIndicator; + +FLUTTER_DARWIN_EXPORT +// NOLINTNEXTLINE(readability-identifier-naming) +extern NSNotificationName const FlutterViewControllerShowHomeIndicator; + +typedef NS_ENUM(NSInteger, FlutterKeyboardMode) { + // NOLINTBEGIN(readability-identifier-naming) + FlutterKeyboardModeHidden = 0, + FlutterKeyboardModeDocked = 1, + FlutterKeyboardModeFloating = 2, + // NOLINTEND(readability-identifier-naming) +}; + +typedef void (^FlutterKeyboardAnimationCallback)(fml::TimePoint); + +@interface FlutterViewController () + +@property(class, nonatomic, readonly) BOOL accessibilityIsOnOffSwitchLabelsEnabled; +@property(nonatomic, readonly) BOOL isPresentingViewController; +@property(nonatomic, readonly) BOOL isVoiceOverRunning; +@property(nonatomic, strong) FlutterKeyboardManager* keyboardManager; + +/** + * @brief Whether the status bar is preferred hidden. + * + * This overrides the |UIViewController:prefersStatusBarHidden|. + * This is ignored when `UIViewControllerBasedStatusBarAppearance` in info.plist + * of the app project is `false`. + */ +@property(nonatomic, assign, readwrite) BOOL prefersStatusBarHidden; + +@property(nonatomic, readonly) FlutterPlatformViewsController* platformViewsController; + +- (FlutterRestorationPlugin*)restorationPlugin; + +// Accepts keypress events, and then calls |nextAction| if the event was not +// handled. +- (void)handlePressEvent:(FlutterUIPressProxy*)press + nextAction:(void (^)())nextAction API_AVAILABLE(ios(13.4)); +- (void)sendDeepLinkToFramework:(NSURL*)url completionHandler:(void (^)(BOOL success))completion; +- (void)addInternalPlugins; +- (void)deregisterNotifications; +- (int32_t)accessibilityFlags; + +- (BOOL)supportsShowingSystemContextMenu; +- (BOOL)stateIsActive; +- (BOOL)stateIsBackground; +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERVIEWCONTROLLER_INTERNAL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewResponder.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewResponder.h new file mode 100644 index 0000000000000000000000000000000000000000..e1f4aafd732830122758eba5f058d1a82db4b634 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewResponder.h @@ -0,0 +1,53 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERVIEWRESPONDER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERVIEWRESPONDER_H_ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + * Protocol to send touch events, typically a `FlutterViewController`. + */ +@protocol FlutterViewResponder + +@property(nonatomic, strong) UIView* view; + +/** + * See `-[UIResponder touchesBegan:withEvent:]` + */ +- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event; + +/** + * See `-[UIResponder touchesMoved:withEvent:]` + */ +- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event; + +/** + * See `-[UIResponder touchesEnded:withEvent:]` + */ +- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event; + +/** + * See `-[UIResponder touchesCancelled:withEvent:]` + */ +- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event; + +/** + * See `-[UIResponder touchesEstimatedPropertiesUpdated:]` + */ +- (void)touchesEstimatedPropertiesUpdated:(NSSet*)touches; + +/** + * Send touches to the Flutter Engine while forcing the change type to be cancelled. + * The `phase`s in `touches` are ignored. + */ +- (void)forceTouchesCancelled:(NSSet*)touches; + +@end +NS_ASSUME_NONNULL_END + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERVIEWRESPONDER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..3b686dea82607b69090f057796b7ca44a8f0d13b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewTest.mm @@ -0,0 +1,67 @@ +// 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. + +#import + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h" + +FLUTTER_ASSERT_ARC + +@interface FakeDelegate : NSObject +@property(nonatomic) BOOL callbackCalled; +@end + +@implementation FakeDelegate + +@synthesize platformViewsController = _platformViewsController; + +- (instancetype)init { + _callbackCalled = NO; + return self; +} + +- (flutter::Rasterizer::Screenshot)takeScreenshot:(flutter::Rasterizer::ScreenshotType)type + asBase64Encoded:(BOOL)base64Encode { + return {}; +} + +- (void)flutterViewAccessibilityDidCall { + _callbackCalled = YES; +} + +@end + +@interface FlutterViewTest : XCTestCase +@end + +@implementation FlutterViewTest + +- (void)testFlutterViewEnableSemanticsWhenIsAccessibilityElementIsCalled { + FakeDelegate* delegate = [[FakeDelegate alloc] init]; + FlutterView* view = [[FlutterView alloc] initWithDelegate:delegate opaque:NO enableWideGamut:NO]; + delegate.callbackCalled = NO; + XCTAssertFalse(view.isAccessibilityElement); + XCTAssertTrue(delegate.callbackCalled); +} + +- (void)testFlutterViewBackgroundColorIsNil { + FakeDelegate* delegate = [[FakeDelegate alloc] init]; + FlutterView* view = [[FlutterView alloc] initWithDelegate:delegate opaque:NO enableWideGamut:NO]; + XCTAssertNil(view.backgroundColor); +} + +- (void)testLayerScalesMatchScreenAfterLayoutSubviews { + FakeDelegate* delegate = [[FakeDelegate alloc] init]; + FlutterView* view = [[FlutterView alloc] initWithDelegate:delegate opaque:NO enableWideGamut:NO]; + view.layer.contentsScale = CGFloat(-99.0); + view.layer.rasterizationScale = CGFloat(-99.0); + UIScreen* screen = [view screen]; + XCTAssertNotEqual(view.layer.contentsScale, screen.scale); + XCTAssertNotEqual(view.layer.rasterizationScale, screen.scale); + [view layoutSubviews]; + XCTAssertEqual(view.layer.contentsScale, screen.scale); + XCTAssertEqual(view.layer.rasterizationScale, screen.scale); +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/IOKit.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/IOKit.h new file mode 100644 index 0000000000000000000000000000000000000000..4b1e8446af4b65dbde828b0c12b26193e7c9be01 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/IOKit.h @@ -0,0 +1,108 @@ +// 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. + +// These declarations are an amalgamation of different headers whose +// symbols exist in IOKit.framework. The headers have been removed +// from the iOS SDKs but all the functions are documented here: +// * https://developer.apple.com/documentation/iokit/iokitlib_h?language=objc +// * https://developer.apple.com/documentation/iokit/iokit_functions?language=objc +// * file:///Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/IOKit.framework/Versions/A/Headers/IOKitLib.h + +#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG || \ + FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_PROFILE +#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_IOKIT_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_IOKIT_H_ + +#if defined(__cplusplus) +extern "C" { +#endif // defined(__cplusplus) + +#include +#include +#include + +#define IOKIT +#include + +constexpr const char* kIOServicePlane = "IOService"; + +typedef io_object_t io_registry_entry_t; +typedef io_object_t io_service_t; +typedef io_object_t io_connect_t; +typedef io_object_t io_iterator_t; + +enum { + kIOReturnSuccess = 0, +}; + +extern const mach_port_t kIOMasterPortDefault; + +kern_return_t IOObjectRetain(io_object_t object); +kern_return_t IOObjectRelease(io_object_t object); +boolean_t IOObjectConformsTo(io_object_t object, const io_name_t name); +uint32_t IOObjectGetKernelRetainCount(io_object_t object); +kern_return_t IOObjectGetClass(io_object_t object, io_name_t name); +CFStringRef IOObjectCopyClass(io_object_t object); +CFStringRef IOObjectCopySuperclassForClass(CFStringRef name); +CFStringRef IOObjectCopyBundleIdentifierForClass(CFStringRef name); + +io_registry_entry_t IORegistryGetRootEntry(mach_port_t master); +kern_return_t IORegistryEntryGetName(io_registry_entry_t entry, io_name_t name); +kern_return_t IORegistryEntryGetRegistryEntryID(io_registry_entry_t entry, + uint64_t* entryID); +kern_return_t IORegistryEntryGetPath(io_registry_entry_t entry, + const io_name_t plane, + io_string_t path); +kern_return_t IORegistryEntryGetProperty(io_registry_entry_t entry, + const io_name_t name, + io_struct_inband_t buffer, + uint32_t* size); +kern_return_t IORegistryEntryCreateCFProperties( + io_registry_entry_t entry, + CFMutableDictionaryRef* properties, + CFAllocatorRef allocator, + uint32_t options); +CFTypeRef IORegistryEntryCreateCFProperty(io_registry_entry_t entry, + CFStringRef key, + CFAllocatorRef allocator, + uint32_t options); +kern_return_t IORegistryEntrySetCFProperties(io_registry_entry_t entry, + CFTypeRef properties); + +kern_return_t IORegistryCreateIterator(mach_port_t master, + const io_name_t plane, + uint32_t options, + io_iterator_t* it); +kern_return_t IORegistryEntryCreateIterator(io_registry_entry_t entry, + const io_name_t plane, + uint32_t options, + io_iterator_t* it); +kern_return_t IORegistryEntryGetChildIterator(io_registry_entry_t entry, + const io_name_t plane, + io_iterator_t* it); +kern_return_t IORegistryEntryGetParentIterator(io_registry_entry_t entry, + const io_name_t plane, + io_iterator_t* it); +io_object_t IOIteratorNext(io_iterator_t it); +boolean_t IOIteratorIsValid(io_iterator_t it); +void IOIteratorReset(io_iterator_t it); + +CFMutableDictionaryRef IOServiceMatching(const char* name) CF_RETURNS_RETAINED; +CFMutableDictionaryRef IOServiceNameMatching(const char* name) + CF_RETURNS_RETAINED; +io_service_t IOServiceGetMatchingService( + mach_port_t master, + CFDictionaryRef matching CF_RELEASES_ARGUMENT); +kern_return_t IOServiceGetMatchingServices( + mach_port_t master, + CFDictionaryRef matching CF_RELEASES_ARGUMENT, + io_iterator_t* it); + +#if __cplusplus +} +#endif // __cplusplus + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_IOKIT_H_ +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_IOKIT_H_ + // defined(FLUTTER_RUNTIME_MODE_PROFILE) diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/KeyCodeMap.g.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/KeyCodeMap.g.mm new file mode 100644 index 0000000000000000000000000000000000000000..d8303ab129b27046792389a69e4a50ce48c9a62b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/KeyCodeMap.g.mm @@ -0,0 +1,357 @@ +// 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 +#include +#include "flutter/shell/platform/darwin/ios/framework/Source/KeyCodeMap_Internal.h" + +// DO NOT EDIT -- DO NOT EDIT -- DO NOT EDIT +// This file is generated by +// flutter/flutter:dev/tools/gen_keycodes/bin/gen_keycodes.dart and should not +// be edited directly. +// +// Edit the template +// flutter/flutter:dev/tools/gen_keycodes/data/ios_key_code_map_mm.tmpl instead. +// +// See flutter/flutter:dev/tools/gen_keycodes/README.md for more information. + +/** + * Mask for the 32-bit value portion of the key code. + */ +const uint64_t kValueMask = 0x000ffffffff; + +/** + * The plane value for keys which have a Unicode representation. + */ +const uint64_t kUnicodePlane = 0x00000000000; + +/** + * The plane value for the private keys defined by the iOS embedding. + */ +const uint64_t kIosPlane = 0x01300000000; + +// Maps iOS-specific key code values representing PhysicalKeyboardKey. +// +// iOS doesn't provide a scan code, but a virtual keycode to represent a physical key. +const std::map keyCodeToPhysicalKey = { + {0x00000000, 0x00070000}, // usbReserved + {0x00000001, 0x00070001}, // usbErrorRollOver + {0x00000002, 0x00070002}, // usbPostFail + {0x00000003, 0x00070003}, // usbErrorUndefined + {0x00000004, 0x00070004}, // keyA + {0x00000005, 0x00070005}, // keyB + {0x00000006, 0x00070006}, // keyC + {0x00000007, 0x00070007}, // keyD + {0x00000008, 0x00070008}, // keyE + {0x00000009, 0x00070009}, // keyF + {0x0000000a, 0x0007000a}, // keyG + {0x0000000b, 0x0007000b}, // keyH + {0x0000000c, 0x0007000c}, // keyI + {0x0000000d, 0x0007000d}, // keyJ + {0x0000000e, 0x0007000e}, // keyK + {0x0000000f, 0x0007000f}, // keyL + {0x00000010, 0x00070010}, // keyM + {0x00000011, 0x00070011}, // keyN + {0x00000012, 0x00070012}, // keyO + {0x00000013, 0x00070013}, // keyP + {0x00000014, 0x00070014}, // keyQ + {0x00000015, 0x00070015}, // keyR + {0x00000016, 0x00070016}, // keyS + {0x00000017, 0x00070017}, // keyT + {0x00000018, 0x00070018}, // keyU + {0x00000019, 0x00070019}, // keyV + {0x0000001a, 0x0007001a}, // keyW + {0x0000001b, 0x0007001b}, // keyX + {0x0000001c, 0x0007001c}, // keyY + {0x0000001d, 0x0007001d}, // keyZ + {0x0000001e, 0x0007001e}, // digit1 + {0x0000001f, 0x0007001f}, // digit2 + {0x00000020, 0x00070020}, // digit3 + {0x00000021, 0x00070021}, // digit4 + {0x00000022, 0x00070022}, // digit5 + {0x00000023, 0x00070023}, // digit6 + {0x00000024, 0x00070024}, // digit7 + {0x00000025, 0x00070025}, // digit8 + {0x00000026, 0x00070026}, // digit9 + {0x00000027, 0x00070027}, // digit0 + {0x00000028, 0x00070028}, // enter + {0x00000029, 0x00070029}, // escape + {0x0000002a, 0x0007002a}, // backspace + {0x0000002b, 0x0007002b}, // tab + {0x0000002c, 0x0007002c}, // space + {0x0000002d, 0x0007002d}, // minus + {0x0000002e, 0x0007002e}, // equal + {0x0000002f, 0x0007002f}, // bracketLeft + {0x00000030, 0x00070030}, // bracketRight + {0x00000031, 0x00070031}, // backslash + {0x00000033, 0x00070033}, // semicolon + {0x00000034, 0x00070034}, // quote + {0x00000035, 0x00070035}, // backquote + {0x00000036, 0x00070036}, // comma + {0x00000037, 0x00070037}, // period + {0x00000038, 0x00070038}, // slash + {0x00000039, 0x00070039}, // capsLock + {0x0000003a, 0x0007003a}, // f1 + {0x0000003b, 0x0007003b}, // f2 + {0x0000003c, 0x0007003c}, // f3 + {0x0000003d, 0x0007003d}, // f4 + {0x0000003e, 0x0007003e}, // f5 + {0x0000003f, 0x0007003f}, // f6 + {0x00000040, 0x00070040}, // f7 + {0x00000041, 0x00070041}, // f8 + {0x00000042, 0x00070042}, // f9 + {0x00000043, 0x00070043}, // f10 + {0x00000044, 0x00070044}, // f11 + {0x00000045, 0x00070045}, // f12 + {0x00000046, 0x00070046}, // printScreen + {0x00000047, 0x00070047}, // scrollLock + {0x00000048, 0x00070048}, // pause + {0x00000049, 0x00070049}, // insert + {0x0000004a, 0x0007004a}, // home + {0x0000004b, 0x0007004b}, // pageUp + {0x0000004c, 0x0007004c}, // delete + {0x0000004d, 0x0007004d}, // end + {0x0000004e, 0x0007004e}, // pageDown + {0x0000004f, 0x0007004f}, // arrowRight + {0x00000050, 0x00070050}, // arrowLeft + {0x00000051, 0x00070051}, // arrowDown + {0x00000052, 0x00070052}, // arrowUp + {0x00000053, 0x00070053}, // numLock + {0x00000054, 0x00070054}, // numpadDivide + {0x00000055, 0x00070055}, // numpadMultiply + {0x00000056, 0x00070056}, // numpadSubtract + {0x00000057, 0x00070057}, // numpadAdd + {0x00000058, 0x00070058}, // numpadEnter + {0x00000059, 0x00070059}, // numpad1 + {0x0000005a, 0x0007005a}, // numpad2 + {0x0000005b, 0x0007005b}, // numpad3 + {0x0000005c, 0x0007005c}, // numpad4 + {0x0000005d, 0x0007005d}, // numpad5 + {0x0000005e, 0x0007005e}, // numpad6 + {0x0000005f, 0x0007005f}, // numpad7 + {0x00000060, 0x00070060}, // numpad8 + {0x00000061, 0x00070061}, // numpad9 + {0x00000062, 0x00070062}, // numpad0 + {0x00000063, 0x00070063}, // numpadDecimal + {0x00000064, 0x00070064}, // intlBackslash + {0x00000065, 0x00070065}, // contextMenu + {0x00000066, 0x00070066}, // power + {0x00000067, 0x00070067}, // numpadEqual + {0x00000068, 0x00070068}, // f13 + {0x00000069, 0x00070069}, // f14 + {0x0000006a, 0x0007006a}, // f15 + {0x0000006b, 0x0007006b}, // f16 + {0x0000006c, 0x0007006c}, // f17 + {0x0000006d, 0x0007006d}, // f18 + {0x0000006e, 0x0007006e}, // f19 + {0x0000006f, 0x0007006f}, // f20 + {0x00000070, 0x00070070}, // f21 + {0x00000071, 0x00070071}, // f22 + {0x00000072, 0x00070072}, // f23 + {0x00000073, 0x00070073}, // f24 + {0x00000074, 0x00070074}, // open + {0x00000075, 0x00070075}, // help + {0x00000077, 0x00070077}, // select + {0x00000079, 0x00070079}, // again + {0x0000007a, 0x0007007a}, // undo + {0x0000007b, 0x0007007b}, // cut + {0x0000007c, 0x0007007c}, // copy + {0x0000007d, 0x0007007d}, // paste + {0x0000007e, 0x0007007e}, // find + {0x0000007f, 0x0007007f}, // audioVolumeMute + {0x00000080, 0x00070080}, // audioVolumeUp + {0x00000081, 0x00070081}, // audioVolumeDown + {0x00000085, 0x00070085}, // numpadComma + {0x00000087, 0x00070087}, // intlRo + {0x00000088, 0x00070088}, // kanaMode + {0x00000089, 0x00070089}, // intlYen + {0x0000008a, 0x0007008a}, // convert + {0x0000008b, 0x0007008b}, // nonConvert + {0x00000090, 0x00070090}, // lang1 + {0x00000091, 0x00070091}, // lang2 + {0x00000092, 0x00070092}, // lang3 + {0x00000093, 0x00070093}, // lang4 + {0x00000094, 0x00070094}, // lang5 + {0x0000009b, 0x0007009b}, // abort + {0x000000a3, 0x000700a3}, // props + {0x000000b6, 0x000700b6}, // numpadParenLeft + {0x000000b7, 0x000700b7}, // numpadParenRight + {0x000000bb, 0x000700bb}, // numpadBackspace + {0x000000d0, 0x000700d0}, // numpadMemoryStore + {0x000000d1, 0x000700d1}, // numpadMemoryRecall + {0x000000d2, 0x000700d2}, // numpadMemoryClear + {0x000000d3, 0x000700d3}, // numpadMemoryAdd + {0x000000d4, 0x000700d4}, // numpadMemorySubtract + {0x000000d7, 0x000700d7}, // numpadSignChange + {0x000000d8, 0x000700d8}, // numpadClear + {0x000000d9, 0x000700d9}, // numpadClearEntry + {0x000000e0, 0x000700e0}, // controlLeft + {0x000000e1, 0x000700e1}, // shiftLeft + {0x000000e2, 0x000700e2}, // altLeft + {0x000000e3, 0x000700e3}, // metaLeft + {0x000000e4, 0x000700e4}, // controlRight + {0x000000e5, 0x000700e5}, // shiftRight + {0x000000e6, 0x000700e6}, // altRight + {0x000000e7, 0x000700e7}, // metaRight +}; + +// Maps iOS-specific virtual key code values to logical keys representing +// LogicalKeyboardKey +const std::map keyCodeToLogicalKey = { + {0x00000028, 0x0010000000d}, // Enter + {0x00000029, 0x0010000001b}, // Escape + {0x0000002a, 0x00100000008}, // Backspace + {0x0000002b, 0x00100000009}, // Tab + {0x00000039, 0x00100000104}, // CapsLock + {0x0000003a, 0x00100000801}, // F1 + {0x0000003b, 0x00100000802}, // F2 + {0x0000003c, 0x00100000803}, // F3 + {0x0000003d, 0x00100000804}, // F4 + {0x0000003e, 0x00100000805}, // F5 + {0x0000003f, 0x00100000806}, // F6 + {0x00000040, 0x00100000807}, // F7 + {0x00000041, 0x00100000808}, // F8 + {0x00000042, 0x00100000809}, // F9 + {0x00000043, 0x0010000080a}, // F10 + {0x00000044, 0x0010000080b}, // F11 + {0x00000045, 0x0010000080c}, // F12 + {0x00000049, 0x00100000407}, // Insert + {0x0000004a, 0x00100000306}, // Home + {0x0000004b, 0x00100000308}, // PageUp + {0x0000004c, 0x0010000007f}, // Delete + {0x0000004d, 0x00100000305}, // End + {0x0000004e, 0x00100000307}, // PageDown + {0x0000004f, 0x00100000303}, // ArrowRight + {0x00000050, 0x00100000302}, // ArrowLeft + {0x00000051, 0x00100000301}, // ArrowDown + {0x00000052, 0x00100000304}, // ArrowUp + {0x00000053, 0x0010000010a}, // NumLock + {0x00000054, 0x0020000022f}, // NumpadDivide + {0x00000055, 0x0020000022a}, // NumpadMultiply + {0x00000056, 0x0020000022d}, // NumpadSubtract + {0x00000057, 0x0020000022b}, // NumpadAdd + {0x00000058, 0x0020000020d}, // NumpadEnter + {0x00000059, 0x00200000231}, // Numpad1 + {0x0000005a, 0x00200000232}, // Numpad2 + {0x0000005b, 0x00200000233}, // Numpad3 + {0x0000005c, 0x00200000234}, // Numpad4 + {0x0000005d, 0x00200000235}, // Numpad5 + {0x0000005e, 0x00200000236}, // Numpad6 + {0x0000005f, 0x00200000237}, // Numpad7 + {0x00000060, 0x00200000238}, // Numpad8 + {0x00000061, 0x00200000239}, // Numpad9 + {0x00000062, 0x00200000230}, // Numpad0 + {0x00000063, 0x0020000022e}, // NumpadDecimal + {0x00000065, 0x00100000505}, // ContextMenu + {0x00000067, 0x0020000023d}, // NumpadEqual + {0x00000068, 0x0010000080d}, // F13 + {0x00000069, 0x0010000080e}, // F14 + {0x0000006a, 0x0010000080f}, // F15 + {0x0000006b, 0x00100000810}, // F16 + {0x0000006c, 0x00100000811}, // F17 + {0x0000006d, 0x00100000812}, // F18 + {0x0000006e, 0x00100000813}, // F19 + {0x0000006f, 0x00100000814}, // F20 + {0x0000007f, 0x00100000a11}, // AudioVolumeMute + {0x00000080, 0x00100000a10}, // AudioVolumeUp + {0x00000081, 0x00100000a0f}, // AudioVolumeDown + {0x00000085, 0x0020000022c}, // NumpadComma + {0x00000087, 0x00200000021}, // IntlRo + {0x00000089, 0x00200000022}, // IntlYen + {0x00000090, 0x00200000010}, // Lang1 + {0x00000091, 0x00200000011}, // Lang2 + {0x00000092, 0x00200000012}, // Lang3 + {0x00000093, 0x00200000013}, // Lang4 + {0x00000094, 0x00200000014}, // Lang5 + {0x000000e0, 0x00200000100}, // ControlLeft + {0x000000e1, 0x00200000102}, // ShiftLeft + {0x000000e2, 0x00200000104}, // AltLeft + {0x000000e3, 0x00200000106}, // MetaLeft + {0x000000e4, 0x00200000101}, // ControlRight + {0x000000e5, 0x00200000103}, // ShiftRight + {0x000000e6, 0x00200000105}, // AltRight + {0x000000e7, 0x00200000107}, // MetaRight +}; + +// Maps iOS-specific virtual key codes to an equivalent modifier flag enum +// value. +const std::map keyCodeToModifierFlag = { + {0x000000e1, kModifierFlagShiftLeft}, // ShiftLeft + {0x000000e5, kModifierFlagShiftRight}, // ShiftRight + {0x000000e0, kModifierFlagControlLeft}, // ControlLeft + {0x000000e4, kModifierFlagControlRight}, // ControlRight + {0x000000e2, kModifierFlagAltLeft}, // AltLeft + {0x000000e6, kModifierFlagAltRight}, // AltRight + {0x000000e3, kModifierFlagMetaLeft}, // MetaLeft + {0x000000e7, kModifierFlagMetaRight}, // MetaRight +}; + +// Maps modifier flag enum values to an iOS-specific virtual key code. +const std::map modifierFlagToKeyCode = { + {kModifierFlagShiftLeft, 0x000000e1}, // ShiftLeft + {kModifierFlagShiftRight, 0x000000e5}, // ShiftRight + {kModifierFlagControlLeft, 0x000000e0}, // ControlLeft + {kModifierFlagControlRight, 0x000000e4}, // ControlRight + {kModifierFlagAltLeft, 0x000000e2}, // AltLeft + {kModifierFlagAltRight, 0x000000e6}, // AltRight + {kModifierFlagMetaLeft, 0x000000e3}, // MetaLeft + {kModifierFlagMetaRight, 0x000000e7}, // MetaRight +}; + +// A set of virtual key codes mapping to function keys, so that may be +// identified as such. +const std::set functionKeyCodes = { + 0x0000003a, // f1 + 0x0000003b, // f2 + 0x0000003c, // f3 + 0x0000003d, // f4 + 0x0000003e, // f5 + 0x0000003f, // f6 + 0x00000040, // f7 + 0x00000041, // f8 + 0x00000042, // f9 + 0x00000043, // f10 + 0x00000044, // f11 + 0x00000045, // f12 + 0x00000068, // f13 + 0x00000069, // f14 + 0x0000006a, // f15 + 0x0000006b, // f16 + 0x0000006c, // f17 + 0x0000006d, // f18 + 0x0000006e, // f19 + 0x0000006f, // f20 + 0x00000070, // f21 + 0x00000071, // f22 + 0x00000072, // f23 + 0x00000073, // f24 +}; + +API_AVAILABLE(ios(13.4)) +NSDictionary* specialKeyMapping = @{ + @"UIKeyInputEscape" : @(0x10000001b), + @"UIKeyInputF1" : @(0x100000801), + @"UIKeyInputF2" : @(0x100000802), + @"UIKeyInputF3" : @(0x100000803), + @"UIKeyInputF4" : @(0x100000804), + @"UIKeyInputF5" : @(0x100000805), + @"UIKeyInputF6" : @(0x100000806), + @"UIKeyInputF7" : @(0x100000807), + @"UIKeyInputF8" : @(0x100000808), + @"UIKeyInputF9" : @(0x100000809), + @"UIKeyInputF10" : @(0x10000080a), + @"UIKeyInputF11" : @(0x10000080b), + @"UIKeyInputF12" : @(0x10000080c), + @"UIKeyInputUpArrow" : @(0x100000304), + @"UIKeyInputDownArrow" : @(0x100000301), + @"UIKeyInputLeftArrow" : @(0x100000302), + @"UIKeyInputRightArrow" : @(0x100000303), + @"UIKeyInputHome" : @(0x100000306), + @"UIKeyInputEnd" : @(0x10000000d), + @"UIKeyInputPageUp" : @(0x100000308), + @"UIKeyInputPageDown" : @(0x100000307), +}; + +const uint64_t kCapsLockPhysicalKey = 0x00070039; +const uint64_t kCapsLockLogicalKey = 0x100000104; diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/KeyCodeMap_Internal.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/KeyCodeMap_Internal.h new file mode 100644 index 0000000000000000000000000000000000000000..f01fc43e213166ade59f500d0d33e7dfb5796362 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/KeyCodeMap_Internal.h @@ -0,0 +1,131 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_KEYCODEMAP_INTERNAL_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_KEYCODEMAP_INTERNAL_H_ + +#import +#include +#include + +/** + * Maps iOS-specific key code values representing |PhysicalKeyboardKey|. + * + * MacOS doesn't provide a scan code, but a virtual keycode to represent a + * physical key. + */ +// NOLINTNEXTLINE(readability-identifier-naming) +extern const std::map keyCodeToPhysicalKey; + +/** + * A map from iOS key codes to Flutter's logical key values. + * + * This is used to derive logical keys that can't or shouldn't be derived from + * |charactersIgnoringModifiers|. + */ +// NOLINTNEXTLINE(readability-identifier-naming) +extern const std::map keyCodeToLogicalKey; + +/** + * Maps iOS specific string values of nonvisible keys to logical keys. + * + * TODO(dkwingsmt): Change this getter function to a global variable. I tried to + * do this but the unit test on CI threw errors saying "message sent to + * deallocated instance" on the NSDictionary. + * + * See: + * https://developer.apple.com/documentation/uikit/uikeycommand/input_strings_for_special_keys?language=objc + */ +extern NSDictionary* specialKeyMapping; + +// Several mask constants. See KeyCodeMap.g.mm for their descriptions. + +extern const uint64_t kValueMask; +extern const uint64_t kUnicodePlane; +extern const uint64_t kIosPlane; + +/** + * The physical key for CapsLock, which needs special handling. + */ +extern const uint64_t kCapsLockPhysicalKey; + +/** + * The logical key for CapsLock, which needs special handling. + */ +extern const uint64_t kCapsLockLogicalKey; + +/** + * Bits in |UIKey.modifierFlags| indicating whether a modifier key is pressed. + */ +typedef enum { + // These sided flags are not in any official Apple docs, they are derived from + // experiments. + kModifierFlagControlLeft = 0x1, + kModifierFlagShiftLeft = 0x2, + kModifierFlagShiftRight = 0x4, + kModifierFlagMetaLeft = 0x8, + kModifierFlagMetaRight = 0x10, + kModifierFlagAltLeft = 0x20, + kModifierFlagAltRight = 0x40, + kModifierFlagControlRight = 0x2000, + + // These are equivalent to non-sided iOS values. + kModifierFlagCapsLock = UIKeyModifierAlphaShift, // 0x010000 + kModifierFlagShiftAny = UIKeyModifierShift, // 0x020000 + kModifierFlagControlAny = UIKeyModifierControl, // 0x040000 + kModifierFlagAltAny = UIKeyModifierAlternate, // 0x080000 + kModifierFlagMetaAny = UIKeyModifierCommand, // 0x100000 + kModifierFlagNumPadKey = UIKeyModifierNumericPad // 0x200000 +} ModifierFlag; + +/** + * A mask of all the modifier flags that represent a modifier being pressed, but + * not whether it is the left or right modifier. + */ +constexpr uint32_t kModifierFlagAnyMask = + kModifierFlagShiftAny | kModifierFlagControlAny | kModifierFlagAltAny | kModifierFlagMetaAny; + +/** + * A mask of the modifier flags that represent only left or right modifier + * keys, and not the generic "Any" mask. + */ +constexpr uint32_t kModifierFlagSidedMask = kModifierFlagControlLeft | kModifierFlagShiftLeft | + kModifierFlagShiftRight | kModifierFlagMetaLeft | + kModifierFlagMetaRight | kModifierFlagAltLeft | + kModifierFlagAltRight | kModifierFlagControlRight; + +/** + * Map |UIKey.keyCode| to the matching sided modifier in UIEventModifierFlags. + */ +// NOLINTNEXTLINE(readability-identifier-naming) +extern const std::map keyCodeToModifierFlag; + +/** + * Map a bit of bitmask of sided modifiers in UIEventModifierFlags to their + * corresponding |UIKey.keyCode|. + */ +// NOLINTNEXTLINE(readability-identifier-naming) +extern const std::map modifierFlagToKeyCode; + +/** + * Maps a sided modifier key to the corresponding flag matching either side of + * that type of modifier. + */ +// NOLINTNEXTLINE(readability-identifier-naming) +extern const std::map sidedModifierToAny; + +/** + * Maps a non-sided modifier key to the corresponding flag matching the left key + * of that type of modifier. + */ +// NOLINTNEXTLINE(readability-identifier-naming) +extern const std::map anyModifierToLeft; + +/** + * A set of keycodes corresponding to function keys. + */ +// NOLINTNEXTLINE(readability-identifier-naming) +extern const std::set functionKeyCodes; + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_KEYCODEMAP_INTERNAL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject+UIFocusSystem.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject+UIFocusSystem.mm new file mode 100644 index 0000000000000000000000000000000000000000..c3262de538dabea8426c6b12daba767df190ae6b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject+UIFocusSystem.mm @@ -0,0 +1,241 @@ +// 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. + +#import "SemanticsObject.h" +#include "flutter/lib/ui/semantics/semantics_node.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterSemanticsScrollView.h" + +FLUTTER_ASSERT_ARC + +// The SemanticsObject class conforms to UIFocusItem and UIFocusItemContainer +// protocols, so the SemanticsObject tree can also be used to represent +// interactive UI components on screen that can receive UIFocusSystem focus. +// +// Typically, physical key events received by the FlutterViewController is +// first delivered to the framework, but that stopped working for navigation keys +// since iOS 15 when full keyboard access (FKA) is on, because those events are +// consumed by the UIFocusSystem and never dispatched to the UIResponders in the +// application (see +// https://developer.apple.com/documentation/uikit/uikeycommand/3780513-wantspriorityoversystembehavior +// ). FKA relies on the iOS focus engine, to enable FKA on iOS 15+, we use +// SemanticsObject to provide the iOS focus engine with the required hierarchical +// information and geometric context. +// +// The focus engine focus is different from accessibility focus, or even the +// currentFocus of the Flutter FocusManager in the framework. On iOS 15+, FKA +// key events are dispatched to the current iOS focus engine focus (and +// translated to calls such as -[NSObject accessibilityActivate]), while most +// other key events are dispatched to the framework. +@interface SemanticsObject (UIFocusSystem) +/// The `UIFocusItem` that represents this SemanticsObject. +/// +/// For regular `SemanticsObject`s, this method returns `self`, +/// for `FlutterScrollableSemanticsObject`s, this method returns its scroll view. +- (id)focusItem; +@end + +@implementation SemanticsObject (UIFocusSystem) + +- (id)focusItem { + return self; +} + +#pragma mark - UIFocusEnvironment Conformance + +- (void)setNeedsFocusUpdate { +} + +- (void)updateFocusIfNeeded { +} + +- (BOOL)shouldUpdateFocusInContext:(UIFocusUpdateContext*)context { + return YES; +} + +- (void)didUpdateFocusInContext:(UIFocusUpdateContext*)context + withAnimationCoordinator:(UIFocusAnimationCoordinator*)coordinator { +} + +- (id)parentFocusEnvironment { + // The root SemanticsObject node's parent is the FlutterView. + return self.parent.focusItem ?: self.bridge->view(); +} + +- (NSArray>*)preferredFocusEnvironments { + return nil; +} + +- (id)focusItemContainer { + return self; +} + +#pragma mark - UIFocusItem Conformance + +- (BOOL)canBecomeFocused { + if ((self.node.flags & static_cast(flutter::SemanticsFlags::kIsHidden)) != 0) { + return NO; + } + // Currently only supports SemanticsObjects that handle + // -[NSObject accessibilityActivate]. + return self.node.HasAction(flutter::SemanticsAction::kTap); +} + +// The frame is described in the `coordinateSpace` of the +// `parentFocusEnvironment` (all `parentFocusEnvironment`s are `UIFocusItem`s). +// +// See also the `coordinateSpace` implementation. +// TODO(LongCatIsLooong): use CoreGraphics types. +- (CGRect)frame { + SkPoint quad[4] = {SkPoint::Make(self.node.rect.left(), self.node.rect.top()), + SkPoint::Make(self.node.rect.left(), self.node.rect.bottom()), + SkPoint::Make(self.node.rect.right(), self.node.rect.top()), + SkPoint::Make(self.node.rect.right(), self.node.rect.bottom())}; + + SkM44 transform = self.node.transform; + FlutterSemanticsScrollView* scrollView; + for (SemanticsObject* ancestor = self.parent; ancestor; ancestor = ancestor.parent) { + if ([ancestor isKindOfClass:[FlutterScrollableSemanticsObject class]]) { + scrollView = ((FlutterScrollableSemanticsObject*)ancestor).scrollView; + break; + } + transform = ancestor.node.transform * transform; + } + + for (auto& vertex : quad) { + SkV4 vector = transform.map(vertex.x(), vertex.y(), 0, 1); + vertex = SkPoint::Make(vector.x / vector.w, vector.y / vector.w); + } + + SkRect rect; + rect.setBounds(quad, 4); + // If this UIFocusItemContainer's coordinateSpace is a UIScrollView, offset + // the rect by `contentOffset` because the contentOffset translation is + // incorporated into the paint transform at different node depth in UIKit + // and Flutter. In Flutter, the translation is added to the cells + // while in UIKit the viewport's bounds is manipulated (IOW, each cell's frame + // in the UIScrollView coordinateSpace does not change when the UIScrollView + // scrolls). + CGRect unscaledRect = + CGRectMake(rect.x() + scrollView.bounds.origin.x, rect.y() + scrollView.bounds.origin.y, + rect.width(), rect.height()); + if (scrollView) { + return unscaledRect; + } + // `rect` could be in physical pixels since the root RenderObject ("RenderView") + // applies a transform that turns logical pixels to physical pixels. Undo the + // transform by dividing the coordinates by the screen's scale factor, if this + // UIFocusItem's reported `coordinateSpace` is the root view (which means this + // UIFocusItem is not inside of a scroll view). + // + // Screen can be nil if the FlutterView is covered by another native view. + CGFloat scale = (self.bridge->view().window.screen ?: UIScreen.mainScreen).scale; + return CGRectMake(unscaledRect.origin.x / scale, unscaledRect.origin.y / scale, + unscaledRect.size.width / scale, unscaledRect.size.height / scale); +} + +#pragma mark - UIFocusItemContainer Conformance + +- (NSArray>*)focusItemsInRect:(CGRect)rect { + // It seems the iOS focus system relies heavily on focusItemsInRect + // (instead of preferredFocusEnvironments) for directional navigation. + // + // The order of the items seems to be important, menus and dialogs become + // unreachable via FKA if the returned children are organized + // in hit-test order. + // + // This method is only supposed to return items within the given + // rect but returning everything in the subtree seems to work fine. + NSMutableArray>* reversedItems = + [[NSMutableArray alloc] initWithCapacity:self.childrenInHitTestOrder.count]; + for (NSUInteger i = 0; i < self.childrenInHitTestOrder.count; ++i) { + SemanticsObject* child = self.childrenInHitTestOrder[self.childrenInHitTestOrder.count - 1 - i]; + [reversedItems addObject:child.focusItem]; + } + return reversedItems; +} + +- (id)coordinateSpace { + // A regular SemanticsObject uses the same coordinate space as its parent. + return self.parent.coordinateSpace ?: self.bridge->view(); +} + +@end + +/// Scrollable containers interact with the iOS focus engine using the +/// `UIFocusItemScrollableContainer` protocol. The said protocol (and other focus-related protocols) +/// does not provide means to inform the focus system of layout changes. In order for the focus +/// highlight to update properly as the scroll view scrolls, this implementation incorporates a +/// UIScrollView into the focus hierarchy to workaround the highlight update problem. +/// +/// As a result, in the current implementation only scrollable containers and the root node +/// establish their own `coordinateSpace`s. All other `UIFocusItemContainter`s use the same +/// `coordinateSpace` as the containing UIScrollView, or the root `FlutterView`, whichever is +/// closer. +/// +/// See also the `frame` method implementation. +#pragma mark - Scrolling + +@interface FlutterScrollableSemanticsObject (CoordinateSpace) +@end + +@implementation FlutterScrollableSemanticsObject (CoordinateSpace) +- (id)coordinateSpace { + // A scrollable SemanticsObject uses the same coordinate space as the scroll view. + // This may not work very well in nested scroll views. + return self.scrollView; +} + +- (id)focusItem { + return self.scrollView; +} + +@end + +@interface FlutterSemanticsScrollView (UIFocusItemScrollableContainer) < + UIFocusItemScrollableContainer> +@end + +@implementation FlutterSemanticsScrollView (UIFocusItemScrollableContainer) + +#pragma mark - FlutterSemanticsScrollView UIFocusItemScrollableContainer Conformance + +- (CGSize)visibleSize { + return self.frame.size; +} + +- (void)setContentOffset:(CGPoint)contentOffset { + [super setContentOffset:contentOffset]; + // Do no send flutter::SemanticsAction::kScrollToOffset if it's triggered + // by a framework update. + if (![self.semanticsObject isAccessibilityBridgeAlive] || !self.isDoingSystemScrolling) { + return; + } + + double offset[2] = {contentOffset.x, contentOffset.y}; + FlutterStandardTypedData* offsetData = [FlutterStandardTypedData + typedDataWithFloat64:[NSData dataWithBytes:&offset length:sizeof(offset)]]; + NSData* encoded = [[FlutterStandardMessageCodec sharedInstance] encode:offsetData]; + self.semanticsObject.bridge->DispatchSemanticsAction( + self.semanticsObject.uid, flutter::SemanticsAction::kScrollToOffset, + fml::MallocMapping::Copy(encoded.bytes, encoded.length)); +} + +- (BOOL)canBecomeFocused { + return NO; +} + +- (id)parentFocusEnvironment { + return self.semanticsObject.parentFocusEnvironment; +} + +- (NSArray>*)preferredFocusEnvironments { + return nil; +} + +- (NSArray>*)focusItemsInRect:(CGRect)rect { + return [self.semanticsObject focusItemsInRect:rect]; +} +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h new file mode 100644 index 0000000000000000000000000000000000000000..2c9e0516112eac7cfc5fd90ac864402f0153838a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h @@ -0,0 +1,239 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_SEMANTICSOBJECT_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_SEMANTICSOBJECT_H_ + +#import + +#include "flutter/fml/macros.h" +#include "flutter/fml/memory/weak_ptr.h" +#include "flutter/lib/ui/semantics/semantics_node.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterSemanticsScrollView.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge_ios.h" + +constexpr int32_t kRootNodeId = 0; +// This can be arbitrary number as long as it is bigger than 0. +constexpr float kScrollExtentMaxForInf = 1000; + +@class FlutterCustomAccessibilityAction; +@class FlutterPlatformViewSemanticsContainer; +@class FlutterTouchInterceptingView; + +/** + * A node in the iOS semantics tree. This object is a wrapper over a native accessibiliy + * object, which is stored in the property `nativeAccessibility`. In the most case, the + * `nativeAccessibility` directly returns this object. Some subclasses such as the + * `FlutterScrollableSemanticsObject` creates a native `UIScrollView` as its `nativeAccessibility` + * so that it can interact with iOS. + */ +@interface SemanticsObject : UIAccessibilityElement + +/** + * The globally unique identifier for this node. + */ +@property(nonatomic, readonly) int32_t uid; + +/** + * The parent of this node in the node tree. Will be nil for the root node and + * during transient state changes. + */ +@property(nonatomic, weak, readonly) SemanticsObject* parent; + +/** + * The accessibility bridge that this semantics object is attached to. This + * object may use the bridge to access contextual application information. A weak + * pointer is used because the platform view owns the accessibility bridge. + * If you are referencing this property from an iOS callback, be sure to + * use `isAccessibilityBridgeActive` to protect against the case where this + * node may be orphaned. + */ +@property(nonatomic, readonly) fml::WeakPtr bridge; + +/** + * The semantics node used to produce this semantics object. + */ +@property(nonatomic, readonly) flutter::SemanticsNode node; + +/** + * Whether this semantics object has child semantics objects. + */ +@property(nonatomic, readonly) BOOL hasChildren; + +/** + * Direct children of this semantics object. Each child's `parent` property must + * be equal to this object. + */ +@property(nonatomic, copy) NSArray* children; + +/** + * Direct children of this semantics object in hit test order. Each child's `parent` property + * must be equal to this object. + */ +@property(nonatomic, copy) NSArray* childrenInHitTestOrder; + +/** + * The UIAccessibility that represents this object. + * + * By default, this return self. Subclasses can override to return different + * objects to represent them. For example, FlutterScrollableSemanticsObject[s] + * maintain UIScrollView[s] to represent their UIAccessibility[s]. + */ +@property(nonatomic, readonly) id nativeAccessibility; + +/** + * 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; + +/** + * Called after accessibility bridge finishes a semantics update. + * + * Subclasses can override this method if they contain states that can only be + * updated once every node in the accessibility tree has finished updating. + */ +- (void)accessibilityBridgeDidFinishUpdate; + +#pragma mark - Designated initializers + +- (instancetype)init __attribute__((unavailable("Use initWithBridge instead"))); +- (instancetype)initWithBridge:(fml::WeakPtr)bridge + uid:(int32_t)uid NS_DESIGNATED_INITIALIZER; + +@end + +/** + * An implementation of UIAccessibilityCustomAction which also contains the + * Flutter uid. + */ +@interface FlutterCustomAccessibilityAction : UIAccessibilityCustomAction + +/** + * The uid of the action defined by the flutter application. + */ +@property(nonatomic) int32_t uid; + +@end + +/** + * The default implementation of `SemanticsObject` for most accessibility elements + * in the iOS accessibility tree. + * + * Use this implementation for nodes that do not need to be expressed via UIKit-specific + * protocols (it only implements NSObject). + * + * See also: + * * TextInputSemanticsObject, which implements `UITextInput` protocol to expose + * editable text widgets to a11y. + */ +@interface FlutterSemanticsObject : SemanticsObject +@end + +/** + * Designated to act as an accessibility container of a platform view. + * + * This object does not take any accessibility actions on its own, nor has any accessibility + * label/value/trait/hint... on its own. The accessibility data will be handled by the platform + * view. + * + * See also: + * * `SemanticsObject` for the other type of semantics objects. + * * `FlutterSemanticsObject` for default implementation of `SemanticsObject`. + */ +@interface FlutterPlatformViewSemanticsContainer : SemanticsObject + +- (instancetype)initWithBridge:(fml::WeakPtr)bridge + uid:(int32_t)uid NS_UNAVAILABLE; + +- (instancetype)initWithBridge:(fml::WeakPtr)bridge + uid:(int32_t)uid + platformView:(FlutterTouchInterceptingView*)platformView + NS_DESIGNATED_INITIALIZER; + +@end + +/// The semantics object for switch buttons. This class creates an UISwitch to interact with the +/// iOS. +@interface FlutterSwitchSemanticsObject : SemanticsObject + +@end + +/// The semantics object for scrollable. This class creates an UIScrollView to interact with the +/// iOS. +@interface FlutterScrollableSemanticsObject : SemanticsObject +@property(nonatomic, readonly) FlutterSemanticsScrollView* scrollView; +@end + +/** + * Represents a semantics object that has children and hence has to be presented to the OS as a + * UIAccessibilityContainer. + * + * The SemanticsObject class cannot implement the UIAccessibilityContainer protocol because an + * object that returns YES for isAccessibilityElement cannot also implement + * UIAccessibilityContainer. + * + * With the help of SemanticsObjectContainer, the hierarchy of semantic objects received from + * the framework, such as: + * + * SemanticsObject1 + * SemanticsObject2 + * SemanticsObject3 + * SemanticsObject4 + * + * is translated into the following hierarchy, which is understood by iOS: + * + * SemanticsObjectContainer1 + * SemanticsObject1 + * SemanticsObjectContainer2 + * SemanticsObject2 + * SemanticsObject3 + * SemanticsObject4 + * + * From Flutter's view of the world (the first tree seen above), we construct iOS's view of the + * world (second tree) as follows: We replace each SemanticsObjects that has children with a + * SemanticsObjectContainer, which has the original SemanticsObject and its children as children. + * + * SemanticsObjects have semantic information attached to them which is interpreted by + * VoiceOver (they return YES for isAccessibilityElement). The SemanticsObjectContainers are just + * there for structure and they don't provide any semantic information to VoiceOver (they return + * NO for isAccessibilityElement). + */ +@interface SemanticsObjectContainer : UIAccessibilityElement +- (instancetype)init NS_UNAVAILABLE; ++ (instancetype)new NS_UNAVAILABLE; +- (instancetype)initWithAccessibilityContainer:(id)container NS_UNAVAILABLE; +- (instancetype)initWithSemanticsObject:(SemanticsObject*)semanticsObject + bridge:(fml::WeakPtr)bridge + NS_DESIGNATED_INITIALIZER; + +@property(nonatomic, weak) SemanticsObject* semanticsObject; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_SEMANTICSOBJECT_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.mm new file mode 100644 index 0000000000000000000000000000000000000000..e864cc463a5e3dc100e2c29da4f1f0b21fc33d27 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.mm @@ -0,0 +1,967 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h" + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterSemanticsScrollView.h" + +FLUTTER_ASSERT_ARC + +namespace { + +flutter::SemanticsAction GetSemanticsActionForScrollDirection( + UIAccessibilityScrollDirection direction) { + // To describe the vertical scroll direction, UIAccessibilityScrollDirection uses the + // direction the scroll bar moves in and SemanticsAction uses the direction the finger + // moves in. However, the horizontal scroll direction matches the SemanticsAction direction. + // That is way the following maps vertical opposite of the SemanticsAction, but the horizontal + // maps directly. + switch (direction) { + case UIAccessibilityScrollDirectionRight: + case UIAccessibilityScrollDirectionPrevious: // TODO(abarth): Support RTL using + // _node.textDirection. + return flutter::SemanticsAction::kScrollRight; + case UIAccessibilityScrollDirectionLeft: + case UIAccessibilityScrollDirectionNext: // TODO(abarth): Support RTL using + // _node.textDirection. + return flutter::SemanticsAction::kScrollLeft; + case UIAccessibilityScrollDirectionUp: + return flutter::SemanticsAction::kScrollDown; + case UIAccessibilityScrollDirectionDown: + return flutter::SemanticsAction::kScrollUp; + } + FML_DCHECK(false); // Unreachable + return flutter::SemanticsAction::kScrollUp; +} + +SkM44 GetGlobalTransform(SemanticsObject* reference) { + SkM44 globalTransform = [reference node].transform; + for (SemanticsObject* parent = [reference parent]; parent; parent = parent.parent) { + globalTransform = parent.node.transform * globalTransform; + } + return globalTransform; +} + +SkPoint ApplyTransform(SkPoint& point, const SkM44& transform) { + SkV4 vector = transform.map(point.x(), point.y(), 0, 1); + return SkPoint::Make(vector.x / vector.w, vector.y / vector.w); +} + +CGPoint ConvertPointToGlobal(SemanticsObject* reference, CGPoint local_point) { + SkM44 globalTransform = GetGlobalTransform(reference); + SkPoint point = SkPoint::Make(local_point.x, local_point.y); + point = ApplyTransform(point, globalTransform); + // `rect` is in the physical pixel coordinate system. iOS expects the accessibility frame in + // the logical pixel coordinate system. Therefore, we divide by the `scale` (pixel ratio) to + // convert. + UIScreen* screen = reference.bridge->view().window.screen; + // Screen can be nil if the FlutterView is covered by another native view. + CGFloat scale = (screen ?: UIScreen.mainScreen).scale; + auto result = CGPointMake(point.x() / scale, point.y() / scale); + return [reference.bridge->view() convertPoint:result toView:nil]; +} + +CGRect ConvertRectToGlobal(SemanticsObject* reference, CGRect local_rect) { + SkM44 globalTransform = GetGlobalTransform(reference); + + SkPoint quad[4] = { + SkPoint::Make(local_rect.origin.x, local_rect.origin.y), // top left + SkPoint::Make(local_rect.origin.x + local_rect.size.width, local_rect.origin.y), // top right + SkPoint::Make(local_rect.origin.x + local_rect.size.width, + local_rect.origin.y + local_rect.size.height), // bottom right + SkPoint::Make(local_rect.origin.x, + local_rect.origin.y + local_rect.size.height) // bottom left + }; + for (auto& point : quad) { + point = ApplyTransform(point, globalTransform); + } + SkRect rect; + NSCAssert(rect.setBoundsCheck(quad, 4), @"Transformed points can't form a rect"); + rect.setBounds(quad, 4); + + // `rect` is in the physical pixel coordinate system. iOS expects the accessibility frame in + // the logical pixel coordinate system. Therefore, we divide by the `scale` (pixel ratio) to + // convert. + UIScreen* screen = reference.bridge->view().window.screen; + // Screen can be nil if the FlutterView is covered by another native view. + CGFloat scale = (screen ?: UIScreen.mainScreen).scale; + auto result = + CGRectMake(rect.x() / scale, rect.y() / scale, rect.width() / scale, rect.height() / scale); + return UIAccessibilityConvertFrameToScreenCoordinates(result, reference.bridge->view()); +} + +} // namespace + +@interface FlutterSwitchSemanticsObject () +@property(nonatomic, retain, readonly) UISwitch* nativeSwitch; +@end + +@implementation FlutterSwitchSemanticsObject + +- (instancetype)initWithBridge:(fml::WeakPtr)bridge + uid:(int32_t)uid { + self = [super initWithBridge:bridge uid:uid]; + if (self) { + _nativeSwitch = [[UISwitch alloc] init]; + } + return self; +} + +- (NSMethodSignature*)methodSignatureForSelector:(SEL)sel { + NSMethodSignature* result = [super methodSignatureForSelector:sel]; + if (!result) { + result = [self.nativeSwitch methodSignatureForSelector:sel]; + } + return result; +} + +- (void)forwardInvocation:(NSInvocation*)anInvocation { + anInvocation.target = self.nativeSwitch; + [anInvocation invoke]; +} + +- (NSString*)accessibilityValue { + self.nativeSwitch.on = self.node.HasFlag(flutter::SemanticsFlags::kIsToggled) || + self.node.HasFlag(flutter::SemanticsFlags::kIsChecked); + + if (![self isAccessibilityBridgeAlive]) { + return nil; + } else { + return self.nativeSwitch.accessibilityValue; + } +} + +- (UIAccessibilityTraits)accessibilityTraits { + self.nativeSwitch.enabled = self.node.HasFlag(flutter::SemanticsFlags::kIsEnabled); + + return self.nativeSwitch.accessibilityTraits; +} + +@end // FlutterSwitchSemanticsObject + +@interface FlutterScrollableSemanticsObject () +@property(nonatomic) FlutterSemanticsScrollView* scrollView; +@end + +@implementation FlutterScrollableSemanticsObject + +- (instancetype)initWithBridge:(fml::WeakPtr)bridge + uid:(int32_t)uid { + self = [super initWithBridge:bridge uid:uid]; + if (self) { + _scrollView = [[FlutterSemanticsScrollView alloc] initWithSemanticsObject:self]; + [_scrollView setShowsHorizontalScrollIndicator:NO]; + [_scrollView setShowsVerticalScrollIndicator:NO]; + [_scrollView setContentInset:UIEdgeInsetsZero]; + [_scrollView setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever]; + [self.bridge->view() addSubview:_scrollView]; + } + return self; +} + +- (void)dealloc { + [_scrollView removeFromSuperview]; +} + +- (void)accessibilityBridgeDidFinishUpdate { + // In order to make iOS think this UIScrollView is scrollable, the following + // requirements must be true. + // 1. contentSize must be bigger than the frame size. + // 2. The scrollable isAccessibilityElement must return YES + // + // Once the requirements are met, the iOS uses contentOffset to determine + // what scroll actions are available. e.g. If the view scrolls vertically and + // contentOffset is 0.0, only the scroll down action is available. + self.scrollView.frame = self.accessibilityFrame; + self.scrollView.contentSize = [self contentSizeInternal]; + // See the documentation on `isDoingSystemScrolling`. + if (!self.scrollView.isDoingSystemScrolling) { + [self.scrollView setContentOffset:self.contentOffsetInternal animated:NO]; + } +} + +- (id)nativeAccessibility { + return self.scrollView; +} + +// private methods + +- (float)scrollExtentMax { + if (![self isAccessibilityBridgeAlive]) { + return 0.0f; + } + float scrollExtentMax = self.node.scrollExtentMax; + if (isnan(scrollExtentMax)) { + scrollExtentMax = 0.0f; + } else if (!isfinite(scrollExtentMax)) { + scrollExtentMax = kScrollExtentMaxForInf + [self scrollPosition]; + } + return scrollExtentMax; +} + +- (float)scrollPosition { + if (![self isAccessibilityBridgeAlive]) { + return 0.0f; + } + float scrollPosition = self.node.scrollPosition; + if (isnan(scrollPosition)) { + scrollPosition = 0.0f; + } + NSCAssert(isfinite(scrollPosition), @"The scrollPosition must not be infinity"); + return scrollPosition; +} + +- (CGSize)contentSizeInternal { + CGRect result; + const SkRect& rect = self.node.rect; + + if (self.node.actions & flutter::kVerticalScrollSemanticsActions) { + result = CGRectMake(rect.x(), rect.y(), rect.width(), rect.height() + [self scrollExtentMax]); + } else if (self.node.actions & flutter::kHorizontalScrollSemanticsActions) { + result = CGRectMake(rect.x(), rect.y(), rect.width() + [self scrollExtentMax], rect.height()); + } else { + result = CGRectMake(rect.x(), rect.y(), rect.width(), rect.height()); + } + return ConvertRectToGlobal(self, result).size; +} + +- (CGPoint)contentOffsetInternal { + CGPoint result; + CGPoint origin = self.scrollView.frame.origin; + const SkRect& rect = self.node.rect; + if (self.node.actions & flutter::kVerticalScrollSemanticsActions) { + result = ConvertPointToGlobal(self, CGPointMake(rect.x(), rect.y() + [self scrollPosition])); + } else if (self.node.actions & flutter::kHorizontalScrollSemanticsActions) { + result = ConvertPointToGlobal(self, CGPointMake(rect.x() + [self scrollPosition], rect.y())); + } else { + result = origin; + } + return CGPointMake(result.x - origin.x, result.y - origin.y); +} + +@end // FlutterScrollableSemanticsObject + +@implementation FlutterCustomAccessibilityAction { +} +@end + +@interface SemanticsObject () +@property(nonatomic) SemanticsObjectContainer* container; + +/** Should only be called in conjunction with setting child/parent relationship. */ +@property(nonatomic, weak, readwrite) SemanticsObject* parent; + +@end + +@implementation SemanticsObject { + NSMutableArray* _children; + BOOL _inDealloc; +} + +#pragma mark - Designated initializers + +- (instancetype)initWithBridge:(fml::WeakPtr)bridge + uid:(int32_t)uid { + FML_DCHECK(bridge) << "bridge must be set"; + FML_DCHECK(uid >= kRootNodeId); + // Initialize with the UIView as the container. + // The UIView will not necessarily be accessibility parent for this object. + // The bridge informs the OS of the actual structure via + // `accessibilityContainer` and `accessibilityElementAtIndex`. + self = [super initWithAccessibilityContainer:bridge->view()]; + + if (self) { + _bridge = bridge; + _uid = uid; + _children = [[NSMutableArray alloc] init]; + _childrenInHitTestOrder = [[NSArray alloc] init]; + } + + return self; +} + +- (void)dealloc { + // Set parent and children parents to nil explicitly in dealloc. + // -[UIAccessibilityElement dealloc] has in the past called into -accessibilityContainer + // and self.children. There have also been crashes related to iOS + // accessing methods during dealloc, and there's a lag before the tree changes. + // See https://github.com/flutter/engine/pull/4602 and + // https://github.com/flutter/engine/pull/27786. + for (SemanticsObject* child in _children) { + child.parent = nil; + } + [_children removeAllObjects]; + + _parent = nil; + _inDealloc = YES; +} + +#pragma mark - Semantic object property accesser + +- (void)setChildren:(NSArray*)children { + for (SemanticsObject* child in _children) { + child.parent = nil; + } + _children = [children mutableCopy]; + for (SemanticsObject* child in _children) { + child.parent = self; + } +} + +- (void)setChildrenInHitTestOrder:(NSArray*)childrenInHitTestOrder { + for (SemanticsObject* child in _childrenInHitTestOrder) { + child.parent = nil; + } + _childrenInHitTestOrder = [childrenInHitTestOrder copy]; + for (SemanticsObject* child in _childrenInHitTestOrder) { + child.parent = self; + } +} + +- (BOOL)hasChildren { + return [self.children count] != 0; +} + +#pragma mark - Semantic object method + +- (BOOL)isAccessibilityBridgeAlive { + return self.bridge.get() != nil; +} + +- (void)setSemanticsNode:(const flutter::SemanticsNode*)node { + _node = *node; +} + +- (void)accessibilityBridgeDidFinishUpdate { /* Do nothing by default */ +} + +/** + * Whether calling `setSemanticsNode:` with `node` would cause a layout change. + */ +- (BOOL)nodeWillCauseLayoutChange:(const flutter::SemanticsNode*)node { + return self.node.rect != node->rect || self.node.transform != node->transform; +} + +/** + * Whether calling `setSemanticsNode:` with `node` would cause a scroll event. + */ +- (BOOL)nodeWillCauseScroll:(const flutter::SemanticsNode*)node { + return !isnan(self.node.scrollPosition) && !isnan(node->scrollPosition) && + self.node.scrollPosition != node->scrollPosition; +} + +/** + * Whether calling `setSemanticsNode:` with `node` should trigger an + * announcement. + */ +- (BOOL)nodeShouldTriggerAnnouncement:(const flutter::SemanticsNode*)node { + // The node dropped the live region flag, if it ever had one. + if (!node || !node->HasFlag(flutter::SemanticsFlags::kIsLiveRegion)) { + return NO; + } + + // The node has gained a new live region flag, always announce. + if (!self.node.HasFlag(flutter::SemanticsFlags::kIsLiveRegion)) { + return YES; + } + + // The label has updated, and the new node has a live region flag. + return self.node.label != node->label; +} + +- (void)replaceChildAtIndex:(NSInteger)index withChild:(SemanticsObject*)child { + SemanticsObject* oldChild = _children[index]; + oldChild.parent = nil; + child.parent = self; + [_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; +} + +- (id)nativeAccessibility { + return self; +} + +- (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; +} + +- (void)showOnScreen { + self.bridge->DispatchSemanticsAction(self.uid, flutter::SemanticsAction::kShowOnScreen); +} + +#pragma mark - UIAccessibility overrides + +- (BOOL)isAccessibilityElement { + if (![self isAccessibilityBridgeAlive]) { + return false; + } + + // Note: hit detection will only apply to elements that report + // -isAccessibilityElement of YES. The framework will continue scanning the + // entire element tree looking for such a hit. + + // We enforce in the framework that no other useful semantics are merged with these nodes. + if (self.node.HasFlag(flutter::SemanticsFlags::kScopesRoute)) { + return false; + } + + return [self isFocusable]; +} + +- (bool)isFocusable { + // If the node is scrollable AND hidden OR + // The node has a label, value, or hint OR + // The node has non-scrolling related actions. + // + // The kIsHidden flag set with the scrollable flag means this node is now + // hidden but still is a valid target for a11y focus in the tree, e.g. a list + // item that is currently off screen but the a11y navigation needs to know + // about. + return ((self.node.flags & flutter::kScrollableSemanticsFlags) != 0 && + (self.node.flags & static_cast(flutter::SemanticsFlags::kIsHidden)) != 0) || + !self.node.label.empty() || !self.node.value.empty() || !self.node.hint.empty() || + (self.node.actions & ~flutter::kScrollableSemanticsActions) != 0; +} + +- (void)collectRoutes:(NSMutableArray*)edges { + if (self.node.HasFlag(flutter::SemanticsFlags::kScopesRoute)) { + [edges addObject:self]; + } + if ([self hasChildren]) { + for (SemanticsObject* child in self.children) { + [child collectRoutes:edges]; + } + } +} + +- (BOOL)onCustomAccessibilityAction:(FlutterCustomAccessibilityAction*)action { + if (!self.node.HasAction(flutter::SemanticsAction::kCustomAction)) { + return NO; + } + int32_t action_id = action.uid; + std::vector args; + args.push_back(3); // type=int32. + args.push_back(action_id); + args.push_back(action_id >> 8); + args.push_back(action_id >> 16); + args.push_back(action_id >> 24); + self.bridge->DispatchSemanticsAction( + self.uid, flutter::SemanticsAction::kCustomAction, + fml::MallocMapping::Copy(args.data(), args.size() * sizeof(uint8_t))); + return YES; +} + +- (NSString*)accessibilityIdentifier { + if (![self isAccessibilityBridgeAlive]) { + return nil; + } + + if (self.node.identifier.empty()) { + return nil; + } + return @(self.node.identifier.data()); +} + +- (NSString*)accessibilityLabel { + if (![self isAccessibilityBridgeAlive]) { + return nil; + } + NSString* label = nil; + if (!self.node.label.empty()) { + label = @(self.node.label.data()); + } + if (!self.node.tooltip.empty()) { + label = label ? [NSString stringWithFormat:@"%@\n%@", label, @(self.node.tooltip.data())] + : @(self.node.tooltip.data()); + } + return label; +} + +- (bool)containsPoint:(CGPoint)point { + // The point is in global coordinates, so use the global rect here. + return CGRectContainsPoint([self globalRect], point); +} + +// Finds the first eligiable semantics object in hit test order. +- (id)search:(CGPoint)point { + // Search children in hit test order. + for (SemanticsObject* child in [self childrenInHitTestOrder]) { + if ([child containsPoint:point]) { + id childSearchResult = [child search:point]; + if (childSearchResult != nil) { + return childSearchResult; + } + } + } + // Check if the current semantic object should be returned. + if ([self containsPoint:point] && [self isFocusable]) { + return self.nativeAccessibility; + } + return nil; +} + +// iOS uses this method to determine the hittest results when users touch +// explore in VoiceOver. +// +// For overlapping UIAccessibilityElements (e.g. a stack) in IOS, the focus +// goes to the smallest object before IOS 16, but to the top-left object in +// IOS 16. Overrides this method to focus the first eligiable semantics +// object in hit test order. +- (id)_accessibilityHitTest:(CGPoint)point withEvent:(UIEvent*)event { + return [self search:point]; +} + +// iOS calls this method when this item is swipe-to-focusd in VoiceOver. +- (BOOL)accessibilityScrollToVisible { + [self showOnScreen]; + return YES; +} + +// iOS calls this method when this item is swipe-to-focusd in VoiceOver. +- (BOOL)accessibilityScrollToVisibleWithChild:(id)child { + if ([child isKindOfClass:[SemanticsObject class]]) { + [child showOnScreen]; + return YES; + } + return NO; +} + +- (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; + } + + if (self.node.hint.empty()) { + return nil; + } + 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; + } + + if (!self.node.value.empty()) { + return @(self.node.value.data()); + } + + // iOS does not announce values of native radio buttons. + if (self.node.HasFlag(flutter::SemanticsFlags::kIsInMutuallyExclusiveGroup)) { + return nil; + } + + // FlutterSwitchSemanticsObject should supercede these conditionals. + if (self.node.HasFlag(flutter::SemanticsFlags::kHasToggledState) || + self.node.HasFlag(flutter::SemanticsFlags::kHasCheckedState)) { + if (self.node.HasFlag(flutter::SemanticsFlags::kIsToggled) || + self.node.HasFlag(flutter::SemanticsFlags::kIsChecked)) { + return @"1"; + } else { + return @"0"; + } + } + + 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); + } + + if (self.node.HasFlag(flutter::SemanticsFlags::kIsHidden)) { + return [super accessibilityFrame]; + } + return [self globalRect]; +} + +- (CGRect)globalRect { + const SkRect& rect = self.node.rect; + CGRect localRect = CGRectMake(rect.x(), rect.y(), rect.width(), rect.height()); + return ConvertRectToGlobal(self, localRect); +} + +#pragma mark - UIAccessibilityElement protocol + +- (void)setAccessibilityContainer:(id)container { + // Explicit noop. The containers are calculated lazily in `accessibilityContainer`. + // See also: https://github.com/flutter/flutter/issues/54366 +} + +- (id)accessibilityContainer { + if (_inDealloc) { + // In iOS9, `accessibilityContainer` will be called by `[UIAccessibilityElementSuperCategory + // dealloc]` during `[super dealloc]`. And will crash when accessing `_children` which has + // called `[_children release]` in `[SemanticsObject dealloc]`. + // https://github.com/flutter/flutter/issues/87247 + return nil; + } + + if (![self isAccessibilityBridgeAlive]) { + return nil; + } + + if ([self hasChildren] || self.uid == kRootNodeId) { + if (self.container == nil) { + self.container = [[SemanticsObjectContainer alloc] initWithSemanticsObject:self + bridge:self.bridge]; + } + return self.container; + } + if (self.parent == nil) { + // This can happen when we have released the accessibility tree but iOS is + // still holding onto our objects. iOS can take some time before it + // realizes that the tree has changed. + return nil; + } + return self.parent.accessibilityContainer; +} + +#pragma mark - UIAccessibilityAction overrides + +- (BOOL)accessibilityActivate { + if (![self isAccessibilityBridgeAlive]) { + return NO; + } + if (!self.node.HasAction(flutter::SemanticsAction::kTap)) { + // Prevent sliders to receive a regular tap which will change the value. + // + // This is needed because it causes slider to select to middle if it + // does not have a semantics tap. + if (self.node.HasFlag(flutter::SemanticsFlags::kIsSlider)) { + return YES; + } + return NO; + } + self.bridge->DispatchSemanticsAction(self.uid, flutter::SemanticsAction::kTap); + return YES; +} + +- (void)accessibilityIncrement { + if (![self isAccessibilityBridgeAlive]) { + return; + } + if (self.node.HasAction(flutter::SemanticsAction::kIncrease)) { + self.node.value = self.node.increasedValue; + self.bridge->DispatchSemanticsAction(self.uid, flutter::SemanticsAction::kIncrease); + } +} + +- (void)accessibilityDecrement { + if (![self isAccessibilityBridgeAlive]) { + return; + } + if (self.node.HasAction(flutter::SemanticsAction::kDecrease)) { + self.node.value = self.node.decreasedValue; + self.bridge->DispatchSemanticsAction(self.uid, flutter::SemanticsAction::kDecrease); + } +} + +- (BOOL)accessibilityScroll:(UIAccessibilityScrollDirection)direction { + if (![self isAccessibilityBridgeAlive]) { + return NO; + } + flutter::SemanticsAction action = GetSemanticsActionForScrollDirection(direction); + if (!self.node.HasAction(action)) { + return NO; + } + self.bridge->DispatchSemanticsAction(self.uid, action); + return YES; +} + +- (BOOL)accessibilityPerformEscape { + if (![self isAccessibilityBridgeAlive]) { + return NO; + } + if (!self.node.HasAction(flutter::SemanticsAction::kDismiss)) { + return NO; + } + self.bridge->DispatchSemanticsAction(self.uid, flutter::SemanticsAction::kDismiss); + return YES; +} + +#pragma mark UIAccessibilityFocus overrides + +- (void)accessibilityElementDidBecomeFocused { + if (![self isAccessibilityBridgeAlive]) { + return; + } + self.bridge->AccessibilityObjectDidBecomeFocused(self.uid); + if (self.node.HasFlag(flutter::SemanticsFlags::kIsHidden) || + self.node.HasFlag(flutter::SemanticsFlags::kIsHeader)) { + [self showOnScreen]; + } + if (self.node.HasAction(flutter::SemanticsAction::kDidGainAccessibilityFocus)) { + self.bridge->DispatchSemanticsAction(self.uid, + flutter::SemanticsAction::kDidGainAccessibilityFocus); + } +} + +- (void)accessibilityElementDidLoseFocus { + if (![self isAccessibilityBridgeAlive]) { + return; + } + self.bridge->AccessibilityObjectDidLoseFocus(self.uid); + if (self.node.HasAction(flutter::SemanticsAction::kDidLoseAccessibilityFocus)) { + self.bridge->DispatchSemanticsAction(self.uid, + flutter::SemanticsAction::kDidLoseAccessibilityFocus); + } +} + +- (BOOL)accessibilityRespondsToUserInteraction { + // Return true only if the node contains actions other than system actions. + if ((self.node.actions & ~flutter::kSystemActions) != 0) { + return true; + } + + if (!self.node.customAccessibilityActions.empty()) { + return true; + } + + return false; +} + +@end + +@implementation FlutterSemanticsObject + +#pragma mark - Designated initializers + +- (instancetype)initWithBridge:(fml::WeakPtr)bridge + uid:(int32_t)uid { + self = [super initWithBridge:bridge uid:uid]; + return self; +} + +#pragma mark - UIAccessibility overrides + +- (UIAccessibilityTraits)accessibilityTraits { + UIAccessibilityTraits traits = UIAccessibilityTraitNone; + if (self.node.HasAction(flutter::SemanticsAction::kIncrease) || + self.node.HasAction(flutter::SemanticsAction::kDecrease)) { + traits |= UIAccessibilityTraitAdjustable; + } + // This should also capture radio buttons. + if (self.node.HasFlag(flutter::SemanticsFlags::kHasToggledState) || + self.node.HasFlag(flutter::SemanticsFlags::kHasCheckedState)) { + traits |= UIAccessibilityTraitButton; + } + if (self.node.HasFlag(flutter::SemanticsFlags::kIsSelected)) { + traits |= UIAccessibilityTraitSelected; + } + if (self.node.HasFlag(flutter::SemanticsFlags::kIsButton)) { + traits |= UIAccessibilityTraitButton; + } + if (self.node.HasFlag(flutter::SemanticsFlags::kHasEnabledState) && + !self.node.HasFlag(flutter::SemanticsFlags::kIsEnabled)) { + traits |= UIAccessibilityTraitNotEnabled; + } + if (self.node.HasFlag(flutter::SemanticsFlags::kIsHeader)) { + traits |= UIAccessibilityTraitHeader; + } + if (self.node.HasFlag(flutter::SemanticsFlags::kIsImage)) { + traits |= UIAccessibilityTraitImage; + } + if (self.node.HasFlag(flutter::SemanticsFlags::kIsLiveRegion)) { + traits |= UIAccessibilityTraitUpdatesFrequently; + } + if (self.node.HasFlag(flutter::SemanticsFlags::kIsLink)) { + traits |= UIAccessibilityTraitLink; + } + if (traits == UIAccessibilityTraitNone && ![self hasChildren] && + self.accessibilityLabel.length != 0 && + !self.node.HasFlag(flutter::SemanticsFlags::kIsTextField)) { + traits = UIAccessibilityTraitStaticText; + } + return traits; +} + +@end + +@interface FlutterPlatformViewSemanticsContainer () +@property(nonatomic, weak) UIView* platformView; +@end + +@implementation FlutterPlatformViewSemanticsContainer + +- (instancetype)initWithBridge:(fml::WeakPtr)bridge + uid:(int32_t)uid + platformView:(nonnull FlutterTouchInterceptingView*)platformView { + if (self = [super initWithBridge:bridge uid:uid]) { + _platformView = platformView; + [platformView setFlutterAccessibilityContainer:self]; + } + return self; +} + +- (id)nativeAccessibility { + return self.platformView; +} + +@end + +@implementation SemanticsObjectContainer { + fml::WeakPtr _bridge; +} + +#pragma mark - initializers + +- (instancetype)initWithSemanticsObject:(SemanticsObject*)semanticsObject + bridge:(fml::WeakPtr)bridge { + FML_DCHECK(semanticsObject) << "semanticsObject must be set"; + // Initialize with the UIView as the container. + // The UIView will not necessarily be accessibility parent for this object. + // The bridge informs the OS of the actual structure via + // `accessibilityContainer` and `accessibilityElementAtIndex`. + self = [super initWithAccessibilityContainer:bridge->view()]; + + if (self) { + _semanticsObject = semanticsObject; + _bridge = bridge; + } + + return self; +} + +#pragma mark - UIAccessibilityContainer overrides + +- (NSInteger)accessibilityElementCount { + return self.semanticsObject.children.count + 1; +} + +- (nullable id)accessibilityElementAtIndex:(NSInteger)index { + if (index < 0 || index >= [self accessibilityElementCount]) { + return nil; + } + if (index == 0) { + return self.semanticsObject.nativeAccessibility; + } + + SemanticsObject* child = self.semanticsObject.children[index - 1]; + + if ([child hasChildren]) { + return child.accessibilityContainer; + } + return child.nativeAccessibility; +} + +- (NSInteger)indexOfAccessibilityElement:(id)element { + if (element == self.semanticsObject.nativeAccessibility) { + return 0; + } + + NSArray* children = self.semanticsObject.children; + for (size_t i = 0; i < [children count]; i++) { + SemanticsObject* child = children[i]; + if ((![child hasChildren] && child.nativeAccessibility == element) || + ([child hasChildren] && [child.nativeAccessibility accessibilityContainer] == element)) { + return i + 1; + } + } + return NSNotFound; +} + +#pragma mark - UIAccessibilityElement protocol + +- (BOOL)isAccessibilityElement { + return NO; +} + +- (CGRect)accessibilityFrame { + // For OverlayPortals, the child element is sometimes outside the bounds of the parent + // Even if it's marked accessible, VoiceControl labels will not appear if it's too + // spatially distant. Set the frame to be the max screen size so all children are guaraenteed + // to be contained. + + return UIScreen.mainScreen.bounds; +} + +- (id)accessibilityContainer { + if (!_bridge) { + return nil; + } + return ([self.semanticsObject uid] == kRootNodeId) + ? _bridge->view() + : self.semanticsObject.parent.accessibilityContainer; +} + +#pragma mark - UIAccessibilityAction overrides + +- (BOOL)accessibilityScroll:(UIAccessibilityScrollDirection)direction { + return [self.semanticsObject accessibilityScroll:direction]; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObjectTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObjectTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..b91d83cfefaa23f0b7ab791b2b12dcb5ba3d4aaa --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObjectTest.mm @@ -0,0 +1,1319 @@ +// 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. + +#import +#import + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterSemanticsScrollView.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTouchInterceptingView_Test.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/SemanticsObjectTestMocks.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/TextInputSemanticsObject.h" + +FLUTTER_ASSERT_ARC + +const float kFloatCompareEpsilon = 0.001; + +@interface SemanticsObject (UIFocusSystem) +@end + +@interface FlutterScrollableSemanticsObject (UIFocusItemScrollableContainer) < + UIFocusItemScrollableContainer> +@end + +@interface TextInputSemanticsObject (Test) +- (UIView*)textInputSurrogate; +@end + +@interface SemanticsObjectTest : XCTestCase +@end + +@implementation SemanticsObjectTest + +- (void)testCreate { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + SemanticsObject* object = [[SemanticsObject alloc] initWithBridge:bridge uid:0]; + XCTAssertNotNil(object); +} + +- (void)testSetChildren { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + SemanticsObject* parent = [[SemanticsObject alloc] initWithBridge:bridge uid:0]; + SemanticsObject* child = [[SemanticsObject alloc] initWithBridge:bridge uid:1]; + parent.children = @[ child ]; + XCTAssertEqual(parent, child.parent); + parent.children = @[]; + XCTAssertNil(child.parent); +} + +- (void)testAccessibilityHitTestFocusAtLeaf { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + SemanticsObject* object0 = [[SemanticsObject alloc] initWithBridge:bridge uid:0]; + SemanticsObject* object1 = [[SemanticsObject alloc] initWithBridge:bridge uid:1]; + SemanticsObject* object2 = [[SemanticsObject alloc] initWithBridge:bridge uid:2]; + SemanticsObject* object3 = [[SemanticsObject alloc] initWithBridge:bridge uid:3]; + object0.children = @[ object1 ]; + object0.childrenInHitTestOrder = @[ object1 ]; + object1.children = @[ object2, object3 ]; + object1.childrenInHitTestOrder = @[ object2, object3 ]; + + flutter::SemanticsNode node0; + node0.id = 0; + node0.rect = SkRect::MakeXYWH(0, 0, 200, 200); + node0.label = "0"; + [object0 setSemanticsNode:&node0]; + + flutter::SemanticsNode node1; + node1.id = 1; + node1.rect = SkRect::MakeXYWH(0, 0, 200, 200); + node1.label = "1"; + [object1 setSemanticsNode:&node1]; + + flutter::SemanticsNode node2; + node2.id = 2; + node2.rect = SkRect::MakeXYWH(0, 0, 100, 100); + node2.label = "2"; + [object2 setSemanticsNode:&node2]; + + flutter::SemanticsNode node3; + node3.id = 3; + node3.rect = SkRect::MakeXYWH(0, 0, 200, 200); + node3.label = "3"; + [object3 setSemanticsNode:&node3]; + + CGPoint point = CGPointMake(10, 10); + id hitTestResult = [object0 _accessibilityHitTest:point withEvent:nil]; + + // Focus to object2 because it's the first object in hit test order + XCTAssertEqual(hitTestResult, object2); +} + +- (void)testAccessibilityHitTestNoFocusableItem { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + SemanticsObject* object0 = [[SemanticsObject alloc] initWithBridge:bridge uid:0]; + SemanticsObject* object1 = [[SemanticsObject alloc] initWithBridge:bridge uid:1]; + SemanticsObject* object2 = [[SemanticsObject alloc] initWithBridge:bridge uid:2]; + SemanticsObject* object3 = [[SemanticsObject alloc] initWithBridge:bridge uid:3]; + object0.children = @[ object1 ]; + object0.childrenInHitTestOrder = @[ object1 ]; + object1.children = @[ object2, object3 ]; + object1.childrenInHitTestOrder = @[ object2, object3 ]; + + flutter::SemanticsNode node0; + node0.id = 0; + node0.rect = SkRect::MakeXYWH(0, 0, 200, 200); + [object0 setSemanticsNode:&node0]; + + flutter::SemanticsNode node1; + node1.id = 1; + node1.rect = SkRect::MakeXYWH(0, 0, 200, 200); + [object1 setSemanticsNode:&node1]; + + flutter::SemanticsNode node2; + node2.id = 2; + node2.rect = SkRect::MakeXYWH(0, 0, 100, 100); + [object2 setSemanticsNode:&node2]; + + flutter::SemanticsNode node3; + node3.id = 3; + node3.rect = SkRect::MakeXYWH(0, 0, 200, 200); + [object3 setSemanticsNode:&node3]; + + CGPoint point = CGPointMake(10, 10); + id hitTestResult = [object0 _accessibilityHitTest:point withEvent:nil]; + + XCTAssertNil(hitTestResult); +} + +- (void)testAccessibilityScrollToVisible { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + SemanticsObject* object3 = [[SemanticsObject alloc] initWithBridge:bridge uid:3]; + + flutter::SemanticsNode node3; + node3.id = 3; + node3.rect = SkRect::MakeXYWH(0, 0, 200, 200); + [object3 setSemanticsNode:&node3]; + + [object3 accessibilityScrollToVisible]; + + XCTAssertTrue(bridge->observations.size() == 1); + XCTAssertTrue(bridge->observations[0].id == 3); + XCTAssertTrue(bridge->observations[0].action == flutter::SemanticsAction::kShowOnScreen); +} + +- (void)testAccessibilityScrollToVisibleWithChild { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + SemanticsObject* object3 = [[SemanticsObject alloc] initWithBridge:bridge uid:3]; + + flutter::SemanticsNode node3; + node3.id = 3; + node3.rect = SkRect::MakeXYWH(0, 0, 200, 200); + [object3 setSemanticsNode:&node3]; + + [object3 accessibilityScrollToVisibleWithChild:object3]; + + XCTAssertTrue(bridge->observations.size() == 1); + XCTAssertTrue(bridge->observations[0].id == 3); + XCTAssertTrue(bridge->observations[0].action == flutter::SemanticsAction::kShowOnScreen); +} + +- (void)testAccessibilityHitTestOutOfRect { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + SemanticsObject* object0 = [[SemanticsObject alloc] initWithBridge:bridge uid:0]; + SemanticsObject* object1 = [[SemanticsObject alloc] initWithBridge:bridge uid:1]; + SemanticsObject* object2 = [[SemanticsObject alloc] initWithBridge:bridge uid:2]; + SemanticsObject* object3 = [[SemanticsObject alloc] initWithBridge:bridge uid:3]; + object0.children = @[ object1 ]; + object0.childrenInHitTestOrder = @[ object1 ]; + object1.children = @[ object2, object3 ]; + object1.childrenInHitTestOrder = @[ object2, object3 ]; + + flutter::SemanticsNode node0; + node0.id = 0; + node0.rect = SkRect::MakeXYWH(0, 0, 200, 200); + node0.label = "0"; + [object0 setSemanticsNode:&node0]; + + flutter::SemanticsNode node1; + node1.id = 1; + node1.rect = SkRect::MakeXYWH(0, 0, 200, 200); + node1.label = "1"; + [object1 setSemanticsNode:&node1]; + + flutter::SemanticsNode node2; + node2.id = 2; + node2.rect = SkRect::MakeXYWH(0, 0, 100, 100); + node2.label = "2"; + [object2 setSemanticsNode:&node2]; + + flutter::SemanticsNode node3; + node3.id = 3; + node3.rect = SkRect::MakeXYWH(0, 0, 200, 200); + node3.label = "3"; + [object3 setSemanticsNode:&node3]; + + CGPoint point = CGPointMake(300, 300); + id hitTestResult = [object0 _accessibilityHitTest:point withEvent:nil]; + + XCTAssertNil(hitTestResult); +} + +- (void)testReplaceChildAtIndex { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + SemanticsObject* parent = [[SemanticsObject alloc] initWithBridge:bridge uid:0]; + SemanticsObject* child1 = [[SemanticsObject alloc] initWithBridge:bridge uid:1]; + SemanticsObject* child2 = [[SemanticsObject alloc] initWithBridge:bridge uid:2]; + parent.children = @[ child1 ]; + [parent replaceChildAtIndex:0 withChild:child2]; + XCTAssertNil(child1.parent); + XCTAssertEqual(parent, child2.parent); + XCTAssertEqualObjects(parent.children, @[ child2 ]); +} + +- (void)testPlainSemanticsObjectWithLabelHasStaticTextTrait { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + flutter::SemanticsNode node; + node.label = "foo"; + FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; + [object setSemanticsNode:&node]; + XCTAssertEqual([object accessibilityTraits], UIAccessibilityTraitStaticText); +} + +- (void)testNodeWithImplicitScrollIsAnAccessibilityElementWhenItisHidden { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + flutter::SemanticsNode node; + node.flags = static_cast(flutter::SemanticsFlags::kHasImplicitScrolling) | + static_cast(flutter::SemanticsFlags::kIsHidden); + FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; + [object setSemanticsNode:&node]; + XCTAssertEqual(object.isAccessibilityElement, YES); +} + +- (void)testNodeWithImplicitScrollIsNotAnAccessibilityElementWhenItisNotHidden { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + flutter::SemanticsNode node; + node.flags = static_cast(flutter::SemanticsFlags::kHasImplicitScrolling); + FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; + [object setSemanticsNode:&node]; + XCTAssertEqual(object.isAccessibilityElement, NO); +} + +- (void)testIntresetingSemanticsObjectWithLabelHasStaticTextTrait { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + flutter::SemanticsNode node; + node.label = "foo"; + FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; + SemanticsObject* child1 = [[SemanticsObject alloc] initWithBridge:bridge uid:1]; + object.children = @[ child1 ]; + [object setSemanticsNode:&node]; + XCTAssertEqual([object accessibilityTraits], UIAccessibilityTraitNone); +} + +- (void)testIntresetingSemanticsObjectWithLabelHasStaticTextTrait1 { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + flutter::SemanticsNode node; + node.label = "foo"; + node.flags = static_cast(flutter::SemanticsFlags::kIsTextField); + FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; + [object setSemanticsNode:&node]; + XCTAssertEqual([object accessibilityTraits], UIAccessibilityTraitNone); +} + +- (void)testIntresetingSemanticsObjectWithLabelHasStaticTextTrait2 { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + flutter::SemanticsNode node; + node.label = "foo"; + node.flags = static_cast(flutter::SemanticsFlags::kIsButton); + FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; + [object setSemanticsNode:&node]; + XCTAssertEqual([object accessibilityTraits], UIAccessibilityTraitButton); +} + +- (void)testVerticalFlutterScrollableSemanticsObject { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + + float transformScale = 0.5f; + float screenScale = [[bridge->view() window] screen].scale; + float effectivelyScale = transformScale / screenScale; + float x = 10; + float y = 10; + float w = 100; + float h = 200; + float scrollExtentMax = 500.0; + float scrollPosition = 150.0; + + flutter::SemanticsNode node; + node.flags = static_cast(flutter::SemanticsFlags::kHasImplicitScrolling); + node.actions = flutter::kVerticalScrollSemanticsActions; + node.rect = SkRect::MakeXYWH(x, y, w, h); + node.scrollExtentMax = scrollExtentMax; + node.scrollPosition = scrollPosition; + node.transform = { + transformScale, 0, 0, 0, 0, transformScale, 0, 0, 0, 0, transformScale, 0, 0, 0, 0, 1.0}; + FlutterScrollableSemanticsObject* scrollable = + [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge uid:0]; + [scrollable setSemanticsNode:&node]; + [scrollable accessibilityBridgeDidFinishUpdate]; + UIScrollView* scrollView = [scrollable nativeAccessibility]; + + XCTAssertEqualWithAccuracy(scrollView.frame.origin.x, x * effectivelyScale, kFloatCompareEpsilon); + XCTAssertEqualWithAccuracy(scrollView.frame.origin.y, y * effectivelyScale, kFloatCompareEpsilon); + XCTAssertEqualWithAccuracy(scrollView.frame.size.width, w * effectivelyScale, + kFloatCompareEpsilon); + XCTAssertEqualWithAccuracy(scrollView.frame.size.height, h * effectivelyScale, + kFloatCompareEpsilon); + + XCTAssertEqualWithAccuracy(scrollView.contentSize.width, w * effectivelyScale, + kFloatCompareEpsilon); + XCTAssertEqualWithAccuracy(scrollView.contentSize.height, + (h + scrollExtentMax) * effectivelyScale, kFloatCompareEpsilon); + + XCTAssertEqual(scrollView.contentOffset.x, 0); + XCTAssertEqualWithAccuracy(scrollView.contentOffset.y, scrollPosition * effectivelyScale, + kFloatCompareEpsilon); +} + +- (void)testVerticalFlutterScrollableSemanticsObjectNoWindowDoesNotCrash { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridgeNoWindow()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + + float transformScale = 0.5f; + float x = 10; + float y = 10; + float w = 100; + float h = 200; + float scrollExtentMax = 500.0; + float scrollPosition = 150.0; + + flutter::SemanticsNode node; + node.flags = static_cast(flutter::SemanticsFlags::kHasImplicitScrolling); + node.actions = flutter::kVerticalScrollSemanticsActions; + node.rect = SkRect::MakeXYWH(x, y, w, h); + node.scrollExtentMax = scrollExtentMax; + node.scrollPosition = scrollPosition; + node.transform = { + transformScale, 0, 0, 0, 0, transformScale, 0, 0, 0, 0, transformScale, 0, 0, 0, 0, 1.0}; + FlutterScrollableSemanticsObject* scrollable = + [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge uid:0]; + [scrollable setSemanticsNode:&node]; + [scrollable accessibilityBridgeDidFinishUpdate]; + XCTAssertNoThrow([scrollable accessibilityBridgeDidFinishUpdate]); +} + +- (void)testHorizontalFlutterScrollableSemanticsObject { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + + float transformScale = 0.5f; + float screenScale = [[bridge->view() window] screen].scale; + float effectivelyScale = transformScale / screenScale; + float x = 10; + float y = 10; + float w = 100; + float h = 200; + float scrollExtentMax = 500.0; + float scrollPosition = 150.0; + + flutter::SemanticsNode node; + node.flags = static_cast(flutter::SemanticsFlags::kHasImplicitScrolling); + node.actions = flutter::kHorizontalScrollSemanticsActions; + node.rect = SkRect::MakeXYWH(x, y, w, h); + node.scrollExtentMax = scrollExtentMax; + node.scrollPosition = scrollPosition; + node.transform = { + transformScale, 0, 0, 0, 0, transformScale, 0, 0, 0, 0, transformScale, 0, 0, 0, 0, 1.0}; + FlutterScrollableSemanticsObject* scrollable = + [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge uid:0]; + [scrollable setSemanticsNode:&node]; + [scrollable accessibilityBridgeDidFinishUpdate]; + UIScrollView* scrollView = [scrollable nativeAccessibility]; + + XCTAssertEqualWithAccuracy(scrollView.frame.origin.x, x * effectivelyScale, kFloatCompareEpsilon); + XCTAssertEqualWithAccuracy(scrollView.frame.origin.y, y * effectivelyScale, kFloatCompareEpsilon); + XCTAssertEqualWithAccuracy(scrollView.frame.size.width, w * effectivelyScale, + kFloatCompareEpsilon); + XCTAssertEqualWithAccuracy(scrollView.frame.size.height, h * effectivelyScale, + kFloatCompareEpsilon); + + XCTAssertEqualWithAccuracy(scrollView.contentSize.width, (w + scrollExtentMax) * effectivelyScale, + kFloatCompareEpsilon); + XCTAssertEqualWithAccuracy(scrollView.contentSize.height, h * effectivelyScale, + kFloatCompareEpsilon); + + XCTAssertEqualWithAccuracy(scrollView.contentOffset.x, scrollPosition * effectivelyScale, + kFloatCompareEpsilon); + XCTAssertEqual(scrollView.contentOffset.y, 0); +} + +- (void)testCanHandleInfiniteScrollExtent { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + + float transformScale = 0.5f; + float screenScale = [[bridge->view() window] screen].scale; + float effectivelyScale = transformScale / screenScale; + float x = 10; + float y = 10; + float w = 100; + float h = 200; + float scrollExtentMax = INFINITY; + float scrollPosition = 150.0; + + flutter::SemanticsNode node; + node.flags = static_cast(flutter::SemanticsFlags::kHasImplicitScrolling); + node.actions = flutter::kVerticalScrollSemanticsActions; + node.rect = SkRect::MakeXYWH(x, y, w, h); + node.scrollExtentMax = scrollExtentMax; + node.scrollPosition = scrollPosition; + node.transform = { + transformScale, 0, 0, 0, 0, transformScale, 0, 0, 0, 0, transformScale, 0, 0, 0, 0, 1.0}; + FlutterScrollableSemanticsObject* scrollable = + [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge uid:0]; + [scrollable setSemanticsNode:&node]; + [scrollable accessibilityBridgeDidFinishUpdate]; + UIScrollView* scrollView = [scrollable nativeAccessibility]; + XCTAssertEqualWithAccuracy(scrollView.frame.origin.x, x * effectivelyScale, kFloatCompareEpsilon); + XCTAssertEqualWithAccuracy(scrollView.frame.origin.y, y * effectivelyScale, kFloatCompareEpsilon); + XCTAssertEqualWithAccuracy(scrollView.frame.size.width, w * effectivelyScale, + kFloatCompareEpsilon); + XCTAssertEqualWithAccuracy(scrollView.frame.size.height, h * effectivelyScale, + kFloatCompareEpsilon); + + XCTAssertEqualWithAccuracy(scrollView.contentSize.width, w * effectivelyScale, + kFloatCompareEpsilon); + XCTAssertEqualWithAccuracy(scrollView.contentSize.height, + (h + kScrollExtentMaxForInf + scrollPosition) * effectivelyScale, + kFloatCompareEpsilon); + + XCTAssertEqual(scrollView.contentOffset.x, 0); + XCTAssertEqualWithAccuracy(scrollView.contentOffset.y, scrollPosition * effectivelyScale, + kFloatCompareEpsilon); +} + +- (void)testCanHandleNaNScrollExtentAndScrollPoisition { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + + float transformScale = 0.5f; + float screenScale = [[bridge->view() window] screen].scale; + float effectivelyScale = transformScale / screenScale; + float x = 10; + float y = 10; + float w = 100; + float h = 200; + float scrollExtentMax = std::nan(""); + float scrollPosition = std::nan(""); + + flutter::SemanticsNode node; + node.flags = static_cast(flutter::SemanticsFlags::kHasImplicitScrolling); + node.actions = flutter::kVerticalScrollSemanticsActions; + node.rect = SkRect::MakeXYWH(x, y, w, h); + node.scrollExtentMax = scrollExtentMax; + node.scrollPosition = scrollPosition; + node.transform = { + transformScale, 0, 0, 0, 0, transformScale, 0, 0, 0, 0, transformScale, 0, 0, 0, 0, 1.0}; + FlutterScrollableSemanticsObject* scrollable = + [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge uid:0]; + [scrollable setSemanticsNode:&node]; + [scrollable accessibilityBridgeDidFinishUpdate]; + UIScrollView* scrollView = [scrollable nativeAccessibility]; + + XCTAssertEqualWithAccuracy(scrollView.frame.origin.x, x * effectivelyScale, kFloatCompareEpsilon); + XCTAssertEqualWithAccuracy(scrollView.frame.origin.y, y * effectivelyScale, kFloatCompareEpsilon); + XCTAssertEqualWithAccuracy(scrollView.frame.size.width, w * effectivelyScale, + kFloatCompareEpsilon); + XCTAssertEqualWithAccuracy(scrollView.frame.size.height, h * effectivelyScale, + kFloatCompareEpsilon); + + // Content size equal to the scrollable size. + XCTAssertEqualWithAccuracy(scrollView.contentSize.width, w * effectivelyScale, + kFloatCompareEpsilon); + XCTAssertEqualWithAccuracy(scrollView.contentSize.height, h * effectivelyScale, + kFloatCompareEpsilon); + + XCTAssertEqual(scrollView.contentOffset.x, 0); + XCTAssertEqual(scrollView.contentOffset.y, 0); +} + +- (void)testFlutterScrollableSemanticsObjectIsNotHittestable { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + + flutter::SemanticsNode node; + node.flags = static_cast(flutter::SemanticsFlags::kHasImplicitScrolling); + node.actions = flutter::kHorizontalScrollSemanticsActions; + node.rect = SkRect::MakeXYWH(0, 0, 100, 200); + node.scrollExtentMax = 100.0; + node.scrollPosition = 0.0; + + FlutterScrollableSemanticsObject* scrollable = + [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge uid:0]; + [scrollable setSemanticsNode:&node]; + [scrollable accessibilityBridgeDidFinishUpdate]; + UIScrollView* scrollView = [scrollable nativeAccessibility]; + XCTAssertEqual([scrollView hitTest:CGPointMake(10, 10) withEvent:nil], nil); +} + +- (void)testFlutterScrollableSemanticsObjectIsHiddenWhenVoiceOverIsRunning { + flutter::testing::MockAccessibilityBridge* mock = new flutter::testing::MockAccessibilityBridge(); + mock->isVoiceOverRunningValue = false; + fml::WeakPtrFactory factory(mock); + fml::WeakPtr bridge = factory.GetWeakPtr(); + + flutter::SemanticsNode node; + node.flags = static_cast(flutter::SemanticsFlags::kHasImplicitScrolling); + node.actions = flutter::kHorizontalScrollSemanticsActions; + node.rect = SkRect::MakeXYWH(0, 0, 100, 200); + node.scrollExtentMax = 100.0; + node.scrollPosition = 0.0; + + FlutterScrollableSemanticsObject* scrollable = + [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge uid:0]; + [scrollable setSemanticsNode:&node]; + [scrollable accessibilityBridgeDidFinishUpdate]; + UIScrollView* scrollView = [scrollable nativeAccessibility]; + XCTAssertTrue(scrollView.isAccessibilityElement); + mock->isVoiceOverRunningValue = true; + XCTAssertFalse(scrollView.isAccessibilityElement); +} + +- (void)testFlutterSemanticsObjectHasIdentifier { + flutter::testing::MockAccessibilityBridge* mock = new flutter::testing::MockAccessibilityBridge(); + mock->isVoiceOverRunningValue = true; + fml::WeakPtrFactory factory(mock); + fml::WeakPtr bridge = factory.GetWeakPtr(); + + flutter::SemanticsNode node; + node.identifier = "identifier"; + + FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; + [object setSemanticsNode:&node]; + XCTAssertTrue([object.accessibilityIdentifier isEqualToString:@"identifier"]); +} + +- (void)testFlutterScrollableSemanticsObjectWithLabelValueHintIsNotHiddenWhenVoiceOverIsRunning { + flutter::testing::MockAccessibilityBridge* mock = new flutter::testing::MockAccessibilityBridge(); + mock->isVoiceOverRunningValue = true; + fml::WeakPtrFactory factory(mock); + fml::WeakPtr bridge = factory.GetWeakPtr(); + + flutter::SemanticsNode node; + node.flags = static_cast(flutter::SemanticsFlags::kHasImplicitScrolling); + node.actions = flutter::kHorizontalScrollSemanticsActions; + node.rect = SkRect::MakeXYWH(0, 0, 100, 200); + node.label = "label"; + node.value = "value"; + node.hint = "hint"; + node.scrollExtentMax = 100.0; + node.scrollPosition = 0.0; + + FlutterScrollableSemanticsObject* scrollable = + [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge uid:0]; + [scrollable setSemanticsNode:&node]; + [scrollable accessibilityBridgeDidFinishUpdate]; + UIScrollView* scrollView = [scrollable nativeAccessibility]; + XCTAssertTrue(scrollView.isAccessibilityElement); + XCTAssertTrue( + [scrollView.accessibilityLabel isEqualToString:NSLocalizedString(@"label", @"test")]); + XCTAssertTrue( + [scrollView.accessibilityValue isEqualToString:NSLocalizedString(@"value", @"test")]); + XCTAssertTrue([scrollView.accessibilityHint isEqualToString:NSLocalizedString(@"hint", @"test")]); +} + +- (void)testFlutterSemanticsObjectMergeTooltipToLabel { + flutter::testing::MockAccessibilityBridge* mock = new flutter::testing::MockAccessibilityBridge(); + mock->isVoiceOverRunningValue = true; + fml::WeakPtrFactory factory(mock); + fml::WeakPtr bridge = factory.GetWeakPtr(); + + flutter::SemanticsNode node; + node.rect = SkRect::MakeXYWH(0, 0, 100, 200); + node.label = "label"; + node.tooltip = "tooltip"; + FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; + [object setSemanticsNode:&node]; + XCTAssertTrue(object.isAccessibilityElement); + XCTAssertTrue([object.accessibilityLabel isEqualToString:@"label\ntooltip"]); +} + +- (void)testSemanticsObjectContainerAccessibilityFrameCoversEntireScreen { + flutter::testing::MockAccessibilityBridge* mock = new flutter::testing::MockAccessibilityBridge(); + mock->isVoiceOverRunningValue = true; + fml::WeakPtrFactory factory(mock); + fml::WeakPtr bridge = factory.GetWeakPtr(); + + flutter::SemanticsNode parent; + parent.id = 0; + parent.actions = static_cast(flutter::SemanticsAction::kTap); + + flutter::SemanticsNode child; + child.id = 1; + child.actions = static_cast(flutter::SemanticsAction::kTap); + child.rect = SkRect::MakeXYWH(0, 0, 100, 100); + parent.childrenInTraversalOrder.push_back(1); + + FlutterSemanticsObject* parentObject = [[FlutterSemanticsObject alloc] initWithBridge:bridge + uid:0]; + [parentObject setSemanticsNode:&parent]; + + FlutterSemanticsObject* childObject = [[FlutterSemanticsObject alloc] initWithBridge:bridge + uid:1]; + [childObject setSemanticsNode:&child]; + + parentObject.children = @[ childObject ]; + [parentObject accessibilityBridgeDidFinishUpdate]; + [childObject accessibilityBridgeDidFinishUpdate]; + + SemanticsObjectContainer* container = + static_cast(parentObject.accessibilityContainer); + + XCTAssertTrue(childObject.accessibilityRespondsToUserInteraction); + XCTAssertTrue(CGRectEqualToRect(container.accessibilityFrame, UIScreen.mainScreen.bounds)); +} + +- (void)testFlutterSemanticsObjectAttributedStringsDoNotCrashWhenEmpty { + flutter::testing::MockAccessibilityBridge* mock = new flutter::testing::MockAccessibilityBridge(); + mock->isVoiceOverRunningValue = true; + fml::WeakPtrFactory factory(mock); + fml::WeakPtr bridge = factory.GetWeakPtr(); + + flutter::SemanticsNode node; + node.rect = SkRect::MakeXYWH(0, 0, 100, 200); + FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; + [object setSemanticsNode:&node]; + XCTAssertTrue(object.accessibilityAttributedLabel == nil); +} + +- (void)testFlutterScrollableSemanticsObjectReturnsParentContainerIfNoChildren { + flutter::testing::MockAccessibilityBridge* mock = new flutter::testing::MockAccessibilityBridge(); + mock->isVoiceOverRunningValue = true; + fml::WeakPtrFactory factory(mock); + fml::WeakPtr bridge = factory.GetWeakPtr(); + + flutter::SemanticsNode parent; + parent.id = 0; + parent.rect = SkRect::MakeXYWH(0, 0, 100, 200); + parent.label = "label"; + parent.value = "value"; + parent.hint = "hint"; + + flutter::SemanticsNode node; + node.id = 1; + node.flags = static_cast(flutter::SemanticsFlags::kHasImplicitScrolling); + node.actions = flutter::kHorizontalScrollSemanticsActions; + node.rect = SkRect::MakeXYWH(0, 0, 100, 200); + node.label = "label"; + node.value = "value"; + node.hint = "hint"; + node.scrollExtentMax = 100.0; + node.scrollPosition = 0.0; + parent.childrenInTraversalOrder.push_back(1); + + FlutterSemanticsObject* parentObject = [[FlutterSemanticsObject alloc] initWithBridge:bridge + uid:0]; + [parentObject setSemanticsNode:&parent]; + + FlutterScrollableSemanticsObject* scrollable = + [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge uid:1]; + [scrollable setSemanticsNode:&node]; + UIScrollView* scrollView = [scrollable nativeAccessibility]; + + parentObject.children = @[ scrollable ]; + [parentObject accessibilityBridgeDidFinishUpdate]; + [scrollable accessibilityBridgeDidFinishUpdate]; + XCTAssertTrue(scrollView.isAccessibilityElement); + SemanticsObjectContainer* container = + static_cast(scrollable.accessibilityContainer); + XCTAssertEqual(container.semanticsObject, parentObject); +} + +- (void)testFlutterScrollableSemanticsObjectNoScrollBarOrContentInsets { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + + flutter::SemanticsNode node; + node.flags = static_cast(flutter::SemanticsFlags::kHasImplicitScrolling); + node.actions = flutter::kHorizontalScrollSemanticsActions; + node.rect = SkRect::MakeXYWH(0, 0, 100, 200); + node.scrollExtentMax = 100.0; + node.scrollPosition = 0.0; + + FlutterScrollableSemanticsObject* scrollable = + [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge uid:0]; + [scrollable setSemanticsNode:&node]; + [scrollable accessibilityBridgeDidFinishUpdate]; + UIScrollView* scrollView = [scrollable nativeAccessibility]; + + XCTAssertFalse(scrollView.showsHorizontalScrollIndicator); + XCTAssertFalse(scrollView.showsVerticalScrollIndicator); + XCTAssertEqual(scrollView.contentInsetAdjustmentBehavior, + UIScrollViewContentInsetAdjustmentNever); + XCTAssertTrue(UIEdgeInsetsEqualToEdgeInsets(scrollView.contentInset, UIEdgeInsetsZero)); +} + +- (void)testSemanticsObjectBuildsAttributedString { + fml::WeakPtrFactory factory( + new flutter::testing::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:NSLocalizedString(@"label", @"test")]; + NSDictionary* attributeDict = @{ + UIAccessibilitySpeechAttributeSpellOut : @YES, + }; + [expectedAttributedLabel setAttributes:attributeDict range:NSMakeRange(1, 1)]; + XCTAssertTrue( + [object.accessibilityAttributedLabel isEqualToAttributedString:expectedAttributedLabel]); + + NSMutableAttributedString* expectedAttributedValue = + [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"value", @"test")]; + attributeDict = @{ + UIAccessibilitySpeechAttributeSpellOut : @YES, + }; + [expectedAttributedValue setAttributes:attributeDict range:NSMakeRange(2, 1)]; + XCTAssertTrue( + [object.accessibilityAttributedValue isEqualToAttributedString:expectedAttributedValue]); + + NSMutableAttributedString* expectedAttributedHint = + [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"hint", @"test")]; + attributeDict = @{ + UIAccessibilitySpeechAttributeLanguage : @"en-MX", + }; + [expectedAttributedHint setAttributes:attributeDict range:NSMakeRange(3, 1)]; + XCTAssertTrue( + [object.accessibilityAttributedHint isEqualToAttributedString:expectedAttributedHint]); +} + +- (void)testShouldTriggerAnnouncement { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + SemanticsObject* object = [[SemanticsObject alloc] initWithBridge:bridge uid:0]; + + // Handle nil with no node set. + XCTAssertFalse([object nodeShouldTriggerAnnouncement:nil]); + + // Handle initial setting of node with liveRegion + flutter::SemanticsNode node; + node.flags = static_cast(flutter::SemanticsFlags::kIsLiveRegion); + node.label = "foo"; + XCTAssertTrue([object nodeShouldTriggerAnnouncement:&node]); + + // Handle nil with node set. + [object setSemanticsNode:&node]; + XCTAssertFalse([object nodeShouldTriggerAnnouncement:nil]); + + // Handle new node, still has live region, same label. + XCTAssertFalse([object nodeShouldTriggerAnnouncement:&node]); + + // Handle update node with new label, still has live region. + flutter::SemanticsNode updatedNode; + updatedNode.flags = static_cast(flutter::SemanticsFlags::kIsLiveRegion); + updatedNode.label = "bar"; + XCTAssertTrue([object nodeShouldTriggerAnnouncement:&updatedNode]); + + // Handle dropping the live region flag. + updatedNode.flags = 0; + XCTAssertFalse([object nodeShouldTriggerAnnouncement:&updatedNode]); + + // Handle adding the flag when the label has not changed. + updatedNode.label = "foo"; + [object setSemanticsNode:&updatedNode]; + XCTAssertTrue([object nodeShouldTriggerAnnouncement:&node]); +} + +- (void)testShouldDispatchShowOnScreenActionForHeader { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + SemanticsObject* object = [[SemanticsObject alloc] initWithBridge:bridge uid:1]; + + // Handle initial setting of node with header. + flutter::SemanticsNode node; + node.flags = static_cast(flutter::SemanticsFlags::kIsHeader); + node.label = "foo"; + + [object setSemanticsNode:&node]; + + // Simulate accessibility focus. + [object accessibilityElementDidBecomeFocused]; + + XCTAssertTrue(bridge->observations.size() == 1); + XCTAssertTrue(bridge->observations[0].id == 1); + XCTAssertTrue(bridge->observations[0].action == flutter::SemanticsAction::kShowOnScreen); +} + +- (void)testShouldDispatchShowOnScreenActionForHidden { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + SemanticsObject* object = [[SemanticsObject alloc] initWithBridge:bridge uid:1]; + + // Handle initial setting of node with hidden. + flutter::SemanticsNode node; + node.flags = static_cast(flutter::SemanticsFlags::kIsHidden); + node.label = "foo"; + + [object setSemanticsNode:&node]; + + // Simulate accessibility focus. + [object accessibilityElementDidBecomeFocused]; + + XCTAssertTrue(bridge->observations.size() == 1); + XCTAssertTrue(bridge->observations[0].id == 1); + XCTAssertTrue(bridge->observations[0].action == flutter::SemanticsAction::kShowOnScreen); +} + +- (void)testFlutterSwitchSemanticsObjectMatchesUISwitch { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + FlutterSwitchSemanticsObject* object = [[FlutterSwitchSemanticsObject alloc] initWithBridge:bridge + uid:1]; + + // Handle initial setting of node with header. + flutter::SemanticsNode node; + node.flags = static_cast(flutter::SemanticsFlags::kHasToggledState) | + static_cast(flutter::SemanticsFlags::kIsToggled) | + static_cast(flutter::SemanticsFlags::kIsEnabled); + node.label = "foo"; + [object setSemanticsNode:&node]; + // Create ab real UISwitch to compare the FlutterSwitchSemanticsObject with. + UISwitch* nativeSwitch = [[UISwitch alloc] init]; + nativeSwitch.on = YES; + + XCTAssertEqual(object.accessibilityTraits, nativeSwitch.accessibilityTraits); + XCTAssertEqualObjects(object.accessibilityValue, nativeSwitch.accessibilityValue); + + // Set the toggled to false; + flutter::SemanticsNode update; + update.flags = static_cast(flutter::SemanticsFlags::kHasToggledState) | + static_cast(flutter::SemanticsFlags::kIsEnabled); + update.label = "foo"; + [object setSemanticsNode:&update]; + + nativeSwitch.on = NO; + + XCTAssertEqual(object.accessibilityTraits, nativeSwitch.accessibilityTraits); + XCTAssertEqualObjects(object.accessibilityValue, nativeSwitch.accessibilityValue); +} + +- (void)testFlutterSemanticsObjectOfRadioButton { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; + + // Handle initial setting of node with header. + flutter::SemanticsNode node; + node.flags = static_cast(flutter::SemanticsFlags::kIsInMutuallyExclusiveGroup) | + static_cast(flutter::SemanticsFlags::kHasCheckedState) | + static_cast(flutter::SemanticsFlags::kHasEnabledState) | + static_cast(flutter::SemanticsFlags::kIsEnabled); + node.label = "foo"; + [object setSemanticsNode:&node]; + XCTAssertTrue((object.accessibilityTraits & UIAccessibilityTraitButton) > 0); + XCTAssertNil(object.accessibilityValue); +} + +- (void)testFlutterSwitchSemanticsObjectMatchesUISwitchDisabled { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + FlutterSwitchSemanticsObject* object = [[FlutterSwitchSemanticsObject alloc] initWithBridge:bridge + uid:1]; + + // Handle initial setting of node with header. + flutter::SemanticsNode node; + node.flags = static_cast(flutter::SemanticsFlags::kHasToggledState) | + static_cast(flutter::SemanticsFlags::kIsToggled); + node.label = "foo"; + [object setSemanticsNode:&node]; + // Create ab real UISwitch to compare the FlutterSwitchSemanticsObject with. + UISwitch* nativeSwitch = [[UISwitch alloc] init]; + nativeSwitch.on = YES; + nativeSwitch.enabled = NO; + + XCTAssertEqual(object.accessibilityTraits, nativeSwitch.accessibilityTraits); + XCTAssertEqualObjects(object.accessibilityValue, nativeSwitch.accessibilityValue); +} + +- (void)testSemanticsObjectDeallocated { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + SemanticsObject* parent = [[SemanticsObject alloc] initWithBridge:bridge uid:0]; + SemanticsObject* child = [[SemanticsObject alloc] initWithBridge:bridge uid:1]; + parent.children = @[ child ]; + // Validate SemanticsObject deallocation does not crash. + // https://github.com/flutter/flutter/issues/66032 + __weak SemanticsObject* weakObject = parent; + parent = nil; + XCTAssertNil(weakObject); +} + +- (void)testFlutterSemanticsObjectReturnsNilContainerWhenBridgeIsNotAlive { + FlutterSemanticsObject* parentObject; + FlutterScrollableSemanticsObject* scrollable; + FlutterSemanticsObject* object2; + + flutter::SemanticsNode parent; + parent.id = 0; + parent.rect = SkRect::MakeXYWH(0, 0, 100, 200); + parent.label = "label"; + parent.value = "value"; + parent.hint = "hint"; + + flutter::SemanticsNode node; + node.id = 1; + node.flags = static_cast(flutter::SemanticsFlags::kHasImplicitScrolling); + node.actions = flutter::kHorizontalScrollSemanticsActions; + node.rect = SkRect::MakeXYWH(0, 0, 100, 200); + node.label = "label"; + node.value = "value"; + node.hint = "hint"; + node.scrollExtentMax = 100.0; + node.scrollPosition = 0.0; + parent.childrenInTraversalOrder.push_back(1); + + flutter::SemanticsNode node2; + node2.id = 2; + node2.rect = SkRect::MakeXYWH(0, 0, 100, 200); + node2.label = "label"; + node2.value = "value"; + node2.hint = "hint"; + node2.scrollExtentMax = 100.0; + node2.scrollPosition = 0.0; + parent.childrenInTraversalOrder.push_back(2); + + { + flutter::testing::MockAccessibilityBridge* mock = + new flutter::testing::MockAccessibilityBridge(); + mock->isVoiceOverRunningValue = true; + fml::WeakPtrFactory factory(mock); + fml::WeakPtr bridge = factory.GetWeakPtr(); + + parentObject = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0]; + [parentObject setSemanticsNode:&parent]; + + scrollable = [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge uid:1]; + [scrollable setSemanticsNode:&node]; + [scrollable accessibilityBridgeDidFinishUpdate]; + + object2 = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:2]; + [object2 setSemanticsNode:&node2]; + + parentObject.children = @[ scrollable, object2 ]; + [parentObject accessibilityBridgeDidFinishUpdate]; + [scrollable accessibilityBridgeDidFinishUpdate]; + [object2 accessibilityBridgeDidFinishUpdate]; + + // Returns the correct container if the bridge is alive. + SemanticsObjectContainer* container = + static_cast(scrollable.accessibilityContainer); + XCTAssertEqual(container.semanticsObject, parentObject); + SemanticsObjectContainer* container2 = + static_cast(object2.accessibilityContainer); + XCTAssertEqual(container2.semanticsObject, parentObject); + } + // The bridge pointer went out of scope and was deallocated. + + XCTAssertNil(scrollable.accessibilityContainer); + XCTAssertNil(object2.accessibilityContainer); +} + +- (void)testAccessibilityHitTestSearchCanReturnPlatformView { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + SemanticsObject* object0 = [[SemanticsObject alloc] initWithBridge:bridge uid:0]; + SemanticsObject* object1 = [[SemanticsObject alloc] initWithBridge:bridge uid:1]; + SemanticsObject* object3 = [[SemanticsObject alloc] initWithBridge:bridge uid:3]; + FlutterTouchInterceptingView* platformView = + [[FlutterTouchInterceptingView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; + FlutterPlatformViewSemanticsContainer* platformViewSemanticsContainer = + [[FlutterPlatformViewSemanticsContainer alloc] initWithBridge:bridge + uid:1 + platformView:platformView]; + + object0.children = @[ object1 ]; + object0.childrenInHitTestOrder = @[ object1 ]; + object1.children = @[ platformViewSemanticsContainer, object3 ]; + object1.childrenInHitTestOrder = @[ platformViewSemanticsContainer, object3 ]; + + flutter::SemanticsNode node0; + node0.id = 0; + node0.rect = SkRect::MakeXYWH(0, 0, 200, 200); + node0.label = "0"; + [object0 setSemanticsNode:&node0]; + + flutter::SemanticsNode node1; + node1.id = 1; + node1.rect = SkRect::MakeXYWH(0, 0, 200, 200); + node1.label = "1"; + [object1 setSemanticsNode:&node1]; + + flutter::SemanticsNode node2; + node2.id = 2; + node2.rect = SkRect::MakeXYWH(0, 0, 100, 100); + node2.label = "2"; + [platformViewSemanticsContainer setSemanticsNode:&node2]; + + flutter::SemanticsNode node3; + node3.id = 3; + node3.rect = SkRect::MakeXYWH(0, 0, 200, 200); + node3.label = "3"; + [object3 setSemanticsNode:&node3]; + + CGPoint point = CGPointMake(10, 10); + id hitTestResult = [object0 _accessibilityHitTest:point withEvent:nil]; + + XCTAssertEqual(hitTestResult, platformView); +} + +- (void)testFlutterPlatformViewSemanticsContainer { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + __weak FlutterTouchInterceptingView* weakPlatformView; + __weak FlutterPlatformViewSemanticsContainer* weakContainer; + @autoreleasepool { + FlutterTouchInterceptingView* platformView = [[FlutterTouchInterceptingView alloc] init]; + weakPlatformView = platformView; + + @autoreleasepool { + FlutterPlatformViewSemanticsContainer* container = + [[FlutterPlatformViewSemanticsContainer alloc] initWithBridge:bridge + uid:1 + platformView:platformView]; + weakContainer = container; + XCTAssertEqualObjects(platformView.accessibilityContainer, container); + XCTAssertNotNil(weakPlatformView); + XCTAssertNotNil(weakContainer); + } + // Check the variables are still lived. + // `container` is `retain` in `platformView`, so it will not be nil here. + XCTAssertNotNil(weakPlatformView); + XCTAssertNotNil(weakContainer); + } + // Check if there's no more strong references to `platformView` after container and platformView + // are released. + XCTAssertNil(weakPlatformView); + XCTAssertNil(weakContainer); +} + +- (void)testTextInputSemanticsObject { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + + flutter::SemanticsNode node; + node.label = "foo"; + node.flags = static_cast(flutter::SemanticsFlags::kIsTextField) | + static_cast(flutter::SemanticsFlags::kIsReadOnly); + TextInputSemanticsObject* object = [[TextInputSemanticsObject alloc] initWithBridge:bridge uid:0]; + [object setSemanticsNode:&node]; + [object accessibilityBridgeDidFinishUpdate]; + XCTAssertEqual([object accessibilityTraits], UIAccessibilityTraitNone); +} + +- (void)testTextInputSemanticsObject_canPerformAction { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + + flutter::SemanticsNode node; + node.label = "foo"; + node.flags = static_cast(flutter::SemanticsFlags::kIsTextField) | + static_cast(flutter::SemanticsFlags::kIsReadOnly); + TextInputSemanticsObject* object = [[TextInputSemanticsObject alloc] initWithBridge:bridge uid:0]; + [object setSemanticsNode:&node]; + [object accessibilityBridgeDidFinishUpdate]; + + id textInputSurrogate = OCMClassMock([UIResponder class]); + id partialSemanticsObject = OCMPartialMock(object); + OCMStub([partialSemanticsObject textInputSurrogate]).andReturn(textInputSurrogate); + + OCMExpect([textInputSurrogate canPerformAction:[OCMArg anySelector] withSender:OCMOCK_ANY]) + .andReturn(YES); + XCTAssertTrue([partialSemanticsObject canPerformAction:@selector(copy:) withSender:nil]); + + OCMExpect([textInputSurrogate canPerformAction:[OCMArg anySelector] withSender:OCMOCK_ANY]) + .andReturn(NO); + XCTAssertFalse([partialSemanticsObject canPerformAction:@selector(copy:) withSender:nil]); +} + +- (void)testTextInputSemanticsObject_editActions { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + + flutter::SemanticsNode node; + node.label = "foo"; + node.flags = static_cast(flutter::SemanticsFlags::kIsTextField) | + static_cast(flutter::SemanticsFlags::kIsReadOnly); + TextInputSemanticsObject* object = [[TextInputSemanticsObject alloc] initWithBridge:bridge uid:0]; + [object setSemanticsNode:&node]; + [object accessibilityBridgeDidFinishUpdate]; + + id textInputSurrogate = OCMClassMock([UIResponder class]); + id partialSemanticsObject = OCMPartialMock(object); + OCMStub([partialSemanticsObject textInputSurrogate]).andReturn(textInputSurrogate); + + XCTestExpectation* copyExpectation = + [self expectationWithDescription:@"Surrogate's copy method is called."]; + XCTestExpectation* cutExpectation = + [self expectationWithDescription:@"Surrogate's cut method is called."]; + XCTestExpectation* pasteExpectation = + [self expectationWithDescription:@"Surrogate's paste method is called."]; + XCTestExpectation* selectAllExpectation = + [self expectationWithDescription:@"Surrogate's selectAll method is called."]; + XCTestExpectation* deleteExpectation = + [self expectationWithDescription:@"Surrogate's delete method is called."]; + + OCMStub([textInputSurrogate copy:OCMOCK_ANY]).andDo(^(NSInvocation* invocation) { + [copyExpectation fulfill]; + }); + OCMStub([textInputSurrogate cut:OCMOCK_ANY]).andDo(^(NSInvocation* invocation) { + [cutExpectation fulfill]; + }); + OCMStub([textInputSurrogate paste:OCMOCK_ANY]).andDo(^(NSInvocation* invocation) { + [pasteExpectation fulfill]; + }); + OCMStub([textInputSurrogate selectAll:OCMOCK_ANY]).andDo(^(NSInvocation* invocation) { + [selectAllExpectation fulfill]; + }); + OCMStub([textInputSurrogate delete:OCMOCK_ANY]).andDo(^(NSInvocation* invocation) { + [deleteExpectation fulfill]; + }); + + [partialSemanticsObject copy:nil]; + [partialSemanticsObject cut:nil]; + [partialSemanticsObject paste:nil]; + [partialSemanticsObject selectAll:nil]; + [partialSemanticsObject delete:nil]; + + [self waitForExpectationsWithTimeout:1 handler:nil]; +} + +- (void)testSliderSemanticsObject { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + + flutter::SemanticsNode node; + node.flags = static_cast(flutter::SemanticsFlags::kIsSlider); + SemanticsObject* object = [[SemanticsObject alloc] initWithBridge:bridge uid:0]; + [object setSemanticsNode:&node]; + [object accessibilityBridgeDidFinishUpdate]; + XCTAssertEqual([object accessibilityActivate], YES); +} + +- (void)testUIFocusItemConformance { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + SemanticsObject* parent = [[SemanticsObject alloc] initWithBridge:bridge uid:0]; + SemanticsObject* child = [[SemanticsObject alloc] initWithBridge:bridge uid:1]; + parent.children = @[ child ]; + + // parentFocusEnvironment + XCTAssertTrue([parent.parentFocusEnvironment isKindOfClass:[UIView class]]); + XCTAssertEqual(child.parentFocusEnvironment, child.parent); + + // canBecomeFocused + flutter::SemanticsNode childNode; + childNode.flags = static_cast(flutter::SemanticsFlags::kIsHidden); + childNode.actions = static_cast(flutter::SemanticsAction::kTap); + [child setSemanticsNode:&childNode]; + XCTAssertFalse(child.canBecomeFocused); + childNode.flags = 0; + [child setSemanticsNode:&childNode]; + XCTAssertTrue(child.canBecomeFocused); + childNode.actions = 0; + [child setSemanticsNode:&childNode]; + XCTAssertFalse(child.canBecomeFocused); + + CGFloat scale = ((bridge->view().window.screen ?: UIScreen.mainScreen)).scale; + + childNode.rect = SkRect::MakeXYWH(0, 0, 100 * scale, 100 * scale); + [child setSemanticsNode:&childNode]; + flutter::SemanticsNode parentNode; + parentNode.rect = SkRect::MakeXYWH(0, 0, 200, 200); + [parent setSemanticsNode:&parentNode]; + + XCTAssertTrue(CGRectEqualToRect(child.frame, CGRectMake(0, 0, 100, 100))); +} + +- (void)testUIFocusItemContainerConformance { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + SemanticsObject* parent = [[SemanticsObject alloc] initWithBridge:bridge uid:0]; + SemanticsObject* child1 = [[SemanticsObject alloc] initWithBridge:bridge uid:1]; + SemanticsObject* child2 = [[SemanticsObject alloc] initWithBridge:bridge uid:2]; + parent.childrenInHitTestOrder = @[ child1, child2 ]; + + // focusItemsInRect + NSArray>* itemsInRect = [parent focusItemsInRect:CGRectMake(0, 0, 100, 100)]; + XCTAssertEqual(itemsInRect.count, (unsigned long)2); + XCTAssertTrue([itemsInRect containsObject:child1]); + XCTAssertTrue([itemsInRect containsObject:child2]); +} + +- (void)testUIFocusItemScrollableContainerConformance { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + FlutterScrollableSemanticsObject* scrollable = + [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge uid:5]; + + // setContentOffset + CGPoint p = CGPointMake(123.0, 456.0); + [scrollable.scrollView scrollViewWillEndDragging:scrollable.scrollView + withVelocity:CGPointZero + targetContentOffset:&p]; + scrollable.scrollView.contentOffset = p; + [scrollable.scrollView scrollViewDidEndDecelerating:scrollable.scrollView]; + XCTAssertEqual(bridge->observations.size(), (size_t)1); + XCTAssertEqual(bridge->observations[0].id, 5); + XCTAssertEqual(bridge->observations[0].action, flutter::SemanticsAction::kScrollToOffset); + + std::vector args = bridge->observations[0].args; + XCTAssertEqual(args.size(), 3 * sizeof(CGFloat)); + + NSData* encoded = [NSData dataWithBytes:args.data() length:args.size()]; + FlutterStandardTypedData* decoded = [[FlutterStandardMessageCodec sharedInstance] decode:encoded]; + CGPoint point = CGPointZero; + memcpy(&point, decoded.data.bytes, decoded.data.length); + XCTAssertTrue(CGPointEqualToPoint(point, p)); +} + +- (void)testUIFocusItemScrollableContainerNoFeedbackLoops { + fml::WeakPtrFactory factory( + new flutter::testing::MockAccessibilityBridge()); + fml::WeakPtr bridge = factory.GetWeakPtr(); + FlutterScrollableSemanticsObject* scrollable = + [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge uid:5]; + + // setContentOffset + const CGPoint p = CGPointMake(0.0, 456.0); + scrollable.scrollView.contentOffset = p; + bridge->observations.clear(); + + const SkScalar scrollPosition = p.y + 0.0000000000000001; + flutter::SemanticsNode node; + node.flags = static_cast(flutter::SemanticsFlags::kHasImplicitScrolling); + node.actions = flutter::kVerticalScrollSemanticsActions; + node.rect = SkRect::MakeXYWH(0, 0, 100, 200); + node.scrollExtentMax = 10000; + node.scrollPosition = scrollPosition; + node.transform = {1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, scrollPosition, 0, 1.0}; + [scrollable setSemanticsNode:&node]; + [scrollable accessibilityBridgeDidFinishUpdate]; + + XCTAssertEqual(bridge->observations.size(), (size_t)0); +} +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObjectTestMocks.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObjectTestMocks.h new file mode 100644 index 0000000000000000000000000000000000000000..a740349ab137646bac5b438078f43f45801e1a77 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObjectTestMocks.h @@ -0,0 +1,99 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_SEMANTICSOBJECTTESTMOCKS_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_SEMANTICSOBJECTTESTMOCKS_H_ + +#import "flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h" + +const CGRect kScreenSize = CGRectMake(0, 0, 600, 800); + +namespace flutter { +namespace testing { + +class SemanticsActionObservation { + public: + SemanticsActionObservation(int32_t observed_id, SemanticsAction observed_action) + : id(observed_id), action(observed_action), args({}) {} + + SemanticsActionObservation(int32_t observed_id, + SemanticsAction observed_action, + fml::MallocMapping& args) + : id(observed_id), + action(observed_action), + args(args.GetMapping(), args.GetMapping() + args.GetSize()) {} + + int32_t id; + SemanticsAction action; + std::vector args; +}; + +class MockAccessibilityBridge : public AccessibilityBridgeIos { + public: + MockAccessibilityBridge() : observations({}) { + view_ = [[UIView alloc] initWithFrame:kScreenSize]; + window_ = [[UIWindow alloc] initWithFrame:kScreenSize]; + [window_ addSubview:view_]; + } + bool isVoiceOverRunning() const override { return isVoiceOverRunningValue; } + UIView* view() const override { return view_; } + UIView* textInputView() override { return nil; } + void DispatchSemanticsAction(int32_t id, SemanticsAction action) override { + SemanticsActionObservation observation(id, action); + observations.push_back(observation); + } + void DispatchSemanticsAction(int32_t id, + SemanticsAction action, + fml::MallocMapping args) override { + SemanticsActionObservation observation(id, action, args); + observations.push_back(observation); + } + void AccessibilityObjectDidBecomeFocused(int32_t id) override {} + void AccessibilityObjectDidLoseFocus(int32_t id) override {} + FlutterPlatformViewsController* GetPlatformViewsController() const override { return nil; } + std::vector observations; + bool isVoiceOverRunningValue; + + private: + UIView* view_; + UIWindow* window_; +}; + +class MockAccessibilityBridgeNoWindow : public AccessibilityBridgeIos { + public: + MockAccessibilityBridgeNoWindow() : observations({}) { + view_ = [[UIView alloc] initWithFrame:kScreenSize]; + } + bool isVoiceOverRunning() const override { return isVoiceOverRunningValue; } + UIView* view() const override { return view_; } + UIView* textInputView() override { return nil; } + void DispatchSemanticsAction(int32_t id, SemanticsAction action) override { + SemanticsActionObservation observation(id, action); + observations.push_back(observation); + } + void DispatchSemanticsAction(int32_t id, + SemanticsAction action, + fml::MallocMapping args) override { + SemanticsActionObservation observation(id, action, args); + observations.push_back(observation); + } + void AccessibilityObjectDidBecomeFocused(int32_t id) override {} + void AccessibilityObjectDidLoseFocus(int32_t id) override {} + FlutterPlatformViewsController* GetPlatformViewsController() const override { return nil; } + std::vector observations; + bool isVoiceOverRunningValue; + + private: + UIView* view_; +}; +} // namespace testing +} // namespace flutter + +@interface SemanticsObject (Tests) +- (BOOL)accessibilityScrollToVisible; +- (BOOL)accessibilityScrollToVisibleWithChild:(id)child; +- (id)_accessibilityHitTest:(CGPoint)point withEvent:(UIEvent*)event; +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_SEMANTICSOBJECTTESTMOCKS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/TextInputSemanticsObject.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/TextInputSemanticsObject.h new file mode 100644 index 0000000000000000000000000000000000000000..a349c716d7c5d7d32503036b72d3a1fce766442d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/TextInputSemanticsObject.h @@ -0,0 +1,23 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_TEXTINPUTSEMANTICSOBJECT_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_TEXTINPUTSEMANTICSOBJECT_H_ + +#import + +#import "flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h" + +/** + * An implementation of `SemanticsObject` specialized for expressing text + * fields. + * + * Delegates to `FlutterTextInputView` when the object corresponds to a text + * field that currently owns input focus. Delegates to + * `FlutterInactiveTextInput` otherwise. + */ +@interface TextInputSemanticsObject : SemanticsObject +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_TEXTINPUTSEMANTICSOBJECT_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/TextInputSemanticsObject.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/TextInputSemanticsObject.mm new file mode 100644 index 0000000000000000000000000000000000000000..0057d05e0effc9fab54d639f0334107ee7da6647 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/TextInputSemanticsObject.mm @@ -0,0 +1,501 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/TextInputSemanticsObject.h" + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h" + +FLUTTER_ASSERT_ARC + +static const UIAccessibilityTraits kUIAccessibilityTraitUndocumentedEmptyLine = 0x800000000000; + +/** + * An implementation of `UITextInput` used for text fields that do not currently + * have input focus. + * + * This class is used by `TextInputSemanticsObject`. + */ +@interface FlutterInactiveTextInput : UIView +@property(nonatomic, copy) NSString* text; +@end + +@implementation FlutterInactiveTextInput + +// Synthesize properties declared in UITextInput protocol. +@synthesize beginningOfDocument = _beginningOfDocument; +@synthesize endOfDocument = _endOfDocument; +@synthesize inputDelegate = _inputDelegate; +@synthesize markedTextRange = _markedTextRange; +@synthesize markedTextStyle = _markedTextStyle; +@synthesize selectedTextRange = _selectedTextRange; +@synthesize tokenizer = _tokenizer; + +- (BOOL)hasText { + return self.text.length > 0; +} + +- (NSString*)textInRange:(UITextRange*)range { + if (!range) { + return nil; + } + NSAssert([range isKindOfClass:[FlutterTextRange class]], + @"Expected a FlutterTextRange for range (got %@).", [range class]); + NSRange textRange = ((FlutterTextRange*)range).range; + if (textRange.location == NSNotFound) { + // Avoids [crashes](https://github.com/flutter/flutter/issues/138464) from an assertion + // against NSNotFound. + // TODO(hellohuanlin): This is a temp workaround, but we should look into why + // framework is providing NSNotFound to the engine. + // https://github.com/flutter/flutter/issues/160100 + return nil; + } + return [self.text substringWithRange:textRange]; +} + +- (void)replaceRange:(UITextRange*)range withText:(NSString*)text { + // This method is required but not called by accessibility API for + // features we are using it for. It may need to be implemented if + // requirements change. +} + +- (void)setMarkedText:(NSString*)markedText selectedRange:(NSRange)markedSelectedRange { + // This method is required but not called by accessibility API for + // features we are using it for. It may need to be implemented if + // requirements change. +} + +- (void)unmarkText { + // This method is required but not called by accessibility API for + // features we are using it for. It may need to be implemented if + // requirements change. +} + +- (UITextRange*)textRangeFromPosition:(UITextPosition*)fromPosition + toPosition:(UITextPosition*)toPosition { + NSUInteger fromIndex = ((FlutterTextPosition*)fromPosition).index; + NSUInteger toIndex = ((FlutterTextPosition*)toPosition).index; + return [FlutterTextRange rangeWithNSRange:NSMakeRange(fromIndex, toIndex - fromIndex)]; +} + +- (UITextPosition*)positionFromPosition:(UITextPosition*)position offset:(NSInteger)offset { + // This method is required but not called by accessibility API for + // features we are using it for. It may need to be implemented if + // requirements change. + return nil; +} + +- (UITextPosition*)positionFromPosition:(UITextPosition*)position + inDirection:(UITextLayoutDirection)direction + offset:(NSInteger)offset { + // This method is required but not called by accessibility API for + // features we are using it for. It may need to be implemented if + // requirements change. + return nil; +} + +- (NSComparisonResult)comparePosition:(UITextPosition*)position toPosition:(UITextPosition*)other { + // This method is required but not called by accessibility API for + // features we are using it for. It may need to be implemented if + // requirements change. + return NSOrderedSame; +} + +- (NSInteger)offsetFromPosition:(UITextPosition*)from toPosition:(UITextPosition*)toPosition { + // This method is required but not called by accessibility API for + // features we are using it for. It may need to be implemented if + // requirements change. + return 0; +} + +- (UITextPosition*)positionWithinRange:(UITextRange*)range + farthestInDirection:(UITextLayoutDirection)direction { + // This method is required but not called by accessibility API for + // features we are using it for. It may need to be implemented if + // requirements change. + return nil; +} + +- (UITextRange*)characterRangeByExtendingPosition:(UITextPosition*)position + inDirection:(UITextLayoutDirection)direction { + // This method is required but not called by accessibility API for + // features we are using it for. It may need to be implemented if + // requirements change. + return nil; +} + +- (UITextWritingDirection)baseWritingDirectionForPosition:(UITextPosition*)position + inDirection:(UITextStorageDirection)direction { + // Not editable. Does not apply. + return UITextWritingDirectionNatural; +} + +- (void)setBaseWritingDirection:(UITextWritingDirection)writingDirection + forRange:(UITextRange*)range { + // Not editable. Does not apply. +} + +- (CGRect)firstRectForRange:(UITextRange*)range { + // This method is required but not called by accessibility API for + // features we are using it for. It may need to be implemented if + // requirements change. + return CGRectZero; +} + +- (CGRect)caretRectForPosition:(UITextPosition*)position { + // This method is required but not called by accessibility API for + // features we are using it for. It may need to be implemented if + // requirements change. + return CGRectZero; +} + +- (UITextPosition*)closestPositionToPoint:(CGPoint)point { + // This method is required but not called by accessibility API for + // features we are using it for. It may need to be implemented if + // requirements change. + return nil; +} + +- (UITextPosition*)closestPositionToPoint:(CGPoint)point withinRange:(UITextRange*)range { + // This method is required but not called by accessibility API for + // features we are using it for. It may need to be implemented if + // requirements change. + return nil; +} + +- (NSArray*)selectionRectsForRange:(UITextRange*)range { + // This method is required but not called by accessibility API for + // features we are using it for. It may need to be implemented if + // requirements change. + return @[]; +} + +- (UITextRange*)characterRangeAtPoint:(CGPoint)point { + // This method is required but not called by accessibility API for + // features we are using it for. It may need to be implemented if + // requirements change. + return nil; +} + +- (void)insertText:(NSString*)text { + // This method is required but not called by accessibility API for + // features we are using it for. It may need to be implemented if + // requirements change. +} + +- (void)deleteBackward { + // This method is required but not called by accessibility API for + // features we are using it for. It may need to be implemented if + // requirements change. +} + +@end + +@implementation TextInputSemanticsObject { + FlutterInactiveTextInput* _inactive_text_input; +} + +- (instancetype)initWithBridge:(fml::WeakPtr)bridge + uid:(int32_t)uid { + self = [super initWithBridge:bridge uid:uid]; + + if (self) { + _inactive_text_input = [[FlutterInactiveTextInput alloc] init]; + } + + return self; +} + +#pragma mark - SemanticsObject overrides + +- (void)setSemanticsNode:(const flutter::SemanticsNode*)node { + [super setSemanticsNode:node]; + _inactive_text_input.text = @(node->value.data()); + FlutterTextInputView* textInput = (FlutterTextInputView*)[self bridge]->textInputView(); + if ([self node].HasFlag(flutter::SemanticsFlags::kIsFocused)) { + textInput.backingTextInputAccessibilityObject = self; + // The text input view must have a non-trivial size for the accessibility + // system to send text editing events. + textInput.frame = CGRectMake(0.0, 0.0, 1.0, 1.0); + } else if (textInput.backingTextInputAccessibilityObject == self) { + textInput.backingTextInputAccessibilityObject = nil; + } +} + +#pragma mark - UIAccessibility overrides + +/** + * The UITextInput whose accessibility properties we present to UIKit as + * substitutes for Flutter's text field properties. + * + * When the field is currently focused (i.e. it is being edited), we use + * the FlutterTextInputView used by FlutterTextInputPlugin. Otherwise, + * we use an FlutterInactiveTextInput. + */ +- (UIView*)textInputSurrogate { + if ([self node].HasFlag(flutter::SemanticsFlags::kIsFocused)) { + return [self bridge]->textInputView(); + } else { + return _inactive_text_input; + } +} + +- (UIView*)textInputView { + return [self textInputSurrogate]; +} + +- (void)accessibilityElementDidBecomeFocused { + if (![self isAccessibilityBridgeAlive]) { + return; + } + [[self textInputSurrogate] accessibilityElementDidBecomeFocused]; + [super accessibilityElementDidBecomeFocused]; +} + +- (void)accessibilityElementDidLoseFocus { + if (![self isAccessibilityBridgeAlive]) { + return; + } + [[self textInputSurrogate] accessibilityElementDidLoseFocus]; + [super accessibilityElementDidLoseFocus]; +} + +- (BOOL)accessibilityElementIsFocused { + if (![self isAccessibilityBridgeAlive]) { + return false; + } + return [self node].HasFlag(flutter::SemanticsFlags::kIsFocused); +} + +- (BOOL)accessibilityActivate { + if (![self isAccessibilityBridgeAlive]) { + return false; + } + return [[self textInputSurrogate] accessibilityActivate]; +} + +- (NSString*)accessibilityLabel { + if (![self isAccessibilityBridgeAlive]) { + return nil; + } + + NSString* label = [super accessibilityLabel]; + if (label != nil) { + return label; + } + return [self textInputSurrogate].accessibilityLabel; +} + +- (NSString*)accessibilityHint { + if (![self isAccessibilityBridgeAlive]) { + return nil; + } + NSString* hint = [super accessibilityHint]; + if (hint != nil) { + return hint; + } + return [self textInputSurrogate].accessibilityHint; +} + +- (NSString*)accessibilityValue { + if (![self isAccessibilityBridgeAlive]) { + return nil; + } + NSString* value = [super accessibilityValue]; + if (value != nil) { + return value; + } + return [self textInputSurrogate].accessibilityValue; +} + +- (UIAccessibilityTraits)accessibilityTraits { + if (![self isAccessibilityBridgeAlive]) { + return 0; + } + UIAccessibilityTraits results = + [super accessibilityTraits] | [self textInputSurrogate].accessibilityTraits; + // We remove an undocumented flag to get rid of a bug where single-tapping + // a text input field incorrectly says "empty line". + // See also: https://github.com/flutter/flutter/issues/52487 + return results & (~kUIAccessibilityTraitUndocumentedEmptyLine); +} + +#pragma mark - UITextInput overrides + +- (NSString*)textInRange:(UITextRange*)range { + return [[self textInputSurrogate] textInRange:range]; +} + +- (void)replaceRange:(UITextRange*)range withText:(NSString*)text { + return [[self textInputSurrogate] replaceRange:range withText:text]; +} + +- (BOOL)shouldChangeTextInRange:(UITextRange*)range replacementText:(NSString*)text { + return [[self textInputSurrogate] shouldChangeTextInRange:range replacementText:text]; +} + +- (UITextRange*)selectedTextRange { + return [[self textInputSurrogate] selectedTextRange]; +} + +- (void)setSelectedTextRange:(UITextRange*)range { + [[self textInputSurrogate] setSelectedTextRange:range]; +} + +- (UITextRange*)markedTextRange { + return [[self textInputSurrogate] markedTextRange]; +} + +- (NSDictionary*)markedTextStyle { + return [[self textInputSurrogate] markedTextStyle]; +} + +- (void)setMarkedTextStyle:(NSDictionary*)style { + [[self textInputSurrogate] setMarkedTextStyle:style]; +} + +- (void)setMarkedText:(NSString*)markedText selectedRange:(NSRange)selectedRange { + [[self textInputSurrogate] setMarkedText:markedText selectedRange:selectedRange]; +} + +- (void)unmarkText { + [[self textInputSurrogate] unmarkText]; +} + +- (UITextStorageDirection)selectionAffinity { + return [[self textInputSurrogate] selectionAffinity]; +} + +- (UITextPosition*)beginningOfDocument { + return [[self textInputSurrogate] beginningOfDocument]; +} + +- (UITextPosition*)endOfDocument { + return [[self textInputSurrogate] endOfDocument]; +} + +- (id)inputDelegate { + return [[self textInputSurrogate] inputDelegate]; +} + +- (void)setInputDelegate:(id)delegate { + [[self textInputSurrogate] setInputDelegate:delegate]; +} + +- (id)tokenizer { + return [[self textInputSurrogate] tokenizer]; +} + +- (UITextRange*)textRangeFromPosition:(UITextPosition*)fromPosition + toPosition:(UITextPosition*)toPosition { + return [[self textInputSurrogate] textRangeFromPosition:fromPosition toPosition:toPosition]; +} + +- (UITextPosition*)positionFromPosition:(UITextPosition*)position offset:(NSInteger)offset { + return [[self textInputSurrogate] positionFromPosition:position offset:offset]; +} + +- (UITextPosition*)positionFromPosition:(UITextPosition*)position + inDirection:(UITextLayoutDirection)direction + offset:(NSInteger)offset { + return [[self textInputSurrogate] positionFromPosition:position + inDirection:direction + offset:offset]; +} + +- (NSComparisonResult)comparePosition:(UITextPosition*)position toPosition:(UITextPosition*)other { + return [[self textInputSurrogate] comparePosition:position toPosition:other]; +} + +- (NSInteger)offsetFromPosition:(UITextPosition*)from toPosition:(UITextPosition*)toPosition { + return [[self textInputSurrogate] offsetFromPosition:from toPosition:toPosition]; +} + +- (UITextPosition*)positionWithinRange:(UITextRange*)range + farthestInDirection:(UITextLayoutDirection)direction { + return [[self textInputSurrogate] positionWithinRange:range farthestInDirection:direction]; +} + +- (UITextRange*)characterRangeByExtendingPosition:(UITextPosition*)position + inDirection:(UITextLayoutDirection)direction { + return [[self textInputSurrogate] characterRangeByExtendingPosition:position + inDirection:direction]; +} + +- (UITextWritingDirection)baseWritingDirectionForPosition:(UITextPosition*)position + inDirection:(UITextStorageDirection)direction { + return [[self textInputSurrogate] baseWritingDirectionForPosition:position inDirection:direction]; +} + +- (void)setBaseWritingDirection:(UITextWritingDirection)writingDirection + forRange:(UITextRange*)range { + [[self textInputSurrogate] setBaseWritingDirection:writingDirection forRange:range]; +} + +- (CGRect)firstRectForRange:(UITextRange*)range { + return [[self textInputSurrogate] firstRectForRange:range]; +} + +- (CGRect)caretRectForPosition:(UITextPosition*)position { + return [[self textInputSurrogate] caretRectForPosition:position]; +} + +- (UITextPosition*)closestPositionToPoint:(CGPoint)point { + return [[self textInputSurrogate] closestPositionToPoint:point]; +} + +- (UITextPosition*)closestPositionToPoint:(CGPoint)point withinRange:(UITextRange*)range { + return [[self textInputSurrogate] closestPositionToPoint:point withinRange:range]; +} + +- (NSArray*)selectionRectsForRange:(UITextRange*)range { + return [[self textInputSurrogate] selectionRectsForRange:range]; +} + +- (UITextRange*)characterRangeAtPoint:(CGPoint)point { + return [[self textInputSurrogate] characterRangeAtPoint:point]; +} + +- (void)insertText:(NSString*)text { + [[self textInputSurrogate] insertText:text]; +} + +- (void)deleteBackward { + [[self textInputSurrogate] deleteBackward]; +} + +#pragma mark - UIKeyInput overrides + +- (BOOL)hasText { + return [[self textInputSurrogate] hasText]; +} + +#pragma mark - UIResponder overrides + +- (void)cut:(id)sender { + [[self textInputSurrogate] cut:sender]; +} + +- (void)copy:(id)sender { + [[self textInputSurrogate] copy:sender]; +} + +- (void)paste:(id)sender { + [[self textInputSurrogate] paste:sender]; +} + +// TODO(hellohuanlin): should also support `select:`, which is not implemented by the surrogate yet. +// See: https://github.com/flutter/flutter/issues/107578. +- (void)selectAll:(id)sender { + [[self textInputSurrogate] selectAll:sender]; +} + +- (void)delete:(id)sender { + [[self textInputSurrogate] delete:sender]; +} + +- (BOOL)canPerformAction:(SEL)action withSender:(id)sender { + return [[self textInputSurrogate] canPerformAction:action withSender:sender]; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/UIViewController+FlutterScreenAndSceneIfLoaded.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/UIViewController+FlutterScreenAndSceneIfLoaded.h new file mode 100644 index 0000000000000000000000000000000000000000..d8ef23dcde98e446817e324e78266d1afffebe62 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/UIViewController+FlutterScreenAndSceneIfLoaded.h @@ -0,0 +1,21 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_UIVIEWCONTROLLER_FLUTTERSCREENANDSCENEIFLOADED_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_UIVIEWCONTROLLER_FLUTTERSCREENANDSCENEIFLOADED_H_ + +#import + +@interface UIViewController (FlutterScreenAndSceneIfLoaded) + +/// Returns a UIWindowScene if the UIViewController's view is loaded, and nil otherwise. +- (UIWindowScene*)flutterWindowSceneIfViewLoaded API_AVAILABLE(ios(13.0)); + +/// Before iOS 13, returns the main screen; After iOS 13, returns the screen the UIViewController is +/// attached to if its view is loaded, and nil otherwise. +- (UIScreen*)flutterScreenIfViewLoaded; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_UIVIEWCONTROLLER_FLUTTERSCREENANDSCENEIFLOADED_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/UIViewController+FlutterScreenAndSceneIfLoaded.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/UIViewController+FlutterScreenAndSceneIfLoaded.mm new file mode 100644 index 0000000000000000000000000000000000000000..b141b65768a0ebccfc930467040684f0c8457c69 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/UIViewController+FlutterScreenAndSceneIfLoaded.mm @@ -0,0 +1,33 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/UIViewController+FlutterScreenAndSceneIfLoaded.h" + +#include "flutter/fml/logging.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" + +FLUTTER_ASSERT_ARC + +@implementation UIViewController (FlutterScreenAndSceneIfLoaded) + +- (UIWindowScene*)flutterWindowSceneIfViewLoaded { + if (self.viewIfLoaded == nil) { + FML_LOG(WARNING) << "Trying to access the window scene before the view is loaded."; + return nil; + } + return self.viewIfLoaded.window.windowScene; +} + +- (UIScreen*)flutterScreenIfViewLoaded { + if (@available(iOS 13.0, *)) { + if (self.viewIfLoaded == nil) { + FML_LOG(WARNING) << "Trying to access the screen before the view is loaded."; + return nil; + } + return [self flutterWindowSceneIfViewLoaded].screen; + } + return UIScreen.mainScreen; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/UIViewController_FlutterScreenAndSceneIfLoadedTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/UIViewController_FlutterScreenAndSceneIfLoadedTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..c68e22da6bcac8c985a7efb684754f7b55cc26ff --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/UIViewController_FlutterScreenAndSceneIfLoadedTest.mm @@ -0,0 +1,81 @@ +// 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. + +#import + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/UIViewController+FlutterScreenAndSceneIfLoaded.h" + +FLUTTER_ASSERT_ARC + +@interface UIViewController_FlutterViewAndSceneIfLoadedTest : XCTestCase +@end + +@implementation UIViewController_FlutterViewAndSceneIfLoadedTest + +- (void)testWindowSceneIfViewLoadedReturnsWindowSceneIfViewLoaded { + if (@available(iOS 13.0, *)) { + UIViewController* viewController = [[UIViewController alloc] initWithNibName:nil bundle:nil]; + + NSSet* scenes = UIApplication.sharedApplication.connectedScenes; + XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test"); + UIScene* scene = scenes.anyObject; + XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test"); + UIWindowScene* windowScene = (UIWindowScene*)scene; + XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test"); + UIWindow* window = windowScene.windows[0]; + [window addSubview:viewController.view]; + + [viewController loadView]; + XCTAssertEqual(viewController.flutterWindowSceneIfViewLoaded, windowScene, + @"Must return the correct window scene when view loaded"); + } +} + +- (void)testWindowSceneIfViewLoadedReturnsNilIfViewNotLoaded { + if (@available(iOS 13.0, *)) { + UIViewController* viewController = [[UIViewController alloc] initWithNibName:nil bundle:nil]; + XCTAssertNil(viewController.flutterWindowSceneIfViewLoaded, + @"Must return nil window scene when view not loaded"); + } +} + +- (void)testScreenIfViewLoadedReturnsMainScreenBeforeIOS13 { + if (@available(iOS 13.0, *)) { + return; + } + + UIViewController* viewController = [[UIViewController alloc] initWithNibName:nil bundle:nil]; + XCTAssertEqual(viewController.flutterScreenIfViewLoaded, UIScreen.mainScreen, + @"Must return UIScreen.mainScreen before iOS 13"); +} + +- (void)testScreenIfViewLoadedReturnsScreenIfViewLoadedAfterIOS13 { + if (@available(iOS 13.0, *)) { + UIViewController* viewController = [[UIViewController alloc] initWithNibName:nil bundle:nil]; + + NSSet* scenes = UIApplication.sharedApplication.connectedScenes; + XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test"); + UIScene* scene = scenes.anyObject; + XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test"); + UIWindowScene* windowScene = (UIWindowScene*)scene; + XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test"); + UIWindow* window = windowScene.windows[0]; + [window addSubview:viewController.view]; + + [viewController loadView]; + XCTAssertEqual(viewController.flutterScreenIfViewLoaded, windowScene.screen, + @"Must return the correct screen when view loaded"); + } +} + +- (void)testScreenIfViewLoadedReturnsNilIfViewNotLoadedAfterIOS13 { + if (@available(iOS 13.0, *)) { + UIViewController* viewController = [[UIViewController alloc] initWithNibName:nil bundle:nil]; + XCTAssertNil(viewController.flutterScreenIfViewLoaded, + @"Must return nil screen when view not loaded"); + } +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/VsyncWaiterIosTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/VsyncWaiterIosTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..4a547bf28596e21283d526afe54ae428bbfee272 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/VsyncWaiterIosTest.mm @@ -0,0 +1,146 @@ +// 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. + +#import +#import + +#include "flutter/fml/raster_thread_merger.h" +#include "flutter/fml/thread.h" + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.h" + +FLUTTER_ASSERT_ARC +namespace { +fml::RefPtr CreateNewThread(const std::string& name) { + auto thread = std::make_unique(name); + auto runner = thread->GetTaskRunner(); + return runner; +} +} // namespace + +@interface VSyncClient (Testing) + +- (CADisplayLink*)getDisplayLink; +- (void)onDisplayLink:(CADisplayLink*)link; + +@end + +@interface VsyncWaiterIosTest : XCTestCase +@end + +@implementation VsyncWaiterIosTest + +- (void)testSetAllowPauseAfterVsyncCorrect { + auto thread_task_runner = CreateNewThread("VsyncWaiterIosTest"); + VSyncClient* vsyncClient = [[VSyncClient alloc] + initWithTaskRunner:thread_task_runner + callback:[](std::unique_ptr recorder) {}]; + CADisplayLink* link = [vsyncClient getDisplayLink]; + vsyncClient.allowPauseAfterVsync = NO; + [vsyncClient await]; + [vsyncClient onDisplayLink:link]; + XCTAssertFalse(link.isPaused); + + vsyncClient.allowPauseAfterVsync = YES; + [vsyncClient await]; + [vsyncClient onDisplayLink:link]; + XCTAssertTrue(link.isPaused); +} + +- (void)testSetCorrectVariableRefreshRates { + auto thread_task_runner = CreateNewThread("VsyncWaiterIosTest"); + auto callback = [](std::unique_ptr recorder) {}; + id bundleMock = OCMPartialMock([NSBundle mainBundle]); + OCMStub([bundleMock objectForInfoDictionaryKey:kCADisableMinimumFrameDurationOnPhoneKey]) + .andReturn(@YES); + id mockDisplayLinkManager = [OCMockObject mockForClass:[DisplayLinkManager class]]; + double maxFrameRate = 120; + [[[mockDisplayLinkManager stub] andReturnValue:@(maxFrameRate)] displayRefreshRate]; + + VSyncClient* vsyncClient = [[VSyncClient alloc] initWithTaskRunner:thread_task_runner + callback:callback]; + CADisplayLink* link = [vsyncClient getDisplayLink]; + if (@available(iOS 15.0, *)) { + XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.maximum, maxFrameRate, 0.1); + XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.preferred, maxFrameRate, 0.1); + XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.minimum, maxFrameRate / 2, 0.1); + } else { + XCTAssertEqualWithAccuracy(link.preferredFramesPerSecond, maxFrameRate, 0.1); + } +} + +- (void)testDoNotSetVariableRefreshRatesIfCADisableMinimumFrameDurationOnPhoneIsNotOn { + auto thread_task_runner = CreateNewThread("VsyncWaiterIosTest"); + auto callback = [](std::unique_ptr recorder) {}; + id bundleMock = OCMPartialMock([NSBundle mainBundle]); + OCMStub([bundleMock objectForInfoDictionaryKey:kCADisableMinimumFrameDurationOnPhoneKey]) + .andReturn(@NO); + id mockDisplayLinkManager = [OCMockObject mockForClass:[DisplayLinkManager class]]; + double maxFrameRate = 120; + [[[mockDisplayLinkManager stub] andReturnValue:@(maxFrameRate)] displayRefreshRate]; + + VSyncClient* vsyncClient = [[VSyncClient alloc] initWithTaskRunner:thread_task_runner + callback:callback]; + CADisplayLink* link = [vsyncClient getDisplayLink]; + if (@available(iOS 15.0, *)) { + XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.maximum, 0, 0.1); + XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.preferred, 0, 0.1); + XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.minimum, 0, 0.1); + } else { + XCTAssertEqualWithAccuracy(link.preferredFramesPerSecond, 0, 0.1); + } +} + +- (void)testDoNotSetVariableRefreshRatesIfCADisableMinimumFrameDurationOnPhoneIsNotSet { + auto thread_task_runner = CreateNewThread("VsyncWaiterIosTest"); + auto callback = [](std::unique_ptr recorder) {}; + id mockDisplayLinkManager = [OCMockObject mockForClass:[DisplayLinkManager class]]; + double maxFrameRate = 120; + [[[mockDisplayLinkManager stub] andReturnValue:@(maxFrameRate)] displayRefreshRate]; + VSyncClient* vsyncClient = [[VSyncClient alloc] initWithTaskRunner:thread_task_runner + callback:callback]; + CADisplayLink* link = [vsyncClient getDisplayLink]; + if (@available(iOS 15.0, *)) { + XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.maximum, 0, 0.1); + XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.preferred, 0, 0.1); + XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.minimum, 0, 0.1); + } else { + XCTAssertEqualWithAccuracy(link.preferredFramesPerSecond, 0, 0.1); + } +} + +- (void)testAwaitAndPauseWillWorkCorrectly { + auto thread_task_runner = CreateNewThread("VsyncWaiterIosTest"); + VSyncClient* vsyncClient = [[VSyncClient alloc] + initWithTaskRunner:thread_task_runner + callback:[](std::unique_ptr recorder) {}]; + + CADisplayLink* link = [vsyncClient getDisplayLink]; + XCTAssertTrue(link.isPaused); + + [vsyncClient await]; + XCTAssertFalse(link.isPaused); + + [vsyncClient pause]; + XCTAssertTrue(link.isPaused); +} + +- (void)testReleasesLinkOnInvalidation { + __weak CADisplayLink* weakLink; + @autoreleasepool { + auto thread_task_runner = CreateNewThread("VsyncWaiterIosTest"); + VSyncClient* vsyncClient = [[VSyncClient alloc] + initWithTaskRunner:thread_task_runner + callback:[](std::unique_ptr recorder) {}]; + + weakLink = [vsyncClient getDisplayLink]; + XCTAssertNotNil(weakLink); + [vsyncClient invalidate]; + } + // VSyncClient has released the CADisplayLink. + XCTAssertNil(weakLink); +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.h new file mode 100644 index 0000000000000000000000000000000000000000..b397d42f418a07bdd67aa557300eccd6aabb4b7d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.h @@ -0,0 +1,111 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_BRIDGE_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_BRIDGE_H_ + +#import + +#include +#include +#include +#include + +#include "flutter/fml/macros.h" +#include "flutter/fml/memory/weak_ptr.h" +#include "flutter/lib/ui/semantics/custom_accessibility_action.h" +#include "flutter/lib/ui/semantics/semantics_node.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge_ios.h" + +namespace flutter { +class PlatformViewIOS; + +/** + * An accessibility instance is bound to one `FlutterViewController` and + * `FlutterView` instance. + * + * It helps populate the UIView's accessibilityElements property from Flutter's + * semantics nodes. + */ +class AccessibilityBridge final : public AccessibilityBridgeIos { + public: + /** Delegate for handling iOS operations. */ + class IosDelegate { + public: + virtual ~IosDelegate() = default; + /// Returns true when the FlutterViewController associated with the `view` + /// is presenting a modal view controller. + virtual bool IsFlutterViewControllerPresentingModalViewController( + FlutterViewController* view_controller) = 0; + virtual void PostAccessibilityNotification(UIAccessibilityNotifications notification, + id argument) = 0; + }; + + AccessibilityBridge(FlutterViewController* view_controller, + PlatformViewIOS* platform_view, + __weak FlutterPlatformViewsController* platform_views_controller, + std::unique_ptr ios_delegate = nullptr); + ~AccessibilityBridge(); + + void UpdateSemantics(flutter::SemanticsNodeUpdates nodes, + const flutter::CustomAccessibilityActionUpdates& actions); + void HandleEvent(NSDictionary* annotatedEvent); + void DispatchSemanticsAction(int32_t id, flutter::SemanticsAction action) override; + void DispatchSemanticsAction(int32_t id, + flutter::SemanticsAction action, + fml::MallocMapping args) override; + void AccessibilityObjectDidBecomeFocused(int32_t id) override; + void AccessibilityObjectDidLoseFocus(int32_t id) override; + + UIView* textInputView() override; + + UIView* view() const override { return view_controller_.view; } + + bool isVoiceOverRunning() const override { return view_controller_.isVoiceOverRunning; } + + fml::WeakPtr GetWeakPtr(); + + FlutterPlatformViewsController* GetPlatformViewsController() const override { + return platform_views_controller_; + }; + + void clearState(); + + private: + SemanticsObject* GetOrCreateObject(int32_t id, flutter::SemanticsNodeUpdates& updates); + SemanticsObject* FindNextFocusableIfNecessary(); + // Finds the first focusable SemanticsObject rooted at the parent. This includes the parent itself + // if it is a focusable SemanticsObject. + // + // If the parent is nil, this function use the root SemanticsObject as the parent. + SemanticsObject* FindFirstFocusable(SemanticsObject* parent); + void VisitObjectsRecursivelyAndRemove(SemanticsObject* object, + NSMutableArray* doomed_uids); + + FlutterViewController* view_controller_; + PlatformViewIOS* platform_view_; + __weak FlutterPlatformViewsController* platform_views_controller_; + // If the this id is kSemanticObjectIdInvalid, it means either nothing has + // been focused or the focus is currently outside of the flutter application + // (i.e. the status bar or keyboard) + int32_t last_focused_semantics_object_id_; + + NSMutableDictionary* objects_; + FlutterBasicMessageChannel* accessibility_channel_; + int32_t previous_route_id_ = 0; + std::unordered_map actions_; + std::vector previous_routes_; + std::unique_ptr ios_delegate_; + fml::WeakPtrFactory weak_factory_; // Must be the last member. + FML_DISALLOW_COPY_AND_ASSIGN(AccessibilityBridge); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_BRIDGE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.mm new file mode 100644 index 0000000000000000000000000000000000000000..8d35ef97ff79b77b9007111c504871d94cb256fb --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.mm @@ -0,0 +1,387 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.h" + +#include + +#include "flutter/fml/logging.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/TextInputSemanticsObject.h" +#import "flutter/shell/platform/darwin/ios/platform_view_ios.h" + +#include "flutter/common/constants.h" + +#pragma GCC diagnostic error "-Wundeclared-selector" + +FLUTTER_ASSERT_ARC + +namespace flutter { +namespace { + +constexpr int32_t kSemanticObjectIdInvalid = -1; + +class DefaultIosDelegate : public AccessibilityBridge::IosDelegate { + public: + bool IsFlutterViewControllerPresentingModalViewController( + FlutterViewController* view_controller) override { + if (view_controller) { + return view_controller.isPresentingViewController; + } else { + return false; + } + } + + void PostAccessibilityNotification(UIAccessibilityNotifications notification, + id argument) override { + UIAccessibilityPostNotification(notification, argument); + } +}; +} // namespace + +AccessibilityBridge::AccessibilityBridge( + FlutterViewController* view_controller, + PlatformViewIOS* platform_view, + __weak FlutterPlatformViewsController* platform_views_controller, + std::unique_ptr ios_delegate) + : view_controller_(view_controller), + platform_view_(platform_view), + platform_views_controller_(platform_views_controller), + last_focused_semantics_object_id_(kSemanticObjectIdInvalid), + objects_([[NSMutableDictionary alloc] init]), + previous_routes_({}), + ios_delegate_(ios_delegate ? std::move(ios_delegate) + : std::make_unique()), + weak_factory_(this) { + accessibility_channel_ = [[FlutterBasicMessageChannel alloc] + initWithName:@"flutter/accessibility" + binaryMessenger:platform_view->GetOwnerViewController().engine.binaryMessenger + codec:[FlutterStandardMessageCodec sharedInstance]]; + [accessibility_channel_ setMessageHandler:^(id message, FlutterReply reply) { + HandleEvent((NSDictionary*)message); + }]; +} + +AccessibilityBridge::~AccessibilityBridge() { + [accessibility_channel_ setMessageHandler:nil]; + clearState(); +} + +UIView* AccessibilityBridge::textInputView() { + return [[platform_view_->GetOwnerViewController().engine textInputPlugin] textInputView]; +} + +void AccessibilityBridge::AccessibilityObjectDidBecomeFocused(int32_t id) { + last_focused_semantics_object_id_ = id; + [accessibility_channel_ sendMessage:@{@"type" : @"didGainFocus", @"nodeId" : @(id)}]; +} + +void AccessibilityBridge::AccessibilityObjectDidLoseFocus(int32_t id) { + if (last_focused_semantics_object_id_ == id) { + last_focused_semantics_object_id_ = kSemanticObjectIdInvalid; + } +} + +void AccessibilityBridge::UpdateSemantics( + flutter::SemanticsNodeUpdates nodes, + const flutter::CustomAccessibilityActionUpdates& actions) { + BOOL layoutChanged = NO; + BOOL scrollOccured = NO; + BOOL needsAnnouncement = NO; + for (const auto& entry : actions) { + const flutter::CustomAccessibilityAction& action = entry.second; + actions_[action.id] = action; + } + for (const auto& entry : nodes) { + const flutter::SemanticsNode& node = entry.second; + SemanticsObject* object = GetOrCreateObject(node.id, nodes); + layoutChanged = layoutChanged || [object nodeWillCauseLayoutChange:&node]; + scrollOccured = scrollOccured || [object nodeWillCauseScroll:&node]; + needsAnnouncement = [object nodeShouldTriggerAnnouncement:&node]; + [object setSemanticsNode:&node]; + NSUInteger newChildCount = node.childrenInTraversalOrder.size(); + NSMutableArray* newChildren = [[NSMutableArray alloc] initWithCapacity:newChildCount]; + for (NSUInteger i = 0; i < newChildCount; ++i) { + SemanticsObject* child = GetOrCreateObject(node.childrenInTraversalOrder[i], nodes); + [newChildren addObject:child]; + } + NSMutableArray* newChildrenInHitTestOrder = + [[NSMutableArray alloc] initWithCapacity:newChildCount]; + for (NSUInteger i = 0; i < newChildCount; ++i) { + SemanticsObject* child = GetOrCreateObject(node.childrenInHitTestOrder[i], nodes); + [newChildrenInHitTestOrder addObject:child]; + } + object.children = newChildren; + object.childrenInHitTestOrder = newChildrenInHitTestOrder; + if (!node.customAccessibilityActions.empty()) { + NSMutableArray* accessibilityCustomActions = + [[NSMutableArray alloc] init]; + for (int32_t action_id : node.customAccessibilityActions) { + flutter::CustomAccessibilityAction& action = actions_[action_id]; + if (action.overrideId != -1) { + // iOS does not support overriding standard actions, so we ignore any + // custom actions that have an override id provided. + continue; + } + NSString* label = @(action.label.data()); + SEL selector = @selector(onCustomAccessibilityAction:); + FlutterCustomAccessibilityAction* customAction = + [[FlutterCustomAccessibilityAction alloc] initWithName:label + target:object + selector:selector]; + customAction.uid = action_id; + [accessibilityCustomActions addObject:customAction]; + } + object.accessibilityCustomActions = accessibilityCustomActions; + } + + if (needsAnnouncement) { + // Try to be more polite - iOS 11+ supports + // UIAccessibilitySpeechAttributeQueueAnnouncement which should avoid + // interrupting system notifications or other elements. + // Expectation: roughly match the behavior of polite announcements on + // Android. + NSString* announcement = [[NSString alloc] initWithUTF8String:object.node.label.c_str()]; + UIAccessibilityPostNotification( + UIAccessibilityAnnouncementNotification, + [[NSAttributedString alloc] initWithString:announcement + attributes:@{ + UIAccessibilitySpeechAttributeQueueAnnouncement : @YES + }]); + } + } + + SemanticsObject* root = objects_[@(kRootNodeId)]; + + bool routeChanged = false; + SemanticsObject* lastAdded = nil; + + if (root) { + if (!view_controller_.view.accessibilityElements) { + view_controller_.view.accessibilityElements = + @[ [root accessibilityContainer] ?: [NSNull null] ]; + } + NSMutableArray* newRoutes = [[NSMutableArray alloc] init]; + [root collectRoutes:newRoutes]; + // Finds the last route that is not in the previous routes. + for (SemanticsObject* route in newRoutes) { + if (std::find(previous_routes_.begin(), previous_routes_.end(), [route uid]) == + previous_routes_.end()) { + lastAdded = route; + } + } + // If all the routes are in the previous route, get the last route. + if (lastAdded == nil && [newRoutes count] > 0) { + int index = [newRoutes count] - 1; + lastAdded = [newRoutes objectAtIndex:index]; + } + // There are two cases if lastAdded != nil + // 1. lastAdded is not in previous routes. In this case, + // [lastAdded uid] != previous_route_id_ + // 2. All new routes are in previous routes and + // lastAdded = newRoutes.last. + // In the first case, we need to announce new route. In the second case, + // we need to announce if one list is shorter than the other. + if (lastAdded != nil && + ([lastAdded uid] != previous_route_id_ || [newRoutes count] != previous_routes_.size())) { + previous_route_id_ = [lastAdded uid]; + routeChanged = true; + } + previous_routes_.clear(); + for (SemanticsObject* route in newRoutes) { + previous_routes_.push_back([route uid]); + } + } else { + view_controller_.viewIfLoaded.accessibilityElements = nil; + } + + NSMutableArray* doomed_uids = [NSMutableArray arrayWithArray:objects_.allKeys]; + if (root) { + VisitObjectsRecursivelyAndRemove(root, doomed_uids); + } + [objects_ removeObjectsForKeys:doomed_uids]; + + for (SemanticsObject* object in objects_.allValues) { + [object accessibilityBridgeDidFinishUpdate]; + } + + if (!ios_delegate_->IsFlutterViewControllerPresentingModalViewController(view_controller_)) { + layoutChanged = layoutChanged || [doomed_uids count] > 0; + + if (routeChanged) { + NSString* routeName = [lastAdded routeName]; + ios_delegate_->PostAccessibilityNotification(UIAccessibilityScreenChangedNotification, + routeName); + } + + if (layoutChanged) { + SemanticsObject* next = FindNextFocusableIfNecessary(); + SemanticsObject* lastFocused = [objects_ objectForKey:@(last_focused_semantics_object_id_)]; + // Only specify the focus item if the new focus is different, avoiding double focuses on the + // same item. See: https://github.com/flutter/flutter/issues/104176. If there is a route + // change, we always refocus. + ios_delegate_->PostAccessibilityNotification( + UIAccessibilityLayoutChangedNotification, + (routeChanged || next != lastFocused) ? next.nativeAccessibility : NULL); + } else if (scrollOccured) { + // TODO(chunhtai): figure out what string to use for notification. At this + // point, it is guarantee the previous focused object is still in the tree + // so that we don't need to worry about focus lost. (e.g. "Screen 0 of 3") + ios_delegate_->PostAccessibilityNotification( + UIAccessibilityPageScrolledNotification, + FindNextFocusableIfNecessary().nativeAccessibility); + } + } +} + +void AccessibilityBridge::DispatchSemanticsAction(int32_t node_uid, + flutter::SemanticsAction action) { + // TODO(team-ios): Remove implicit view assumption. + // https://github.com/flutter/flutter/issues/142845 + platform_view_->DispatchSemanticsAction(kFlutterImplicitViewId, node_uid, action, {}); +} + +void AccessibilityBridge::DispatchSemanticsAction(int32_t node_uid, + flutter::SemanticsAction action, + fml::MallocMapping args) { + // TODO(team-ios): Remove implicit view assumption. + // https://github.com/flutter/flutter/issues/142845 + platform_view_->DispatchSemanticsAction(kFlutterImplicitViewId, node_uid, action, + std::move(args)); +} + +static void ReplaceSemanticsObject(SemanticsObject* oldObject, + SemanticsObject* newObject, + NSMutableDictionary* objects) { + // `newObject` should represent the same id as `oldObject`. + FML_DCHECK(oldObject.node.id == newObject.uid); + NSNumber* nodeId = @(oldObject.node.id); + NSUInteger positionInChildlist = [oldObject.parent.children indexOfObject:oldObject]; + oldObject.children = @[]; + [oldObject.parent replaceChildAtIndex:positionInChildlist withChild:newObject]; + [objects removeObjectForKey:nodeId]; + objects[nodeId] = newObject; +} + +static SemanticsObject* CreateObject(const flutter::SemanticsNode& node, + const fml::WeakPtr& weak_ptr) { + if (node.HasFlag(flutter::SemanticsFlags::kIsTextField) && + !node.HasFlag(flutter::SemanticsFlags::kIsReadOnly)) { + // Text fields are backed by objects that implement UITextInput. + return [[TextInputSemanticsObject alloc] initWithBridge:weak_ptr uid:node.id]; + } else if (!node.HasFlag(flutter::SemanticsFlags::kIsInMutuallyExclusiveGroup) && + (node.HasFlag(flutter::SemanticsFlags::kHasToggledState) || + node.HasFlag(flutter::SemanticsFlags::kHasCheckedState))) { + return [[FlutterSwitchSemanticsObject alloc] initWithBridge:weak_ptr uid:node.id]; + } else if (node.HasFlag(flutter::SemanticsFlags::kHasImplicitScrolling)) { + return [[FlutterScrollableSemanticsObject alloc] initWithBridge:weak_ptr uid:node.id]; + } else if (node.IsPlatformViewNode()) { + FlutterPlatformViewsController* platformViewsController = + weak_ptr->GetPlatformViewsController(); + FlutterTouchInterceptingView* touchInterceptingView = + [platformViewsController flutterTouchInterceptingViewForId:node.platformViewId]; + return [[FlutterPlatformViewSemanticsContainer alloc] initWithBridge:weak_ptr + uid:node.id + platformView:touchInterceptingView]; + } else { + return [[FlutterSemanticsObject alloc] initWithBridge:weak_ptr uid:node.id]; + } +} + +static bool DidFlagChange(const flutter::SemanticsNode& oldNode, + const flutter::SemanticsNode& newNode, + SemanticsFlags flag) { + return oldNode.HasFlag(flag) != newNode.HasFlag(flag); +} + +SemanticsObject* AccessibilityBridge::GetOrCreateObject(int32_t uid, + flutter::SemanticsNodeUpdates& updates) { + SemanticsObject* object = objects_[@(uid)]; + if (!object) { + object = CreateObject(updates[uid], GetWeakPtr()); + objects_[@(uid)] = object; + } else { + // Existing node case + auto nodeEntry = updates.find(object.node.id); + if (nodeEntry != updates.end()) { + // There's an update for this node + flutter::SemanticsNode node = nodeEntry->second; + if (DidFlagChange(object.node, node, flutter::SemanticsFlags::kIsTextField) || + DidFlagChange(object.node, node, flutter::SemanticsFlags::kIsReadOnly) || + DidFlagChange(object.node, node, flutter::SemanticsFlags::kHasCheckedState) || + DidFlagChange(object.node, node, flutter::SemanticsFlags::kHasToggledState) || + DidFlagChange(object.node, node, flutter::SemanticsFlags::kHasImplicitScrolling)) { + // The node changed its type. In this case, we cannot reuse the existing + // SemanticsObject implementation. Instead, we replace it with a new + // instance. + SemanticsObject* newSemanticsObject = CreateObject(node, GetWeakPtr()); + ReplaceSemanticsObject(object, newSemanticsObject, objects_); + object = newSemanticsObject; + } + } + } + return object; +} + +void AccessibilityBridge::VisitObjectsRecursivelyAndRemove(SemanticsObject* object, + NSMutableArray* doomed_uids) { + [doomed_uids removeObject:@(object.uid)]; + for (SemanticsObject* child in [object children]) + VisitObjectsRecursivelyAndRemove(child, doomed_uids); +} + +SemanticsObject* AccessibilityBridge::FindNextFocusableIfNecessary() { + // This property will be -1 if the focus is outside of the flutter + // application. In this case, we should not refocus anything. + if (last_focused_semantics_object_id_ == kSemanticObjectIdInvalid) { + return nil; + } + + // Tries to refocus the previous focused semantics object to avoid random jumps. + return FindFirstFocusable(objects_[@(last_focused_semantics_object_id_)]); +} + +SemanticsObject* AccessibilityBridge::FindFirstFocusable(SemanticsObject* parent) { + SemanticsObject* currentObject = parent ?: objects_[@(kRootNodeId)]; + if (!currentObject) { + return nil; + } + if (currentObject.isAccessibilityElement) { + return currentObject; + } + + for (SemanticsObject* child in [currentObject children]) { + SemanticsObject* candidate = FindFirstFocusable(child); + if (candidate) { + return candidate; + } + } + return nil; +} + +void AccessibilityBridge::HandleEvent(NSDictionary* annotatedEvent) { + NSString* type = annotatedEvent[@"type"]; + if ([type isEqualToString:@"announce"]) { + NSString* message = annotatedEvent[@"data"][@"message"]; + ios_delegate_->PostAccessibilityNotification(UIAccessibilityAnnouncementNotification, message); + } + if ([type isEqualToString:@"focus"]) { + SemanticsObject* node = objects_[annotatedEvent[@"nodeId"]]; + ios_delegate_->PostAccessibilityNotification(UIAccessibilityLayoutChangedNotification, node); + } +} + +fml::WeakPtr AccessibilityBridge::GetWeakPtr() { + return weak_factory_.GetWeakPtr(); +} + +void AccessibilityBridge::clearState() { + [objects_ removeAllObjects]; + previous_route_id_ = 0; + previous_routes_.clear(); + view_controller_.viewIfLoaded.accessibilityElements = nil; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge_ios.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge_ios.h new file mode 100644 index 0000000000000000000000000000000000000000..2168ca050d072284860150aeaaa39f1ea30ac901 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge_ios.h @@ -0,0 +1,47 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_BRIDGE_IOS_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_BRIDGE_IOS_H_ + +#include +#include + +#import "flutter/fml/mapping.h" +#include "flutter/lib/ui/semantics/semantics_node.h" + +@class UIView; +@class FlutterPlatformViewsController; + +namespace flutter { + +/// Interface that represents an accessibility bridge for iOS. +class AccessibilityBridgeIos { + public: + virtual ~AccessibilityBridgeIos() = default; + virtual UIView* view() const = 0; + virtual bool isVoiceOverRunning() const = 0; + virtual UIView* textInputView() = 0; + virtual void DispatchSemanticsAction(int32_t id, flutter::SemanticsAction action) = 0; + virtual void DispatchSemanticsAction(int32_t id, + flutter::SemanticsAction action, + fml::MallocMapping args) = 0; + /** + * A callback that is called when a SemanticObject receives focus. + * + * The input id is the uid of the newly focused SemanticObject. + */ + virtual void AccessibilityObjectDidBecomeFocused(int32_t id) = 0; + /** + * A callback that is called when a SemanticObject loses focus + * + * The input id is the uid of the newly focused SemanticObject. + */ + virtual void AccessibilityObjectDidLoseFocus(int32_t id) = 0; + virtual FlutterPlatformViewsController* GetPlatformViewsController() const = 0; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_BRIDGE_IOS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge_test.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge_test.mm new file mode 100644 index 0000000000000000000000000000000000000000..39edc77869f8b3fed7884af9cfbdbe055e50dee8 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge_test.mm @@ -0,0 +1,2404 @@ +// 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. + +#import +#import + +#import "flutter/fml/thread.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterPlatformViews.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterSemanticsScrollView.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.h" +#import "flutter/shell/platform/darwin/ios/platform_view_ios.h" + +FLUTTER_ASSERT_ARC + +@class MockPlatformView; +__weak static MockPlatformView* gMockPlatformView = nil; + +@interface MockPlatformView : UIView +@end +@implementation MockPlatformView + +- (instancetype)init { + self = [super init]; + if (self) { + gMockPlatformView = self; + } + return self; +} + +- (void)dealloc { + gMockPlatformView = nil; +} + +@end + +@interface MockFlutterPlatformView : NSObject +@property(nonatomic, strong) UIView* view; +@end + +@implementation MockFlutterPlatformView + +- (instancetype)init { + if (self = [super init]) { + _view = [[MockPlatformView alloc] init]; + } + return self; +} + +@end + +@interface MockFlutterPlatformFactory : NSObject +@end + +@implementation MockFlutterPlatformFactory +- (NSObject*)createWithFrame:(CGRect)frame + viewIdentifier:(int64_t)viewId + arguments:(id _Nullable)args { + return [[MockFlutterPlatformView alloc] init]; +} + +@end + +namespace flutter { +namespace { +class MockDelegate : public PlatformView::Delegate { + public: + void OnPlatformViewCreated(std::unique_ptr surface) override {} + void OnPlatformViewDestroyed() override {} + void OnPlatformViewScheduleFrame() override {} + void OnPlatformViewAddView(int64_t view_id, + const ViewportMetrics& viewport_metrics, + AddViewCallback callback) override {} + void OnPlatformViewRemoveView(int64_t view_id, RemoveViewCallback callback) override {} + void OnPlatformViewSendViewFocusEvent(const ViewFocusEvent& event) override {}; + void OnPlatformViewSetNextFrameCallback(const fml::closure& closure) override {} + void OnPlatformViewSetViewportMetrics(int64_t view_id, const ViewportMetrics& metrics) override {} + const flutter::Settings& OnPlatformViewGetSettings() const override { return settings_; } + void OnPlatformViewDispatchPlatformMessage(std::unique_ptr message) override {} + void OnPlatformViewDispatchPointerDataPacket(std::unique_ptr packet) override { + } + void OnPlatformViewDispatchSemanticsAction(int64_t view_id, + int32_t node_id, + SemanticsAction action, + fml::MallocMapping args) override {} + void OnPlatformViewSetSemanticsEnabled(bool enabled) override {} + void OnPlatformViewSetAccessibilityFeatures(int32_t flags) override {} + void OnPlatformViewRegisterTexture(std::shared_ptr texture) override {} + void OnPlatformViewUnregisterTexture(int64_t texture_id) override {} + void OnPlatformViewMarkTextureFrameAvailable(int64_t texture_id) override {} + + void LoadDartDeferredLibrary(intptr_t loading_unit_id, + std::unique_ptr snapshot_data, + std::unique_ptr snapshot_instructions) override { + } + void LoadDartDeferredLibraryError(intptr_t loading_unit_id, + const std::string error_message, + bool transient) override {} + void UpdateAssetResolverByType(std::unique_ptr updated_asset_resolver, + flutter::AssetResolver::AssetResolverType type) override {} + + flutter::Settings settings_; +}; + +class MockIosDelegate : public AccessibilityBridge::IosDelegate { + public: + bool IsFlutterViewControllerPresentingModalViewController( + FlutterViewController* view_controller) override { + return result_IsFlutterViewControllerPresentingModalViewController_; + }; + + void PostAccessibilityNotification(UIAccessibilityNotifications notification, + id argument) override { + if (on_PostAccessibilityNotification_) { + on_PostAccessibilityNotification_(notification, argument); + } + } + std::function on_PostAccessibilityNotification_; + bool result_IsFlutterViewControllerPresentingModalViewController_ = false; +}; +} // namespace +} // namespace flutter + +namespace { +fml::RefPtr CreateNewThread(const std::string& name) { + auto thread = std::make_unique(name); + auto runner = thread->GetTaskRunner(); + return runner; +} +} // namespace + +@interface AccessibilityBridgeTest : XCTestCase +@end + +@implementation AccessibilityBridgeTest + +- (void)testCreate { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + auto bridge = + std::make_unique(/*view=*/nil, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil); + XCTAssertTrue(bridge.get()); +} + +- (void)testUpdateSemanticsEmpty { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id mockFlutterView = OCMClassMock([FlutterView class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + OCMStub([mockFlutterViewController viewIfLoaded]).andReturn(mockFlutterView); + OCMExpect([mockFlutterView setAccessibilityElements:[OCMArg isNil]]); + auto bridge = + std::make_unique(/*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil); + flutter::SemanticsNodeUpdates nodes; + flutter::CustomAccessibilityActionUpdates actions; + bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); + OCMVerifyAll(mockFlutterView); +} + +- (void)testUpdateSemanticsOneNode { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id mockFlutterView = OCMClassMock([FlutterView class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); + std::string label = "some label"; + + __block auto bridge = + std::make_unique(/*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil); + + OCMExpect([mockFlutterView setAccessibilityElements:[OCMArg checkWithBlock:^BOOL(NSArray* value) { + if ([value count] != 1) { + return NO; + } else { + SemanticsObjectContainer* container = value[0]; + SemanticsObject* object = container.semanticsObject; + return object.uid == kRootNodeId && + object.bridge.get() == bridge.get() && + object.node.label == label; + } + }]]); + + flutter::SemanticsNodeUpdates nodes; + flutter::SemanticsNode semantics_node; + semantics_node.id = kRootNodeId; + semantics_node.label = label; + nodes[kRootNodeId] = semantics_node; + flutter::CustomAccessibilityActionUpdates actions; + bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); + OCMVerifyAll(mockFlutterView); +} + +- (void)testIsVoiceOverRunning { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id mockFlutterView = OCMClassMock([FlutterView class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); + OCMStub([mockFlutterViewController isVoiceOverRunning]).andReturn(YES); + + __block auto bridge = + std::make_unique(/*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil); + + XCTAssertTrue(bridge->isVoiceOverRunning()); +} + +- (void)testSemanticsDeallocated { + @autoreleasepool { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = thread_task_runner; + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id mockFlutterView = OCMClassMock([FlutterView class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); + std::string label = "some label"; + flutterPlatformViewsController.flutterView = mockFlutterView; + + MockFlutterPlatformFactory* factory = [[MockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + auto bridge = std::make_unique( + /*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/flutterPlatformViewsController); + + flutter::SemanticsNodeUpdates nodes; + flutter::SemanticsNode semantics_node; + semantics_node.id = 2; + semantics_node.platformViewId = 2; + semantics_node.label = label; + nodes[kRootNodeId] = semantics_node; + flutter::CustomAccessibilityActionUpdates actions; + bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); + XCTAssertNotNil(gMockPlatformView); + [flutterPlatformViewsController reset]; + } + XCTAssertNil(gMockPlatformView); +} + +- (void)testSemanticsDeallocatedWithoutLoadingView { + id engine = OCMClassMock([FlutterEngine class]); + FlutterViewController* flutterViewController = + [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; + @autoreleasepool { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = thread_task_runner; + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + + MockFlutterPlatformFactory* factory = [[MockFlutterPlatformFactory alloc] init]; + [flutterPlatformViewsController + registerViewFactory:factory + withId:@"MockFlutterPlatformView" + gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; + FlutterResult result = ^(id result) { + }; + [flutterPlatformViewsController + onMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockFlutterPlatformView" + }] + result:result]; + + auto bridge = std::make_unique( + /*view_controller=*/flutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/flutterPlatformViewsController); + + XCTAssertNotNil(gMockPlatformView); + [flutterPlatformViewsController reset]; + platform_view->NotifyDestroyed(); + } + XCTAssertNil(gMockPlatformView); + XCTAssertNil(flutterViewController.viewIfLoaded); + [flutterViewController deregisterNotifications]; +} + +- (void)testReplacedSemanticsDoesNotCleanupChildren { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = thread_task_runner; + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id engine = OCMClassMock([FlutterEngine class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + FlutterView* flutterView = [[FlutterView alloc] initWithDelegate:engine + opaque:YES + enableWideGamut:NO]; + OCMStub([mockFlutterViewController view]).andReturn(flutterView); + std::string label = "some label"; + auto bridge = std::make_unique( + /*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/flutterPlatformViewsController); + @autoreleasepool { + flutter::SemanticsNodeUpdates nodes; + flutter::SemanticsNode parent; + parent.id = 0; + parent.rect = SkRect::MakeXYWH(0, 0, 100, 200); + parent.label = "label"; + parent.value = "value"; + parent.hint = "hint"; + + flutter::SemanticsNode node; + node.id = 1; + node.rect = SkRect::MakeXYWH(0, 0, 100, 200); + node.label = "label"; + node.value = "value"; + node.hint = "hint"; + node.scrollExtentMax = 100.0; + node.scrollPosition = 0.0; + parent.childrenInTraversalOrder.push_back(1); + parent.childrenInHitTestOrder.push_back(1); + + flutter::SemanticsNode child; + child.id = 2; + child.rect = SkRect::MakeXYWH(0, 0, 100, 200); + child.label = "label"; + child.value = "value"; + child.hint = "hint"; + node.childrenInTraversalOrder.push_back(2); + node.childrenInHitTestOrder.push_back(2); + + nodes[0] = parent; + nodes[1] = node; + nodes[2] = child; + flutter::CustomAccessibilityActionUpdates actions; + bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); + + // Add implicit scroll from node 1 to cause replacement. + flutter::SemanticsNodeUpdates new_nodes; + flutter::SemanticsNode new_node; + new_node.id = 1; + new_node.rect = SkRect::MakeXYWH(0, 0, 100, 200); + new_node.flags = static_cast(flutter::SemanticsFlags::kHasImplicitScrolling); + new_node.actions = flutter::kHorizontalScrollSemanticsActions; + new_node.label = "label"; + new_node.value = "value"; + new_node.hint = "hint"; + new_node.scrollExtentMax = 100.0; + new_node.scrollPosition = 0.0; + new_node.childrenInTraversalOrder.push_back(2); + new_node.childrenInHitTestOrder.push_back(2); + + new_nodes[1] = new_node; + bridge->UpdateSemantics(/*nodes=*/new_nodes, /*actions=*/actions); + } + /// The old node should be deallocated at this moment. Procced to check + /// accessibility tree integrity. + id rootContainer = flutterView.accessibilityElements[0]; + XCTAssertTrue([rootContainer accessibilityElementCount] == + 2); // one for root, one for scrollable. + id scrollableContainer = [rootContainer accessibilityElementAtIndex:1]; + XCTAssertTrue([scrollableContainer accessibilityElementCount] == + 2); // one for scrollable, one for scrollable child. + id child = [scrollableContainer accessibilityElementAtIndex:1]; + /// Replacing node 1 should not accidentally clean up its child's container. + XCTAssertNotNil([child accessibilityContainer]); +} + +- (void)testScrollableSemanticsDeallocated { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = thread_task_runner; + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id engine = OCMClassMock([FlutterEngine class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + FlutterView* flutterView = [[FlutterView alloc] initWithDelegate:engine + opaque:YES + enableWideGamut:NO]; + OCMStub([mockFlutterViewController view]).andReturn(flutterView); + std::string label = "some label"; + @autoreleasepool { + auto bridge = std::make_unique( + /*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/flutterPlatformViewsController); + + flutter::SemanticsNodeUpdates nodes; + flutter::SemanticsNode parent; + parent.id = 0; + parent.rect = SkRect::MakeXYWH(0, 0, 100, 200); + parent.label = "label"; + parent.value = "value"; + parent.hint = "hint"; + + flutter::SemanticsNode node; + node.id = 1; + node.flags = static_cast(flutter::SemanticsFlags::kHasImplicitScrolling); + node.actions = flutter::kHorizontalScrollSemanticsActions; + node.rect = SkRect::MakeXYWH(0, 0, 100, 200); + node.label = "label"; + node.value = "value"; + node.hint = "hint"; + node.scrollExtentMax = 100.0; + node.scrollPosition = 0.0; + parent.childrenInTraversalOrder.push_back(1); + parent.childrenInHitTestOrder.push_back(1); + nodes[0] = parent; + nodes[1] = node; + flutter::CustomAccessibilityActionUpdates actions; + bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); + XCTAssertTrue([flutterView.subviews count] == 1); + XCTAssertTrue([flutterView.subviews[0] isKindOfClass:[FlutterSemanticsScrollView class]]); + XCTAssertTrue([flutterView.subviews[0].accessibilityLabel isEqualToString:@"label"]); + + // Remove the scrollable from the tree. + flutter::SemanticsNodeUpdates new_nodes; + flutter::SemanticsNode new_parent; + new_parent.id = 0; + new_parent.rect = SkRect::MakeXYWH(0, 0, 100, 200); + new_parent.label = "label"; + new_parent.value = "value"; + new_parent.hint = "hint"; + new_nodes[0] = new_parent; + bridge->UpdateSemantics(/*nodes=*/new_nodes, /*actions=*/actions); + } + XCTAssertTrue([flutterView.subviews count] == 0); +} + +- (void)testBridgeReplacesSemanticsNode { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id engine = OCMClassMock([FlutterEngine class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + FlutterView* flutterView = [[FlutterView alloc] initWithDelegate:engine + opaque:YES + enableWideGamut:NO]; + OCMStub([mockFlutterViewController view]).andReturn(flutterView); + std::string label = "some label"; + @autoreleasepool { + auto bridge = std::make_unique( + /*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/flutterPlatformViewsController); + + flutter::SemanticsNodeUpdates nodes; + flutter::SemanticsNode parent; + parent.id = 0; + parent.rect = SkRect::MakeXYWH(0, 0, 100, 200); + parent.label = "label"; + parent.value = "value"; + parent.hint = "hint"; + + flutter::SemanticsNode node; + node.id = 1; + node.flags = static_cast(flutter::SemanticsFlags::kHasImplicitScrolling); + node.actions = flutter::kHorizontalScrollSemanticsActions; + node.rect = SkRect::MakeXYWH(0, 0, 100, 200); + node.label = "label"; + node.value = "value"; + node.hint = "hint"; + node.scrollExtentMax = 100.0; + node.scrollPosition = 0.0; + parent.childrenInTraversalOrder.push_back(1); + parent.childrenInHitTestOrder.push_back(1); + nodes[0] = parent; + nodes[1] = node; + flutter::CustomAccessibilityActionUpdates actions; + bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); + XCTAssertTrue([flutterView.subviews count] == 1); + XCTAssertTrue([flutterView.subviews[0] isKindOfClass:[FlutterSemanticsScrollView class]]); + XCTAssertTrue([flutterView.subviews[0].accessibilityLabel isEqualToString:@"label"]); + + // Remove implicit scroll from node 1. + flutter::SemanticsNodeUpdates new_nodes; + flutter::SemanticsNode new_node; + new_node.id = 1; + new_node.rect = SkRect::MakeXYWH(0, 0, 100, 200); + new_node.label = "label"; + new_node.value = "value"; + new_node.hint = "hint"; + new_node.scrollExtentMax = 100.0; + new_node.scrollPosition = 0.0; + new_nodes[1] = new_node; + bridge->UpdateSemantics(/*nodes=*/new_nodes, /*actions=*/actions); + } + XCTAssertTrue([flutterView.subviews count] == 0); +} + +- (void)testAnnouncesRouteChanges { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id mockFlutterView = OCMClassMock([FlutterView class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); + + NSMutableArray*>* accessibility_notifications = + [[NSMutableArray alloc] init]; + auto ios_delegate = std::make_unique(); + ios_delegate->on_PostAccessibilityNotification_ = + [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { + [accessibility_notifications addObject:@{ + @"notification" : @(notification), + @"argument" : argument ? argument : [NSNull null], + }]; + }; + __block auto bridge = + std::make_unique(/*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil, + /*ios_delegate=*/std::move(ios_delegate)); + + flutter::CustomAccessibilityActionUpdates actions; + flutter::SemanticsNodeUpdates nodes; + + flutter::SemanticsNode node1; + node1.id = 1; + node1.label = "node1"; + node1.flags = static_cast(flutter::SemanticsFlags::kScopesRoute); + node1.childrenInTraversalOrder = {2, 3}; + node1.childrenInHitTestOrder = {2, 3}; + nodes[node1.id] = node1; + flutter::SemanticsNode node2; + node2.id = 2; + node2.label = "node2"; + nodes[node2.id] = node2; + flutter::SemanticsNode node3; + node3.id = 3; + node3.flags = static_cast(flutter::SemanticsFlags::kNamesRoute); + node3.label = "node3"; + nodes[node3.id] = node3; + flutter::SemanticsNode root_node; + root_node.id = kRootNodeId; + root_node.flags = static_cast(flutter::SemanticsFlags::kScopesRoute); + root_node.childrenInTraversalOrder = {1}; + root_node.childrenInHitTestOrder = {1}; + nodes[root_node.id] = root_node; + bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); + + XCTAssertEqual([accessibility_notifications count], 1ul); + XCTAssertEqualObjects(accessibility_notifications[0][@"argument"], @"node3"); + XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], + UIAccessibilityScreenChangedNotification); +} + +- (void)testRadioButtonIsNotSwitchButton { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id engine = OCMClassMock([FlutterEngine class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + FlutterView* flutterView = [[FlutterView alloc] initWithDelegate:engine + opaque:YES + enableWideGamut:NO]; + OCMStub([mockFlutterViewController view]).andReturn(flutterView); + auto ios_delegate = std::make_unique(); + __block auto bridge = + std::make_unique(/*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil, + /*ios_delegate=*/std::move(ios_delegate)); + + flutter::CustomAccessibilityActionUpdates actions; + flutter::SemanticsNodeUpdates nodes; + + flutter::SemanticsNode root_node; + root_node.id = kRootNodeId; + root_node.flags = static_cast(flutter::SemanticsFlags::kIsInMutuallyExclusiveGroup) | + static_cast(flutter::SemanticsFlags::kIsEnabled) | + static_cast(flutter::SemanticsFlags::kHasCheckedState) | + static_cast(flutter::SemanticsFlags::kHasEnabledState); + nodes[root_node.id] = root_node; + bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); + + SemanticsObjectContainer* rootContainer = flutterView.accessibilityElements[0]; + FlutterSemanticsObject* rootNode = [rootContainer accessibilityElementAtIndex:0]; + + XCTAssertTrue((rootNode.accessibilityTraits & UIAccessibilityTraitButton) > 0); + XCTAssertNil(rootNode.accessibilityValue); +} + +- (void)testSemanticObjectWithNoAccessibilityFlagNotMarkedAsResponsiveToUserInteraction { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id engine = OCMClassMock([FlutterEngine class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + FlutterView* flutterView = [[FlutterView alloc] initWithDelegate:engine + opaque:YES + enableWideGamut:NO]; + OCMStub([mockFlutterViewController view]).andReturn(flutterView); + auto ios_delegate = std::make_unique(); + __block auto bridge = + std::make_unique(/*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil, + /*ios_delegate=*/std::move(ios_delegate)); + + flutter::CustomAccessibilityActionUpdates actions; + flutter::SemanticsNodeUpdates nodes; + + flutter::SemanticsNode root_node; + root_node.id = kRootNodeId; + + nodes[root_node.id] = root_node; + bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); + + SemanticsObjectContainer* rootContainer = flutterView.accessibilityElements[0]; + FlutterSemanticsObject* rootNode = [rootContainer accessibilityElementAtIndex:0]; + + XCTAssertFalse(rootNode.accessibilityRespondsToUserInteraction); +} + +- (void)testSemanticObjectWithAccessibilityFlagsMarkedAsResponsiveToUserInteraction { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id engine = OCMClassMock([FlutterEngine class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + FlutterView* flutterView = [[FlutterView alloc] initWithDelegate:engine + opaque:YES + enableWideGamut:NO]; + OCMStub([mockFlutterViewController view]).andReturn(flutterView); + auto ios_delegate = std::make_unique(); + __block auto bridge = + std::make_unique(/*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil, + /*ios_delegate=*/std::move(ios_delegate)); + + flutter::CustomAccessibilityActionUpdates actions; + flutter::SemanticsNodeUpdates nodes; + + flutter::SemanticsNode root_node; + root_node.id = kRootNodeId; + root_node.actions = static_cast(flutter::SemanticsAction::kTap); + + nodes[root_node.id] = root_node; + bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); + + SemanticsObjectContainer* rootContainer = flutterView.accessibilityElements[0]; + FlutterSemanticsObject* rootNode = [rootContainer accessibilityElementAtIndex:0]; + + XCTAssertTrue(rootNode.accessibilityRespondsToUserInteraction); +} + +// Regression test for: +// https://github.com/flutter/flutter/issues/158477 +- (void)testLabeledParentAndChildNotInteractive { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/flutterPlatformViewsController, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id engine = OCMClassMock([FlutterEngine class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + FlutterView* flutterView = [[FlutterView alloc] initWithDelegate:engine + opaque:YES + enableWideGamut:NO]; + OCMStub([mockFlutterViewController view]).andReturn(flutterView); + + @autoreleasepool { + auto bridge = std::make_unique( + /*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/flutterPlatformViewsController); + + flutter::SemanticsNodeUpdates nodes; + + flutter::SemanticsNode parent; + parent.id = 0; + parent.rect = SkRect::MakeXYWH(0, 0, 100, 200); + parent.label = "parent_label"; + + flutter::SemanticsNode node; + node.id = 1; + node.rect = SkRect::MakeXYWH(0, 0, 100, 200); + node.label = "child_label"; + + parent.childrenInTraversalOrder.push_back(1); + parent.childrenInHitTestOrder.push_back(1); + nodes[0] = parent; + nodes[1] = node; + flutter::CustomAccessibilityActionUpdates actions; + bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); + + SemanticsObjectContainer* parentContainer = flutterView.accessibilityElements[0]; + FlutterSemanticsObject* parentNode = [parentContainer accessibilityElementAtIndex:0]; + FlutterSemanticsObject* childNode = [parentContainer accessibilityElementAtIndex:1]; + + XCTAssertTrue([parentNode.accessibilityLabel isEqualToString:@"parent_label"]); + XCTAssertTrue([childNode.accessibilityLabel isEqualToString:@"child_label"]); + XCTAssertFalse(parentNode.accessibilityRespondsToUserInteraction); + XCTAssertFalse(childNode.accessibilityRespondsToUserInteraction); + } +} + +- (void)testLayoutChangeWithNonAccessibilityElement { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id mockFlutterView = OCMClassMock([FlutterView class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); + + NSMutableArray*>* accessibility_notifications = + [[NSMutableArray alloc] init]; + auto ios_delegate = std::make_unique(); + ios_delegate->on_PostAccessibilityNotification_ = + [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { + [accessibility_notifications addObject:@{ + @"notification" : @(notification), + @"argument" : argument ? argument : [NSNull null], + }]; + }; + __block auto bridge = + std::make_unique(/*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil, + /*ios_delegate=*/std::move(ios_delegate)); + + flutter::CustomAccessibilityActionUpdates actions; + flutter::SemanticsNodeUpdates nodes; + + flutter::SemanticsNode node1; + node1.id = 1; + node1.label = "node1"; + node1.childrenInTraversalOrder = {2, 3}; + node1.childrenInHitTestOrder = {2, 3}; + nodes[node1.id] = node1; + flutter::SemanticsNode node2; + node2.id = 2; + node2.label = "node2"; + nodes[node2.id] = node2; + flutter::SemanticsNode node3; + node3.id = 3; + node3.label = "node3"; + nodes[node3.id] = node3; + flutter::SemanticsNode root_node; + root_node.id = kRootNodeId; + root_node.label = "root"; + root_node.childrenInTraversalOrder = {1}; + root_node.childrenInHitTestOrder = {1}; + nodes[root_node.id] = root_node; + bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); + + // Simulates the focusing on the node 1. + bridge->AccessibilityObjectDidBecomeFocused(1); + + // In this update, we make node 1 unfocusable and trigger the + // layout change. The accessibility bridge should send layoutchange + // notification with the first focusable node under node 1 + flutter::CustomAccessibilityActionUpdates new_actions; + flutter::SemanticsNodeUpdates new_nodes; + + flutter::SemanticsNode new_node1; + new_node1.id = 1; + new_node1.childrenInTraversalOrder = {2}; + new_node1.childrenInHitTestOrder = {2}; + new_nodes[new_node1.id] = new_node1; + bridge->UpdateSemantics(/*nodes=*/new_nodes, /*actions=*/new_actions); + + XCTAssertEqual([accessibility_notifications count], 1ul); + SemanticsObject* focusObject = accessibility_notifications[0][@"argument"]; + // Since node 1 is no longer focusable (no label), it will focus node 2 instead. + XCTAssertEqual([focusObject uid], 2); + XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], + UIAccessibilityLayoutChangedNotification); +} + +- (void)testLayoutChangeDoesCallNativeAccessibility { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id mockFlutterView = OCMClassMock([FlutterView class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); + + NSMutableArray*>* accessibility_notifications = + [[NSMutableArray alloc] init]; + auto ios_delegate = std::make_unique(); + ios_delegate->on_PostAccessibilityNotification_ = + [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { + [accessibility_notifications addObject:@{ + @"notification" : @(notification), + @"argument" : argument ? argument : [NSNull null], + }]; + }; + __block auto bridge = + std::make_unique(/*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil, + /*ios_delegate=*/std::move(ios_delegate)); + + flutter::CustomAccessibilityActionUpdates actions; + flutter::SemanticsNodeUpdates nodes; + + flutter::SemanticsNode node1; + node1.id = 1; + node1.label = "node1"; + nodes[node1.id] = node1; + flutter::SemanticsNode root_node; + root_node.id = kRootNodeId; + root_node.label = "root"; + root_node.flags = static_cast(flutter::SemanticsFlags::kHasImplicitScrolling); + root_node.childrenInTraversalOrder = {1}; + root_node.childrenInHitTestOrder = {1}; + nodes[root_node.id] = root_node; + bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); + + // Simulates the focusing on the node 0. + bridge->AccessibilityObjectDidBecomeFocused(0); + + // Remove node 1 to trigger a layout change notification + flutter::CustomAccessibilityActionUpdates new_actions; + flutter::SemanticsNodeUpdates new_nodes; + + flutter::SemanticsNode new_root_node; + new_root_node.id = kRootNodeId; + new_root_node.label = "root"; + new_root_node.flags = static_cast(flutter::SemanticsFlags::kHasImplicitScrolling); + new_nodes[new_root_node.id] = new_root_node; + bridge->UpdateSemantics(/*nodes=*/new_nodes, /*actions=*/new_actions); + + XCTAssertEqual([accessibility_notifications count], 1ul); + id focusObject = accessibility_notifications[0][@"argument"]; + + // Make sure the focused item is not specificed when it stays the same. + // See: https://github.com/flutter/flutter/issues/104176 + XCTAssertEqualObjects(focusObject, [NSNull null]); + XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], + UIAccessibilityLayoutChangedNotification); +} + +- (void)testLayoutChangeDoesCallNativeAccessibilityWhenFocusChanged { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id mockFlutterView = OCMClassMock([FlutterView class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); + + NSMutableArray*>* accessibility_notifications = + [[NSMutableArray alloc] init]; + auto ios_delegate = std::make_unique(); + ios_delegate->on_PostAccessibilityNotification_ = + [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { + [accessibility_notifications addObject:@{ + @"notification" : @(notification), + @"argument" : argument ? argument : [NSNull null], + }]; + }; + __block auto bridge = + std::make_unique(/*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil, + /*ios_delegate=*/std::move(ios_delegate)); + + flutter::CustomAccessibilityActionUpdates actions; + flutter::SemanticsNodeUpdates nodes; + + flutter::SemanticsNode node1; + node1.id = 1; + node1.label = "node1"; + nodes[node1.id] = node1; + flutter::SemanticsNode root_node; + root_node.id = kRootNodeId; + root_node.label = "root"; + root_node.flags = static_cast(flutter::SemanticsFlags::kHasImplicitScrolling); + root_node.childrenInTraversalOrder = {1}; + root_node.childrenInHitTestOrder = {1}; + nodes[root_node.id] = root_node; + bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); + + // Simulates the focusing on the node 1. + bridge->AccessibilityObjectDidBecomeFocused(1); + + // Remove node 1 to trigger a layout change notification, and focus should be one root + flutter::CustomAccessibilityActionUpdates new_actions; + flutter::SemanticsNodeUpdates new_nodes; + + flutter::SemanticsNode new_root_node; + new_root_node.id = kRootNodeId; + new_root_node.label = "root"; + new_root_node.flags = static_cast(flutter::SemanticsFlags::kHasImplicitScrolling); + new_nodes[new_root_node.id] = new_root_node; + bridge->UpdateSemantics(/*nodes=*/new_nodes, /*actions=*/new_actions); + + XCTAssertEqual([accessibility_notifications count], 1ul); + SemanticsObject* focusObject2 = accessibility_notifications[0][@"argument"]; + + // Bridge should ask accessibility to focus on root because node 1 is moved from screen. + XCTAssertTrue([focusObject2 isKindOfClass:[FlutterSemanticsScrollView class]]); + XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], + UIAccessibilityLayoutChangedNotification); +} + +- (void)testScrollableSemanticsContainerReturnsCorrectChildren { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id mockFlutterView = OCMClassMock([FlutterView class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); + + OCMExpect([mockFlutterView + setAccessibilityElements:[OCMArg checkWithBlock:^BOOL(NSArray* value) { + if ([value count] != 1) { + return NO; + } + SemanticsObjectContainer* container = value[0]; + SemanticsObject* object = container.semanticsObject; + FlutterScrollableSemanticsObject* scrollable = + (FlutterScrollableSemanticsObject*)object.children[0]; + id nativeScrollable = scrollable.nativeAccessibility; + SemanticsObjectContainer* scrollableContainer = [nativeScrollable accessibilityContainer]; + return [scrollableContainer indexOfAccessibilityElement:nativeScrollable] == 1; + }]]); + auto ios_delegate = std::make_unique(); + __block auto bridge = + std::make_unique(/*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil, + /*ios_delegate=*/std::move(ios_delegate)); + + flutter::CustomAccessibilityActionUpdates actions; + flutter::SemanticsNodeUpdates nodes; + + flutter::SemanticsNode node1; + node1.id = 1; + node1.label = "node1"; + node1.flags = static_cast(flutter::SemanticsFlags::kHasImplicitScrolling); + nodes[node1.id] = node1; + flutter::SemanticsNode root_node; + root_node.id = kRootNodeId; + root_node.label = "root"; + root_node.childrenInTraversalOrder = {1}; + root_node.childrenInHitTestOrder = {1}; + nodes[root_node.id] = root_node; + bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); + OCMVerifyAll(mockFlutterView); +} + +- (void)testAnnouncesRouteChangesAndLayoutChangeInOneUpdate { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id mockFlutterView = OCMClassMock([FlutterView class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); + + NSMutableArray*>* accessibility_notifications = + [[NSMutableArray alloc] init]; + auto ios_delegate = std::make_unique(); + ios_delegate->on_PostAccessibilityNotification_ = + [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { + [accessibility_notifications addObject:@{ + @"notification" : @(notification), + @"argument" : argument ? argument : [NSNull null], + }]; + }; + __block auto bridge = + std::make_unique(/*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil, + /*ios_delegate=*/std::move(ios_delegate)); + + flutter::CustomAccessibilityActionUpdates actions; + flutter::SemanticsNodeUpdates nodes; + + flutter::SemanticsNode node1; + node1.id = 1; + node1.label = "node1"; + node1.flags = static_cast(flutter::SemanticsFlags::kScopesRoute) | + static_cast(flutter::SemanticsFlags::kNamesRoute); + nodes[node1.id] = node1; + flutter::SemanticsNode node3; + node3.id = 3; + node3.label = "node3"; + nodes[node3.id] = node3; + flutter::SemanticsNode root_node; + root_node.id = kRootNodeId; + root_node.label = "root"; + root_node.childrenInTraversalOrder = {1, 3}; + root_node.childrenInHitTestOrder = {1, 3}; + nodes[root_node.id] = root_node; + bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); + + XCTAssertEqual([accessibility_notifications count], 1ul); + XCTAssertEqualObjects(accessibility_notifications[0][@"argument"], @"node1"); + XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], + UIAccessibilityScreenChangedNotification); + + // Simulates the focusing on the node 0. + bridge->AccessibilityObjectDidBecomeFocused(0); + + flutter::SemanticsNodeUpdates new_nodes; + + flutter::SemanticsNode new_node1; + new_node1.id = 1; + new_node1.label = "new_node1"; + new_node1.flags = static_cast(flutter::SemanticsFlags::kScopesRoute) | + static_cast(flutter::SemanticsFlags::kNamesRoute); + new_node1.childrenInTraversalOrder = {2}; + new_node1.childrenInHitTestOrder = {2}; + new_nodes[new_node1.id] = new_node1; + flutter::SemanticsNode new_node2; + new_node2.id = 2; + new_node2.label = "new_node2"; + new_node2.flags = static_cast(flutter::SemanticsFlags::kScopesRoute) | + static_cast(flutter::SemanticsFlags::kNamesRoute); + new_nodes[new_node2.id] = new_node2; + flutter::SemanticsNode new_root_node; + new_root_node.id = kRootNodeId; + new_root_node.label = "root"; + new_root_node.childrenInTraversalOrder = {1}; + new_root_node.childrenInHitTestOrder = {1}; + new_nodes[new_root_node.id] = new_root_node; + bridge->UpdateSemantics(/*nodes=*/new_nodes, /*actions=*/actions); + XCTAssertEqual([accessibility_notifications count], 3ul); + XCTAssertEqualObjects(accessibility_notifications[1][@"argument"], @"new_node2"); + XCTAssertEqual([accessibility_notifications[1][@"notification"] unsignedIntValue], + UIAccessibilityScreenChangedNotification); + SemanticsObject* focusObject = accessibility_notifications[2][@"argument"]; + XCTAssertEqual([focusObject uid], 0); + XCTAssertEqual([accessibility_notifications[2][@"notification"] unsignedIntValue], + UIAccessibilityLayoutChangedNotification); +} + +- (void)testAnnouncesRouteChangesWhenAddAdditionalRoute { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id mockFlutterView = OCMClassMock([FlutterView class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); + + NSMutableArray*>* accessibility_notifications = + [[NSMutableArray alloc] init]; + auto ios_delegate = std::make_unique(); + ios_delegate->on_PostAccessibilityNotification_ = + [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { + [accessibility_notifications addObject:@{ + @"notification" : @(notification), + @"argument" : argument ? argument : [NSNull null], + }]; + }; + __block auto bridge = + std::make_unique(/*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil, + /*ios_delegate=*/std::move(ios_delegate)); + + flutter::CustomAccessibilityActionUpdates actions; + flutter::SemanticsNodeUpdates nodes; + + flutter::SemanticsNode node1; + node1.id = 1; + node1.label = "node1"; + node1.flags = static_cast(flutter::SemanticsFlags::kScopesRoute) | + static_cast(flutter::SemanticsFlags::kNamesRoute); + nodes[node1.id] = node1; + flutter::SemanticsNode root_node; + root_node.id = kRootNodeId; + root_node.flags = static_cast(flutter::SemanticsFlags::kScopesRoute); + root_node.childrenInTraversalOrder = {1}; + root_node.childrenInHitTestOrder = {1}; + nodes[root_node.id] = root_node; + bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); + + XCTAssertEqual([accessibility_notifications count], 1ul); + XCTAssertEqualObjects(accessibility_notifications[0][@"argument"], @"node1"); + XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], + UIAccessibilityScreenChangedNotification); + + flutter::SemanticsNodeUpdates new_nodes; + + flutter::SemanticsNode new_node1; + new_node1.id = 1; + new_node1.label = "new_node1"; + new_node1.flags = static_cast(flutter::SemanticsFlags::kScopesRoute) | + static_cast(flutter::SemanticsFlags::kNamesRoute); + new_node1.childrenInTraversalOrder = {2}; + new_node1.childrenInHitTestOrder = {2}; + new_nodes[new_node1.id] = new_node1; + flutter::SemanticsNode new_node2; + new_node2.id = 2; + new_node2.label = "new_node2"; + new_node2.flags = static_cast(flutter::SemanticsFlags::kScopesRoute) | + static_cast(flutter::SemanticsFlags::kNamesRoute); + new_nodes[new_node2.id] = new_node2; + flutter::SemanticsNode new_root_node; + new_root_node.id = kRootNodeId; + new_root_node.flags = static_cast(flutter::SemanticsFlags::kScopesRoute); + new_root_node.childrenInTraversalOrder = {1}; + new_root_node.childrenInHitTestOrder = {1}; + new_nodes[new_root_node.id] = new_root_node; + bridge->UpdateSemantics(/*nodes=*/new_nodes, /*actions=*/actions); + XCTAssertEqual([accessibility_notifications count], 2ul); + XCTAssertEqualObjects(accessibility_notifications[1][@"argument"], @"new_node2"); + XCTAssertEqual([accessibility_notifications[1][@"notification"] unsignedIntValue], + UIAccessibilityScreenChangedNotification); +} + +- (void)testAnnouncesRouteChangesRemoveRouteInMiddle { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id mockFlutterView = OCMClassMock([FlutterView class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); + + NSMutableArray*>* accessibility_notifications = + [[NSMutableArray alloc] init]; + auto ios_delegate = std::make_unique(); + ios_delegate->on_PostAccessibilityNotification_ = + [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { + [accessibility_notifications addObject:@{ + @"notification" : @(notification), + @"argument" : argument ? argument : [NSNull null], + }]; + }; + __block auto bridge = + std::make_unique(/*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil, + /*ios_delegate=*/std::move(ios_delegate)); + + flutter::CustomAccessibilityActionUpdates actions; + flutter::SemanticsNodeUpdates nodes; + + flutter::SemanticsNode node1; + node1.id = 1; + node1.label = "node1"; + node1.flags = static_cast(flutter::SemanticsFlags::kScopesRoute) | + static_cast(flutter::SemanticsFlags::kNamesRoute); + node1.childrenInTraversalOrder = {2}; + node1.childrenInHitTestOrder = {2}; + nodes[node1.id] = node1; + flutter::SemanticsNode node2; + node2.id = 2; + node2.label = "node2"; + node2.flags = static_cast(flutter::SemanticsFlags::kScopesRoute) | + static_cast(flutter::SemanticsFlags::kNamesRoute); + nodes[node2.id] = node2; + flutter::SemanticsNode root_node; + root_node.id = kRootNodeId; + root_node.flags = static_cast(flutter::SemanticsFlags::kScopesRoute); + root_node.childrenInTraversalOrder = {1}; + root_node.childrenInHitTestOrder = {1}; + nodes[root_node.id] = root_node; + bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); + + XCTAssertEqual([accessibility_notifications count], 1ul); + XCTAssertEqualObjects(accessibility_notifications[0][@"argument"], @"node2"); + XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], + UIAccessibilityScreenChangedNotification); + + flutter::SemanticsNodeUpdates new_nodes; + + flutter::SemanticsNode new_node1; + new_node1.id = 1; + new_node1.label = "new_node1"; + new_node1.childrenInTraversalOrder = {2}; + new_node1.childrenInHitTestOrder = {2}; + new_nodes[new_node1.id] = new_node1; + flutter::SemanticsNode new_node2; + new_node2.id = 2; + new_node2.label = "new_node2"; + new_node2.flags = static_cast(flutter::SemanticsFlags::kScopesRoute) | + static_cast(flutter::SemanticsFlags::kNamesRoute); + new_nodes[new_node2.id] = new_node2; + flutter::SemanticsNode new_root_node; + new_root_node.id = kRootNodeId; + new_root_node.flags = static_cast(flutter::SemanticsFlags::kScopesRoute); + new_root_node.childrenInTraversalOrder = {1}; + new_root_node.childrenInHitTestOrder = {1}; + new_nodes[new_root_node.id] = new_root_node; + bridge->UpdateSemantics(/*nodes=*/new_nodes, /*actions=*/actions); + XCTAssertEqual([accessibility_notifications count], 2ul); + XCTAssertEqualObjects(accessibility_notifications[1][@"argument"], @"new_node2"); + XCTAssertEqual([accessibility_notifications[1][@"notification"] unsignedIntValue], + UIAccessibilityScreenChangedNotification); +} + +- (void)testHandleEvent { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id mockFlutterView = OCMClassMock([FlutterView class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); + + NSMutableArray*>* accessibility_notifications = + [[NSMutableArray alloc] init]; + auto ios_delegate = std::make_unique(); + ios_delegate->on_PostAccessibilityNotification_ = + [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { + [accessibility_notifications addObject:@{ + @"notification" : @(notification), + @"argument" : argument ? argument : [NSNull null], + }]; + }; + __block auto bridge = + std::make_unique(/*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil, + /*ios_delegate=*/std::move(ios_delegate)); + + NSDictionary* annotatedEvent = @{@"type" : @"focus", @"nodeId" : @123}; + + bridge->HandleEvent(annotatedEvent); + + XCTAssertEqual([accessibility_notifications count], 1ul); + XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], + UIAccessibilityLayoutChangedNotification); +} + +- (void)testAccessibilityObjectDidBecomeFocused { + flutter::MockDelegate mock_delegate; + auto thread = std::make_unique("AccessibilityBridgeTest"); + auto thread_task_runner = thread->GetTaskRunner(); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + id messenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + id engine = OCMClassMock([FlutterEngine class]); + id flutterViewController = OCMClassMock([FlutterViewController class]); + + OCMStub([flutterViewController engine]).andReturn(engine); + OCMStub([engine binaryMessenger]).andReturn(messenger); + FlutterBinaryMessengerConnection connection = 123; + OCMStub([messenger setMessageHandlerOnChannel:@"flutter/accessibility" + binaryMessageHandler:[OCMArg any]]) + .andReturn(connection); + + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + fml::AutoResetWaitableEvent latch; + thread_task_runner->PostTask([&] { + platform_view->SetOwnerViewController(flutterViewController); + auto bridge = + std::make_unique(/*view=*/nil, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil); + XCTAssertTrue(bridge.get()); + OCMVerify([messenger setMessageHandlerOnChannel:@"flutter/accessibility" + binaryMessageHandler:[OCMArg isNotNil]]); + + bridge->AccessibilityObjectDidBecomeFocused(123); + + NSDictionary* annotatedEvent = @{@"type" : @"didGainFocus", @"nodeId" : @123}; + NSData* encodedMessage = [[FlutterStandardMessageCodec sharedInstance] encode:annotatedEvent]; + + OCMVerify([messenger sendOnChannel:@"flutter/accessibility" message:encodedMessage]); + latch.Signal(); + }); + latch.Wait(); + + [engine stopMocking]; +} + +- (void)testAnnouncesRouteChangesWhenNoNamesRoute { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id mockFlutterView = OCMClassMock([FlutterView class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); + + NSMutableArray*>* accessibility_notifications = + [[NSMutableArray alloc] init]; + auto ios_delegate = std::make_unique(); + ios_delegate->on_PostAccessibilityNotification_ = + [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { + [accessibility_notifications addObject:@{ + @"notification" : @(notification), + @"argument" : argument ? argument : [NSNull null], + }]; + }; + __block auto bridge = + std::make_unique(/*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil, + /*ios_delegate=*/std::move(ios_delegate)); + + flutter::CustomAccessibilityActionUpdates actions; + flutter::SemanticsNodeUpdates nodes; + + flutter::SemanticsNode node1; + node1.id = 1; + node1.label = "node1"; + node1.flags = static_cast(flutter::SemanticsFlags::kScopesRoute) | + static_cast(flutter::SemanticsFlags::kNamesRoute); + node1.childrenInTraversalOrder = {2, 3}; + node1.childrenInHitTestOrder = {2, 3}; + nodes[node1.id] = node1; + flutter::SemanticsNode node2; + node2.id = 2; + node2.label = "node2"; + nodes[node2.id] = node2; + flutter::SemanticsNode node3; + node3.id = 3; + node3.label = "node3"; + nodes[node3.id] = node3; + flutter::SemanticsNode root_node; + root_node.id = kRootNodeId; + root_node.childrenInTraversalOrder = {1}; + root_node.childrenInHitTestOrder = {1}; + nodes[root_node.id] = root_node; + bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); + + // Notification should focus first focusable node, which is node1. + XCTAssertEqual([accessibility_notifications count], 1ul); + id focusObject = accessibility_notifications[0][@"argument"]; + XCTAssertTrue([focusObject isKindOfClass:[NSString class]]); + XCTAssertEqualObjects(focusObject, @"node1"); + XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], + UIAccessibilityScreenChangedNotification); +} + +- (void)testAnnouncesLayoutChangeWithNilIfLastFocusIsRemoved { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + id mockFlutterView = OCMClassMock([FlutterView class]); + OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); + + NSMutableArray*>* accessibility_notifications = + [[NSMutableArray alloc] init]; + auto ios_delegate = std::make_unique(); + ios_delegate->on_PostAccessibilityNotification_ = + [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { + [accessibility_notifications addObject:@{ + @"notification" : @(notification), + @"argument" : argument ? argument : [NSNull null], + }]; + }; + __block auto bridge = + std::make_unique(/*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil, + /*ios_delegate=*/std::move(ios_delegate)); + + flutter::CustomAccessibilityActionUpdates actions; + flutter::SemanticsNodeUpdates first_update; + + flutter::SemanticsNode route_node; + route_node.id = 1; + route_node.label = "route"; + first_update[route_node.id] = route_node; + flutter::SemanticsNode root_node; + root_node.id = kRootNodeId; + root_node.label = "root"; + root_node.childrenInTraversalOrder = {1}; + root_node.childrenInHitTestOrder = {1}; + first_update[root_node.id] = root_node; + bridge->UpdateSemantics(/*nodes=*/first_update, /*actions=*/actions); + + XCTAssertEqual([accessibility_notifications count], 0ul); + // Simulates the focusing on the node 1. + bridge->AccessibilityObjectDidBecomeFocused(1); + + flutter::SemanticsNodeUpdates second_update; + // Simulates the removal of the node 1 + flutter::SemanticsNode new_root_node; + new_root_node.id = kRootNodeId; + new_root_node.label = "root"; + second_update[root_node.id] = new_root_node; + bridge->UpdateSemantics(/*nodes=*/second_update, /*actions=*/actions); + SemanticsObject* focusObject = accessibility_notifications[0][@"argument"]; + // The node 1 was removed, so the bridge will set the focus object to root. + XCTAssertEqual([focusObject uid], 0); + XCTAssertEqualObjects([focusObject accessibilityLabel], @"root"); + XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], + UIAccessibilityLayoutChangedNotification); +} + +- (void)testAnnouncesLayoutChangeWithTheSameItemFocused { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + id mockFlutterView = OCMClassMock([FlutterView class]); + OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); + + NSMutableArray*>* accessibility_notifications = + [[NSMutableArray alloc] init]; + auto ios_delegate = std::make_unique(); + ios_delegate->on_PostAccessibilityNotification_ = + [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { + [accessibility_notifications addObject:@{ + @"notification" : @(notification), + @"argument" : argument ? argument : [NSNull null], + }]; + }; + __block auto bridge = + std::make_unique(/*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil, + /*ios_delegate=*/std::move(ios_delegate)); + + flutter::CustomAccessibilityActionUpdates actions; + flutter::SemanticsNodeUpdates first_update; + + flutter::SemanticsNode node_one; + node_one.id = 1; + node_one.label = "route1"; + first_update[node_one.id] = node_one; + flutter::SemanticsNode node_two; + node_two.id = 2; + node_two.label = "route2"; + first_update[node_two.id] = node_two; + flutter::SemanticsNode root_node; + root_node.id = kRootNodeId; + root_node.label = "root"; + root_node.childrenInTraversalOrder = {1, 2}; + root_node.childrenInHitTestOrder = {1, 2}; + first_update[root_node.id] = root_node; + bridge->UpdateSemantics(/*nodes=*/first_update, /*actions=*/actions); + + XCTAssertEqual([accessibility_notifications count], 0ul); + // Simulates the focusing on the node 1. + bridge->AccessibilityObjectDidBecomeFocused(1); + + flutter::SemanticsNodeUpdates second_update; + // Simulates the removal of the node 2. + flutter::SemanticsNode new_root_node; + new_root_node.id = kRootNodeId; + new_root_node.label = "root"; + new_root_node.childrenInTraversalOrder = {1}; + new_root_node.childrenInHitTestOrder = {1}; + second_update[root_node.id] = new_root_node; + bridge->UpdateSemantics(/*nodes=*/second_update, /*actions=*/actions); + id focusObject = accessibility_notifications[0][@"argument"]; + // Since we have focused on the node 1 right before the layout changed, the bridge should not ask + // to refocus again on the same node. + XCTAssertEqualObjects(focusObject, [NSNull null]); + XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], + UIAccessibilityLayoutChangedNotification); +} + +- (void)testAnnouncesLayoutChangeWhenFocusMovedOutside { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + id mockFlutterView = OCMClassMock([FlutterView class]); + OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); + + NSMutableArray*>* accessibility_notifications = + [[NSMutableArray alloc] init]; + auto ios_delegate = std::make_unique(); + ios_delegate->on_PostAccessibilityNotification_ = + [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { + [accessibility_notifications addObject:@{ + @"notification" : @(notification), + @"argument" : argument ? argument : [NSNull null], + }]; + }; + __block auto bridge = + std::make_unique(/*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil, + /*ios_delegate=*/std::move(ios_delegate)); + + flutter::CustomAccessibilityActionUpdates actions; + flutter::SemanticsNodeUpdates first_update; + + flutter::SemanticsNode node_one; + node_one.id = 1; + node_one.label = "route1"; + first_update[node_one.id] = node_one; + flutter::SemanticsNode node_two; + node_two.id = 2; + node_two.label = "route2"; + first_update[node_two.id] = node_two; + flutter::SemanticsNode root_node; + root_node.id = kRootNodeId; + root_node.label = "root"; + root_node.childrenInTraversalOrder = {1, 2}; + root_node.childrenInHitTestOrder = {1, 2}; + first_update[root_node.id] = root_node; + bridge->UpdateSemantics(/*nodes=*/first_update, /*actions=*/actions); + + XCTAssertEqual([accessibility_notifications count], 0ul); + // Simulates the focusing on the node 1. + bridge->AccessibilityObjectDidBecomeFocused(1); + // Simulates that the focus move outside of flutter. + bridge->AccessibilityObjectDidLoseFocus(1); + + flutter::SemanticsNodeUpdates second_update; + // Simulates the removal of the node 2. + flutter::SemanticsNode new_root_node; + new_root_node.id = kRootNodeId; + new_root_node.label = "root"; + new_root_node.childrenInTraversalOrder = {1}; + new_root_node.childrenInHitTestOrder = {1}; + second_update[root_node.id] = new_root_node; + bridge->UpdateSemantics(/*nodes=*/second_update, /*actions=*/actions); + NSNull* focusObject = accessibility_notifications[0][@"argument"]; + // Since the focus is moved outside of the app right before the layout + // changed, the bridge should not try to refocus anything . + XCTAssertEqual(focusObject, [NSNull null]); + XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], + UIAccessibilityLayoutChangedNotification); +} + +- (void)testAnnouncesScrollChangeWithLastFocused { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + id mockFlutterView = OCMClassMock([FlutterView class]); + OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); + + NSMutableArray*>* accessibility_notifications = + [[NSMutableArray alloc] init]; + auto ios_delegate = std::make_unique(); + ios_delegate->on_PostAccessibilityNotification_ = + [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { + [accessibility_notifications addObject:@{ + @"notification" : @(notification), + @"argument" : argument ? argument : [NSNull null], + }]; + }; + __block auto bridge = + std::make_unique(/*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil, + /*ios_delegate=*/std::move(ios_delegate)); + + flutter::CustomAccessibilityActionUpdates actions; + flutter::SemanticsNodeUpdates first_update; + + flutter::SemanticsNode node_one; + node_one.id = 1; + node_one.label = "route1"; + node_one.scrollPosition = 0.0; + first_update[node_one.id] = node_one; + flutter::SemanticsNode root_node; + root_node.id = kRootNodeId; + root_node.label = "root"; + root_node.childrenInTraversalOrder = {1}; + root_node.childrenInHitTestOrder = {1}; + first_update[root_node.id] = root_node; + bridge->UpdateSemantics(/*nodes=*/first_update, /*actions=*/actions); + + // The first update will trigger a scroll announcement, but we are not interested in it. + [accessibility_notifications removeAllObjects]; + + // Simulates the focusing on the node 1. + bridge->AccessibilityObjectDidBecomeFocused(1); + + flutter::SemanticsNodeUpdates second_update; + // Simulates the scrolling on the node 1. + flutter::SemanticsNode new_node_one; + new_node_one.id = 1; + new_node_one.label = "route1"; + new_node_one.scrollPosition = 1.0; + second_update[new_node_one.id] = new_node_one; + bridge->UpdateSemantics(/*nodes=*/second_update, /*actions=*/actions); + SemanticsObject* focusObject = accessibility_notifications[0][@"argument"]; + // Since we have focused on the node 1 right before the scrolling, the bridge should refocus the + // node 1. + XCTAssertEqual([focusObject uid], 1); + XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], + UIAccessibilityPageScrolledNotification); +} + +- (void)testAnnouncesScrollChangeDoesCallNativeAccessibility { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + id mockFlutterView = OCMClassMock([FlutterView class]); + OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); + + NSMutableArray*>* accessibility_notifications = + [[NSMutableArray alloc] init]; + auto ios_delegate = std::make_unique(); + ios_delegate->on_PostAccessibilityNotification_ = + [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { + [accessibility_notifications addObject:@{ + @"notification" : @(notification), + @"argument" : argument ? argument : [NSNull null], + }]; + }; + __block auto bridge = + std::make_unique(/*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil, + /*ios_delegate=*/std::move(ios_delegate)); + + flutter::CustomAccessibilityActionUpdates actions; + flutter::SemanticsNodeUpdates first_update; + + flutter::SemanticsNode node_one; + node_one.id = 1; + node_one.label = "route1"; + node_one.flags = static_cast(flutter::SemanticsFlags::kHasImplicitScrolling); + node_one.scrollPosition = 0.0; + first_update[node_one.id] = node_one; + flutter::SemanticsNode root_node; + root_node.id = kRootNodeId; + root_node.label = "root"; + root_node.childrenInTraversalOrder = {1}; + root_node.childrenInHitTestOrder = {1}; + first_update[root_node.id] = root_node; + bridge->UpdateSemantics(/*nodes=*/first_update, /*actions=*/actions); + + // The first update will trigger a scroll announcement, but we are not interested in it. + [accessibility_notifications removeAllObjects]; + + // Simulates the focusing on the node 1. + bridge->AccessibilityObjectDidBecomeFocused(1); + + flutter::SemanticsNodeUpdates second_update; + // Simulates the scrolling on the node 1. + flutter::SemanticsNode new_node_one; + new_node_one.id = 1; + new_node_one.label = "route1"; + new_node_one.flags = static_cast(flutter::SemanticsFlags::kHasImplicitScrolling); + new_node_one.scrollPosition = 1.0; + second_update[new_node_one.id] = new_node_one; + bridge->UpdateSemantics(/*nodes=*/second_update, /*actions=*/actions); + SemanticsObject* focusObject = accessibility_notifications[0][@"argument"]; + // Make sure refocus event is sent with the nativeAccessibility of node_one + // which is a FlutterSemanticsScrollView. + XCTAssertTrue([focusObject isKindOfClass:[FlutterSemanticsScrollView class]]); + XCTAssertEqual([accessibility_notifications[0][@"notification"] unsignedIntValue], + UIAccessibilityPageScrolledNotification); +} + +- (void)testAnnouncesIgnoresRouteChangesWhenModal { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id mockFlutterView = OCMClassMock([FlutterView class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); + std::string label = "some label"; + + NSMutableArray*>* accessibility_notifications = + [[NSMutableArray alloc] init]; + auto ios_delegate = std::make_unique(); + ios_delegate->on_PostAccessibilityNotification_ = + [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { + [accessibility_notifications addObject:@{ + @"notification" : @(notification), + @"argument" : argument ? argument : [NSNull null], + }]; + }; + ios_delegate->result_IsFlutterViewControllerPresentingModalViewController_ = true; + __block auto bridge = + std::make_unique(/*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil, + /*ios_delegate=*/std::move(ios_delegate)); + + flutter::CustomAccessibilityActionUpdates actions; + flutter::SemanticsNodeUpdates nodes; + + flutter::SemanticsNode route_node; + route_node.id = 1; + route_node.flags = static_cast(flutter::SemanticsFlags::kScopesRoute) | + static_cast(flutter::SemanticsFlags::kNamesRoute); + route_node.label = "route"; + nodes[route_node.id] = route_node; + flutter::SemanticsNode root_node; + root_node.id = kRootNodeId; + root_node.label = label; + root_node.childrenInTraversalOrder = {1}; + root_node.childrenInHitTestOrder = {1}; + nodes[root_node.id] = root_node; + bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); + + XCTAssertEqual([accessibility_notifications count], 0ul); +} + +- (void)testAnnouncesIgnoresLayoutChangeWhenModal { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id mockFlutterView = OCMClassMock([FlutterView class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); + + NSMutableArray*>* accessibility_notifications = + [[NSMutableArray alloc] init]; + auto ios_delegate = std::make_unique(); + ios_delegate->on_PostAccessibilityNotification_ = + [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { + [accessibility_notifications addObject:@{ + @"notification" : @(notification), + @"argument" : argument ? argument : [NSNull null], + }]; + }; + ios_delegate->result_IsFlutterViewControllerPresentingModalViewController_ = true; + __block auto bridge = + std::make_unique(/*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil, + /*ios_delegate=*/std::move(ios_delegate)); + + flutter::CustomAccessibilityActionUpdates actions; + flutter::SemanticsNodeUpdates nodes; + + flutter::SemanticsNode child_node; + child_node.id = 1; + child_node.label = "child_node"; + nodes[child_node.id] = child_node; + flutter::SemanticsNode root_node; + root_node.id = kRootNodeId; + root_node.label = "root"; + root_node.childrenInTraversalOrder = {1}; + root_node.childrenInHitTestOrder = {1}; + nodes[root_node.id] = root_node; + bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); + + // Removes child_node to simulate a layout change. + flutter::SemanticsNodeUpdates new_nodes; + flutter::SemanticsNode new_root_node; + new_root_node.id = kRootNodeId; + new_root_node.label = "root"; + new_nodes[new_root_node.id] = new_root_node; + bridge->UpdateSemantics(/*nodes=*/new_nodes, /*actions=*/actions); + + XCTAssertEqual([accessibility_notifications count], 0ul); +} + +- (void)testAnnouncesIgnoresScrollChangeWhenModal { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id mockFlutterView = OCMClassMock([FlutterView class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); + + NSMutableArray*>* accessibility_notifications = + [[NSMutableArray alloc] init]; + auto ios_delegate = std::make_unique(); + ios_delegate->on_PostAccessibilityNotification_ = + [accessibility_notifications](UIAccessibilityNotifications notification, id argument) { + [accessibility_notifications addObject:@{ + @"notification" : @(notification), + @"argument" : argument ? argument : [NSNull null], + }]; + }; + ios_delegate->result_IsFlutterViewControllerPresentingModalViewController_ = true; + __block auto bridge = + std::make_unique(/*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil, + /*ios_delegate=*/std::move(ios_delegate)); + + flutter::CustomAccessibilityActionUpdates actions; + flutter::SemanticsNodeUpdates nodes; + + flutter::SemanticsNode root_node; + root_node.id = kRootNodeId; + root_node.label = "root"; + root_node.scrollPosition = 1; + nodes[root_node.id] = root_node; + bridge->UpdateSemantics(/*nodes=*/nodes, /*actions=*/actions); + + // Removes child_node to simulate a layout change. + flutter::SemanticsNodeUpdates new_nodes; + flutter::SemanticsNode new_root_node; + new_root_node.id = kRootNodeId; + new_root_node.label = "root"; + new_root_node.scrollPosition = 2; + new_nodes[new_root_node.id] = new_root_node; + bridge->UpdateSemantics(/*nodes=*/new_nodes, /*actions=*/actions); + + XCTAssertEqual([accessibility_notifications count], 0ul); +} + +- (void)testAccessibilityMessageAfterDeletion { + flutter::MockDelegate mock_delegate; + auto thread = std::make_unique("AccessibilityBridgeTest"); + auto thread_task_runner = thread->GetTaskRunner(); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + id messenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + id engine = OCMClassMock([FlutterEngine class]); + id flutterViewController = OCMClassMock([FlutterViewController class]); + + OCMStub([flutterViewController engine]).andReturn(engine); + OCMStub([engine binaryMessenger]).andReturn(messenger); + FlutterBinaryMessengerConnection connection = 123; + OCMStub([messenger setMessageHandlerOnChannel:@"flutter/accessibility" + binaryMessageHandler:[OCMArg any]]) + .andReturn(connection); + + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + fml::AutoResetWaitableEvent latch; + thread_task_runner->PostTask([&] { + platform_view->SetOwnerViewController(flutterViewController); + auto bridge = + std::make_unique(/*view=*/nil, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil); + XCTAssertTrue(bridge.get()); + OCMVerify([messenger setMessageHandlerOnChannel:@"flutter/accessibility" + binaryMessageHandler:[OCMArg isNotNil]]); + bridge.reset(); + latch.Signal(); + }); + latch.Wait(); + OCMVerify([messenger cleanUpConnection:connection]); + [engine stopMocking]; +} + +- (void)testFlutterSemanticsScrollViewManagedObjectLifecycleCorrectly { + flutter::MockDelegate mock_delegate; + auto thread_task_runner = CreateNewThread("AccessibilityBridgeTest"); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + id mockFlutterView = OCMClassMock([FlutterView class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + OCMStub([mockFlutterViewController view]).andReturn(mockFlutterView); + + auto ios_delegate = std::make_unique(); + __block auto bridge = + std::make_unique(/*view_controller=*/mockFlutterViewController, + /*platform_view=*/platform_view.get(), + /*platform_views_controller=*/nil, + /*ios_delegate=*/std::move(ios_delegate)); + + FlutterSemanticsScrollView* flutterSemanticsScrollView; + @autoreleasepool { + FlutterScrollableSemanticsObject* semanticsObject = + [[FlutterScrollableSemanticsObject alloc] initWithBridge:bridge->GetWeakPtr() uid:1234]; + + flutterSemanticsScrollView = semanticsObject.nativeAccessibility; + } + XCTAssertTrue(flutterSemanticsScrollView); + // If the _semanticsObject is not a weak pointer this (or any other method on + // flutterSemanticsScrollView) will cause an EXC_BAD_ACCESS. + XCTAssertFalse([flutterSemanticsScrollView isAccessibilityElement]); +} + +- (void)testPlatformViewDestructorDoesNotCallSemanticsAPIs { + class TestDelegate : public flutter::MockDelegate { + public: + void OnPlatformViewSetSemanticsEnabled(bool enabled) override { set_semantics_enabled_calls++; } + int set_semantics_enabled_calls = 0; + }; + + TestDelegate test_delegate; + auto thread = std::make_unique("AccessibilityBridgeTest"); + auto thread_task_runner = thread->GetTaskRunner(); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + + fml::AutoResetWaitableEvent latch; + thread_task_runner->PostTask([&] { + auto platform_view = std::make_unique( + /*delegate=*/test_delegate, + /*rendering_api=*/test_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + FlutterPlatformViewsController* flutterPlatformViewsController = + [[FlutterPlatformViewsController alloc] init]; + flutterPlatformViewsController.taskRunner = thread_task_runner; + + OCMStub([mockFlutterViewController platformViewsController]) + .andReturn(flutterPlatformViewsController); + platform_view->SetOwnerViewController(mockFlutterViewController); + + platform_view->SetSemanticsEnabled(true); + XCTAssertNotEqual(test_delegate.set_semantics_enabled_calls, 0); + + // Deleting PlatformViewIOS should not call OnPlatformViewSetSemanticsEnabled + test_delegate.set_semantics_enabled_calls = 0; + platform_view.reset(); + XCTAssertEqual(test_delegate.set_semantics_enabled_calls, 0); + + latch.Signal(); + }); + latch.Wait(); +} + +- (void)testResetsAccessibilityElementsOnHotRestart { + flutter::MockDelegate mock_delegate; + auto thread = std::make_unique("AccessibilityBridgeTest"); + auto thread_task_runner = thread->GetTaskRunner(); + flutter::TaskRunners runners(/*label=*/self.name.UTF8String, + /*platform=*/thread_task_runner, + /*raster=*/thread_task_runner, + /*ui=*/thread_task_runner, + /*io=*/thread_task_runner); + id mockFlutterView = OCMClassMock([FlutterView class]); + id mockFlutterViewController = OCMClassMock([FlutterViewController class]); + OCMStub([mockFlutterViewController viewIfLoaded]).andReturn(mockFlutterView); + + fml::AutoResetWaitableEvent latch; + thread_task_runner->PostTask([&] { + auto platform_view = std::make_unique( + /*delegate=*/mock_delegate, + /*rendering_api=*/mock_delegate.settings_.enable_impeller + ? flutter::IOSRenderingAPI::kMetal + : flutter::IOSRenderingAPI::kSoftware, + /*platform_views_controller=*/nil, + /*task_runners=*/runners, + /*worker_task_runner=*/nil, + /*is_gpu_disabled_sync_switch=*/std::make_shared()); + + platform_view->SetOwnerViewController(mockFlutterViewController); + platform_view->SetSemanticsEnabled(true); + + OCMExpect([mockFlutterView setAccessibilityElements:[OCMArg isNil]]); + platform_view->OnPreEngineRestart(); + OCMVerifyAll(mockFlutterView); + + latch.Signal(); + }); + latch.Wait(); +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/availability_version_check_test.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/availability_version_check_test.mm new file mode 100644 index 0000000000000000000000000000000000000000..c843893c216e811b520012f72c9821385904d102 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/availability_version_check_test.mm @@ -0,0 +1,26 @@ +// 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. + +#import + +#import +#import + +#import "flutter/shell/platform/darwin/common/availability_version_check.h" + +@interface AvailabilityVersionCheckTest : XCTestCase +@end + +@implementation AvailabilityVersionCheckTest + +- (void)testSimple { + auto maybe_product_version = flutter::ProductVersionFromSystemVersionPList(); + XCTAssertTrue(maybe_product_version.has_value()); + if (maybe_product_version.has_value()) { + auto product_version = maybe_product_version.value(); + XCTAssertTrue(product_version > std::make_tuple(0, 0, 0)); + } +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/connection_collection.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/connection_collection.h new file mode 100644 index 0000000000000000000000000000000000000000..1269edad17a30e9009f36c07d5b05a8e8b7695e5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/connection_collection.h @@ -0,0 +1,36 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_CONNECTION_COLLECTION_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_CONNECTION_COLLECTION_H_ + +#include +#include +#include + +namespace flutter { + +/// Maintains a current integer assigned to a name (connections). +class ConnectionCollection { + public: + typedef int64_t Connection; + static const Connection kInvalidConnection = 0; + + Connection AquireConnection(const std::string& name); + ///\returns the name of the channel when cleanup is successful, otherwise + /// the empty string. + std::string CleanupConnection(Connection connection); + + static bool IsValidConnection(Connection connection); + + static Connection MakeErrorConnection(int errCode); + + private: + std::map connections_; + Connection counter_ = 0; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_CONNECTION_COLLECTION_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/connection_collection.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/connection_collection.mm new file mode 100644 index 0000000000000000000000000000000000000000..b52eb17f23dbb2473975e5f76cb32f7264830451 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/connection_collection.mm @@ -0,0 +1,46 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/connection_collection.h" + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" + +FLUTTER_ASSERT_ARC + +namespace flutter { +ConnectionCollection::Connection ConnectionCollection::AquireConnection(const std::string& name) { + Connection nextConnection = ++counter_; + connections_[name] = nextConnection; + return nextConnection; +} + +std::string ConnectionCollection::CleanupConnection(ConnectionCollection::Connection connection) { + if (connection > 0) { + std::string channel; + for (auto& keyValue : connections_) { + if (keyValue.second == connection) { + channel = keyValue.first; + break; + } + } + if (channel.length() > 0) { + connections_.erase(channel); + return channel; + } + } + return ""; +} + +bool ConnectionCollection::IsValidConnection(ConnectionCollection::Connection connection) { + return connection > 0; +} + +ConnectionCollection::Connection ConnectionCollection::MakeErrorConnection(int errCode) { + if (errCode < 0) { + return -1 * errCode; + } + return errCode; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/connection_collection_test.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/connection_collection_test.mm new file mode 100644 index 0000000000000000000000000000000000000000..5672b9f127f19c98e07ea1ff8cb8ecf86d07c897 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/connection_collection_test.mm @@ -0,0 +1,22 @@ +// 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. + +#import +#import + +#import "flutter/shell/platform/darwin/ios/framework/Source/connection_collection.h" + +@interface ConnectionCollectionTest : XCTestCase +@end + +@implementation ConnectionCollectionTest + +- (void)testSimple { + auto connections = std::make_unique(); + flutter::ConnectionCollection::Connection connection = connections->AquireConnection("foo"); + XCTAssertTrue(connections->CleanupConnection(connection) == "foo"); + XCTAssertTrue(connections->CleanupConnection(connection).empty()); +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/overlay_layer_pool.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/overlay_layer_pool.h new file mode 100644 index 0000000000000000000000000000000000000000..8e734e3ec781ab60556bb910b7268a4c35dfb51a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/overlay_layer_pool.h @@ -0,0 +1,94 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_OVERLAY_LAYER_POOL_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_OVERLAY_LAYER_POOL_H_ + +#include +#include + +#import + +#include "flow/surface.h" + +#import "flutter/shell/platform/darwin/ios/ios_context.h" + +namespace flutter { + +class IOSSurface; + +/// @brief State holder for a Flutter overlay layer. +struct OverlayLayer { + OverlayLayer(UIView* overlay_view, + UIView* overlay_view_wrapper, + std::unique_ptr ios_surface, + std::unique_ptr surface); + + ~OverlayLayer() = default; + + UIView* overlay_view; + UIView* overlay_view_wrapper; + std::unique_ptr ios_surface; + std::unique_ptr surface; + + // Whether a frame for this layer was submitted. + bool did_submit_last_frame; + + void UpdateViewState(UIView* flutter_view, SkRect rect, int64_t view_id, int64_t overlay_id); +}; + +/// @brief Storage for Overlay layers across frames. +/// +/// Note: this class does not synchronize access to its layers or any layer removal. As it +/// is currently used, layers must be created on the platform thread but other methods of +/// it are called on the raster thread. This is safe as overlay layers are only ever added +/// while the raster thread is latched. +class OverlayLayerPool { + public: + OverlayLayerPool() = default; + + ~OverlayLayerPool() = default; + + /// @brief Gets a layer from the pool if available. + /// + /// The layer is marked as used until [RecycleLayers] is called. + std::shared_ptr GetNextLayer(); + + /// @brief Create a new overlay layer. + /// + /// This method can only be called on the Platform thread. + void CreateLayer(const std::shared_ptr& ios_context, MTLPixelFormat pixel_format); + + /// @brief Removes unused layers from the pool. Returns the unused layers. + std::vector> RemoveUnusedLayers(); + + /// @brief Marks the layers in the pool as available for reuse. + void RecycleLayers(); + + /// @brief The count of layers currently in the pool. + size_t size() const; + + private: + OverlayLayerPool(const OverlayLayerPool&) = delete; + OverlayLayerPool& operator=(const OverlayLayerPool&) = delete; + + // The index of the entry in the layers_ vector that determines the beginning of the unused + // layers. For example, consider the following vector: + // _____ + // | 0 | + /// |---| + /// | 1 | <-- available_layer_index_ + /// |---| + /// | 2 | + /// |---| + /// + /// This indicates that entries starting from 1 can be reused meanwhile the entry at position 0 + /// cannot be reused. + size_t available_layer_index_ = 0; + std::vector> layers_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_OVERLAY_LAYER_POOL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/overlay_layer_pool.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/overlay_layer_pool.mm new file mode 100644 index 0000000000000000000000000000000000000000..a413ab49e7d6420775dafb464dd31d5b4073bf4b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/overlay_layer_pool.mm @@ -0,0 +1,120 @@ +// 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/shell/platform/darwin/ios/framework/Source/overlay_layer_pool.h" + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterOverlayView.h" +#import "flutter/shell/platform/darwin/ios/ios_surface.h" + +namespace flutter { + +OverlayLayer::OverlayLayer(UIView* overlay_view, + UIView* overlay_view_wrapper, + std::unique_ptr ios_surface, + std::unique_ptr surface) + : overlay_view(overlay_view), + overlay_view_wrapper(overlay_view_wrapper), + ios_surface(std::move(ios_surface)), + surface(std::move(surface)){}; + +void OverlayLayer::UpdateViewState(UIView* flutter_view, + SkRect rect, + int64_t view_id, + int64_t overlay_id) { + auto screenScale = [UIScreen mainScreen].scale; + // Set the size of the overlay view wrapper. + // This wrapper view masks the overlay view. + overlay_view_wrapper.frame = CGRectMake(rect.x() / screenScale, rect.y() / screenScale, + rect.width() / screenScale, rect.height() / screenScale); + // Set a unique view identifier, so the overlay_view_wrapper can be identified in XCUITests. + overlay_view_wrapper.accessibilityIdentifier = + [NSString stringWithFormat:@"platform_view[%lld].overlay[%lld]", view_id, overlay_id]; + + // Set the size of the overlay view. + // This size is equal to the device screen size. + overlay_view.frame = [flutter_view convertRect:flutter_view.bounds toView:overlay_view_wrapper]; + // Set a unique view identifier, so the overlay_view can be identified in XCUITests. + overlay_view.accessibilityIdentifier = + [NSString stringWithFormat:@"platform_view[%lld].overlay_view[%lld]", view_id, overlay_id]; +} + +// OverlayLayerPool +//////////////////////////////////////////////////////// + +std::shared_ptr OverlayLayerPool::GetNextLayer() { + std::shared_ptr result; + if (available_layer_index_ < layers_.size()) { + result = layers_[available_layer_index_]; + available_layer_index_++; + } + + return result; +} + +void OverlayLayerPool::CreateLayer(const std::shared_ptr& ios_context, + MTLPixelFormat pixel_format) { + FML_DCHECK([[NSThread currentThread] isMainThread]); + std::shared_ptr layer; + UIView* overlay_view; + UIView* overlay_view_wrapper; + + CGFloat screenScale = [UIScreen mainScreen].scale; + overlay_view = [[FlutterOverlayView alloc] initWithContentsScale:screenScale + pixelFormat:pixel_format]; + overlay_view_wrapper = [[FlutterOverlayView alloc] initWithContentsScale:screenScale + pixelFormat:pixel_format]; + + CALayer* ca_layer = overlay_view.layer; + std::unique_ptr ios_surface = IOSSurface::Create(ios_context, ca_layer); + std::unique_ptr surface = ios_surface->CreateGPUSurface(); + + layer = std::make_shared(overlay_view, overlay_view_wrapper, std::move(ios_surface), + std::move(surface)); + + // The overlay view wrapper masks the overlay view. + // This is required to keep the backing surface size unchanged between frames. + // + // Otherwise, changing the size of the overlay would require a new surface, + // which can be very expensive. + // + // This is the case of an animation in which the overlay size is changing in every frame. + // + // +------------------------+ + // | overlay_view | + // | +--------------+ | +--------------+ + // | | wrapper | | == mask => | overlay_view | + // | +--------------+ | +--------------+ + // +------------------------+ + layer->overlay_view_wrapper.clipsToBounds = YES; + [layer->overlay_view_wrapper addSubview:layer->overlay_view]; + + layers_.push_back(layer); +} + +void OverlayLayerPool::RecycleLayers() { + available_layer_index_ = 0; +} + +std::vector> OverlayLayerPool::RemoveUnusedLayers() { + std::vector> results; + for (size_t i = available_layer_index_; i < layers_.size(); i++) { + results.push_back(layers_[i]); + } + // Leave at least one overlay layer, to work around cases where scrolling + // platform views under an app bar continually adds and removes an + // overlay layer. This logic could be removed if https://github.com/flutter/flutter/issues/150646 + // is fixed. + static constexpr size_t kLeakLayerCount = 1; + size_t erase_offset = std::max(available_layer_index_, kLeakLayerCount); + if (erase_offset < layers_.size()) { + layers_.erase(layers_.begin() + erase_offset, layers_.end()); + } + return results; +} + +size_t OverlayLayerPool::size() const { + return layers_.size(); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/platform_message_response_darwin.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/platform_message_response_darwin.h new file mode 100644 index 0000000000000000000000000000000000000000..9a83e500218e2e36e2bae238ac39b4f2bb7fc9a4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/platform_message_response_darwin.h @@ -0,0 +1,40 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_PLATFORM_MESSAGE_RESPONSE_DARWIN_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_PLATFORM_MESSAGE_RESPONSE_DARWIN_H_ + +#include + +#include "flutter/fml/macros.h" +#include "flutter/fml/make_copyable.h" +#include "flutter/fml/task_runner.h" +#include "flutter/lib/ui/window/platform_message_response.h" +#import "flutter/shell/platform/darwin/common/buffer_conversions.h" + +typedef void (^PlatformMessageResponseCallback)(NSData*); + +namespace flutter { + +class PlatformMessageResponseDarwin : public flutter::PlatformMessageResponse { + public: + void Complete(std::unique_ptr data) override; + + void CompleteEmpty() override; + + private: + explicit PlatformMessageResponseDarwin(PlatformMessageResponseCallback callback, + fml::RefPtr platform_task_runner); + + ~PlatformMessageResponseDarwin() override; + + PlatformMessageResponseCallback callback_; + fml::RefPtr platform_task_runner_; + + FML_FRIEND_MAKE_REF_COUNTED(PlatformMessageResponseDarwin); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_PLATFORM_MESSAGE_RESPONSE_DARWIN_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/platform_message_response_darwin.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/platform_message_response_darwin.mm new file mode 100644 index 0000000000000000000000000000000000000000..e8a719422b04e2568ed527903642991564ba7ae9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/platform_message_response_darwin.mm @@ -0,0 +1,32 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/platform_message_response_darwin.h" + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" + +FLUTTER_ASSERT_ARC + +namespace flutter { + +PlatformMessageResponseDarwin::PlatformMessageResponseDarwin( + PlatformMessageResponseCallback callback, + fml::RefPtr platform_task_runner) + : callback_(callback), platform_task_runner_(std::move(platform_task_runner)) {} + +PlatformMessageResponseDarwin::~PlatformMessageResponseDarwin() = default; + +void PlatformMessageResponseDarwin::Complete(std::unique_ptr data) { + fml::RefPtr self(this); + platform_task_runner_->PostTask(fml::MakeCopyable([self, data = std::move(data)]() mutable { + self->callback_(CopyMappingPtrToNSData(std::move(data))); + })); +} + +void PlatformMessageResponseDarwin::CompleteEmpty() { + fml::RefPtr self(this); + platform_task_runner_->PostTask(fml::MakeCopyable([self]() mutable { self->callback_(nil); })); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/profiler_metrics_ios.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/profiler_metrics_ios.h new file mode 100644 index 0000000000000000000000000000000000000000..38ca90469ab9c3c044bd92b8812a55527c1958c4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/profiler_metrics_ios.h @@ -0,0 +1,40 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_PROFILER_METRICS_IOS_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_PROFILER_METRICS_IOS_H_ + +#include + +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/shell/profiling/sampling_profiler.h" + +namespace flutter { + +/** + * @brief Utility class that gathers profiling metrics used by + * `flutter::SamplingProfiler`. + * + * @see flutter::SamplingProfiler + */ +class ProfilerMetricsIOS { + public: + ProfilerMetricsIOS() = default; + + ProfileSample GenerateSample(); + + private: + std::optional CpuUsage(); + + std::optional MemoryUsage(); + + FML_DISALLOW_COPY_AND_ASSIGN(ProfilerMetricsIOS); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_PROFILER_METRICS_IOS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/profiler_metrics_ios.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/profiler_metrics_ios.mm new file mode 100644 index 0000000000000000000000000000000000000000..0a4ba99a0dd1d68888a4a5b889052d72648948a6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/profiler_metrics_ios.mm @@ -0,0 +1,211 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/profiler_metrics_ios.h" + +#import + +#import "flutter/fml/platform/darwin/cf_utils.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/IOKit.h" + +FLUTTER_ASSERT_ARC + +namespace { + +// RAII holder for `thread_array_t` this is so any early returns in +// `ProfilerMetricsIOS::CpuUsage` don't leak them. +class MachThreads { + public: + thread_array_t threads = NULL; + mach_msg_type_number_t thread_count = 0; + + MachThreads() = default; + + ~MachThreads() { + [[maybe_unused]] kern_return_t kernel_return_code = vm_deallocate( + mach_task_self(), reinterpret_cast(threads), thread_count * sizeof(thread_t)); + FML_DCHECK(kernel_return_code == KERN_SUCCESS) << "Failed to deallocate thread infos."; + } + + private: + FML_DISALLOW_COPY_AND_ASSIGN(MachThreads); +}; + +} // namespace + +#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG || \ + FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_PROFILE + +namespace fml { + +/// fml::CFRef retain and release implementations for io_object_t and related types. +template <> +struct CFRefTraits { + static constexpr io_object_t kNullValue = 0; + static void Retain(io_object_t instance) { IOObjectRetain(instance); } + static void Release(io_object_t instance) { IOObjectRelease(instance); } +}; + +} // namespace fml + +#endif + +namespace flutter { +namespace { + +#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG || \ + FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_PROFILE + +std::optional FindGpuUsageInfo(io_iterator_t iterator) { + for (fml::CFRef reg_entry(IOIteratorNext(iterator)); reg_entry.Get(); + reg_entry.Reset(IOIteratorNext(iterator))) { + CFMutableDictionaryRef cf_service_dictionary; + if (IORegistryEntryCreateCFProperties(reg_entry.Get(), &cf_service_dictionary, + kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess) { + continue; + } + // Transfer ownership to ARC-managed pointer. + NSDictionary* service_dictionary = (__bridge_transfer NSDictionary*)cf_service_dictionary; + cf_service_dictionary = nullptr; + NSDictionary* performanceStatistics = service_dictionary[@"PerformanceStatistics"]; + NSNumber* utilization = performanceStatistics[@"Device Utilization %"]; + if (utilization) { + return (GpuUsageInfo){.percent_usage = [utilization doubleValue]}; + } + } + return std::nullopt; +} + +[[maybe_unused]] std::optional FindSimulatorGpuUsageInfo() { + io_iterator_t io_iterator; + if (IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceNameMatching("IntelAccelerator"), + &io_iterator) == kIOReturnSuccess) { + fml::CFRef iterator(io_iterator); + return FindGpuUsageInfo(iterator.Get()); + } + return std::nullopt; +} + +[[maybe_unused]] std::optional FindDeviceGpuUsageInfo() { + io_iterator_t io_iterator; + if (IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceNameMatching("sgx"), + &io_iterator) == kIOReturnSuccess) { + fml::CFRef iterator(io_iterator); + for (fml::CFRef reg_entry(IOIteratorNext(iterator.Get())); reg_entry.Get(); + reg_entry.Reset(IOIteratorNext(iterator.Get()))) { + io_iterator_t io_inner_iterator; + if (IORegistryEntryGetChildIterator(reg_entry.Get(), kIOServicePlane, &io_inner_iterator) == + kIOReturnSuccess) { + fml::CFRef inner_iterator(io_inner_iterator); + std::optional result = FindGpuUsageInfo(inner_iterator.Get()); + if (result.has_value()) { + return result; + } + } + } + } + return std::nullopt; +} + +#endif // FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG || + // FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_PROFILE + +std::optional PollGpuUsage() { +#if (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_RELEASE || \ + FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_JIT_RELEASE) + return std::nullopt; +#elif TARGET_IPHONE_SIMULATOR + return FindSimulatorGpuUsageInfo(); +#elif TARGET_OS_IOS + return FindDeviceGpuUsageInfo(); +#endif // TARGET_IPHONE_SIMULATOR +} +} // namespace + +ProfileSample ProfilerMetricsIOS::GenerateSample() { + return {.cpu_usage = CpuUsage(), .memory_usage = MemoryUsage(), .gpu_usage = PollGpuUsage()}; +} + +std::optional ProfilerMetricsIOS::CpuUsage() { + kern_return_t kernel_return_code; + MachThreads mach_threads = MachThreads(); + + // Get threads in the task + kernel_return_code = + task_threads(mach_task_self(), &mach_threads.threads, &mach_threads.thread_count); + if (kernel_return_code != KERN_SUCCESS) { + return std::nullopt; + } + + double total_cpu_usage = 0.0; + uint32_t num_threads = mach_threads.thread_count; + + // Add the CPU usage for each thread. It should be noted that there may be some CPU usage missing + // from this calculation. If a thread ends between calls to this routine, then its info will be + // lost. We could solve this by installing a callback using pthread_key_create. The callback would + // report the thread is ending and allow the code to get the CPU usage. But we need to call + // pthread_setspecific in each thread to set the key's value to a non-null value for the callback + // to work. If we really need this information and if we have a good mechanism for calling + // pthread_setspecific in every thread, then we can include that value in the CPU usage. + for (mach_msg_type_number_t i = 0; i < mach_threads.thread_count; i++) { + thread_basic_info_data_t basic_thread_info; + mach_msg_type_number_t thread_info_count = THREAD_BASIC_INFO_COUNT; + kernel_return_code = + thread_info(mach_threads.threads[i], THREAD_BASIC_INFO, + reinterpret_cast(&basic_thread_info), &thread_info_count); + switch (kernel_return_code) { + case KERN_SUCCESS: { + const double current_thread_cpu_usage = + basic_thread_info.cpu_usage / static_cast(TH_USAGE_SCALE); + total_cpu_usage += current_thread_cpu_usage; + break; + } + case MACH_SEND_TIMEOUT: + case MACH_SEND_TIMED_OUT: + case MACH_SEND_INVALID_DEST: + // Ignore as this thread been destroyed. The possible return codes are not really well + // documented. This handling is inspired from the following sources: + // - https://opensource.apple.com/source/xnu/xnu-4903.221.2/tests/task_inspect.c.auto.html + // - https://github.com/apple/swift-corelibs-libdispatch/blob/main/src/queue.c#L6617 + num_threads--; + break; + default: + return std::nullopt; + } + } + + flutter::CpuUsageInfo cpu_usage_info = {.num_threads = num_threads, + .total_cpu_usage = total_cpu_usage * 100.0}; + return cpu_usage_info; +} + +std::optional ProfilerMetricsIOS::MemoryUsage() { + kern_return_t kernel_return_code; + task_vm_info_data_t task_memory_info; + mach_msg_type_number_t task_memory_info_count = TASK_VM_INFO_COUNT; + + kernel_return_code = + task_info(mach_task_self(), TASK_VM_INFO, reinterpret_cast(&task_memory_info), + &task_memory_info_count); + if (kernel_return_code != KERN_SUCCESS) { + return std::nullopt; + } + + // `phys_footprint` is Apple's recommended way to measure app's memory usage. It provides the + // best approximate to xcode memory gauge. According to its source code explanation, the physical + // footprint mainly consists of app's internal memory data and IOKit mappings. `resident_size` + // is the total physical memory used by the app, so we simply do `resident_size - phys_footprint` + // to obtain the shared memory usage. + const double dirty_memory_usage = + static_cast(task_memory_info.phys_footprint) / 1024.0 / 1024.0; + const double owned_shared_memory_usage = + static_cast(task_memory_info.resident_size) / 1024.0 / 1024.0 - dirty_memory_usage; + flutter::MemoryUsageInfo memory_usage_info = { + .dirty_memory_usage = dirty_memory_usage, + .owned_shared_memory_usage = owned_shared_memory_usage}; + return memory_usage_info; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.h new file mode 100644 index 0000000000000000000000000000000000000000..b9f575b87f3db1752a51a54ef413ad6a42e5b0ac --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.h @@ -0,0 +1,99 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_VSYNC_WAITER_IOS_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_VSYNC_WAITER_IOS_H_ + +#include + +#include "flutter/fml/macros.h" +#include "flutter/shell/common/variable_refresh_rate_reporter.h" +#include "flutter/shell/common/vsync_waiter.h" + +//------------------------------------------------------------------------------ +/// @brief Info.plist key enabling the full range of ProMotion refresh rates for CADisplayLink +/// callbacks and CAAnimation animations in the app. +/// +/// @see +/// https://developer.apple.com/documentation/quartzcore/optimizing_promotion_refresh_rates_for_iphone_13_pro_and_ipad_pro#3885321 +/// +extern NSString* const kCADisableMinimumFrameDurationOnPhoneKey; + +@interface DisplayLinkManager : NSObject + +//------------------------------------------------------------------------------ +/// @brief Whether the max refresh rate on iPhone ProMotion devices are enabled. This reflects +/// the value of `CADisableMinimumFrameDurationOnPhone` in the info.plist file. On iPads +/// that support ProMotion, the max refresh rate is always enabled. +/// +/// @return YES if the max refresh rate on ProMotion devices is enabled. +/// +@property(class, nonatomic, readonly) BOOL maxRefreshRateEnabledOnIPhone; + +//------------------------------------------------------------------------------ +/// @brief The display refresh rate used for reporting purposes. The engine does not care +/// about this for frame scheduling. It is only used by tools for instrumentation. The +/// engine uses the duration field of the link per frame for frame scheduling. +/// +/// @attention Do not use the this call in frame scheduling. It is only meant for reporting. +/// +/// @return The refresh rate in frames per second. +/// +@property(class, nonatomic, readonly) double displayRefreshRate; + +@end + +@interface VSyncClient : NSObject + +//------------------------------------------------------------------------------ +/// @brief Default value is YES. Vsync client will pause vsync callback after receiving +/// a vsync signal. Setting this property to NO can avoid this and vsync client +/// will trigger vsync callback continuously. +/// +/// +/// @param allowPauseAfterVsync Allow vsync client to pause after receiving a vsync signal. +/// +@property(nonatomic, assign) BOOL allowPauseAfterVsync; + +- (instancetype)initWithTaskRunner:(fml::RefPtr)task_runner + callback:(flutter::VsyncWaiter::Callback)callback; + +- (void)await; + +- (void)pause; + +//------------------------------------------------------------------------------ +/// @brief Call invalidate before releasing this object to remove from runloops. +/// +- (void)invalidate; + +- (void)setMaxRefreshRate:(double)refreshRate; + +@end + +namespace flutter { + +class VsyncWaiterIOS final : public VsyncWaiter, public VariableRefreshRateReporter { + public: + explicit VsyncWaiterIOS(const flutter::TaskRunners& task_runners); + + ~VsyncWaiterIOS() override; + + // |VariableRefreshRateReporter| + double GetRefreshRate() const override; + + // |VsyncWaiter| + // Made public for testing. + void AwaitVSync() override; + + private: + VSyncClient* client_; + double max_refresh_rate_; + + FML_DISALLOW_COPY_AND_ASSIGN(VsyncWaiterIOS); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_VSYNC_WAITER_IOS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.mm new file mode 100644 index 0000000000000000000000000000000000000000..e73ed315a7ffd4282cdfb412d0d831e5c871c3c2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.mm @@ -0,0 +1,179 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.h" + +#include + +#include +#include +#include + +#include "flutter/common/task_runners.h" +#include "flutter/fml/logging.h" +#include "flutter/fml/memory/task_runner_checker.h" +#include "flutter/fml/trace_event.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" + +FLUTTER_ASSERT_ARC + +NSString* const kCADisableMinimumFrameDurationOnPhoneKey = @"CADisableMinimumFrameDurationOnPhone"; + +@interface VSyncClient () +@property(nonatomic, assign, readonly) double refreshRate; +@end + +// When calculating refresh rate diffrence, anything within 0.1 fps is ignored. +const static double kRefreshRateDiffToIgnore = 0.1; + +namespace flutter { + +VsyncWaiterIOS::VsyncWaiterIOS(const flutter::TaskRunners& task_runners) + : VsyncWaiter(task_runners) { + auto callback = [this](std::unique_ptr recorder) { + const fml::TimePoint start_time = recorder->GetVsyncStartTime(); + const fml::TimePoint target_time = recorder->GetVsyncTargetTime(); + FireCallback(start_time, target_time, true); + }; + client_ = [[VSyncClient alloc] initWithTaskRunner:task_runners_.GetUITaskRunner() + callback:callback]; + max_refresh_rate_ = DisplayLinkManager.displayRefreshRate; +} + +VsyncWaiterIOS::~VsyncWaiterIOS() { + // This way, we will get no more callbacks from the display link that holds a weak (non-nilling) + // reference to this C++ object. + [client_ invalidate]; +} + +void VsyncWaiterIOS::AwaitVSync() { + double new_max_refresh_rate = DisplayLinkManager.displayRefreshRate; + if (fabs(new_max_refresh_rate - max_refresh_rate_) > kRefreshRateDiffToIgnore) { + max_refresh_rate_ = new_max_refresh_rate; + [client_ setMaxRefreshRate:max_refresh_rate_]; + } + [client_ await]; +} + +// |VariableRefreshRateReporter| +double VsyncWaiterIOS::GetRefreshRate() const { + return client_.refreshRate; +} + +} // namespace flutter + +@implementation VSyncClient { + flutter::VsyncWaiter::Callback _callback; + CADisplayLink* _displayLink; +} + +- (instancetype)initWithTaskRunner:(fml::RefPtr)task_runner + callback:(flutter::VsyncWaiter::Callback)callback { + FML_DCHECK(task_runner); + + if (self = [super init]) { + _refreshRate = DisplayLinkManager.displayRefreshRate; + _allowPauseAfterVsync = YES; + _callback = std::move(callback); + _displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(onDisplayLink:)]; + _displayLink.paused = YES; + + [self setMaxRefreshRate:DisplayLinkManager.displayRefreshRate]; + + // Strongly retain the the captured link until it is added to the runloop. + CADisplayLink* localDisplayLink = _displayLink; + task_runner->PostTask([localDisplayLink]() { + [localDisplayLink addToRunLoop:NSRunLoop.currentRunLoop forMode:NSRunLoopCommonModes]; + }); + } + + return self; +} + +- (void)setMaxRefreshRate:(double)refreshRate { + if (!DisplayLinkManager.maxRefreshRateEnabledOnIPhone) { + return; + } + double maxFrameRate = fmax(refreshRate, 60); + double minFrameRate = fmax(maxFrameRate / 2, 60); + if (@available(iOS 15.0, *)) { + _displayLink.preferredFrameRateRange = + CAFrameRateRangeMake(minFrameRate, maxFrameRate, maxFrameRate); + } else { + _displayLink.preferredFramesPerSecond = maxFrameRate; + } +} + +- (void)await { + _displayLink.paused = NO; +} + +- (void)pause { + _displayLink.paused = YES; +} + +- (void)onDisplayLink:(CADisplayLink*)link { + CFTimeInterval delay = CACurrentMediaTime() - link.timestamp; + fml::TimePoint frame_start_time = fml::TimePoint::Now() - fml::TimeDelta::FromSecondsF(delay); + + CFTimeInterval duration = link.targetTimestamp - link.timestamp; + fml::TimePoint frame_target_time = frame_start_time + fml::TimeDelta::FromSecondsF(duration); + + TRACE_EVENT2_INT("flutter", "PlatformVsync", "frame_start_time", + frame_start_time.ToEpochDelta().ToMicroseconds(), "frame_target_time", + frame_target_time.ToEpochDelta().ToMicroseconds()); + + std::unique_ptr recorder = + std::make_unique(); + + _refreshRate = round(1 / (frame_target_time - frame_start_time).ToSecondsF()); + + recorder->RecordVsync(frame_start_time, frame_target_time); + if (_allowPauseAfterVsync) { + link.paused = YES; + } + _callback(std::move(recorder)); +} + +- (void)invalidate { + [_displayLink invalidate]; + _displayLink = nil; // Break retain cycle. +} + +- (CADisplayLink*)getDisplayLink { + return _displayLink; +} + +@end + +@implementation DisplayLinkManager + ++ (double)displayRefreshRate { + CADisplayLink* displayLink = [CADisplayLink displayLinkWithTarget:[[[self class] alloc] init] + selector:@selector(onDisplayLink:)]; + displayLink.paused = YES; + auto preferredFPS = displayLink.preferredFramesPerSecond; + + // From Docs: + // The default value for preferredFramesPerSecond is 0. When this value is 0, the preferred + // frame rate is equal to the maximum refresh rate of the display, as indicated by the + // maximumFramesPerSecond property. + + if (preferredFPS != 0) { + return preferredFPS; + } + + return UIScreen.mainScreen.maximumFramesPerSecond; +} + +- (void)onDisplayLink:(CADisplayLink*)link { + // no-op. +} + ++ (BOOL)maxRefreshRateEnabledOnIPhone { + return [[NSBundle.mainBundle objectForInfoDictionaryKey:kCADisableMinimumFrameDurationOnPhoneKey] + boolValue]; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/module.modulemap b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/module.modulemap new file mode 100644 index 0000000000000000000000000000000000000000..bf81c8a86519f1408959dc65141c7aacea71b2e0 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/framework/module.modulemap @@ -0,0 +1,6 @@ +framework module Flutter { + umbrella header "Flutter.h" + + export * + module * { export * } +} diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_context.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_context.h new file mode 100644 index 0000000000000000000000000000000000000000..da8df41347cf9eddab37e1ddfdba5fe263d5681d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_context.h @@ -0,0 +1,100 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_IOS_CONTEXT_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_CONTEXT_H_ + +#include + +#include "flutter/common/graphics/gl_context_switch.h" +#include "flutter/common/graphics/texture.h" +#include "flutter/common/settings.h" +#include "flutter/fml/concurrent_message_loop.h" +#include "flutter/fml/macros.h" +#include "flutter/fml/synchronization/sync_switch.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterTexture.h" +#import "flutter/shell/platform/darwin/ios/rendering_api_selection.h" +#include "impeller/display_list/aiks_context.h" + +namespace impeller { +class Context; +} // namespace impeller + +namespace flutter { + +//------------------------------------------------------------------------------ +/// @brief Manages the lifetime of the on-screen and off-screen rendering +/// contexts on iOS. On-screen contexts are used by Flutter for +/// rendering into the surface. The lifecycle of this context may be +/// tied to the lifecycle of the surface. On the other hand, the +/// lifecycle of the off-screen context it tied to that of the +/// platform view. This one object used to manage both context +/// because GPU handles may need to be shared between the two +/// context. To achieve this, context may need references to one +/// another at creation time. This one object manages the creation, +/// use and collection of both contexts in a client rendering API +/// agnostic manner. +/// +class IOSContext { + public: + //---------------------------------------------------------------------------- + /// @brief Create an iOS context object capable of creating the on-screen + /// and off-screen GPU context for use by Impeller. + /// + /// In case the engine does not support the specified client + /// rendering API, this a `nullptr` may be returned. + /// + /// @param[in] api A client rendering API supported by the + /// engine/platform. + /// @param[in] backend A client rendering backend supported by the + /// engine/platform. + /// + /// @return A valid context on success. `nullptr` on failure. + /// + static std::unique_ptr Create( + IOSRenderingAPI api, + IOSRenderingBackend backend, + const std::shared_ptr& is_gpu_disabled_sync_switch, + const Settings& settings); + + //---------------------------------------------------------------------------- + /// @brief Collects the context object. This must happen on the thread on + /// which this object was created. + /// + virtual ~IOSContext(); + + //---------------------------------------------------------------------------- + /// @brief Get the rendering backend used by this context. + /// + /// @return The rendering backend. + /// + virtual IOSRenderingBackend GetBackend() const; + + //---------------------------------------------------------------------------- + /// @brief Creates an external texture proxy of the appropriate client + /// rendering API. + /// + /// @param[in] texture_id The texture identifier + /// @param[in] texture The texture + /// + /// @return The texture proxy if the rendering backend supports embedder + /// provided external textures. + /// + virtual std::unique_ptr CreateExternalTexture(int64_t texture_id, + NSObject* texture) = 0; + + virtual std::shared_ptr GetImpellerContext() const; + + virtual std::shared_ptr GetAiksContext() const; + + protected: + explicit IOSContext(); + + private: + FML_DISALLOW_COPY_AND_ASSIGN(IOSContext); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_CONTEXT_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_context.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_context.mm new file mode 100644 index 0000000000000000000000000000000000000000..7db29ea3b0d30f87e14b79bf4b643e5e4ada7306 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_context.mm @@ -0,0 +1,63 @@ +// 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/shell/platform/darwin/ios/ios_context.h" +#include +#include "flutter/shell/platform/darwin/ios/rendering_api_selection.h" + +#include "flutter/fml/logging.h" +#include "flutter/shell/platform/darwin/ios/ios_context_metal_impeller.h" +#include "flutter/shell/platform/darwin/ios/ios_context_noop.h" + +FLUTTER_ASSERT_ARC + +namespace flutter { + +IOSContext::IOSContext() = default; + +IOSContext::~IOSContext() = default; + +std::unique_ptr IOSContext::Create( + IOSRenderingAPI api, + IOSRenderingBackend backend, + const std::shared_ptr& is_gpu_disabled_sync_switch, + const Settings& settings) { + switch (api) { + case IOSRenderingAPI::kSoftware: + FML_LOG(IMPORTANT) + << "Software rendering is incompatible with Impeller.\n" + "Software rendering may have been automatically selected when running on a " + "simulator " + "in an environment that does not support Metal. Enabling GPU passthrough in your " + "environment may fix this."; + return std::make_unique(); + case IOSRenderingAPI::kMetal: + switch (backend) { + case IOSRenderingBackend::kSkia: + FML_LOG(FATAL) << "Impeller opt-out unavailable."; + return nullptr; + case IOSRenderingBackend::kImpeller: + return std::make_unique(settings, is_gpu_disabled_sync_switch); + } + default: + break; + } + FML_CHECK(false); + return nullptr; +} + +IOSRenderingBackend IOSContext::GetBackend() const { + // Overridden by Impeller subclasses. + return IOSRenderingBackend::kSkia; +} + +std::shared_ptr IOSContext::GetImpellerContext() const { + return nullptr; +} + +std::shared_ptr IOSContext::GetAiksContext() const { + return nullptr; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_context_metal_impeller.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_context_metal_impeller.h new file mode 100644 index 0000000000000000000000000000000000000000..00f489199e9b67799421b6e6a007cbb38b730c01 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_context_metal_impeller.h @@ -0,0 +1,50 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_IOS_CONTEXT_METAL_IMPELLER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_CONTEXT_METAL_IMPELLER_H_ + +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalImpeller.h" +#include "flutter/shell/platform/darwin/ios/ios_context.h" +#include "impeller/display_list/aiks_context.h" + +namespace impeller { + +class Context; + +} // namespace impeller + +namespace flutter { + +class IOSContextMetalImpeller final : public IOSContext { + public: + explicit IOSContextMetalImpeller( + const Settings& settings, + const std::shared_ptr& is_gpu_disabled_sync_switch); + + ~IOSContextMetalImpeller(); + + IOSRenderingBackend GetBackend() const override; + + private: + FlutterDarwinContextMetalImpeller* darwin_context_metal_impeller_; + std::shared_ptr aiks_context_; + + // |IOSContext| + std::unique_ptr CreateExternalTexture(int64_t texture_id, + NSObject* texture) override; + + // |IOSContext| + std::shared_ptr GetImpellerContext() const override; + + // |IOSContext| + std::shared_ptr GetAiksContext() const override; + + FML_DISALLOW_COPY_AND_ASSIGN(IOSContextMetalImpeller); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_CONTEXT_METAL_IMPELLER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_context_metal_impeller.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_context_metal_impeller.mm new file mode 100644 index 0000000000000000000000000000000000000000..83eda049d0d9e7350b4083323a4e659a9ce0dcfc --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_context_metal_impeller.mm @@ -0,0 +1,60 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/ios_context_metal_impeller.h" + +#include "flutter/impeller/entity/mtl/entity_shaders.h" +#import "flutter/shell/platform/darwin/ios/ios_external_texture_metal.h" +#include "impeller/display_list/aiks_context.h" +#include "impeller/typographer/backends/skia/typographer_context_skia.h" + +FLUTTER_ASSERT_ARC + +namespace flutter { +namespace { +impeller::Flags SettingsToFlags(const Settings& settings) { + return impeller::Flags{ + .antialiased_lines = settings.impeller_antialiased_lines, + }; +} +} // namespace + +IOSContextMetalImpeller::IOSContextMetalImpeller( + const Settings& settings, + const std::shared_ptr& is_gpu_disabled_sync_switch) + : darwin_context_metal_impeller_([[FlutterDarwinContextMetalImpeller alloc] + init:SettingsToFlags(settings) + gpuDisabledSyncSwitch:is_gpu_disabled_sync_switch]) { + if (darwin_context_metal_impeller_.context) { + aiks_context_ = std::make_shared( + darwin_context_metal_impeller_.context, impeller::TypographerContextSkia::Make()); + } +} + +IOSContextMetalImpeller::~IOSContextMetalImpeller() = default; + +IOSRenderingBackend IOSContextMetalImpeller::GetBackend() const { + return IOSRenderingBackend::kImpeller; +} + +// |IOSContext| +std::shared_ptr IOSContextMetalImpeller::GetImpellerContext() const { + return darwin_context_metal_impeller_.context; +} + +// |IOSContext| +std::shared_ptr IOSContextMetalImpeller::GetAiksContext() const { + return aiks_context_; +} + +// |IOSContext| +std::unique_ptr IOSContextMetalImpeller::CreateExternalTexture( + int64_t texture_id, + NSObject* texture) { + return std::make_unique([darwin_context_metal_impeller_ + createExternalTextureWithIdentifier:texture_id + texture:texture]); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_context_noop.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_context_noop.h new file mode 100644 index 0000000000000000000000000000000000000000..71ee138705adf662a5b5e09bfca7c9341d27f6a2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_context_noop.h @@ -0,0 +1,34 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_IOS_CONTEXT_NOOP_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_CONTEXT_NOOP_H_ + +#import "flutter/shell/platform/darwin/ios/ios_context.h" + +namespace flutter { + +/// @brief A noop rendering context for usage on simulators without metal support. +class IOSContextNoop final : public IOSContext { + public: + IOSContextNoop(); + + // |IOSContext| + ~IOSContextNoop(); + + // |IOSContext| + std::unique_ptr CreateExternalTexture(int64_t texture_id, + NSObject* texture) override; + + IOSRenderingBackend GetBackend() const override; + + private: + IOSContextNoop(const IOSContextNoop&) = delete; + + IOSContextNoop& operator=(const IOSContextNoop&) = delete; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_CONTEXT_NOOP_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_context_noop.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_context_noop.mm new file mode 100644 index 0000000000000000000000000000000000000000..8c50308924a54ba12576fafecb8c8b983c528a30 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_context_noop.mm @@ -0,0 +1,36 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/ios_context_noop.h" +#include "flutter/shell/platform/darwin/ios/rendering_api_selection.h" +#include "ios_context.h" + +FLUTTER_ASSERT_ARC + +namespace flutter { + +IOSContextNoop::IOSContextNoop() = default; + +// |IOSContext| +IOSContextNoop::~IOSContextNoop() = default; + +// |IOSContext| +IOSRenderingBackend IOSContextNoop::GetBackend() const { + return IOSRenderingBackend::kImpeller; +} + +// |IOSContext| +std::unique_ptr IOSContextNoop::CreateExternalTexture(int64_t texture_id, + NSObject* texture) { + // Don't use FML for logging as it will contain engine specific details. This is a user facing + // message. + NSLog(@"Flutter: Attempted to composite external texture sources using the noop backend. " + @"This backend is only used on simulators. This feature is only available on actual " + @"devices where Metal is used for rendering."); + + // Not supported in this backend. + return nullptr; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_context_noop_unittests.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_context_noop_unittests.mm new file mode 100644 index 0000000000000000000000000000000000000000..f5c882f1501401ca8d8bebfd84c23a968cb6f63d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_context_noop_unittests.mm @@ -0,0 +1,24 @@ +// 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 +#import + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#include "shell/platform/darwin/ios/ios_context_noop.h" +#include "shell/platform/darwin/ios/rendering_api_selection.h" + +FLUTTER_ASSERT_ARC + +@interface IOSContextNoopTest : XCTestCase +@end + +@implementation IOSContextNoopTest +- (void)testCreateNoop { + flutter::IOSContextNoop noop; + + XCTAssertTrue(noop.GetBackend() == flutter::IOSRenderingBackend::kImpeller); +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_external_texture_metal.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_external_texture_metal.h new file mode 100644 index 0000000000000000000000000000000000000000..0d317aa6041e54c957e4b316e9da29ed3201971e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_external_texture_metal.h @@ -0,0 +1,48 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_IOS_EXTERNAL_TEXTURE_METAL_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_EXTERNAL_TEXTURE_METAL_H_ + +#include "flutter/common/graphics/texture.h" +#include "flutter/fml/macros.h" +#import "flutter/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.h" + +namespace flutter { + +class IOSExternalTextureMetal final : public Texture { + public: + explicit IOSExternalTextureMetal( + FlutterDarwinExternalTextureMetal* darwin_external_texture_metal); + + // |Texture| + ~IOSExternalTextureMetal(); + + private: + FlutterDarwinExternalTextureMetal* darwin_external_texture_metal_; + + // |Texture| + void Paint(PaintContext& context, + const DlRect& bounds, + bool freeze, + const DlImageSampling sampling) override; + + // |Texture| + void OnGrContextCreated() override; + + // |Texture| + void OnGrContextDestroyed() override; + + // |Texture| + void MarkNewFrameAvailable() override; + + // |Texture| + void OnTextureUnregistered() override; + + FML_DISALLOW_COPY_AND_ASSIGN(IOSExternalTextureMetal); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_EXTERNAL_TEXTURE_METAL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_external_texture_metal.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_external_texture_metal.mm new file mode 100644 index 0000000000000000000000000000000000000000..3414f7fd159c04af1d05db1ccbc57a7338560fc5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_external_texture_metal.mm @@ -0,0 +1,45 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/ios_external_texture_metal.h" +#include "flow/layers/layer.h" + +FLUTTER_ASSERT_ARC + +namespace flutter { + +IOSExternalTextureMetal::IOSExternalTextureMetal( + FlutterDarwinExternalTextureMetal* darwin_external_texture_metal) + : Texture([darwin_external_texture_metal textureID]), + darwin_external_texture_metal_(darwin_external_texture_metal) {} + +IOSExternalTextureMetal::~IOSExternalTextureMetal() = default; + +void IOSExternalTextureMetal::Paint(PaintContext& context, + const DlRect& bounds, + bool freeze, + const DlImageSampling sampling) { + [darwin_external_texture_metal_ paintContext:context + bounds:ToSkRect(bounds) + freeze:freeze + sampling:sampling]; +} + +void IOSExternalTextureMetal::OnGrContextCreated() { + [darwin_external_texture_metal_ onGrContextCreated]; +} + +void IOSExternalTextureMetal::OnGrContextDestroyed() { + [darwin_external_texture_metal_ onGrContextDestroyed]; +} + +void IOSExternalTextureMetal::MarkNewFrameAvailable() { + [darwin_external_texture_metal_ markNewFrameAvailable]; +} + +void IOSExternalTextureMetal::OnTextureUnregistered() { + [darwin_external_texture_metal_ onTextureUnregistered]; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_external_view_embedder.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_external_view_embedder.h new file mode 100644 index 0000000000000000000000000000000000000000..d22fc3fb47743945318eb5be401febf441552188 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_external_view_embedder.h @@ -0,0 +1,82 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_IOS_EXTERNAL_VIEW_EMBEDDER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_EXTERNAL_VIEW_EMBEDDER_H_ + +#include "flutter/flow/embedded_views.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h" + +namespace flutter { + +class IOSExternalViewEmbedder : public ExternalViewEmbedder { + public: + IOSExternalViewEmbedder( + __weak FlutterPlatformViewsController* platform_views_controller, + const std::shared_ptr& context); + + // |ExternalViewEmbedder| + virtual ~IOSExternalViewEmbedder() override; + + private: + __weak FlutterPlatformViewsController* platform_views_controller_; + std::shared_ptr ios_context_; + + // |ExternalViewEmbedder| + DlCanvas* GetRootCanvas() override; + + // |ExternalViewEmbedder| + void CancelFrame() override; + + // |ExternalViewEmbedder| + void BeginFrame(GrDirectContext* context, + const fml::RefPtr& + raster_thread_merger) override; + + // |ExternalViewEmbedder| + void PrepareFlutterView(SkISize frame_size, + double device_pixel_ratio) override; + + // |ExternalViewEmbedder| + void PrerollCompositeEmbeddedView( + int64_t view_id, + std::unique_ptr params) override; + + // |ExternalViewEmbedder| + PostPrerollResult PostPrerollAction( + const fml::RefPtr& raster_thread_merger) + override; + + // |ExternalViewEmbedder| + DlCanvas* CompositeEmbeddedView(int64_t view_id) override; + + // |ExternalViewEmbedder| + void SubmitFlutterView( + int64_t flutter_view_id, + GrDirectContext* context, + const std::shared_ptr& aiks_context, + std::unique_ptr frame) override; + + // |ExternalViewEmbedder| + void EndFrame(bool should_resubmit_frame, + const fml::RefPtr& + raster_thread_merger) override; + + // |ExternalViewEmbedder| + bool SupportsDynamicThreadMerging() override; + + // |ExternalViewEmbedder| + void PushFilterToVisitedPlatformViews( + const std::shared_ptr& filter, + const SkRect& filter_rect) override; + + // |ExternalViewEmbedder| + void PushVisitedPlatformView(int64_t view_id) override; + + FML_DISALLOW_COPY_AND_ASSIGN(IOSExternalViewEmbedder); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_EXTERNAL_VIEW_EMBEDDER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_external_view_embedder.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_external_view_embedder.mm new file mode 100644 index 0000000000000000000000000000000000000000..575071c6a52b4c7d26cccbf0af7828606656db15 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_external_view_embedder.mm @@ -0,0 +1,116 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/ios_external_view_embedder.h" +#include "fml/task_runner.h" + +#include "flutter/common/constants.h" + +FLUTTER_ASSERT_ARC + +namespace flutter { + +IOSExternalViewEmbedder::IOSExternalViewEmbedder( + __weak FlutterPlatformViewsController* platform_views_controller, + const std::shared_ptr& context) + : platform_views_controller_(platform_views_controller), ios_context_(context) { + FML_CHECK(ios_context_); +} + +IOSExternalViewEmbedder::~IOSExternalViewEmbedder() = default; + +// |ExternalViewEmbedder| +DlCanvas* IOSExternalViewEmbedder::GetRootCanvas() { + // On iOS, the root surface is created from the on-screen render target. Only the surfaces for the + // various overlays are controlled by this class. + return nullptr; +} + +// |ExternalViewEmbedder| +void IOSExternalViewEmbedder::CancelFrame() { + TRACE_EVENT0("flutter", "IOSExternalViewEmbedder::CancelFrame"); + FML_CHECK(platform_views_controller_); + [platform_views_controller_ cancelFrame]; +} + +// |ExternalViewEmbedder| +void IOSExternalViewEmbedder::BeginFrame( + GrDirectContext* context, + const fml::RefPtr& raster_thread_merger) {} + +// |ExternalViewEmbedder| +void IOSExternalViewEmbedder::PrepareFlutterView(SkISize frame_size, double device_pixel_ratio) { + FML_CHECK(platform_views_controller_); + [platform_views_controller_ beginFrameWithSize:frame_size]; +} + +// |ExternalViewEmbedder| +void IOSExternalViewEmbedder::PrerollCompositeEmbeddedView( + int64_t view_id, + std::unique_ptr params) { + TRACE_EVENT0("flutter", "IOSExternalViewEmbedder::PrerollCompositeEmbeddedView"); + FML_CHECK(platform_views_controller_); + [platform_views_controller_ prerollCompositeEmbeddedView:view_id withParams:std::move(params)]; +} + +// |ExternalViewEmbedder| +PostPrerollResult IOSExternalViewEmbedder::PostPrerollAction( + const fml::RefPtr& raster_thread_merger) { + TRACE_EVENT0("flutter", "IOSExternalViewEmbedder::PostPrerollAction"); + FML_CHECK(platform_views_controller_); + PostPrerollResult result = + [platform_views_controller_ postPrerollActionWithThreadMerger:raster_thread_merger]; + return result; +} + +// |ExternalViewEmbedder| +DlCanvas* IOSExternalViewEmbedder::CompositeEmbeddedView(int64_t view_id) { + TRACE_EVENT0("flutter", "IOSExternalViewEmbedder::CompositeEmbeddedView"); + FML_CHECK(platform_views_controller_); + return [platform_views_controller_ compositeEmbeddedViewWithId:view_id]; +} + +// |ExternalViewEmbedder| +void IOSExternalViewEmbedder::SubmitFlutterView( + int64_t flutter_view_id, + GrDirectContext* context, + const std::shared_ptr& aiks_context, + std::unique_ptr frame) { + TRACE_EVENT0("flutter", "IOSExternalViewEmbedder::SubmitFlutterView"); + + // TODO(dkwingsmt): This class only supports rendering into the implicit view. + // Properly support multi-view in the future. + FML_DCHECK(flutter_view_id == kFlutterImplicitViewId); + FML_CHECK(platform_views_controller_); + [platform_views_controller_ submitFrame:std::move(frame) withIosContext:ios_context_]; + TRACE_EVENT0("flutter", "IOSExternalViewEmbedder::DidSubmitFrame"); +} + +// |ExternalViewEmbedder| +void IOSExternalViewEmbedder::EndFrame( + bool should_resubmit_frame, + const fml::RefPtr& raster_thread_merger) { + TRACE_EVENT0("flutter", "IOSExternalViewEmbedder::EndFrame"); + [platform_views_controller_ endFrameWithResubmit:should_resubmit_frame + threadMerger:raster_thread_merger]; +} + +// |ExternalViewEmbedder| +bool IOSExternalViewEmbedder::SupportsDynamicThreadMerging() { + return false; +} + +// |ExternalViewEmbedder| +void IOSExternalViewEmbedder::PushFilterToVisitedPlatformViews( + const std::shared_ptr& filter, + const SkRect& filter_rect) { + [platform_views_controller_ pushFilterToVisitedPlatformViews:filter withRect:filter_rect]; +} + +// |ExternalViewEmbedder| +void IOSExternalViewEmbedder::PushVisitedPlatformView(int64_t view_id) { + [platform_views_controller_ pushVisitedPlatformViewId:view_id]; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_surface.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_surface.h new file mode 100644 index 0000000000000000000000000000000000000000..a9fd3f5f5d250b9336acea5aeea20170ff36634a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_surface.h @@ -0,0 +1,45 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_IOS_SURFACE_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_SURFACE_H_ + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h" + +#include + +#include "flutter/flow/embedded_views.h" +#include "flutter/flow/surface.h" +#include "flutter/fml/macros.h" + +@class CALayer; + +namespace flutter { + +class IOSSurface { + public: + static std::unique_ptr Create(std::shared_ptr context, CALayer* layer); + + std::shared_ptr GetContext() const; + + virtual ~IOSSurface(); + + virtual bool IsValid() const = 0; + + virtual void UpdateStorageSizeIfNecessary() = 0; + + virtual std::unique_ptr CreateGPUSurface() = 0; + + protected: + explicit IOSSurface(std::shared_ptr ios_context); + + private: + std::shared_ptr ios_context_; + + FML_DISALLOW_COPY_AND_ASSIGN(IOSSurface); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_SURFACE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_surface.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_surface.mm new file mode 100644 index 0000000000000000000000000000000000000000..f4abe826f7216594a747adcf9622ce722a24f05c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_surface.mm @@ -0,0 +1,50 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/ios_surface.h" + +#include + +#import "flutter/shell/platform/darwin/ios/ios_surface_metal_impeller.h" +#import "flutter/shell/platform/darwin/ios/ios_surface_noop.h" +#include "flutter/shell/platform/darwin/ios/rendering_api_selection.h" + +FLUTTER_ASSERT_ARC + +namespace flutter { + +std::unique_ptr IOSSurface::Create(std::shared_ptr context, + CALayer* layer) { + FML_DCHECK(layer); + FML_DCHECK(context); + + if (@available(iOS METAL_IOS_VERSION_BASELINE, *)) { + if ([layer isKindOfClass:[CAMetalLayer class]]) { + switch (context->GetBackend()) { + case IOSRenderingBackend::kSkia: + FML_LOG(FATAL) << "Impeller opt-out unavailable."; + return nullptr; + case IOSRenderingBackend::kImpeller: + return std::make_unique( + static_cast(layer), // Metal layer + std::move(context) // context + ); + } + } + } + return std::make_unique(std::move(context)); +} + +IOSSurface::IOSSurface(std::shared_ptr ios_context) + : ios_context_(std::move(ios_context)) { + FML_DCHECK(ios_context_); +} + +IOSSurface::~IOSSurface() = default; + +std::shared_ptr IOSSurface::GetContext() const { + return ios_context_; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_surface_metal_impeller.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_surface_metal_impeller.h new file mode 100644 index 0000000000000000000000000000000000000000..f071e08a1360b2d179d20c19b8149bb4d792317a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_surface_metal_impeller.h @@ -0,0 +1,67 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_IOS_SURFACE_METAL_IMPELLER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_SURFACE_METAL_IMPELLER_H_ + +#include "flutter/fml/macros.h" +#include "flutter/shell/gpu/gpu_surface_metal_delegate.h" +#include "flutter/shell/platform/darwin/ios/ios_surface.h" + +@class CAMetalLayer; + +namespace impeller { +class Context; +} // namespace impeller + +namespace flutter { + +class SK_API_AVAILABLE_CA_METAL_LAYER IOSSurfaceMetalImpeller final + : public IOSSurface, + public GPUSurfaceMetalDelegate { + public: + IOSSurfaceMetalImpeller(CAMetalLayer* layer, const std::shared_ptr& context); + + // |IOSSurface| + ~IOSSurfaceMetalImpeller(); + + private: + CAMetalLayer* layer_; + const std::shared_ptr impeller_context_; + std::shared_ptr aiks_context_; + bool is_valid_ = false; + + // |IOSSurface| + bool IsValid() const override; + + // |IOSSurface| + void UpdateStorageSizeIfNecessary() override; + + // |IOSSurface| + std::unique_ptr CreateGPUSurface() override; + + // |GPUSurfaceMetalDelegate| + GPUCAMetalLayerHandle GetCAMetalLayer(const SkISize& frame_info) const override + __attribute__((cf_audited_transfer)); + + // |GPUSurfaceMetalDelegate| + bool PresentDrawable(GrMTLHandle drawable) const override __attribute__((cf_audited_transfer)); + + // |GPUSurfaceMetalDelegate| + GPUMTLTextureInfo GetMTLTexture(const SkISize& frame_info) const override + __attribute__((cf_audited_transfer)); + + // |GPUSurfaceMetalDelegate| + bool PresentTexture(GPUMTLTextureInfo texture) const override + __attribute__((cf_audited_transfer)); + + // |GPUSurfaceMetalDelegate| + bool AllowsDrawingWhenGpuDisabled() const override; + + FML_DISALLOW_COPY_AND_ASSIGN(IOSSurfaceMetalImpeller); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_SURFACE_METAL_IMPELLER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_surface_metal_impeller.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_surface_metal_impeller.mm new file mode 100644 index 0000000000000000000000000000000000000000..8ec9bb8eef0559a3eae0f1fb98fa920985bfece7 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_surface_metal_impeller.mm @@ -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. + +#import "flutter/shell/platform/darwin/ios/ios_surface_metal_impeller.h" + +#include "flutter/impeller/renderer/backend/metal/formats_mtl.h" +#include "flutter/impeller/renderer/context.h" +#include "flutter/shell/gpu/gpu_surface_metal_impeller.h" +#include "impeller/display_list/aiks_context.h" +#include "impeller/typographer/backends/skia/typographer_context_skia.h" +#include "impeller/typographer/typographer_context.h" + +FLUTTER_ASSERT_ARC + +namespace flutter { + +IOSSurfaceMetalImpeller::IOSSurfaceMetalImpeller(CAMetalLayer* layer, + const std::shared_ptr& context) + : IOSSurface(context), + GPUSurfaceMetalDelegate(MTLRenderTargetType::kCAMetalLayer), + layer_(layer), + impeller_context_(context ? context->GetImpellerContext() : nullptr), + aiks_context_(context ? context->GetAiksContext() : nullptr) { + if (!impeller_context_ || !aiks_context_) { + return; + } + is_valid_ = true; +} + +// |IOSSurface| +IOSSurfaceMetalImpeller::~IOSSurfaceMetalImpeller() = default; + +// |IOSSurface| +bool IOSSurfaceMetalImpeller::IsValid() const { + return is_valid_; +} + +// |IOSSurface| +void IOSSurfaceMetalImpeller::UpdateStorageSizeIfNecessary() { + // Nothing to do. +} + +// |IOSSurface| +std::unique_ptr IOSSurfaceMetalImpeller::CreateGPUSurface() { + impeller_context_->UpdateOffscreenLayerPixelFormat( + impeller::FromMTLPixelFormat(layer_.pixelFormat)); + return std::make_unique(this, // + aiks_context_ // + ); +} + +// |GPUSurfaceMetalDelegate| +GPUCAMetalLayerHandle IOSSurfaceMetalImpeller::GetCAMetalLayer(const SkISize& frame_info) const { + const auto drawable_size = CGSizeMake(frame_info.width(), frame_info.height()); + if (!CGSizeEqualToSize(drawable_size, layer_.drawableSize)) { + layer_.drawableSize = drawable_size; + } + + // Flutter needs to read from the color attachment in cases where there are effects such as + // backdrop filters. Flutter plugins that create platform views may also read from the layer. + layer_.framebufferOnly = NO; + + return (__bridge GPUCAMetalLayerHandle)layer_; +} + +// |GPUSurfaceMetalDelegate| +bool IOSSurfaceMetalImpeller::PresentDrawable(GrMTLHandle drawable) const { + FML_DCHECK(false); + return false; +} + +// |GPUSurfaceMetalDelegate| +GPUMTLTextureInfo IOSSurfaceMetalImpeller::GetMTLTexture(const SkISize& frame_info) const { + FML_CHECK(false); + return GPUMTLTextureInfo{ + .texture_id = -1, // + .texture = nullptr // + }; +} + +// |GPUSurfaceMetalDelegate| +bool IOSSurfaceMetalImpeller::PresentTexture(GPUMTLTextureInfo texture) const { + FML_CHECK(false); + return false; +} + +// |GPUSurfaceMetalDelegate| +bool IOSSurfaceMetalImpeller::AllowsDrawingWhenGpuDisabled() const { + return false; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_surface_noop.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_surface_noop.h new file mode 100644 index 0000000000000000000000000000000000000000..c97c80c356d1705fde22ff5de4ff58e0488edae5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_surface_noop.h @@ -0,0 +1,43 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_IOS_SURFACE_NOOP_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_SURFACE_NOOP_H_ + +#import "flutter/shell/platform/darwin/ios/ios_context.h" +#import "flutter/shell/platform/darwin/ios/ios_surface.h" + +@class CALayer; + +namespace flutter { + +/// @brief A rendering surface that accepts rendering intent but does not render +/// anything. +/// +/// This is useful for running on platforms that need an engine instance and +/// don't have the required drivers. +class IOSSurfaceNoop final : public IOSSurface { + public: + explicit IOSSurfaceNoop(std::shared_ptr context); + + ~IOSSurfaceNoop() override; + + // |IOSSurface| + bool IsValid() const override; + + // |IOSSurface| + void UpdateStorageSizeIfNecessary() override; + + // |IOSSurface| + std::unique_ptr CreateGPUSurface() override; + + private: + IOSSurfaceNoop(const IOSSurfaceNoop&) = delete; + + IOSSurfaceNoop& operator=(const IOSSurfaceNoop&) = delete; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_SURFACE_NOOP_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_surface_noop.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_surface_noop.mm new file mode 100644 index 0000000000000000000000000000000000000000..a41c5e53cd5d14482cab93982a83576625dac4aa --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_surface_noop.mm @@ -0,0 +1,35 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/ios_surface_noop.h" +#include "shell/gpu/gpu_surface_noop.h" + +#include + +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/platform/darwin/cf_utils.h" +#include "flutter/fml/trace_event.h" + +FLUTTER_ASSERT_ARC + +namespace flutter { + +IOSSurfaceNoop::IOSSurfaceNoop(std::shared_ptr context) + : IOSSurface(std::move(context)) {} + +IOSSurfaceNoop::~IOSSurfaceNoop() = default; + +bool IOSSurfaceNoop::IsValid() const { + return true; +} + +void IOSSurfaceNoop::UpdateStorageSizeIfNecessary() {} + +std::unique_ptr IOSSurfaceNoop::CreateGPUSurface() { + return std::make_unique(); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_surface_noop_unittests.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_surface_noop_unittests.mm new file mode 100644 index 0000000000000000000000000000000000000000..b85dbfedcc0102d8b53450319c96a13b0b97adbd --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/ios_surface_noop_unittests.mm @@ -0,0 +1,33 @@ +// 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 +#import + +#import "flutter/shell/platform/darwin/ios/ios_surface_noop.h" + +#import "flutter/common/task_runners.h" +#import "flutter/fml/message_loop.h" +#import "flutter/fml/thread.h" +#import "flutter/lib/ui/window/platform_message.h" +#import "flutter/lib/ui/window/platform_message_response.h" +#import "flutter/shell/common/thread_host.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/ios_context_noop.h" + +FLUTTER_ASSERT_ARC + +@interface IOSSurfaceNoopTest : XCTestCase +@end + +@implementation IOSSurfaceNoopTest +- (void)testCreateSurface { + auto context = std::make_shared(); + flutter::IOSSurfaceNoop noop(context); + + XCTAssertTrue(noop.IsValid()); + XCTAssertTrue(!!noop.CreateGPUSurface()); +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/platform_message_handler_ios.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/platform_message_handler_ios.h new file mode 100644 index 0000000000000000000000000000000000000000..2c0900276071199ce495e24390b887f6769af28f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/platform_message_handler_ios.h @@ -0,0 +1,47 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_PLATFORM_MESSAGE_HANDLER_IOS_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_PLATFORM_MESSAGE_HANDLER_IOS_H_ + +#include "flutter/fml/task_runner.h" +#include "flutter/shell/common/platform_message_handler.h" +#import "flutter/shell/platform/darwin/ios/flutter_task_queue_dispatch.h" + +namespace flutter { + +class PlatformMessageHandlerIos : public PlatformMessageHandler { + public: + static NSObject* MakeBackgroundTaskQueue(); + + explicit PlatformMessageHandlerIos(fml::RefPtr platform_task_runner); + + void HandlePlatformMessage(std::unique_ptr message) override; + + bool DoesHandlePlatformMessageOnPlatformThread() const override; + + void InvokePlatformMessageResponseCallback(int response_id, + std::unique_ptr mapping) override; + + void InvokePlatformMessageEmptyResponseCallback(int response_id) override; + + void SetMessageHandler(const std::string& channel, + FlutterBinaryMessageHandler handler, + NSObject* task_queue); + + struct HandlerInfo { + NSObject* task_queue; + FlutterBinaryMessageHandler handler; + }; + + private: + std::unordered_map message_handlers_; + const fml::RefPtr platform_task_runner_; + std::mutex message_handlers_mutex_; + FML_DISALLOW_COPY_AND_ASSIGN(PlatformMessageHandlerIos); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_PLATFORM_MESSAGE_HANDLER_IOS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/platform_message_handler_ios.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/platform_message_handler_ios.mm new file mode 100644 index 0000000000000000000000000000000000000000..06110e1b5b7890afa09ab7bf78ee3e83cd2218cf --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/platform_message_handler_ios.mm @@ -0,0 +1,132 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/platform_message_handler_ios.h" + +#include "flutter/fml/trace_event.h" +#include "flutter/lib/ui/window/platform_message.h" +#include "flutter/lib/ui/window/platform_message_response.h" +#include "flutter/shell/platform/darwin/common/buffer_conversions.h" + +FLUTTER_ASSERT_ARC + +static uint64_t platform_message_counter = 1; + +@interface FLTSerialTaskQueue : NSObject +@property(nonatomic, readonly) dispatch_queue_t queue; +@end + +@implementation FLTSerialTaskQueue +- (instancetype)init { + self = [super init]; + if (self) { + _queue = dispatch_queue_create("FLTSerialTaskQueue", DISPATCH_QUEUE_SERIAL); + } + return self; +} + +- (void)dispatch:(dispatch_block_t)block { + dispatch_async(self.queue, block); +} +@end + +namespace flutter { + +NSObject* PlatformMessageHandlerIos::MakeBackgroundTaskQueue() { + return [[FLTSerialTaskQueue alloc] init]; +} + +PlatformMessageHandlerIos::PlatformMessageHandlerIos( + fml::RefPtr platform_task_runner) + : platform_task_runner_(std::move(platform_task_runner)) {} + +void PlatformMessageHandlerIos::HandlePlatformMessage(std::unique_ptr message) { + // This can be called from any isolate's thread. + @autoreleasepool { + fml::RefPtr completer = message->response(); + HandlerInfo handler_info; + { + // TODO(gaaclarke): This mutex is a bottleneck for multiple isolates sending + // messages at the same time. This could be potentially changed to a + // read-write lock. + std::lock_guard lock(message_handlers_mutex_); + auto it = message_handlers_.find(message->channel()); + if (it != message_handlers_.end()) { + handler_info = it->second; + } + } + if (handler_info.handler) { + FlutterBinaryMessageHandler handler = handler_info.handler; + NSData* data = nil; + if (message->hasData()) { + data = ConvertMappingToNSData(message->releaseData()); + } + + uint64_t platform_message_id = platform_message_counter++; + TRACE_EVENT_ASYNC_BEGIN1("flutter", "PlatformChannel ScheduleHandler", platform_message_id, + "channel", message->channel().c_str()); + dispatch_block_t run_handler = ^{ + handler(data, ^(NSData* reply) { + TRACE_EVENT_ASYNC_END0("flutter", "PlatformChannel ScheduleHandler", platform_message_id); + // Called from any thread. + if (completer) { + if (reply) { + completer->Complete(ConvertNSDataToMappingPtr(reply)); + } else { + completer->CompleteEmpty(); + } + } + }); + }; + + if (handler_info.task_queue) { + [handler_info.task_queue dispatch:run_handler]; + } else { + dispatch_async(dispatch_get_main_queue(), run_handler); + } + } else { + if (completer) { + completer->CompleteEmpty(); + } + } + } +} + +bool PlatformMessageHandlerIos::DoesHandlePlatformMessageOnPlatformThread() const { + return false; +} + +void PlatformMessageHandlerIos::InvokePlatformMessageResponseCallback( + int response_id, + std::unique_ptr mapping) { + // Called from any thread. + // TODO(gaaclarke): This vestigal from the Android implementation, find a way + // to migrate this to PlatformMessageHandlerAndroid. +} + +void PlatformMessageHandlerIos::InvokePlatformMessageEmptyResponseCallback(int response_id) { + // Called from any thread. + // TODO(gaaclarke): This vestigal from the Android implementation, find a way + // to migrate this to PlatformMessageHandlerAndroid. +} + +void PlatformMessageHandlerIos::SetMessageHandler(const std::string& channel, + FlutterBinaryMessageHandler handler, + NSObject* task_queue) { + FML_CHECK(platform_task_runner_->RunsTasksOnCurrentThread()); + // Use `respondsToSelector` instead of `conformsToProtocol` to accomodate + // injecting your own `FlutterTaskQueue`. This is not a supported usage but + // not one worth breaking. + FML_CHECK(!task_queue || [task_queue respondsToSelector:@selector(dispatch:)]); + /// TODO(gaaclarke): This should be migrated to a lockfree datastructure. + std::lock_guard lock(message_handlers_mutex_); + message_handlers_.erase(channel); + if (handler) { + message_handlers_[channel] = { + .task_queue = (NSObject*)task_queue, + .handler = handler, + }; + } +} +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/platform_message_handler_ios_test.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/platform_message_handler_ios_test.mm new file mode 100644 index 0000000000000000000000000000000000000000..c10f3720bc9f19e042ee5bdf11ab1dc3d3347f9d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/platform_message_handler_ios_test.mm @@ -0,0 +1,136 @@ +// 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. + +#import + +#import "flutter/shell/platform/darwin/ios/platform_message_handler_ios.h" + +#import "flutter/common/task_runners.h" +#import "flutter/fml/message_loop.h" +#import "flutter/fml/thread.h" +#import "flutter/lib/ui/window/platform_message.h" +#import "flutter/lib/ui/window/platform_message_response.h" +#import "flutter/shell/common/thread_host.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" + +FLUTTER_ASSERT_ARC + +// NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) +namespace { +using namespace flutter; +fml::RefPtr CreateNewThread(const std::string& name) { + auto thread = std::make_unique(name); + auto runner = thread->GetTaskRunner(); + return runner; +} + +fml::RefPtr GetCurrentTaskRunner() { + fml::MessageLoop::EnsureInitializedForCurrentThread(); + return fml::MessageLoop::GetCurrent().GetTaskRunner(); +} + +class MockPlatformMessageResponse : public PlatformMessageResponse { + public: + static fml::RefPtr Create() { + return fml::AdoptRef(new MockPlatformMessageResponse()); + } + void Complete(std::unique_ptr data) override { is_complete_ = true; } + void CompleteEmpty() override { is_complete_ = true; } +}; +} // namespace + +@interface PlatformMessageHandlerIosTest : XCTestCase +@end + +@implementation PlatformMessageHandlerIosTest +- (void)testCreate { + TaskRunners task_runners("test", GetCurrentTaskRunner(), CreateNewThread("raster"), + CreateNewThread("ui"), CreateNewThread("io")); + auto handler = std::make_unique(task_runners.GetPlatformTaskRunner()); + XCTAssertTrue(handler); +} + +- (void)testSetAndCallHandler { + ThreadHost thread_host("io.flutter.test." + std::string(self.name.UTF8String), + ThreadHost::Type::kRaster | ThreadHost::Type::kIo | ThreadHost::Type::kUi); + TaskRunners task_runners( + "test", GetCurrentTaskRunner(), thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), thread_host.io_thread->GetTaskRunner()); + + auto handler = std::make_unique(task_runners.GetPlatformTaskRunner()); + std::string channel = "foo"; + XCTestExpectation* didCallReply = [self expectationWithDescription:@"didCallReply"]; + handler->SetMessageHandler( + channel, + ^(NSData* _Nullable data, FlutterBinaryReply _Nonnull reply) { + reply(nil); + [didCallReply fulfill]; + }, + nil); + auto response = MockPlatformMessageResponse::Create(); + task_runners.GetUITaskRunner()->PostTask([channel, response, &handler] { + auto platform_message = std::make_unique(channel, response); + handler->HandlePlatformMessage(std::move(platform_message)); + }); + [self waitForExpectationsWithTimeout:1.0 handler:nil]; + XCTAssertTrue(response->is_complete()); +} + +- (void)testSetClearAndCallHandler { + ThreadHost thread_host("io.flutter.test." + std::string(self.name.UTF8String), + ThreadHost::Type::kRaster | ThreadHost::Type::kIo | ThreadHost::Type::kUi); + TaskRunners task_runners( + "test", GetCurrentTaskRunner(), thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), thread_host.io_thread->GetTaskRunner()); + + auto handler = std::make_unique(task_runners.GetPlatformTaskRunner()); + std::string channel = "foo"; + XCTestExpectation* didCallMessage = [self expectationWithDescription:@"didCallMessage"]; + handler->SetMessageHandler( + channel, + ^(NSData* _Nullable data, FlutterBinaryReply _Nonnull reply) { + XCTFail(@"This shouldn't be called"); + reply(nil); + }, + nil); + handler->SetMessageHandler(channel, nil, nil); + auto response = MockPlatformMessageResponse::Create(); + task_runners.GetUITaskRunner()->PostTask([channel, response, &handler, &didCallMessage] { + auto platform_message = std::make_unique(channel, response); + handler->HandlePlatformMessage(std::move(platform_message)); + [didCallMessage fulfill]; + }); + [self waitForExpectationsWithTimeout:1.0 handler:nil]; + XCTAssertTrue(response->is_complete()); +} + +- (void)testSetAndCallHandlerTaskQueue { + ThreadHost thread_host("io.flutter.test." + std::string(self.name.UTF8String), + ThreadHost::Type::kRaster | ThreadHost::Type::kIo | ThreadHost::Type::kUi); + TaskRunners task_runners( + "test", GetCurrentTaskRunner(), thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), thread_host.io_thread->GetTaskRunner()); + + auto handler = std::make_unique(task_runners.GetPlatformTaskRunner()); + std::string channel = "foo"; + XCTestExpectation* didCallReply = [self expectationWithDescription:@"didCallReply"]; + NSObject* taskQueue = PlatformMessageHandlerIos::MakeBackgroundTaskQueue(); + handler->SetMessageHandler( + channel, + ^(NSData* _Nullable data, FlutterBinaryReply _Nonnull reply) { + XCTAssertFalse([NSThread isMainThread]); + reply(nil); + [didCallReply fulfill]; + }, + taskQueue); + auto response = MockPlatformMessageResponse::Create(); + task_runners.GetUITaskRunner()->PostTask([channel, response, &handler] { + auto platform_message = std::make_unique(channel, response); + handler->HandlePlatformMessage(std::move(platform_message)); + }); + [self waitForExpectationsWithTimeout:1.0 handler:nil]; + XCTAssertTrue(response->is_complete()); +} +@end +// NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks) diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.h new file mode 100644 index 0000000000000000000000000000000000000000..274dff306ce8daa7f841b9e44b3a871cb8fe664e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.h @@ -0,0 +1,181 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_PLATFORM_VIEW_IOS_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_PLATFORM_VIEW_IOS_H_ + +#include + +#include "flutter/fml/closure.h" +#include "flutter/fml/macros.h" +#include "flutter/shell/common/platform_view.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterTexture.h" +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.h" +#import "flutter/shell/platform/darwin/ios/ios_context.h" +#import "flutter/shell/platform/darwin/ios/ios_external_view_embedder.h" +#import "flutter/shell/platform/darwin/ios/ios_surface.h" +#import "flutter/shell/platform/darwin/ios/platform_message_handler_ios.h" +#import "flutter/shell/platform/darwin/ios/rendering_api_selection.h" + +@class FlutterViewController; + +namespace flutter { + +/** + * A bridge connecting the platform agnostic shell and the iOS embedding. + * + * The shell provides and requests for UI related data and this PlatformView subclass fulfills + * it with iOS specific capabilities. As an example, the iOS embedding (the `FlutterEngine` and the + * `FlutterViewController`) sends pointer data to the shell and receives the shell's request for a + * Impeller AiksContext and supplies it. + * + * Despite the name "view", this class is unrelated to UIViews on iOS and doesn't have the same + * lifecycle. It's a long lived bridge owned by the `FlutterEngine` and can be attached and + * detached sequentially to multiple `FlutterViewController`s and `FlutterView`s. + */ +class PlatformViewIOS final : public PlatformView { + public: + PlatformViewIOS(PlatformView::Delegate& delegate, + const std::shared_ptr& context, + __weak FlutterPlatformViewsController* platform_views_controller, + const flutter::TaskRunners& task_runners); + + explicit PlatformViewIOS( + PlatformView::Delegate& delegate, + IOSRenderingAPI rendering_api, + __weak FlutterPlatformViewsController* platform_views_controller, + const flutter::TaskRunners& task_runners, + const std::shared_ptr& worker_task_runner, + const std::shared_ptr& is_gpu_disabled_sync_switch); + + ~PlatformViewIOS() override; + + /** + * Returns the `FlutterViewController` currently attached to the `FlutterEngine` owning + * this PlatformViewIOS. + */ + FlutterViewController* GetOwnerViewController() const __attribute__((cf_audited_transfer)); + + /** + * Updates the `FlutterViewController` currently attached to the `FlutterEngine` owning + * this PlatformViewIOS. This should be updated when the `FlutterEngine` + * is given a new `FlutterViewController`. + */ + void SetOwnerViewController(__weak FlutterViewController* owner_controller); + + /** + * Called one time per `FlutterViewController` when the `FlutterViewController`'s + * UIView is first loaded. + * + * Can be used to perform late initialization after `FlutterViewController`'s + * init. + */ + void attachView(); + + /** + * Called through when an external texture such as video or camera is + * given to the `FlutterEngine` or `FlutterViewController`. + */ + void RegisterExternalTexture(int64_t id, NSObject* texture); + + // |PlatformView| + PointerDataDispatcherMaker GetDispatcherMaker() override; + + // |PlatformView| + void SetSemanticsEnabled(bool enabled) override; + + // |PlatformView| + void HandlePlatformMessage(std::unique_ptr message) override; + + // |PlatformView| + std::unique_ptr CreateRenderingSurface() override; + + // |PlatformView| + std::shared_ptr CreateExternalViewEmbedder() override; + + // |PlatformView| + std::shared_ptr GetImpellerContext() const override; + + // |PlatformView| + void SetAccessibilityFeatures(int32_t flags) override; + + // |PlatformView| + void UpdateSemantics(int64_t view_id, + flutter::SemanticsNodeUpdates update, + flutter::CustomAccessibilityActionUpdates actions) override; + + // |PlatformView| + std::unique_ptr CreateVSyncWaiter() override; + + // |PlatformView| + void OnPreEngineRestart() const override; + + // |PlatformView| + std::unique_ptr> ComputePlatformResolvedLocales( + const std::vector& supported_locale_data) override; + + /** Accessor for the `IOSContext` associated with the platform view. */ + const std::shared_ptr& GetIosContext() { return ios_context_; } + + std::shared_ptr GetPlatformMessageHandlerIos() const { + return platform_message_handler_; + } + + std::shared_ptr GetPlatformMessageHandler() const override { + return platform_message_handler_; + } + + private: + /// Smart pointer for use with objective-c observers. + /// This guarantees we remove the observer. + class ScopedObserver { + public: + ScopedObserver(); + ~ScopedObserver(); + void reset(id observer); + ScopedObserver(const ScopedObserver&) = delete; + ScopedObserver& operator=(const ScopedObserver&) = delete; + + private: + id observer_ = nil; + }; + + /// Wrapper that guarantees we communicate clearing Accessibility + /// information to Dart. + class AccessibilityBridgeManager { + public: + explicit AccessibilityBridgeManager(const std::function& set_semantics_enabled); + AccessibilityBridgeManager(const std::function& set_semantics_enabled, + AccessibilityBridge* bridge); + explicit operator bool() const noexcept { return static_cast(accessibility_bridge_); } + AccessibilityBridge* get() const noexcept { return accessibility_bridge_.get(); } + void Set(std::unique_ptr bridge); + void Clear(); + + private: + FML_DISALLOW_COPY_AND_ASSIGN(AccessibilityBridgeManager); + std::unique_ptr accessibility_bridge_; + std::function set_semantics_enabled_; + }; + + __weak FlutterViewController* owner_controller_; + // Since the `ios_surface_` is created on the platform thread but + // used on the raster thread we need to protect it with a mutex. + std::mutex ios_surface_mutex_; + std::unique_ptr ios_surface_; + std::shared_ptr ios_context_; + __weak FlutterPlatformViewsController* platform_views_controller_; + AccessibilityBridgeManager accessibility_bridge_; + ScopedObserver dealloc_view_controller_observer_; + std::vector platform_resolved_locale_; + std::shared_ptr platform_message_handler_; + + FML_DISALLOW_COPY_AND_ASSIGN(PlatformViewIOS); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_PLATFORM_VIEW_IOS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.mm new file mode 100644 index 0000000000000000000000000000000000000000..15f6223d70095d4ea28370767022c6e5bdb9a157 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.mm @@ -0,0 +1,263 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/platform_view_ios.h" +#include + +#include + +#include "flutter/common/task_runners.h" +#include "flutter/fml/synchronization/waitable_event.h" +#include "flutter/fml/trace_event.h" +#include "flutter/shell/common/shell_io_manager.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.h" + +FLUTTER_ASSERT_ARC + +namespace flutter { + +PlatformViewIOS::AccessibilityBridgeManager::AccessibilityBridgeManager( + const std::function& set_semantics_enabled) + : AccessibilityBridgeManager(set_semantics_enabled, nullptr) {} + +PlatformViewIOS::AccessibilityBridgeManager::AccessibilityBridgeManager( + const std::function& set_semantics_enabled, + AccessibilityBridge* bridge) + : accessibility_bridge_(bridge), set_semantics_enabled_(set_semantics_enabled) { + if (bridge) { + set_semantics_enabled_(true); + } +} + +void PlatformViewIOS::AccessibilityBridgeManager::Set(std::unique_ptr bridge) { + accessibility_bridge_ = std::move(bridge); + set_semantics_enabled_(true); +} + +void PlatformViewIOS::AccessibilityBridgeManager::Clear() { + set_semantics_enabled_(false); + accessibility_bridge_.reset(); +} + +PlatformViewIOS::PlatformViewIOS(PlatformView::Delegate& delegate, + const std::shared_ptr& context, + __weak FlutterPlatformViewsController* platform_views_controller, + const flutter::TaskRunners& task_runners) + : PlatformView(delegate, task_runners), + ios_context_(context), + platform_views_controller_(platform_views_controller), + accessibility_bridge_([this](bool enabled) { PlatformView::SetSemanticsEnabled(enabled); }), + platform_message_handler_( + new PlatformMessageHandlerIos(task_runners.GetPlatformTaskRunner())) {} + +PlatformViewIOS::PlatformViewIOS( + PlatformView::Delegate& delegate, + IOSRenderingAPI rendering_api, + __weak FlutterPlatformViewsController* platform_views_controller, + const flutter::TaskRunners& task_runners, + const std::shared_ptr& worker_task_runner, + const std::shared_ptr& is_gpu_disabled_sync_switch) + : PlatformViewIOS(delegate, + IOSContext::Create(rendering_api, + delegate.OnPlatformViewGetSettings().enable_impeller + ? IOSRenderingBackend::kImpeller + : IOSRenderingBackend::kSkia, + is_gpu_disabled_sync_switch, + delegate.OnPlatformViewGetSettings()), + platform_views_controller, + task_runners) {} + +PlatformViewIOS::~PlatformViewIOS() = default; + +// |PlatformView| +void PlatformViewIOS::HandlePlatformMessage(std::unique_ptr message) { + platform_message_handler_->HandlePlatformMessage(std::move(message)); +} + +FlutterViewController* PlatformViewIOS::GetOwnerViewController() const { + return owner_controller_; +} + +void PlatformViewIOS::SetOwnerViewController(__weak FlutterViewController* owner_controller) { + FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); + std::lock_guard guard(ios_surface_mutex_); + if (ios_surface_ || !owner_controller) { + NotifyDestroyed(); + ios_surface_.reset(); + accessibility_bridge_.Clear(); + } + owner_controller_ = owner_controller; + + // Add an observer that will clear out the owner_controller_ ivar and + // the accessibility_bridge_ in case the view controller is deleted. + dealloc_view_controller_observer_.reset([[NSNotificationCenter defaultCenter] + addObserverForName:FlutterViewControllerWillDealloc + object:owner_controller_ + queue:[NSOperationQueue mainQueue] + usingBlock:^(NSNotification* note) { + // Implicit copy of 'this' is fine. + accessibility_bridge_.Clear(); + owner_controller_ = nil; + }]); + + if (owner_controller_ && owner_controller_.isViewLoaded) { + this->attachView(); + } + // Do not call `NotifyCreated()` here - let FlutterViewController take care + // of that when its Viewport is sized. If `NotifyCreated()` is called here, + // it can occasionally get invoked before the viewport is sized resulting in + // a framebuffer that will not be able to completely attach. +} + +void PlatformViewIOS::attachView() { + FML_DCHECK(owner_controller_); + FML_DCHECK(owner_controller_.isViewLoaded) << "FlutterViewController's view should be loaded " + "before attaching to PlatformViewIOS."; + FlutterView* flutter_view = static_cast(owner_controller_.view); + CALayer* ca_layer = flutter_view.layer; + ios_surface_ = IOSSurface::Create(ios_context_, ca_layer); + FML_DCHECK(ios_surface_ != nullptr); + + if (accessibility_bridge_) { + accessibility_bridge_.Set(std::make_unique( + owner_controller_, this, owner_controller_.platformViewsController)); + } +} + +PointerDataDispatcherMaker PlatformViewIOS::GetDispatcherMaker() { + return [](DefaultPointerDataDispatcher::Delegate& delegate) { + return std::make_unique(delegate); + }; +} + +void PlatformViewIOS::RegisterExternalTexture(int64_t texture_id, + NSObject* texture) { + RegisterTexture(ios_context_->CreateExternalTexture(texture_id, texture)); +} + +// |PlatformView| +std::unique_ptr PlatformViewIOS::CreateRenderingSurface() { + FML_DCHECK(task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()); + std::lock_guard guard(ios_surface_mutex_); + if (!ios_surface_) { + FML_DLOG(INFO) << "Could not CreateRenderingSurface, this PlatformViewIOS " + "has no ViewController."; + return nullptr; + } + return ios_surface_->CreateGPUSurface(); +} + +// |PlatformView| +std::shared_ptr PlatformViewIOS::CreateExternalViewEmbedder() { + return std::make_shared(platform_views_controller_, ios_context_); +} + +// |PlatformView| +std::shared_ptr PlatformViewIOS::GetImpellerContext() const { + return ios_context_->GetImpellerContext(); +} + +// |PlatformView| +void PlatformViewIOS::SetSemanticsEnabled(bool enabled) { + if (!owner_controller_) { + FML_LOG(WARNING) << "Could not set semantics to enabled, this " + "PlatformViewIOS has no ViewController."; + return; + } + if (enabled && !accessibility_bridge_) { + accessibility_bridge_.Set(std::make_unique( + owner_controller_, this, owner_controller_.platformViewsController)); + } else if (!enabled && accessibility_bridge_) { + accessibility_bridge_.Clear(); + } else { + PlatformView::SetSemanticsEnabled(enabled); + } +} + +// |shell:PlatformView| +void PlatformViewIOS::SetAccessibilityFeatures(int32_t flags) { + PlatformView::SetAccessibilityFeatures(flags); +} + +// |PlatformView| +void PlatformViewIOS::UpdateSemantics(int64_t view_id, + flutter::SemanticsNodeUpdates update, + flutter::CustomAccessibilityActionUpdates actions) { + FML_DCHECK(owner_controller_); + if (accessibility_bridge_) { + accessibility_bridge_.get()->UpdateSemantics(std::move(update), actions); + [[NSNotificationCenter defaultCenter] postNotificationName:FlutterSemanticsUpdateNotification + object:owner_controller_]; + } +} + +// |PlatformView| +std::unique_ptr PlatformViewIOS::CreateVSyncWaiter() { + return std::make_unique(task_runners_); +} + +void PlatformViewIOS::OnPreEngineRestart() const { + if (accessibility_bridge_) { + accessibility_bridge_.get()->clearState(); + } + if (!owner_controller_) { + return; + } + [owner_controller_.platformViewsController reset]; + [owner_controller_.restorationPlugin reset]; +} + +std::unique_ptr> PlatformViewIOS::ComputePlatformResolvedLocales( + const std::vector& supported_locale_data) { + size_t localeDataLength = 3; + NSMutableArray* supported_locale_identifiers = + [NSMutableArray arrayWithCapacity:supported_locale_data.size() / localeDataLength]; + for (size_t i = 0; i < supported_locale_data.size(); i += localeDataLength) { + NSDictionary* dict = @{ + NSLocaleLanguageCode : [NSString stringWithUTF8String:supported_locale_data[i].c_str()] + ?: @"", + NSLocaleCountryCode : [NSString stringWithUTF8String:supported_locale_data[i + 1].c_str()] + ?: @"", + NSLocaleScriptCode : [NSString stringWithUTF8String:supported_locale_data[i + 2].c_str()] + ?: @"" + }; + [supported_locale_identifiers addObject:[NSLocale localeIdentifierFromComponents:dict]]; + } + NSArray* result = + [NSBundle preferredLocalizationsFromArray:supported_locale_identifiers]; + + // Output format should be either empty or 3 strings for language, country, and script. + std::unique_ptr> out = std::make_unique>(); + + if (result != nullptr && [result count] > 0) { + NSLocale* locale = [NSLocale localeWithLocaleIdentifier:[result firstObject]]; + NSString* languageCode = [locale languageCode]; + out->emplace_back(languageCode == nullptr ? "" : languageCode.UTF8String); + NSString* countryCode = [locale countryCode]; + out->emplace_back(countryCode == nullptr ? "" : countryCode.UTF8String); + NSString* scriptCode = [locale scriptCode]; + out->emplace_back(scriptCode == nullptr ? "" : scriptCode.UTF8String); + } + return out; +} + +PlatformViewIOS::ScopedObserver::ScopedObserver() {} + +PlatformViewIOS::ScopedObserver::~ScopedObserver() { + if (observer_) { + [[NSNotificationCenter defaultCenter] removeObserver:observer_]; + } +} + +void PlatformViewIOS::ScopedObserver::reset(id observer) { + if (observer != observer_) { + if (observer_) { + [[NSNotificationCenter defaultCenter] removeObserver:observer_]; + } + observer_ = observer; + } +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/rendering_api_selection.h b/flutter/engine/src/flutter/shell/platform/darwin/ios/rendering_api_selection.h new file mode 100644 index 0000000000000000000000000000000000000000..54c4b9049944cda27e2eeae597523e62c40260f0 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/rendering_api_selection.h @@ -0,0 +1,43 @@ +// 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_SHELL_PLATFORM_DARWIN_IOS_RENDERING_API_SELECTION_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_RENDERING_API_SELECTION_H_ + +#include + +#include "flutter/fml/macros.h" + +namespace flutter { + +enum class IOSRenderingAPI { + kSoftware, + kMetal, +}; + +enum class IOSRenderingBackend { + kSkia, + kImpeller, +}; + +// Pass force_software to force software rendering. This is only respected on +// simulators. +IOSRenderingAPI GetRenderingAPIForProcess(bool force_software); + +Class GetCoreAnimationLayerClassForRenderingAPI(IOSRenderingAPI rendering_api); + +} // namespace flutter + +// Flutter supports Metal on all devices with Apple A7 SoC or above that have +// been updated to or past iOS 10.0. The processor was selected as it is the +// first version at which Metal was supported. The iOS version floor was +// selected due to the availability of features used by Skia. +// Support for Metal on simulators was added by Apple in the SDK for iOS 13. +#if TARGET_OS_SIMULATOR +#define METAL_IOS_VERSION_BASELINE 13.0 +#else +#define METAL_IOS_VERSION_BASELINE 10.0 +#endif // TARGET_OS_SIMULATOR + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_RENDERING_API_SELECTION_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/ios/rendering_api_selection.mm b/flutter/engine/src/flutter/shell/platform/darwin/ios/rendering_api_selection.mm new file mode 100644 index 0000000000000000000000000000000000000000..81099d7df1f3fc76a209f54cf60c9c8395d0cedd --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/ios/rendering_api_selection.mm @@ -0,0 +1,80 @@ +// 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. + +#import "flutter/shell/platform/darwin/ios/rendering_api_selection.h" + +#include +#include +#include +#import +#import + +#include "flutter/fml/logging.h" + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.h" + +FLUTTER_ASSERT_ARC + +namespace flutter { + +bool ShouldUseMetalRenderer() { + bool ios_version_supports_metal = false; + if (@available(iOS METAL_IOS_VERSION_BASELINE, *)) { + id device = MTLCreateSystemDefaultDevice(); + ios_version_supports_metal = [device supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily1_v3]; + } + return ios_version_supports_metal; +} + +IOSRenderingAPI GetRenderingAPIForProcess(bool force_software) { +#if TARGET_OS_SIMULATOR + if (force_software) { + return IOSRenderingAPI::kSoftware; + } +#else + if (force_software) { + FML_LOG(WARNING) << "The --enable-software-rendering is only supported on Simulator targets " + "and will be ignored."; + } +#endif // TARGET_OS_SIMULATOR + + static bool should_use_metal = ShouldUseMetalRenderer(); + if (should_use_metal) { + return IOSRenderingAPI::kMetal; + } + + // When Metal isn't available we use Skia software rendering since it performs + // a little better than emulated OpenGL. Also, omitting an OpenGL backend + // reduces binary footprint. +#if TARGET_OS_SIMULATOR + return IOSRenderingAPI::kSoftware; +#else + FML_CHECK(false) << "Metal may only be unavailable on simulators"; + return IOSRenderingAPI::kSoftware; +#endif // TARGET_OS_SIMULATOR +} + +Class GetCoreAnimationLayerClassForRenderingAPI(IOSRenderingAPI rendering_api) { + switch (rendering_api) { + case IOSRenderingAPI::kSoftware: + return [CALayer class]; + case IOSRenderingAPI::kMetal: + if (@available(iOS METAL_IOS_VERSION_BASELINE, *)) { + if ([FlutterMetalLayer enabled]) { + return [FlutterMetalLayer class]; + } else { + return [CAMetalLayer class]; + } + } + FML_CHECK(false) << "Metal availability should already have been checked"; + break; + default: + break; + } + FML_CHECK(false) << "Unknown client rendering API"; + return [CALayer class]; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/BUILD.gn b/flutter/engine/src/flutter/shell/platform/darwin/macos/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..09fd4902461002b765936f1b7830430fcb6977a7 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/BUILD.gn @@ -0,0 +1,401 @@ +# 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. + +assert(is_mac) + +import("//build/config/mac/mac_sdk.gni") +import("//flutter/build/zip_bundle.gni") +import("//flutter/shell/gpu/gpu.gni") +import("//flutter/shell/platform/darwin/common/framework_common.gni") +import("//flutter/shell/platform/glfw/config.gni") +import("//flutter/testing/testing.gni") + +shell_gpu_configuration("macos_gpu_configuration") { + enable_software = true + enable_gl = true + enable_vulkan = false + enable_metal = true +} + +group("macos") { + deps = [ ":flutter_framework" ] + if (build_glfw_shell) { + deps += [ + ":flutter_macos_glfw", + "//flutter/shell/platform/glfw:publish_headers_glfw", + "//flutter/shell/platform/glfw/client_wrapper:publish_wrapper_glfw", + ] + } +} + +_flutter_framework_name = "FlutterMacOS" +_flutter_framework_filename = "$_flutter_framework_name.framework" +_flutter_framework_dir = "$root_out_dir/$_flutter_framework_filename" +_framework_binary_subpath = "Versions/A/$_flutter_framework_name" + +# The headers that will be copied to the framework and be accessed from outside +# the Flutter engine source root. +_flutter_framework_headers = [ + "framework/Headers/FlutterAppDelegate.h", + "framework/Headers/FlutterAppLifecycleDelegate.h", + "framework/Headers/FlutterEngine.h", + "framework/Headers/FlutterMacOS.h", + "framework/Headers/FlutterPlatformViews.h", + "framework/Headers/FlutterPluginMacOS.h", + "framework/Headers/FlutterPluginRegistrarMacOS.h", + "framework/Headers/FlutterViewController.h", +] + +_flutter_framework_headers_copy_dir = + "$_flutter_framework_dir/Versions/A/Headers" + +source_set("flutter_framework_source") { + visibility = [ ":*" ] + cflags_objc = flutter_cflags_objc + cflags_objcc = flutter_cflags_objcc + + sources = [ + "framework/Source/AccessibilityBridgeMac.h", + "framework/Source/AccessibilityBridgeMac.mm", + "framework/Source/FlutterAppDelegate.mm", + "framework/Source/FlutterAppLifecycleDelegate.mm", + "framework/Source/FlutterBackingStore.h", + "framework/Source/FlutterBackingStore.mm", + "framework/Source/FlutterChannelKeyResponder.h", + "framework/Source/FlutterChannelKeyResponder.mm", + "framework/Source/FlutterCompositor.h", + "framework/Source/FlutterCompositor.mm", + "framework/Source/FlutterDartProject.mm", + "framework/Source/FlutterDartProject_Internal.h", + "framework/Source/FlutterDisplayLink.h", + "framework/Source/FlutterDisplayLink.mm", + "framework/Source/FlutterEmbedderKeyResponder.h", + "framework/Source/FlutterEmbedderKeyResponder.mm", + "framework/Source/FlutterEngine.mm", + "framework/Source/FlutterEngine_Internal.h", + "framework/Source/FlutterExternalTexture.h", + "framework/Source/FlutterExternalTexture.mm", + "framework/Source/FlutterKeyPrimaryResponder.h", + "framework/Source/FlutterKeyboardLayout.h", + "framework/Source/FlutterKeyboardLayout.mm", + "framework/Source/FlutterKeyboardManager.h", + "framework/Source/FlutterKeyboardManager.mm", + "framework/Source/FlutterMenuPlugin.h", + "framework/Source/FlutterMenuPlugin.mm", + "framework/Source/FlutterMenuPlugin_Internal.h", + "framework/Source/FlutterMouseCursorPlugin.h", + "framework/Source/FlutterMouseCursorPlugin.mm", + "framework/Source/FlutterMutatorView.h", + "framework/Source/FlutterMutatorView.mm", + "framework/Source/FlutterPlatformNodeDelegateMac.h", + "framework/Source/FlutterPlatformNodeDelegateMac.mm", + "framework/Source/FlutterPlatformViewController.h", + "framework/Source/FlutterPlatformViewController.mm", + "framework/Source/FlutterRenderer.h", + "framework/Source/FlutterRenderer.mm", + "framework/Source/FlutterResizeSynchronizer.h", + "framework/Source/FlutterResizeSynchronizer.mm", + "framework/Source/FlutterRunLoop.h", + "framework/Source/FlutterRunLoop.mm", + "framework/Source/FlutterSurface.h", + "framework/Source/FlutterSurface.mm", + "framework/Source/FlutterSurfaceManager.h", + "framework/Source/FlutterSurfaceManager.mm", + "framework/Source/FlutterTextInputPlugin.h", + "framework/Source/FlutterTextInputPlugin.mm", + "framework/Source/FlutterTextInputSemanticsObject.h", + "framework/Source/FlutterTextInputSemanticsObject.mm", + "framework/Source/FlutterTextureRegistrar.h", + "framework/Source/FlutterTextureRegistrar.mm", + "framework/Source/FlutterTimeConverter.h", + "framework/Source/FlutterTimeConverter.mm", + "framework/Source/FlutterVSyncWaiter.h", + "framework/Source/FlutterVSyncWaiter.mm", + "framework/Source/FlutterView.h", + "framework/Source/FlutterView.mm", + "framework/Source/FlutterViewController.mm", + "framework/Source/FlutterViewController_Internal.h", + "framework/Source/FlutterViewEngineProvider.h", + "framework/Source/FlutterViewEngineProvider.mm", + "framework/Source/FlutterViewProvider.h", + "framework/Source/KeyCodeMap.g.mm", + ] + + sources += _flutter_framework_headers + + deps = [ + ":macos_gpu_configuration", + "//flutter/flow:flow", + "//flutter/fml", + "//flutter/shell/platform/common:common_cpp_accessibility", + "//flutter/shell/platform/common:common_cpp_enums", + "//flutter/shell/platform/common:common_cpp_input", + "//flutter/shell/platform/common:common_cpp_switches", + "//flutter/shell/platform/darwin/common:availability_version_check", + "//flutter/shell/platform/darwin/common:framework_common", + "//flutter/shell/platform/darwin/graphics:graphics", + "//flutter/shell/platform/embedder:embedder_as_internal_library", + "//flutter/skia", + ] + + public_configs = [ "//flutter:config" ] + + defines = [ + "FLUTTER_FRAMEWORK", + "FLUTTER_ENGINE_NO_PROTOTYPES", + ] + + frameworks = [ + "Carbon.framework", + "Cocoa.framework", + "CoreVideo.framework", + "IOSurface.framework", + "Metal.framework", + "QuartzCore.framework", + ] +} + +shared_library("flutter_framework_dylib") { + visibility = [ ":*" ] + output_name = "$_flutter_framework_name" + + ldflags = [ + "-Wl,-install_name,@rpath/$_flutter_framework_filename/$_framework_binary_subpath", + "-fapplication-extension", + ] + + deps = [ ":flutter_framework_source" ] +} + +test_fixtures("flutter_desktop_darwin_fixtures") { + dart_main = "framework/Source/fixtures/flutter_desktop_test.dart" + + fixtures = [ "//flutter/third_party/icu/common/icudtl.dat" ] +} + +executable("flutter_desktop_darwin_unittests") { + testonly = true + cflags_objc = flutter_cflags_objc + cflags_objcc = flutter_cflags_objcc + ldflags = [ "-ObjC" ] + + sources = [ + "framework/Source/AccessibilityBridgeMacTest.mm", + "framework/Source/FlutterAppDelegateTest.mm", + "framework/Source/FlutterAppLifecycleDelegateTest.mm", + "framework/Source/FlutterChannelKeyResponderTest.mm", + "framework/Source/FlutterDisplayLinkTest.mm", + "framework/Source/FlutterEmbedderExternalTextureTest.mm", + "framework/Source/FlutterEmbedderKeyResponderTest.mm", + "framework/Source/FlutterEngineTest.mm", + "framework/Source/FlutterEngineTestUtils.h", + "framework/Source/FlutterEngineTestUtils.mm", + "framework/Source/FlutterKeyboardManagerTest.mm", + "framework/Source/FlutterMenuPluginTest.mm", + "framework/Source/FlutterMutatorViewTest.mm", + "framework/Source/FlutterPlatformNodeDelegateMacTest.mm", + "framework/Source/FlutterPlatformViewControllerTest.mm", + "framework/Source/FlutterResizeSynchronizerTest.mm", + "framework/Source/FlutterSurfaceManagerTest.mm", + "framework/Source/FlutterTextInputPluginTest.mm", + "framework/Source/FlutterTextInputSemanticsObjectTest.mm", + "framework/Source/FlutterVSyncWaiterTest.mm", + "framework/Source/FlutterViewControllerTest.mm", + "framework/Source/FlutterViewControllerTestUtils.h", + "framework/Source/FlutterViewControllerTestUtils.mm", + "framework/Source/FlutterViewEngineProviderTest.mm", + "framework/Source/FlutterViewTest.mm", + "framework/Source/KeyCodeMapTest.mm", + "framework/Source/TestFlutterPlatformView.h", + "framework/Source/TestFlutterPlatformView.mm", + ] + + deps = [ + ":flutter_desktop_darwin_fixtures", + ":flutter_framework_source", + "//flutter/fml", + "//flutter/shell/platform/common:common_cpp_accessibility", + "//flutter/shell/platform/common:common_cpp_enums", + "//flutter/shell/platform/darwin/common:framework_common", + "//flutter/shell/platform/darwin/graphics", + "//flutter/shell/platform/embedder:embedder_as_internal_library", + "//flutter/shell/platform/embedder:embedder_test_utils", + "//flutter/testing", + "//flutter/testing:autoreleasepool_test", + "//flutter/testing:dart", + "//flutter/testing:skia", + "//flutter/testing:testing_lib", + "//flutter/third_party/ocmock:ocmock", + ] +} + +copy("copy_dylib") { + visibility = [ ":*" ] + + sources = [ "$root_out_dir/lib$_flutter_framework_name.dylib" ] + outputs = [ "$_flutter_framework_dir/$_framework_binary_subpath" ] + + deps = [ ":flutter_framework_dylib" ] +} + +copy("copy_framework_info_plist") { + visibility = [ ":*" ] + sources = [ "framework/Info.plist" ] + outputs = [ "$_flutter_framework_dir/Versions/A/Resources/Info.plist" ] +} + +copy("copy_framework_module_map") { + visibility = [ ":*" ] + sources = [ "framework/module.modulemap" ] + outputs = [ "$_flutter_framework_dir/Versions/A/Modules/module.modulemap" ] +} + +# Copy privacy manifest. This file is required by Apple for third-party SDKs. +# See https://developer.apple.com/documentation/bundleresources/privacy_manifest_files +copy("copy_framework_privacy_manifest") { + visibility = [ ":*" ] + sources = [ "framework/PrivacyInfo.xcprivacy" ] + outputs = + [ "$_flutter_framework_dir/Versions/A/Resources/PrivacyInfo.xcprivacy" ] +} + +action("copy_framework_headers") { + script = "//flutter/sky/tools/install_framework_headers.py" + visibility = [ ":*" ] + sources = get_path_info(_flutter_framework_headers, "abspath") + + framework_common_headers + outputs = [] + foreach(header, sources) { + header_basename = get_path_info(header, "file") + outputs += [ "$_flutter_framework_headers_copy_dir/$header_basename" ] + } + args = [ + "--location", + rebase_path("$_flutter_framework_headers_copy_dir"), + "--headers", + ] + rebase_path(sources, "", "//") +} + +copy("copy_framework_icu") { + visibility = [ ":*" ] + sources = [ "//flutter/third_party/icu/flutter/icudtl.dat" ] + outputs = + [ "$_flutter_framework_dir/Versions/A/Resources/{{source_file_part}}" ] +} + +copy("copy_license") { + visibility = [ ":*" ] + sources = [ "//LICENSE" ] + outputs = [ "$root_out_dir/LICENSE" ] +} + +action("_generate_symlinks") { + visibility = [ ":*" ] + script = "//build/config/mac/package_framework.py" + outputs = [ + "$root_build_dir/$_flutter_framework_name.stamp", + "$root_out_dir/$_flutter_framework_filename", + ] + args = [ + "--framework", + "$_flutter_framework_filename", + "--version", + "A", + "--contents", + "$_flutter_framework_name", + "Resources", + "Headers", + "Modules", + "--stamp", + "$_flutter_framework_name.stamp", + ] + deps = [ + ":copy_dylib", + ":copy_framework_headers", + ":copy_framework_icu", + ":copy_framework_info_plist", + ":copy_framework_module_map", + ":copy_framework_privacy_manifest", + ":copy_license", + ] + metadata = { + macos_framework_without_entitlement = + [ "FlutterMacOS.framework.zip/Versions/A/FlutterMacOS" ] + } +} + +group("universal_flutter_framework") { + visibility = [ ":*" ] + deps = [ + ":_generate_symlinks", + ":_generate_symlinks_and_verify_framework_module", + ] +} + +action("flutter_framework") { + script = "//flutter/sky/tools/create_xcframework.py" + outputs = [ "$root_out_dir/FlutterMacOS.xcframework" ] + args = [ + "--frameworks", + rebase_path(_flutter_framework_dir), + "--name", + "FlutterMacOS", + "--location", + rebase_path(root_out_dir), + ] + deps = [ ":universal_flutter_framework" ] +} + +if (build_glfw_shell) { + shared_library("flutter_macos_glfw") { + deps = [ "//flutter/shell/platform/glfw:flutter_glfw" ] + + public_configs = [ "//flutter:config" ] + } +} + +zip_bundle("zip_macos_flutter_framework") { + deps = [ + ":_generate_symlinks", + ":macos_framework_without_entitlement_config", + ] + prefix = "$full_platform_name-$flutter_runtime_mode/" + if (flutter_runtime_mode == "debug") { + prefix = "$full_platform_name/" + } + output = "${prefix}FlutterMacOS.framework.zip" + visibility = [ ":*" ] + files = [ + { + source = "$root_out_dir/FlutterMacOS.framework" + destination = "FlutterMacOS.framework" + }, + ] +} + +generated_file("macos_framework_without_entitlement_config") { + outputs = [ "$target_gen_dir/framework_without_entitlements.txt" ] + + data_keys = [ "macos_framework_without_entitlement" ] + + deps = [ ":_generate_symlinks" ] +} + +shared_library("_generate_symlinks_and_verify_framework_module") { + framework_search_path = rebase_path("$root_out_dir") + visibility = [ ":*" ] + cflags_objc = [ "-F$framework_search_path" ] + + ldflags = [ + "-F$framework_search_path", + "-fapplication-extension", + "-Xlinker", + "-fatal_warnings", + ] + frameworks = [ "FlutterMacOS.framework" ] + + sources = [ "framework/Source/FlutterUmbrellaImportTests.m" ] + + deps = [ ":_generate_symlinks" ] +} diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/README.md b/flutter/engine/src/flutter/shell/platform/darwin/macos/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8d74d685d7bbf79b919a5983aa9abcf4891319a6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/README.md @@ -0,0 +1,55 @@ +# Flutter macOS Embedder + +This directory contains files specific to the Flutter macOS embedder. The +embedder is built as a macOS framework that is linked into the target +application. The framework is composed both of macOS-specific code and code +shared with the iOS embedder. These can be found in: +``` +flutter/shell/platform/darwin/common/framework +flutter/shell/platform/darwin/macos/framework +``` + +Additionally, the framework relies on utility code shared across all embedders, +which is found in: +``` +flutter/shell/platform/common +``` + +To learn more, see the [Engine architecture wiki][wiki_arch]. + +## Building + +Building all artifacts required for macOS occurs in two steps: +* Host binary build: Builds tooling used by the Flutter tool to build Flutter + applications targeting macOS. +* macOS Target build: Builds the framework that implements the macOS Flutter + embedder and exposes public API such as `FlutterViewController` used by + Flutter applications. + +Once you've [prepared your environment for engine development][wiki_engine_env], +you can build the macOS embedder from the `src/flutter` directory using the +following commands: +```sh +# Perform the host build. +./tools/gn --unopt +ninja -C ../out/host_debug_unopt + +# Perform the macOS target build. +./tools/gn --unopt --mac +ninja -C ../out/mac_debug_unopt +``` +Builds are architecture-specific, and can be controlled by specifying +`--mac-cpu=arm64` or `--mac-cpu=x64` (default) when invoking `gn`. + +## Testing + +The macOS-specific embedder tests are built as the +`flutter_desktop_darwin_unittests` binary. Like all gtest-based test binaries, a +subset of tests can be run by applying a filter such as +`--gtest_filter='FlutterViewControllerTest.*Key*'`. + +More general details on testing can be found on the [Wiki][wiki_engine_testing]. + +[wiki_arch]: https://github.com/flutter/flutter/wiki/The-Engine-architecture +[wiki_engine_env]: https://github.com/flutter/flutter/wiki/Setting-up-the-Engine-development-environment +[wiki_engine_testing]: https://github.com/flutter/flutter/wiki/Testing-the-engine diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppDelegate.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppDelegate.h new file mode 100644 index 0000000000000000000000000000000000000000..9390a011655dd21ec90588ff5ba95547a7463eea --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppDelegate.h @@ -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. + +#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERAPPDELEGATE_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERAPPDELEGATE_H_ + +#import + +#import "FlutterAppLifecycleDelegate.h" +#import "FlutterMacros.h" + +/** + * A protocol to be implemented by the `NSApplicationDelegate` of an application to enable the + * Flutter framework and any Flutter plugins to register to receive application life cycle events. + * + * Implementers should forward all of the `NSApplicationDelegate` methods corresponding to the + * handlers in FlutterAppLifecycleDelegate to any registered delegates. + */ +FLUTTER_DARWIN_EXPORT +@protocol FlutterAppLifecycleProvider + +/** + * Adds an object implementing |FlutterAppLifecycleDelegate| to the list of + * delegates to be informed of application lifecycle events. + */ +- (void)addApplicationLifecycleDelegate:(nonnull NSObject*)delegate; + +/** + * Removes an object implementing |FlutterAppLifecycleDelegate| to the list of + * delegates to be informed of application lifecycle events. + */ +- (void)removeApplicationLifecycleDelegate:(nonnull NSObject*)delegate; + +@end + +/** + * |NSApplicationDelegate| subclass for simple apps that want default behavior. + * + * This class implements the following behaviors: + * * Updates the application name of items in the application menu to match the name in + * the app's Info.plist, assuming it is set to APP_NAME initially. |applicationMenu| must be + * set before the application finishes launching for this to take effect. + * * Updates the main Flutter window's title to match the name in the app's Info.plist. + * |mainFlutterWindow| must be set before the application finishes launching for this to take + * effect. + * * Forwards `NSApplicationDelegate` callbacks to plugins that register for them. + * + * App delegates for Flutter applications are *not* required to inherit from + * this class. Developers of custom app delegate classes should copy and paste + * code as necessary from FlutterAppDelegate.mm. + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterAppDelegate : NSObject + +/** + * The application menu in the menu bar. + */ +@property(weak, nonatomic, nullable) IBOutlet NSMenu* applicationMenu; + +/** + * The primary application window containing a FlutterViewController. This is + * primarily intended for use in single-window applications. + */ +@property(weak, nonatomic, nullable) IBOutlet NSWindow* mainFlutterWindow; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERAPPDELEGATE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppLifecycleDelegate.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppLifecycleDelegate.h new file mode 100644 index 0000000000000000000000000000000000000000..85ce96aa65c517aabaeb5309fba73171911c40ff --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppLifecycleDelegate.h @@ -0,0 +1,147 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERAPPLIFECYCLEDELEGATE_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERAPPLIFECYCLEDELEGATE_H_ + +#import +#include + +#import "FlutterMacros.h" + +NS_ASSUME_NONNULL_BEGIN + +#pragma mark - +/** + * Protocol for listener of lifecycle events from the NSApplication, typically a + * FlutterPlugin. + */ +FLUTTER_DARWIN_EXPORT +@protocol FlutterAppLifecycleDelegate + +@optional +/** + * Called when the |FlutterAppDelegate| gets the applicationWillFinishLaunching + * notification. + */ +- (void)handleWillFinishLaunching:(NSNotification*)notification; + +/** + * Called when the |FlutterAppDelegate| gets the applicationDidFinishLaunching + * notification. + */ +- (void)handleDidFinishLaunching:(NSNotification*)notification; + +/** + * Called when the |FlutterAppDelegate| gets the applicationWillBecomeActive + * notification. + */ +- (void)handleWillBecomeActive:(NSNotification*)notification; + +/** + * Called when the |FlutterAppDelegate| gets the applicationDidBecomeActive + * notification. + */ +- (void)handleDidBecomeActive:(NSNotification*)notification; + +/** + * Called when the |FlutterAppDelegate| gets the applicationWillResignActive + * notification. + */ +- (void)handleWillResignActive:(NSNotification*)notification; + +/** + * Called when the |FlutterAppDelegate| gets the applicationWillResignActive + * notification. + */ +- (void)handleDidResignActive:(NSNotification*)notification; + +/** + * Called when the |FlutterAppDelegate| gets the applicationWillHide + * notification. + */ +- (void)handleWillHide:(NSNotification*)notification; + +/** + * Called when the |FlutterAppDelegate| gets the applicationDidHide + * notification. + */ +- (void)handleDidHide:(NSNotification*)notification; + +/** + * Called when the |FlutterAppDelegate| gets the applicationWillUnhide + * notification. + */ +- (void)handleWillUnhide:(NSNotification*)notification; + +/** + * Called when the |FlutterAppDelegate| gets the applicationDidUnhide + * notification. + */ +- (void)handleDidUnhide:(NSNotification*)notification; + +/** + * Called when the |FlutterAppDelegate| gets the applicationDidUnhide + * notification. + */ +- (void)handleDidChangeScreenParameters:(NSNotification*)notification; + +/** + * Called when the |FlutterAppDelegate| gets the applicationDidUnhide + * notification. + */ +- (void)handleDidChangeOcclusionState:(NSNotification*)notification; + +/** + * Called when the |FlutterAppDelegate| gets the application:openURLs: + * callback. + * + * Implementers should return YES if they handle the URLs, otherwise NO. + * Delegates will be called in order of registration, and once a delegate + * returns YES, no further delegates will reiceve this callback. + */ +- (BOOL)handleOpenURLs:(NSArray*)urls; + +/** + * Called when the |FlutterAppDelegate| gets the applicationWillTerminate + * notification. + * + * Applications should not rely on always receiving all possible notifications. + * + * For example, if the application is killed with a task manager, a kill signal, + * the user pulls the power from the device, or there is a rapid unscheduled + * disassembly of the device, no notification will be sent before the + * application is suddenly terminated, and this notification may be skipped. + */ +- (void)handleWillTerminate:(NSNotification*)notification; +@end + +#pragma mark - + +/** + * Propagates `NSAppDelegate` callbacks to registered delegates. + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterAppLifecycleRegistrar : NSObject + +/** + * Registers `delegate` to receive lifecycle callbacks via this + * FlutterAppLifecycleDelegate as long as it is alive. + * + * `delegate` will only be referenced weakly. + */ +- (void)addDelegate:(NSObject*)delegate; + +/** + * Unregisters `delegate` so that it will no longer receive life cycle callbacks + * via this FlutterAppLifecycleDelegate. + * + * `delegate` will only be referenced weakly. + */ +- (void)removeDelegate:(NSObject*)delegate; +@end + +NS_ASSUME_NONNULL_END + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERAPPLIFECYCLEDELEGATE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h new file mode 100644 index 0000000000000000000000000000000000000000..306bfceb08b79352f69dd0df54579c0c297b21e4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h @@ -0,0 +1,103 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERENGINE_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERENGINE_H_ + +#import + +#include + +#import "FlutterAppLifecycleDelegate.h" +#import "FlutterBinaryMessenger.h" +#import "FlutterDartProject.h" +#import "FlutterHourFormat.h" +#import "FlutterMacros.h" +#import "FlutterPluginRegistrarMacOS.h" +#import "FlutterTexture.h" + +// TODO(stuartmorgan): Merge this file with the iOS FlutterEngine.h. + +@class FlutterViewController; + +/** + * Coordinates a single instance of execution of a Flutter engine. + * + * A FlutterEngine can only be attached with one controller from the native + * code. + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterEngine + : NSObject + +/** + * Initializes an engine with the given project. + * + * @param labelPrefix Currently unused; in the future, may be used for labelling threads + * as with the iOS FlutterEngine. + * @param project The project configuration. If nil, a default FlutterDartProject will be used. + */ +- (nonnull instancetype)initWithName:(nonnull NSString*)labelPrefix + project:(nullable FlutterDartProject*)project; + +/** + * Initializes an engine that can run headlessly with the given project. + * + * @param labelPrefix Currently unused; in the future, may be used for labelling threads + * as with the iOS FlutterEngine. + * @param project The project configuration. If nil, a default FlutterDartProject will be used. + */ +- (nonnull instancetype)initWithName:(nonnull NSString*)labelPrefix + project:(nullable FlutterDartProject*)project + allowHeadlessExecution:(BOOL)allowHeadlessExecution NS_DESIGNATED_INITIALIZER; + +- (nonnull instancetype)init NS_UNAVAILABLE; + +/** + * Runs a Dart program on an Isolate from the main Dart library (i.e. the library that + * contains `main()`). + * + * The first call to this method will create a new Isolate. Subsequent calls will return + * immediately. + * + * @param entrypoint The name of a top-level function from the same Dart + * library that contains the app's main() function. If this is nil, it will + * default to `main()`. If it is not the app's main() function, that function + * must be decorated with `@pragma(vm:entry-point)` to ensure the method is not + * tree-shaken by the Dart compiler. + * @return YES if the call succeeds in creating and running a Flutter Engine instance; NO otherwise. + */ +- (BOOL)runWithEntrypoint:(nullable NSString*)entrypoint; + +/** + * The `FlutterViewController` of this engine, if any. + * + * This view is used by legacy APIs that assume a single view. + * + * Setting this field from nil to a non-nil view controller also updates + * the view controller's engine and ID. + * + * Setting this field from non-nil to nil will terminate the engine if + * allowHeadlessExecution is NO. + * + * Setting this field from non-nil to a different non-nil FlutterViewController + * is prohibited and will throw an assertion error. + */ +@property(nonatomic, nullable, weak) FlutterViewController* viewController; + +/** + * The `FlutterBinaryMessenger` for communicating with this engine. + */ +@property(nonatomic, nonnull, readonly) id binaryMessenger; + +/** + * Shuts the Flutter engine if it is running. The FlutterEngine instance must always be shutdown + * before it may be collected. Not shutting down the FlutterEngine instance before releasing it will + * result in the leak of that engine instance. + */ +- (void)shutDownEngine; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERENGINE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterMacOS.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterMacOS.h new file mode 100644 index 0000000000000000000000000000000000000000..f79332512f8b5e85c6e89e72c674e50a0dc07cb2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterMacOS.h @@ -0,0 +1,21 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERMACOS_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERMACOS_H_ + +#import "FlutterAppDelegate.h" +#import "FlutterAppLifecycleDelegate.h" +#import "FlutterBinaryMessenger.h" +#import "FlutterChannels.h" +#import "FlutterCodecs.h" +#import "FlutterDartProject.h" +#import "FlutterEngine.h" +#import "FlutterMacros.h" +#import "FlutterPluginMacOS.h" +#import "FlutterPluginRegistrarMacOS.h" +#import "FlutterTexture.h" +#import "FlutterViewController.h" + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERMACOS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterPlatformViews.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterPlatformViews.h new file mode 100644 index 0000000000000000000000000000000000000000..2f35b898c3df3fecf499f4e16e47e96a019f8a00 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterPlatformViews.h @@ -0,0 +1,40 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERPLATFORMVIEWS_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERPLATFORMVIEWS_H_ + +#import + +#import "FlutterCodecs.h" +#import "FlutterMacros.h" + +@protocol FlutterPlatformViewFactory + +/** + * Create a Platform View which is an `NSView`. + * + * A MacOS plugin should implement this method and return an `NSView`, which can be embedded in a + * Flutter App. + * + * The implementation of this method should create a new `NSView`. + * + * @param viewId A unique identifier for this view. + * @param args Parameters for creating the view sent from the Dart side of the + * Flutter app. If `createArgsCodec` is not implemented, or if no creation arguments were sent from + * the Dart code, this will be null. Otherwise this will be the value sent from the Dart code as + * decoded by `createArgsCodec`. + */ +- (nonnull NSView*)createWithViewIdentifier:(int64_t)viewId arguments:(nullable id)args; + +/** + * Returns the `FlutterMessageCodec` for decoding the args parameter of `createWithFrame`. + * + * Only implement this if `createWithFrame` needs an arguments parameter. + */ +@optional +- (nullable NSObject*)createArgsCodec; +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERPLATFORMVIEWS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginMacOS.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginMacOS.h new file mode 100644 index 0000000000000000000000000000000000000000..8cc14928e1f8858cfc6bd4c07d0cafa09a7bfbb1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginMacOS.h @@ -0,0 +1,56 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERPLUGINMACOS_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERPLUGINMACOS_H_ + +#import + +#import "FlutterAppLifecycleDelegate.h" +#import "FlutterChannels.h" +#import "FlutterCodecs.h" +#import "FlutterMacros.h" + +NS_ASSUME_NONNULL_BEGIN + +@protocol FlutterPluginRegistrar; + +/** + * Implemented by the platform side of a Flutter plugin. + * + * Defines a set of optional callback methods and a method to set up the plugin + * and register it to be called by other application components. + * + * Currently the macOS version of FlutterPlugin has very limited functionality, but is expected to + * expand over time to more closely match the functionality of the iOS FlutterPlugin. + */ +FLUTTER_DARWIN_EXPORT +@protocol FlutterPlugin + +/** + * Creates an instance of the plugin to register with |registrar| using the desired + * FlutterPluginRegistrar methods. + */ ++ (void)registerWithRegistrar:(id)registrar; + +@optional + +/** + * Called when a message is sent from Flutter on a channel that a plugin instance has subscribed + * to via -[FlutterPluginRegistrar addMethodCallDelegate:channel:]. + * + * The |result| callback must be called exactly once, with one of: + * - FlutterMethodNotImplemented, if the method call is unknown. + * - A FlutterError, if the method call was understood but there was a + * problem handling it. + * - Any other value (including nil) to indicate success. The value will + * be returned to the Flutter caller, and must be serializable to JSON. + */ +- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result; + +NS_ASSUME_NONNULL_END + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERPLUGINMACOS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginRegistrarMacOS.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginRegistrarMacOS.h new file mode 100644 index 0000000000000000000000000000000000000000..5b990dd84da18f8a7e4416a33c40a2301d4c8858 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginRegistrarMacOS.h @@ -0,0 +1,151 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERPLUGINREGISTRARMACOS_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERPLUGINREGISTRARMACOS_H_ + +#import + +#import "FlutterBinaryMessenger.h" +#import "FlutterChannels.h" +#import "FlutterMacros.h" +#import "FlutterPlatformViews.h" +#import "FlutterPluginMacOS.h" +#import "FlutterTexture.h" + +// TODO(stuartmorgan): Merge this file and FlutterPluginMacOS.h with the iOS FlutterPlugin.h, +// sharing all but the platform-specific methods. + +/** + * The protocol for an object managing registration for a plugin. It provides access to application + * context, as allowing registering for callbacks for handling various conditions. + * + * Currently the macOS PluginRegistrar has very limited functionality, but is expected to expand + * over time to more closely match the functionality of FlutterPluginRegistrar. + */ +FLUTTER_DARWIN_EXPORT +@protocol FlutterPluginRegistrar + +/** + * The binary messenger used for creating channels to communicate with the Flutter engine. + */ +@property(nonnull, readonly) id messenger; + +/** + * Returns a `FlutterTextureRegistry` for registering textures + * provided by the plugin. + */ +@property(nonnull, readonly) id textures; + +/** + * The view displaying Flutter content. + * + * This property is provided for backwards compatibility for apps + * that assume a single view. This will eventually be replaced by + * a multi-view API variant. + * + * This method may return |nil|, for instance in a headless environment. + */ +@property(nullable, readonly) NSView* view; + +/** + * Registers |delegate| to receive handleMethodCall:result: callbacks for the given |channel|. + */ +- (void)addMethodCallDelegate:(nonnull id)delegate + channel:(nonnull FlutterMethodChannel*)channel; + +/** + * Registers the plugin as a receiver of `NSApplicationDelegate` calls. + * + * @param delegate The receiving object, such as the plugin's main class. + */ +- (void)addApplicationDelegate:(nonnull NSObject*)delegate; + +/** + * Registers a `FlutterPlatformViewFactory` for creation of platform views. + * + * Plugins expose `NSView` for embedding in Flutter apps by registering a view factory. + * + * @param factory The view factory that will be registered. + * @param factoryId A unique identifier for the factory, the Dart code of the Flutter app can use + * this identifier to request creation of a `NSView` by the registered factory. + */ +- (void)registerViewFactory:(nonnull NSObject*)factory + withId:(nonnull NSString*)factoryId; + +/** + * Publishes a value for external use of the plugin. + * + * Plugins may publish a single value, such as an instance of the + * plugin's main class, for situations where external control or + * interaction is needed. + * + * The published value will be available from the `FlutterPluginRegistry`. + * Repeated calls overwrite any previous publication. + * + * @param value The value to be published. + */ +- (void)publish:(nonnull NSObject*)value; + +/** + * Returns the file name for the given asset. + * The returned file name can be used to access the asset in the application's main bundle. + * + * @param asset The name of the asset. The name can be hierarchical. + * @return the file name to be used for lookup in the main bundle. + */ +- (nonnull NSString*)lookupKeyForAsset:(nonnull NSString*)asset; + +/** + * Returns the file name for the given asset which originates from the specified package. + * The returned file name can be used to access the asset in the application's main bundle. + * + * + * @param asset The name of the asset. The name can be hierarchical. + * @param package The name of the package from which the asset originates. + * @return the file name to be used for lookup in the main bundle. + */ +- (nonnull NSString*)lookupKeyForAsset:(nonnull NSString*)asset + fromPackage:(nonnull NSString*)package; + +@end + +/** + * A registry of Flutter macOS plugins. + * + * Plugins are identified by unique string keys, typically the name of the + * plugin's main class. + * + * Plugins typically need contextual information and the ability to register + * callbacks for various application events. To keep the API of the registry + * focused, these facilities are not provided directly by the registry, but by + * a `FlutterPluginRegistrar`, created by the registry in exchange for the unique + * key of the plugin. + * + * There is no implied connection between the registry and the registrar. + * Specifically, callbacks registered by the plugin via the registrar may be + * relayed directly to the underlying iOS application objects. + */ +@protocol FlutterPluginRegistry + +/** + * Returns a registrar for registering a plugin. + * + * @param pluginKey The unique key identifying the plugin. + */ +- (nonnull id)registrarForPlugin:(nonnull NSString*)pluginKey; + +/** + * Returns a value published by the specified plugin. + * + * @param pluginKey The unique key identifying the plugin. + * @return An object published by the plugin, if any. Will be `NSNull` if + * nothing has been published. Will be `nil` if the plugin has not been + * registered. + */ +- (nullable NSObject*)valuePublishedByPlugin:(nonnull NSString*)pluginKey; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERPLUGINREGISTRARMACOS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h new file mode 100644 index 0000000000000000000000000000000000000000..f20aea4125c9a309ee62ad0de2f863271ab5d0c7 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h @@ -0,0 +1,214 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERVIEWCONTROLLER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERVIEWCONTROLLER_H_ + +#import + +#import "FlutterEngine.h" +#import "FlutterMacros.h" +#import "FlutterPlatformViews.h" +#import "FlutterPluginRegistrarMacOS.h" + +/** + * A unique identifier for a view within which Flutter content is hosted. + * + * Identifiers are guaranteed to be unique for views owned by a given engine but + * may collide for views owned by different engines. + */ +typedef int64_t FlutterViewIdentifier; + +/** + * Values for the `mouseTrackingMode` property. + */ +typedef NS_ENUM(NSInteger, FlutterMouseTrackingMode) { + // Hover events will never be sent to Flutter. + kFlutterMouseTrackingModeNone = 0, + // NOLINTNEXTLINE(readability-identifier-naming) + FlutterMouseTrackingModeNone __attribute__((deprecated)) = kFlutterMouseTrackingModeNone, + + // Hover events will be sent to Flutter when the view is in the key window. + kFlutterMouseTrackingModeInKeyWindow = 1, + // NOLINTNEXTLINE(readability-identifier-naming) + FlutterMouseTrackingModeInKeyWindow + __attribute__((deprecated)) = kFlutterMouseTrackingModeInKeyWindow, + + // Hover events will be sent to Flutter when the view is in the active app. + kFlutterMouseTrackingModeInActiveApp = 2, + // NOLINTNEXTLINE(readability-identifier-naming) + FlutterMouseTrackingModeInActiveApp + __attribute__((deprecated)) = kFlutterMouseTrackingModeInActiveApp, + + // Hover events will be sent to Flutter regardless of window and app focus. + kFlutterMouseTrackingModeAlways = 3, + // NOLINTNEXTLINE(readability-identifier-naming) + FlutterMouseTrackingModeAlways __attribute__((deprecated)) = kFlutterMouseTrackingModeAlways, +}; + +/** + * Controls a view that displays Flutter content and manages input. + * + * A FlutterViewController works with a FlutterEngine. Upon creation, the view + * controller is always added to an engine, either a given engine, or it implicitly + * creates an engine and add itself to that engine. + * + * The FlutterEngine assigns each view controller attached to it a unique ID. + * Each view controller corresponds to a view, and the ID is used by the framework + * to specify which view to operate. + * + * A FlutterViewController can also be unattached to an engine after it is manually + * unset from the engine, or transiently during the initialization process. + * An unattached view controller is invalid. Whether the view controller is attached + * can be queried using FlutterViewController#attached. + * + * The FlutterViewController strongly references the FlutterEngine, while + * the engine weakly the view controller. When a FlutterViewController is deallocated, + * it automatically removes itself from its attached engine. When a FlutterEngine + * has no FlutterViewControllers attached, it might shut down itself or not depending + * on its configuration. + */ +FLUTTER_DARWIN_EXPORT +@interface FlutterViewController : NSViewController + +/** + * The Flutter engine associated with this view controller. + */ +@property(nonatomic, nonnull, readonly) FlutterEngine* engine; + +/** + * The style of mouse tracking to use for the view. Defaults to + * FlutterMouseTrackingModeInKeyWindow. + */ +@property(nonatomic) FlutterMouseTrackingMode mouseTrackingMode; + +/** + * Initializes a controller that will run the given project. + * + * In this initializer, this controller creates an engine, and is attached to + * that engine as the default controller. In this way, this controller can not + * be set to other engines. This initializer is suitable for the first Flutter + * view controller of the app. To use the controller with an existing engine, + * use initWithEngine:nibName:bundle: instead. + * + * @param project The project to run in this view controller. If nil, a default `FlutterDartProject` + * will be used. + */ +- (nonnull instancetype)initWithProject:(nullable FlutterDartProject*)project + NS_DESIGNATED_INITIALIZER; + +- (nonnull instancetype)initWithNibName:(nullable NSString*)nibNameOrNil + bundle:(nullable NSBundle*)nibBundleOrNil + NS_DESIGNATED_INITIALIZER; +- (nonnull instancetype)initWithCoder:(nonnull NSCoder*)nibNameOrNil NS_DESIGNATED_INITIALIZER; +/** + * Initializes this FlutterViewController with an existing `FlutterEngine`. + * + * The initialized view controller will add itself to the engine as part of this process. + * + * This initializer is suitable for both the first Flutter view controller and + * the following ones of the app. + * + * @param engine The `FlutterEngine` instance to attach to. Cannot be nil. + * @param nibName The NIB name to initialize this controller with. + * @param nibBundle The NIB bundle. + */ +- (nonnull instancetype)initWithEngine:(nonnull FlutterEngine*)engine + nibName:(nullable NSString*)nibName + bundle:(nullable NSBundle*)nibBundle NS_DESIGNATED_INITIALIZER; + +/** + * The identifier for this view controller, if it is attached. + * + * The identifier is assigned when the view controller is attached to a + * `FlutterEngine`. + * + * If the view controller is detached (see `FlutterViewController#attached`), + * reading this property throws an assertion. + */ +@property(nonatomic, readonly) FlutterViewIdentifier viewIdentifier; + +/** + * Return YES if the view controller is attached to an engine. + */ +- (BOOL)attached; + +/** + * Invoked by the engine right before the engine is restarted. + * + * This should reset states to as if the application has just started. It + * usually indicates a hot restart (Shift-R in Flutter CLI.) + */ +- (void)onPreEngineRestart; + +/** + * Returns the file name for the given asset. + * The returned file name can be used to access the asset in the application's + * main bundle. + * + * @param asset The name of the asset. The name can be hierarchical. + * @return The file name to be used for lookup in the main bundle. + */ +- (nonnull NSString*)lookupKeyForAsset:(nonnull NSString*)asset; + +/** + * Returns the file name for the given asset which originates from the specified + * package. + * The returned file name can be used to access the asset in the application's + * main bundle. + * + * @param asset The name of the asset. The name can be hierarchical. + * @param package The name of the package from which the asset originates. + * @return The file name to be used for lookup in the main bundle. + */ +- (nonnull NSString*)lookupKeyForAsset:(nonnull NSString*)asset + fromPackage:(nonnull NSString*)package; + +/** + * The contentView (FlutterView)'s background color is set to black during + * its instantiation. + * + * The containing layer's color can be set to the NSColor provided to this method. + * + * For example, the background may be set after the FlutterViewController + * is instantiated in MainFlutterWindow.swift in the Flutter project. + * ```swift + * import Cocoa + * import FlutterMacOS + * + * class MainFlutterWindow: NSWindow { + * override func awakeFromNib() { + * let flutterViewController = FlutterViewController() + * + * // The background color of the window and `FlutterViewController` + * // are retained separately. + * // + * // In this example, both the MainFlutterWindow and FlutterViewController's + * // FlutterView's backgroundColor are set to clear to achieve a fully + * // transparent effect. + * // + * // If the window's background color is not set, it will use the system + * // default. + * // + * // If the `FlutterView`'s color is not set via `FlutterViewController.setBackgroundColor` + * // it's default will be black. + * self.backgroundColor = NSColor.clear + * flutterViewController.backgroundColor = NSColor.clear + * + * let windowFrame = self.frame + * self.contentViewController = flutterViewController + * self.setFrame(windowFrame, display: true) + * + * RegisterGeneratedPlugins(registry: flutterViewController) + * + * super.awakeFromNib() + * } + * } + * ``` + */ +@property(readwrite, nonatomic, nullable, copy) NSColor* backgroundColor; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERVIEWCONTROLLER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Info.plist b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Info.plist new file mode 100644 index 0000000000000000000000000000000000000000..044a5e31b7ec8bd16075223ed101fce81d709933 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Info.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + FlutterMacOS + CFBundleIdentifier + io.flutter.flutter-macos + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + FlutterMacOS + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1.0 + NSPrincipalClass + + + diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/PrivacyInfo.xcprivacy b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/PrivacyInfo.xcprivacy new file mode 100644 index 0000000000000000000000000000000000000000..4187dabc0f4c81cc47449da68163d63222f497d5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/PrivacyInfo.xcprivacy @@ -0,0 +1,12 @@ + + + + + NSPrivacyTracking + + NSPrivacyTrackingDomains + + NSPrivacyCollectedDataTypes + + + diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMac.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMac.h new file mode 100644 index 0000000000000000000000000000000000000000..9d983a6ae3f0f3f907b13c39863ed1fa535adee5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMac.h @@ -0,0 +1,98 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_ACCESSIBILITYBRIDGEMAC_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_ACCESSIBILITYBRIDGEMAC_H_ + +#import + +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/common/accessibility_bridge.h" + +@class FlutterEngine; +@class FlutterViewController; + +namespace flutter { + +//------------------------------------------------------------------------------ +/// The macOS implementation of AccessibilityBridge. +/// +/// This interacts with macOS accessibility APIs, which includes routing +/// accessibility events fired from the framework to macOS, routing native +/// macOS accessibility events to the framework, and creating macOS-specific +/// FlutterPlatformNodeDelegate objects for each node in the semantics tree. +/// +/// AccessibilityBridgeMac must be created as a shared_ptr, since some methods +/// acquires its weak_ptr. +class AccessibilityBridgeMac : public AccessibilityBridge { + public: + //--------------------------------------------------------------------------- + /// @brief Creates an AccessibilityBridgeMacDelegate. + /// @param[in] flutter_engine The weak reference to the FlutterEngine. + /// @param[in] view_controller The weak reference to the FlutterViewController. + explicit AccessibilityBridgeMac(__weak FlutterEngine* flutter_engine, + __weak FlutterViewController* view_controller); + virtual ~AccessibilityBridgeMac() = default; + + // |FlutterPlatformNodeDelegate::OwnerBridge| + void DispatchAccessibilityAction(AccessibilityNodeId target, + FlutterSemanticsAction action, + fml::MallocMapping data) override; + + protected: + // |AccessibilityBridge| + void OnAccessibilityEvent(ui::AXEventGenerator::TargetedEvent targeted_event) override; + + // |AccessibilityBridge| + std::shared_ptr CreateFlutterPlatformNodeDelegate() override; + + private: + /// A wrapper structure to wraps macOS native accessibility events. + struct NSAccessibilityEvent { + NSAccessibilityNotificationName name; + gfx::NativeViewAccessible target; + NSDictionary* user_info; + }; + + //--------------------------------------------------------------------------- + /// @brief Posts the given event against the given node to the macOS + /// accessibility notification system. + /// @param[in] native_node The event target, must not be nil. + /// @param[in] mac_notification The event name, must not be nil. + virtual void DispatchMacOSNotification(gfx::NativeViewAccessible native_node, + NSAccessibilityNotificationName mac_notification); + + //--------------------------------------------------------------------------- + /// @brief Posts the given event against the given node with the + /// additional attributes to the macOS accessibility notification + /// system. + /// @param[in] native_node The event target, must not be nil. + /// @param[in] mac_notification The event name, must not be nil. + /// @param[in] user_info The additional attributes, must not be nil. + void DispatchMacOSNotificationWithUserInfo(gfx::NativeViewAccessible native_node, + NSAccessibilityNotificationName mac_notification, + NSDictionary* user_info); + + //--------------------------------------------------------------------------- + /// @brief Whether the given event is in current pending events. + /// @param[in] event_type The event to look up. + bool HasPendingEvent(ui::AXEventGenerator::Event event) const; + + //--------------------------------------------------------------------------- + /// @brief Converts the give ui::AXEventGenerator::Event into + /// macOS native accessibility event[s] + /// @param[in] event_type The original event type. + /// @param[in] ax_node The original event target. + std::vector MacOSEventsFromAXEvent(ui::AXEventGenerator::Event event_type, + const ui::AXNode& ax_node) const; + + __weak FlutterEngine* flutter_engine_; + __weak FlutterViewController* view_controller_; + + FML_DISALLOW_COPY_AND_ASSIGN(AccessibilityBridgeMac); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_ACCESSIBILITYBRIDGEMAC_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMac.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMac.mm new file mode 100644 index 0000000000000000000000000000000000000000..b47b8be4d1cb862e5ad8e428cdb2b54b5cfbf79f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMac.mm @@ -0,0 +1,379 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMac.h" + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" +#include "flutter/shell/platform/embedder/embedder.h" + +namespace flutter { + +// Native mac notifications fired. These notifications are not publicly documented. +static NSString* const kAccessibilityLoadCompleteNotification = @"AXLoadComplete"; +static NSString* const kAccessibilityInvalidStatusChangedNotification = @"AXInvalidStatusChanged"; +static NSString* const kAccessibilityLiveRegionCreatedNotification = @"AXLiveRegionCreated"; +static NSString* const kAccessibilityLiveRegionChangedNotification = @"AXLiveRegionChanged"; +static NSString* const kAccessibilityExpandedChanged = @"AXExpandedChanged"; +static NSString* const kAccessibilityMenuItemSelectedNotification = @"AXMenuItemSelected"; + +AccessibilityBridgeMac::AccessibilityBridgeMac(__weak FlutterEngine* flutter_engine, + __weak FlutterViewController* view_controller) + : flutter_engine_(flutter_engine), view_controller_(view_controller) {} + +void AccessibilityBridgeMac::OnAccessibilityEvent( + ui::AXEventGenerator::TargetedEvent targeted_event) { + if (!view_controller_.viewLoaded || !view_controller_.view.window) { + // Don't need to send accessibility events if the there is no view or window. + return; + } + ui::AXNode* ax_node = targeted_event.node; + std::vector events = + MacOSEventsFromAXEvent(targeted_event.event_params.event, *ax_node); + for (const AccessibilityBridgeMac::NSAccessibilityEvent& event : events) { + if (event.user_info != nil) { + DispatchMacOSNotificationWithUserInfo(event.target, event.name, event.user_info); + } else { + DispatchMacOSNotification(event.target, event.name); + } + } +} + +std::vector +AccessibilityBridgeMac::MacOSEventsFromAXEvent(ui::AXEventGenerator::Event event_type, + const ui::AXNode& ax_node) const { + // Gets the native_node with the node_id. + NSCAssert(flutter_engine_, @"Flutter engine should not be deallocated"); + auto platform_node_delegate = GetFlutterPlatformNodeDelegateFromID(ax_node.id()).lock(); + NSCAssert(platform_node_delegate, @"Event target must exist in accessibility bridge."); + auto mac_platform_node_delegate = + std::static_pointer_cast(platform_node_delegate); + gfx::NativeViewAccessible native_node = mac_platform_node_delegate->GetNativeViewAccessible(); + + std::vector events; + switch (event_type) { + case ui::AXEventGenerator::Event::ACTIVE_DESCENDANT_CHANGED: + if (ax_node.data().role == ax::mojom::Role::kTree) { + events.push_back({ + .name = NSAccessibilitySelectedRowsChangedNotification, + .target = native_node, + .user_info = nil, + }); + } else if (ax_node.data().role == ax::mojom::Role::kTextFieldWithComboBox) { + // Even though the selected item in the combo box has changed, don't + // post a focus change because this will take the focus out of + // the combo box where the user might be typing. + events.push_back({ + .name = NSAccessibilitySelectedChildrenChangedNotification, + .target = native_node, + .user_info = nil, + }); + } + // In all other cases, this delegate should post + // |NSAccessibilityFocusedUIElementChangedNotification|, but this is + // handled elsewhere. + break; + case ui::AXEventGenerator::Event::LOAD_COMPLETE: + events.push_back({ + .name = kAccessibilityLoadCompleteNotification, + .target = native_node, + .user_info = nil, + }); + break; + case ui::AXEventGenerator::Event::INVALID_STATUS_CHANGED: + events.push_back({ + .name = kAccessibilityInvalidStatusChangedNotification, + .target = native_node, + .user_info = nil, + }); + break; + case ui::AXEventGenerator::Event::SELECTED_CHILDREN_CHANGED: + if (ui::IsTableLike(ax_node.data().role)) { + events.push_back({ + .name = NSAccessibilitySelectedRowsChangedNotification, + .target = native_node, + .user_info = nil, + }); + } else { + // VoiceOver does not read anything if selection changes on the + // currently focused object, and the focus did not move. Fire a + // selection change if the focus did not change. + NSAccessibilityElement* native_accessibility_node = (NSAccessibilityElement*)native_node; + if (native_accessibility_node.accessibilityFocusedUIElement && + ax_node.data().HasState(ax::mojom::State::kMultiselectable) && + !HasPendingEvent(ui::AXEventGenerator::Event::ACTIVE_DESCENDANT_CHANGED) && + !HasPendingEvent(ui::AXEventGenerator::Event::FOCUS_CHANGED)) { + // Don't fire selected children change, it will sometimes override + // announcement of current focus. + break; + } + events.push_back({ + .name = NSAccessibilitySelectedChildrenChangedNotification, + .target = native_node, + .user_info = nil, + }); + } + break; + case ui::AXEventGenerator::Event::DOCUMENT_SELECTION_CHANGED: { + id focused = mac_platform_node_delegate->GetFocus(); + if ([focused isKindOfClass:[FlutterTextField class]]) { + // If it is a text field, the selection notifications are handled by + // the FlutterTextField directly. Only need to make sure it is the + // first responder. + FlutterTextField* native_text_field = (FlutterTextField*)focused; + if (native_text_field == mac_platform_node_delegate->GetFocus()) { + [native_text_field startEditing]; + } + break; + } + // This event always fires at root + events.push_back({ + .name = NSAccessibilitySelectedTextChangedNotification, + .target = native_node, + .user_info = nil, + }); + // WebKit fires a notification both on the focused object and the page + // root. + const ui::AXTreeData& tree_data = GetAXTreeData(); + int32_t focus = tree_data.focus_id; + if (focus == ui::AXNode::kInvalidAXID || focus != tree_data.sel_anchor_object_id) { + break; // Just fire a notification on the root. + } + auto focus_node = GetFlutterPlatformNodeDelegateFromID(focus).lock(); + if (!focus_node) { + break; // Just fire a notification on the root. + } + events.push_back({ + .name = NSAccessibilitySelectedTextChangedNotification, + .target = focus_node->GetNativeViewAccessible(), + .user_info = nil, + }); + break; + } + case ui::AXEventGenerator::Event::CHECKED_STATE_CHANGED: + events.push_back({ + .name = NSAccessibilityValueChangedNotification, + .target = native_node, + .user_info = nil, + }); + break; + case ui::AXEventGenerator::Event::VALUE_CHANGED: { + if (ax_node.data().role == ax::mojom::Role::kTextField) { + // If it is a text field, the value change notifications are handled by + // the FlutterTextField directly. Only need to make sure it is the + // first responder. + id native_text_field = mac_platform_node_delegate->GetNativeViewAccessible(); + FML_DCHECK([native_text_field isKindOfClass:FlutterTextField.class]); + id focused = mac_platform_node_delegate->GetFocus(); + if (!focused || native_text_field == focused) { + [(FlutterTextField*)native_text_field startEditing]; + } + break; + } + events.push_back({ + .name = NSAccessibilityValueChangedNotification, + .target = native_node, + .user_info = nil, + }); + if (ax_node.data().HasState(ax::mojom::State::kEditable)) { + events.push_back({ + .name = NSAccessibilityValueChangedNotification, + .target = RootDelegate()->GetNativeViewAccessible(), + .user_info = nil, + }); + } + break; + } + case ui::AXEventGenerator::Event::LIVE_REGION_CREATED: + events.push_back({ + .name = kAccessibilityLiveRegionCreatedNotification, + .target = native_node, + .user_info = nil, + }); + break; + case ui::AXEventGenerator::Event::ALERT: { + events.push_back({ + .name = kAccessibilityLiveRegionCreatedNotification, + .target = native_node, + .user_info = nil, + }); + // VoiceOver requires a live region changed notification to actually + // announce the live region. + auto live_region_events = + MacOSEventsFromAXEvent(ui::AXEventGenerator::Event::LIVE_REGION_CHANGED, ax_node); + events.insert(events.end(), live_region_events.begin(), live_region_events.end()); + break; + } + case ui::AXEventGenerator::Event::LIVE_REGION_CHANGED: { + // Uses native VoiceOver support for live regions. + events.push_back({ + .name = kAccessibilityLiveRegionChangedNotification, + .target = native_node, + .user_info = nil, + }); + break; + } + case ui::AXEventGenerator::Event::ROW_COUNT_CHANGED: + events.push_back({ + .name = NSAccessibilityRowCountChangedNotification, + .target = native_node, + .user_info = nil, + }); + break; + case ui::AXEventGenerator::Event::EXPANDED: { + NSAccessibilityNotificationName mac_notification; + if (ax_node.data().role == ax::mojom::Role::kRow || + ax_node.data().role == ax::mojom::Role::kTreeItem) { + mac_notification = NSAccessibilityRowExpandedNotification; + } else { + mac_notification = kAccessibilityExpandedChanged; + } + events.push_back({ + .name = mac_notification, + .target = native_node, + .user_info = nil, + }); + break; + } + case ui::AXEventGenerator::Event::COLLAPSED: { + NSAccessibilityNotificationName mac_notification; + if (ax_node.data().role == ax::mojom::Role::kRow || + ax_node.data().role == ax::mojom::Role::kTreeItem) { + mac_notification = NSAccessibilityRowCollapsedNotification; + } else { + mac_notification = kAccessibilityExpandedChanged; + } + events.push_back({ + .name = mac_notification, + .target = native_node, + .user_info = nil, + }); + break; + } + case ui::AXEventGenerator::Event::MENU_ITEM_SELECTED: + events.push_back({ + .name = kAccessibilityMenuItemSelectedNotification, + .target = native_node, + .user_info = nil, + }); + break; + case ui::AXEventGenerator::Event::CHILDREN_CHANGED: { + // NSAccessibilityCreatedNotification seems to be the only way to let + // Voiceover pick up layout changes. + events.push_back({ + .name = NSAccessibilityCreatedNotification, + .target = view_controller_.view.window, + .user_info = nil, + }); + break; + } + case ui::AXEventGenerator::Event::SUBTREE_CREATED: + case ui::AXEventGenerator::Event::ACCESS_KEY_CHANGED: + case ui::AXEventGenerator::Event::ATK_TEXT_OBJECT_ATTRIBUTE_CHANGED: + case ui::AXEventGenerator::Event::ATOMIC_CHANGED: + case ui::AXEventGenerator::Event::AUTO_COMPLETE_CHANGED: + case ui::AXEventGenerator::Event::BUSY_CHANGED: + case ui::AXEventGenerator::Event::CONTROLS_CHANGED: + case ui::AXEventGenerator::Event::CLASS_NAME_CHANGED: + case ui::AXEventGenerator::Event::DESCRIBED_BY_CHANGED: + case ui::AXEventGenerator::Event::DESCRIPTION_CHANGED: + case ui::AXEventGenerator::Event::DOCUMENT_TITLE_CHANGED: + case ui::AXEventGenerator::Event::DROPEFFECT_CHANGED: + case ui::AXEventGenerator::Event::ENABLED_CHANGED: + case ui::AXEventGenerator::Event::FOCUS_CHANGED: + case ui::AXEventGenerator::Event::FLOW_FROM_CHANGED: + case ui::AXEventGenerator::Event::FLOW_TO_CHANGED: + case ui::AXEventGenerator::Event::GRABBED_CHANGED: + case ui::AXEventGenerator::Event::HASPOPUP_CHANGED: + case ui::AXEventGenerator::Event::HIERARCHICAL_LEVEL_CHANGED: + case ui::AXEventGenerator::Event::IGNORED_CHANGED: + case ui::AXEventGenerator::Event::IMAGE_ANNOTATION_CHANGED: + case ui::AXEventGenerator::Event::KEY_SHORTCUTS_CHANGED: + case ui::AXEventGenerator::Event::LABELED_BY_CHANGED: + case ui::AXEventGenerator::Event::LANGUAGE_CHANGED: + case ui::AXEventGenerator::Event::LAYOUT_INVALIDATED: + case ui::AXEventGenerator::Event::LIVE_REGION_NODE_CHANGED: + case ui::AXEventGenerator::Event::LIVE_RELEVANT_CHANGED: + case ui::AXEventGenerator::Event::LIVE_STATUS_CHANGED: + case ui::AXEventGenerator::Event::LOAD_START: + case ui::AXEventGenerator::Event::MULTILINE_STATE_CHANGED: + case ui::AXEventGenerator::Event::MULTISELECTABLE_STATE_CHANGED: + case ui::AXEventGenerator::Event::NAME_CHANGED: + case ui::AXEventGenerator::Event::OBJECT_ATTRIBUTE_CHANGED: + case ui::AXEventGenerator::Event::OTHER_ATTRIBUTE_CHANGED: + case ui::AXEventGenerator::Event::PLACEHOLDER_CHANGED: + case ui::AXEventGenerator::Event::PORTAL_ACTIVATED: + case ui::AXEventGenerator::Event::POSITION_IN_SET_CHANGED: + case ui::AXEventGenerator::Event::READONLY_CHANGED: + case ui::AXEventGenerator::Event::RELATED_NODE_CHANGED: + case ui::AXEventGenerator::Event::REQUIRED_STATE_CHANGED: + case ui::AXEventGenerator::Event::ROLE_CHANGED: + case ui::AXEventGenerator::Event::SCROLL_HORIZONTAL_POSITION_CHANGED: + case ui::AXEventGenerator::Event::SCROLL_VERTICAL_POSITION_CHANGED: + case ui::AXEventGenerator::Event::SELECTED_CHANGED: + case ui::AXEventGenerator::Event::SET_SIZE_CHANGED: + case ui::AXEventGenerator::Event::SORT_CHANGED: + case ui::AXEventGenerator::Event::STATE_CHANGED: + case ui::AXEventGenerator::Event::TEXT_ATTRIBUTE_CHANGED: + case ui::AXEventGenerator::Event::VALUE_MAX_CHANGED: + case ui::AXEventGenerator::Event::VALUE_MIN_CHANGED: + case ui::AXEventGenerator::Event::VALUE_STEP_CHANGED: + case ui::AXEventGenerator::Event::WIN_IACCESSIBLE_STATE_CHANGED: + // There are some notifications that aren't meaningful on Mac. + // It's okay to skip them. + break; + } + return events; +} + +void AccessibilityBridgeMac::DispatchAccessibilityAction(ui::AXNode::AXID target, + FlutterSemanticsAction action, + fml::MallocMapping data) { + // TODO(mattkae): Remove implicit view assumption. + // https://github.com/flutter/flutter/issues/142845 + NSCAssert(flutter_engine_, @"Flutter engine should not be deallocated"); + NSCAssert(view_controller_.viewLoaded && view_controller_.view.window, + @"The accessibility bridge should not receive accessibility actions if the flutter view" + @"is not loaded or attached to a NSWindow."); + [flutter_engine_ dispatchSemanticsAction:action toTarget:target withData:std::move(data)]; +} + +std::shared_ptr +AccessibilityBridgeMac::CreateFlutterPlatformNodeDelegate() { + return std::make_shared(weak_from_this(), view_controller_); +} + +// Private method +void AccessibilityBridgeMac::DispatchMacOSNotification( + gfx::NativeViewAccessible native_node, + NSAccessibilityNotificationName mac_notification) { + NSCAssert(mac_notification, @"The notification must not be null."); + NSCAssert(native_node, @"The notification target must not be null."); + NSAccessibilityPostNotification(native_node, mac_notification); +} + +void AccessibilityBridgeMac::DispatchMacOSNotificationWithUserInfo( + gfx::NativeViewAccessible native_node, + NSAccessibilityNotificationName mac_notification, + NSDictionary* user_info) { + NSCAssert(mac_notification, @"The notification must not be null."); + NSCAssert(native_node, @"The notification target must not be null."); + NSCAssert(user_info, @"The notification data must not be null."); + NSAccessibilityPostNotificationWithUserInfo(native_node, mac_notification, user_info); +} + +bool AccessibilityBridgeMac::HasPendingEvent(ui::AXEventGenerator::Event event) const { + NSCAssert(flutter_engine_, @"Flutter engine should not be deallocated"); + std::vector pending_events = GetPendingEvents(); + for (const auto& pending_event : GetPendingEvents()) { + if (pending_event.event_params.event == event) { + return true; + } + } + return false; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMacTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMacTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..12a83ec030dc92eb60db3765b377eddd55400243 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMacTest.mm @@ -0,0 +1,305 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMac.h" + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" +#include "flutter/testing/autoreleasepool_test.h" +#include "flutter/testing/testing.h" + +namespace flutter::testing { + +namespace { + +class AccessibilityBridgeMacSpy : public AccessibilityBridgeMac { + public: + using AccessibilityBridgeMac::OnAccessibilityEvent; + + AccessibilityBridgeMacSpy(__weak FlutterEngine* flutter_engine, + __weak FlutterViewController* view_controller) + : AccessibilityBridgeMac(flutter_engine, view_controller) {} + + std::unordered_map actual_notifications; + + private: + void DispatchMacOSNotification(gfx::NativeViewAccessible native_node, + NSAccessibilityNotificationName mac_notification) override { + actual_notifications[[mac_notification UTF8String]] = native_node; + } +}; + +} // namespace +} // namespace flutter::testing + +@interface AccessibilityBridgeTestViewController : FlutterViewController +- (std::shared_ptr)createAccessibilityBridgeWithEngine: + (nonnull FlutterEngine*)engine; +@end + +@implementation AccessibilityBridgeTestViewController +- (std::shared_ptr)createAccessibilityBridgeWithEngine: + (nonnull FlutterEngine*)engine { + return std::make_shared(engine, self); +} +@end + +namespace flutter::testing { + +namespace { + +// Returns an engine configured for the text fixture resource configuration. +FlutterViewController* CreateTestViewController() { + NSString* fixtures = @(testing::GetFixturesPath()); + FlutterDartProject* project = [[FlutterDartProject alloc] + initWithAssetsPath:fixtures + ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; + return [[AccessibilityBridgeTestViewController alloc] initWithProject:project]; +} + +// Test fixture that instantiates and re-uses a single NSWindow across multiple tests. +// +// Works around: http://www.openradar.me/FB13291861 +class AccessibilityBridgeMacWindowTest : public AutoreleasePoolTest { + public: + AccessibilityBridgeMacWindowTest() { + if (!gWindow_) { + gWindow_ = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600) + styleMask:NSBorderlessWindowMask + backing:NSBackingStoreBuffered + defer:NO]; + } + } + + NSWindow* GetWindow() const { return gWindow_; } + + private: + static NSWindow* gWindow_; + FML_DISALLOW_COPY_AND_ASSIGN(AccessibilityBridgeMacWindowTest); +}; + +NSWindow* AccessibilityBridgeMacWindowTest::gWindow_ = nil; + +// Test-specific name for AutoreleasePoolTest fixture. +using AccessibilityBridgeMacTest = AutoreleasePoolTest; + +} // namespace + +TEST_F(AccessibilityBridgeMacWindowTest, SendsAccessibilityCreateNotificationFlutterViewWindow) { + FlutterViewController* viewController = CreateTestViewController(); + FlutterEngine* engine = viewController.engine; + NSWindow* expectedTarget = GetWindow(); + expectedTarget.contentView = viewController.view; + + // Setting up bridge so that the AccessibilityBridgeMacDelegateSpy + // can query semantics information from. + engine.semanticsEnabled = YES; + auto bridge = std::static_pointer_cast( + viewController.accessibilityBridge.lock()); + FlutterSemanticsNode2 root; + root.id = 0; + root.flags = static_cast(0); + root.actions = static_cast(0); + root.text_selection_base = -1; + root.text_selection_extent = -1; + root.label = "root"; + root.hint = ""; + root.value = ""; + root.increased_value = ""; + root.decreased_value = ""; + root.tooltip = ""; + root.child_count = 0; + root.custom_accessibility_actions_count = 0; + bridge->AddFlutterSemanticsNodeUpdate(root); + + bridge->CommitUpdates(); + auto platform_node_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); + + // Creates a targeted event. + ui::AXTree tree; + ui::AXNode ax_node(&tree, nullptr, 0, 0); + ui::AXNodeData node_data; + node_data.id = 0; + ax_node.SetData(node_data); + std::vector intent; + ui::AXEventGenerator::EventParams event_params(ui::AXEventGenerator::Event::CHILDREN_CHANGED, + ax::mojom::EventFrom::kNone, intent); + ui::AXEventGenerator::TargetedEvent targeted_event(&ax_node, event_params); + + bridge->OnAccessibilityEvent(targeted_event); + + ASSERT_EQ(bridge->actual_notifications.size(), 1u); + auto target = bridge->actual_notifications.find([NSAccessibilityCreatedNotification UTF8String]); + ASSERT_NE(target, bridge->actual_notifications.end()); + EXPECT_EQ(target->second, expectedTarget); + [engine shutDownEngine]; +} + +// Flutter used to assume that the accessibility root had ID 0. +// In a multi-view world, each view has its own accessibility root +// with a globally unique node ID. +// +// node1 +// | +// node2 +TEST_F(AccessibilityBridgeMacWindowTest, NonZeroRootNodeId) { + FlutterViewController* viewController = CreateTestViewController(); + FlutterEngine* engine = viewController.engine; + NSWindow* expectedTarget = GetWindow(); + expectedTarget.contentView = viewController.view; + + // Setting up bridge so that the AccessibilityBridgeMacDelegateSpy + // can query semantics information from. + engine.semanticsEnabled = YES; + auto bridge = std::static_pointer_cast( + viewController.accessibilityBridge.lock()); + + FlutterSemanticsNode2 node1; + std::vector node1_children{2}; + node1.id = 1; + node1.flags = static_cast(0); + node1.actions = static_cast(0); + node1.text_selection_base = -1; + node1.text_selection_extent = -1; + node1.label = "node1"; + node1.hint = ""; + node1.value = ""; + node1.increased_value = ""; + node1.decreased_value = ""; + node1.tooltip = ""; + node1.child_count = node1_children.size(); + node1.children_in_traversal_order = node1_children.data(); + node1.children_in_hit_test_order = node1_children.data(); + node1.custom_accessibility_actions_count = 0; + + FlutterSemanticsNode2 node2; + node2.id = 2; + node2.flags = static_cast(0); + node2.actions = static_cast(0); + node2.text_selection_base = -1; + node2.text_selection_extent = -1; + node2.label = "node2"; + node2.hint = ""; + node2.value = ""; + node2.increased_value = ""; + node2.decreased_value = ""; + node2.tooltip = ""; + node2.child_count = 0; + node2.custom_accessibility_actions_count = 0; + + bridge->AddFlutterSemanticsNodeUpdate(node1); + bridge->AddFlutterSemanticsNodeUpdate(node2); + bridge->CommitUpdates(); + + // Look up the root node delegate. + auto root_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock(); + ASSERT_TRUE(root_delegate); + ASSERT_EQ(root_delegate->GetChildCount(), 1); + + // Look up the child node delegate. + auto child_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(2).lock(); + ASSERT_TRUE(child_delegate); + ASSERT_EQ(child_delegate->GetChildCount(), 0); + + // Ensure a node with ID 0 does not exist. + auto invalid_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); + ASSERT_FALSE(invalid_delegate); + + [engine shutDownEngine]; +} + +TEST_F(AccessibilityBridgeMacTest, DoesNotSendAccessibilityCreateNotificationWhenHeadless) { + FlutterViewController* viewController = CreateTestViewController(); + FlutterEngine* engine = viewController.engine; + + // Setting up bridge so that the AccessibilityBridgeMacDelegateSpy + // can query semantics information from. + engine.semanticsEnabled = YES; + auto bridge = std::static_pointer_cast( + viewController.accessibilityBridge.lock()); + FlutterSemanticsNode2 root; + root.id = 0; + root.flags = static_cast(0); + root.actions = static_cast(0); + root.text_selection_base = -1; + root.text_selection_extent = -1; + root.label = "root"; + root.hint = ""; + root.value = ""; + root.increased_value = ""; + root.decreased_value = ""; + root.tooltip = ""; + root.child_count = 0; + root.custom_accessibility_actions_count = 0; + bridge->AddFlutterSemanticsNodeUpdate(root); + + bridge->CommitUpdates(); + auto platform_node_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); + + // Creates a targeted event. + ui::AXTree tree; + ui::AXNode ax_node(&tree, nullptr, 0, 0); + ui::AXNodeData node_data; + node_data.id = 0; + ax_node.SetData(node_data); + std::vector intent; + ui::AXEventGenerator::EventParams event_params(ui::AXEventGenerator::Event::CHILDREN_CHANGED, + ax::mojom::EventFrom::kNone, intent); + ui::AXEventGenerator::TargetedEvent targeted_event(&ax_node, event_params); + + bridge->OnAccessibilityEvent(targeted_event); + + // Does not send any notification if the engine is headless. + EXPECT_EQ(bridge->actual_notifications.size(), 0u); + [engine shutDownEngine]; +} + +TEST_F(AccessibilityBridgeMacTest, DoesNotSendAccessibilityCreateNotificationWhenNoWindow) { + FlutterViewController* viewController = CreateTestViewController(); + FlutterEngine* engine = viewController.engine; + + // Setting up bridge so that the AccessibilityBridgeMacDelegateSpy + // can query semantics information from. + engine.semanticsEnabled = YES; + auto bridge = std::static_pointer_cast( + viewController.accessibilityBridge.lock()); + FlutterSemanticsNode2 root; + root.id = 0; + root.flags = static_cast(0); + root.actions = static_cast(0); + root.text_selection_base = -1; + root.text_selection_extent = -1; + root.label = "root"; + root.hint = ""; + root.value = ""; + root.increased_value = ""; + root.decreased_value = ""; + root.tooltip = ""; + root.child_count = 0; + root.custom_accessibility_actions_count = 0; + bridge->AddFlutterSemanticsNodeUpdate(root); + + bridge->CommitUpdates(); + auto platform_node_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); + + // Creates a targeted event. + ui::AXTree tree; + ui::AXNode ax_node(&tree, nullptr, 0, 0); + ui::AXNodeData node_data; + node_data.id = 0; + ax_node.SetData(node_data); + std::vector intent; + ui::AXEventGenerator::EventParams event_params(ui::AXEventGenerator::Event::CHILDREN_CHANGED, + ax::mojom::EventFrom::kNone, intent); + ui::AXEventGenerator::TargetedEvent targeted_event(&ax_node, event_params); + + bridge->OnAccessibilityEvent(targeted_event); + + // Does not send any notification if the flutter view is not attached to a NSWindow. + EXPECT_EQ(bridge->actual_notifications.size(), 0u); + [engine shutDownEngine]; +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterAppDelegate.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterAppDelegate.mm new file mode 100644 index 0000000000000000000000000000000000000000..02ab46b29829cde64c9ee3d89fe18b6088a22592 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterAppDelegate.mm @@ -0,0 +1,95 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppDelegate.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterAppDelegate_Internal.h" + +#import + +#include "flutter/fml/logging.h" +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppLifecycleDelegate.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterAppLifecycleDelegate_Internal.h" +#include "flutter/shell/platform/embedder/embedder.h" + +@interface FlutterAppDelegate () + +/** + * Returns the display name of the application as set in the Info.plist. + */ +- (NSString*)applicationName; + +@property(nonatomic) FlutterAppLifecycleRegistrar* lifecycleRegistrar; +@end + +@implementation FlutterAppDelegate + +- (instancetype)init { + if (self = [super init]) { + _terminationHandler = nil; + _lifecycleRegistrar = [[FlutterAppLifecycleRegistrar alloc] init]; + } + return self; +} + +- (void)applicationWillFinishLaunching:(NSNotification*)notification { + // Update UI elements to match the application name. + NSString* applicationName = [self applicationName]; + _mainFlutterWindow.title = applicationName; + for (NSMenuItem* menuItem in _applicationMenu.itemArray) { + menuItem.title = [menuItem.title stringByReplacingOccurrencesOfString:@"APP_NAME" + withString:applicationName]; + } +} + +#pragma mark - Delegate handling + +- (void)addApplicationLifecycleDelegate:(NSObject*)delegate { + [self.lifecycleRegistrar addDelegate:delegate]; +} + +- (void)removeApplicationLifecycleDelegate:(NSObject*)delegate { + [self.lifecycleRegistrar removeDelegate:delegate]; +} + +#pragma mark Private Methods + +- (NSString*)applicationName { + NSString* applicationName = + [NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleDisplayName"]; + if (!applicationName) { + applicationName = [NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleName"]; + } + return applicationName; +} + +#pragma mark NSApplicationDelegate + +- (void)application:(NSApplication*)application openURLs:(NSArray*)urls { + for (NSObject* delegate in self.lifecycleRegistrar.delegates) { + if ([delegate respondsToSelector:@selector(handleOpenURLs:)] && + [delegate handleOpenURLs:urls]) { + return; + } + } +} + +- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication* _Nonnull)sender { + // If the framework has already told us to terminate, terminate immediately. + if ([self terminationHandler] == nil || [[self terminationHandler] shouldTerminate]) { + return NSTerminateNow; + } + + // Send a termination request to the framework. + FlutterEngineTerminationHandler* terminationHandler = [self terminationHandler]; + [terminationHandler requestApplicationTermination:sender + exitType:kFlutterAppExitTypeCancelable + result:nil]; + + // Cancel termination to allow the framework to handle the request asynchronously. When the + // termination request returns from the app, if termination is desired, this method will be + // reinvoked with self.terminationHandler.shouldTerminate set to YES. + return NSTerminateCancel; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterAppDelegateTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterAppDelegateTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..6b13959bde9060fd5231889ce04f0d04903e98ef --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterAppDelegateTest.mm @@ -0,0 +1,75 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppDelegate.h" + +#import "flutter/testing/testing.h" +#include "third_party/googletest/googletest/include/gtest/gtest.h" + +@interface AppDelegateNoopFlutterAppLifecycleDelegate : NSObject +@property(nonatomic, copy, nullable) NSArray* receivedURLs; +@end + +@implementation AppDelegateNoopFlutterAppLifecycleDelegate +@end + +@interface AppDelegateTestFlutterAppLifecycleDelegate : NSObject +@property(nonatomic, copy, nullable) NSArray* receivedURLs; +@end + +@implementation AppDelegateTestFlutterAppLifecycleDelegate + +- (BOOL)handleOpenURLs:(NSArray*)urls { + self.receivedURLs = [urls copy]; + return YES; +} + +@end + +namespace flutter::testing { + +TEST(FlutterAppDelegateTest, DoesNotCallDelegatesWithoutHandler) { + FlutterAppDelegate* appDelegate = [[FlutterAppDelegate alloc] init]; + AppDelegateNoopFlutterAppLifecycleDelegate* noopDelegate = + [[AppDelegateNoopFlutterAppLifecycleDelegate alloc] init]; + [appDelegate addApplicationLifecycleDelegate:noopDelegate]; + + [appDelegate application:NSApplication.sharedApplication openURLs:@[]]; + // No EXPECT, since the test is that the call doesn't throw due to calling without checking that + // the method is implemented. +} + +TEST(FlutterAppDelegateTest, ReceivesOpenURLs) { + FlutterAppDelegate* appDelegate = [[FlutterAppDelegate alloc] init]; + AppDelegateTestFlutterAppLifecycleDelegate* delegate = + [[AppDelegateTestFlutterAppLifecycleDelegate alloc] init]; + [appDelegate addApplicationLifecycleDelegate:delegate]; + + NSURL* URL = [NSURL URLWithString:@"https://flutter.dev"]; + EXPECT_NE(URL, nil); + NSArray* URLs = @[ URL ]; + [appDelegate application:NSApplication.sharedApplication openURLs:URLs]; + + EXPECT_EQ([delegate receivedURLs], URLs); +} + +TEST(FlutterAppDelegateTest, OperURLsStopsAfterHandled) { + FlutterAppDelegate* appDelegate = [[FlutterAppDelegate alloc] init]; + AppDelegateTestFlutterAppLifecycleDelegate* firstDelegate = + [[AppDelegateTestFlutterAppLifecycleDelegate alloc] init]; + AppDelegateTestFlutterAppLifecycleDelegate* secondDelegate = + [[AppDelegateTestFlutterAppLifecycleDelegate alloc] init]; + [appDelegate addApplicationLifecycleDelegate:firstDelegate]; + [appDelegate addApplicationLifecycleDelegate:secondDelegate]; + + NSURL* URL = [NSURL URLWithString:@"https://flutter.dev"]; + EXPECT_NE(URL, nil); + NSArray* URLs = @[ URL ]; + [appDelegate application:NSApplication.sharedApplication openURLs:URLs]; + + EXPECT_EQ([firstDelegate receivedURLs], URLs); + EXPECT_EQ([secondDelegate receivedURLs], nil); +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterAppDelegate_Internal.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterAppDelegate_Internal.h new file mode 100644 index 0000000000000000000000000000000000000000..83176f3acdea9526ec870331cdc4bb5388a8c075 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterAppDelegate_Internal.h @@ -0,0 +1,21 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERAPPDELEGATE_INTERNAL_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERAPPDELEGATE_INTERNAL_H_ + +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppDelegate.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" + +@interface FlutterAppDelegate () + +/** + * Holds a weak reference to the termination handler owned by the engine. + * Called by the |FlutterApplication| when termination is requested by the OS. + */ +@property(readwrite, nullable, weak) FlutterEngineTerminationHandler* terminationHandler; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERAPPDELEGATE_INTERNAL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterAppLifecycleDelegate.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterAppLifecycleDelegate.mm new file mode 100644 index 0000000000000000000000000000000000000000..e2439b3bd8a1b6723ee16adfd82bfebd56ca0c84 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterAppLifecycleDelegate.mm @@ -0,0 +1,104 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppLifecycleDelegate.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterAppLifecycleDelegate_Internal.h" + +#include +#include +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/paths.h" + +@implementation FlutterAppLifecycleRegistrar + +- (void)addObserverFor:(NSString*)name selector:(SEL)selector { + [[NSNotificationCenter defaultCenter] addObserver:self selector:selector name:name object:nil]; +} + +- (instancetype)init { + if (self = [super init]) { +// Using a macro to avoid errors where the notification doesn't match the +// selector. +#ifdef OBSERVE_NOTIFICATION +#error OBSERVE_NOTIFICATION ALREADY DEFINED! +#else +#define OBSERVE_NOTIFICATION(SELECTOR) \ + [self addObserverFor:NSApplication##SELECTOR##Notification selector:@selector(handle##SELECTOR:)] +#endif + + OBSERVE_NOTIFICATION(WillFinishLaunching); + OBSERVE_NOTIFICATION(DidFinishLaunching); + OBSERVE_NOTIFICATION(WillBecomeActive); + OBSERVE_NOTIFICATION(DidBecomeActive); + OBSERVE_NOTIFICATION(WillResignActive); + OBSERVE_NOTIFICATION(DidResignActive); + OBSERVE_NOTIFICATION(WillTerminate); + OBSERVE_NOTIFICATION(WillHide); + OBSERVE_NOTIFICATION(DidHide); + OBSERVE_NOTIFICATION(WillUnhide); + OBSERVE_NOTIFICATION(DidUnhide); + OBSERVE_NOTIFICATION(DidChangeScreenParameters); + OBSERVE_NOTIFICATION(DidChangeOcclusionState); + +#undef OBSERVE_NOTIFICATION + + _delegates = [NSPointerArray weakObjectsPointerArray]; + } + return self; +} + +static BOOL IsPowerOfTwo(NSUInteger x) { + return x != 0 && (x & (x - 1)) == 0; +} + +- (void)addDelegate:(NSObject*)delegate { + [_delegates addPointer:(__bridge void*)delegate]; + if (IsPowerOfTwo([_delegates count])) { + [_delegates compact]; + } +} + +- (void)removeDelegate:(NSObject*)delegate { + NSUInteger index = [[_delegates allObjects] indexOfObject:delegate]; + if (index != NSNotFound) { + [_delegates removePointerAtIndex:index]; + } +} + +// This isn't done via performSelector because that can cause leaks due to the +// selector not being known. Using a macro to avoid mismatch errors between the +// notification and the selector. +#ifdef DISTRIBUTE_NOTIFICATION +#error DISTRIBUTE_NOTIFICATION ALREADY DEFINED! +#else +#define DISTRIBUTE_NOTIFICATION(SELECTOR) \ + -(void)handle##SELECTOR : (NSNotification*)notification { \ + for (NSObject * delegate in _delegates) { \ + if ([delegate respondsToSelector:@selector(handle##SELECTOR:)]) { \ + [delegate handle##SELECTOR:notification]; \ + } \ + } \ + } +#endif + +DISTRIBUTE_NOTIFICATION(WillFinishLaunching) +DISTRIBUTE_NOTIFICATION(DidFinishLaunching) +DISTRIBUTE_NOTIFICATION(WillBecomeActive) +DISTRIBUTE_NOTIFICATION(DidBecomeActive) +DISTRIBUTE_NOTIFICATION(WillResignActive) +DISTRIBUTE_NOTIFICATION(DidResignActive) +DISTRIBUTE_NOTIFICATION(WillTerminate) +DISTRIBUTE_NOTIFICATION(WillHide) +DISTRIBUTE_NOTIFICATION(WillUnhide) +DISTRIBUTE_NOTIFICATION(DidHide) +DISTRIBUTE_NOTIFICATION(DidUnhide) +DISTRIBUTE_NOTIFICATION(DidChangeScreenParameters) +DISTRIBUTE_NOTIFICATION(DidChangeOcclusionState) + +#undef DISTRIBUTE_NOTIFICATION + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterAppLifecycleDelegateTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterAppLifecycleDelegateTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..e073cc338514573eba61f6bd6e145e4c7b21ef0e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterAppLifecycleDelegateTest.mm @@ -0,0 +1,237 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppLifecycleDelegate.h" + +#import "flutter/testing/testing.h" +#include "third_party/googletest/googletest/include/gtest/gtest.h" + +@interface TestFlutterAppLifecycleDelegate : NSObject +@property(nonatomic, readwrite, nullable) NSNotification* lastNotification; +@end + +@implementation TestFlutterAppLifecycleDelegate + +- (void)setNotification:(NSNotification*)notification { + self.lastNotification = notification; +} + +- (void)handleWillFinishLaunching:(NSNotification*)notification { + [self setNotification:notification]; +} + +- (void)handleDidFinishLaunching:(NSNotification*)notification { + [self setNotification:notification]; +} + +- (void)handleWillBecomeActive:(NSNotification*)notification { + [self setNotification:notification]; +} + +- (void)handleDidBecomeActive:(NSNotification*)notification { + [self setNotification:notification]; +} + +- (void)handleWillResignActive:(NSNotification*)notification { + [self setNotification:notification]; +} + +- (void)handleDidResignActive:(NSNotification*)notification { + [self setNotification:notification]; +} + +- (void)handleWillHide:(NSNotification*)notification { + [self setNotification:notification]; +} + +- (void)handleDidHide:(NSNotification*)notification { + [self setNotification:notification]; +} + +- (void)handleWillUnhide:(NSNotification*)notification { + [self setNotification:notification]; +} + +- (void)handleDidUnhide:(NSNotification*)notification { + [self setNotification:notification]; +} + +- (void)handleDidChangeScreenParameters:(NSNotification*)notification { + [self setNotification:notification]; +} + +- (void)handleDidChangeOcclusionState:(NSNotification*)notification API_AVAILABLE(macos(10.9)) { + [self setNotification:notification]; +} + +- (void)handleWillTerminate:(NSNotification*)notification { + [self setNotification:notification]; +} + +@end + +namespace flutter::testing { + +TEST(FlutterAppLifecycleDelegateTest, RespondsToWillFinishLaunching) { + FlutterAppLifecycleRegistrar* registrar = [[FlutterAppLifecycleRegistrar alloc] init]; + TestFlutterAppLifecycleDelegate* delegate = [[TestFlutterAppLifecycleDelegate alloc] init]; + [registrar addDelegate:delegate]; + + NSNotification* willFinishLaunching = + [NSNotification notificationWithName:NSApplicationWillFinishLaunchingNotification object:nil]; + [registrar handleWillFinishLaunching:willFinishLaunching]; + EXPECT_EQ([delegate lastNotification], willFinishLaunching); +} + +TEST(FlutterAppLifecycleDelegateTest, RespondsToDidFinishLaunching) { + FlutterAppLifecycleRegistrar* registrar = [[FlutterAppLifecycleRegistrar alloc] init]; + TestFlutterAppLifecycleDelegate* delegate = [[TestFlutterAppLifecycleDelegate alloc] init]; + [registrar addDelegate:delegate]; + + NSNotification* didFinishLaunching = + [NSNotification notificationWithName:NSApplicationDidFinishLaunchingNotification object:nil]; + [registrar handleDidFinishLaunching:didFinishLaunching]; + EXPECT_EQ([delegate lastNotification], didFinishLaunching); +} + +TEST(FlutterAppLifecycleDelegateTest, RespondsToWillBecomeActive) { + FlutterAppLifecycleRegistrar* registrar = [[FlutterAppLifecycleRegistrar alloc] init]; + TestFlutterAppLifecycleDelegate* delegate = [[TestFlutterAppLifecycleDelegate alloc] init]; + [registrar addDelegate:delegate]; + + NSNotification* willBecomeActive = + [NSNotification notificationWithName:NSApplicationWillBecomeActiveNotification object:nil]; + [registrar handleWillBecomeActive:willBecomeActive]; + EXPECT_EQ([delegate lastNotification], willBecomeActive); +} + +TEST(FlutterAppLifecycleDelegateTest, RespondsToDidBecomeActive) { + FlutterAppLifecycleRegistrar* registrar = [[FlutterAppLifecycleRegistrar alloc] init]; + TestFlutterAppLifecycleDelegate* delegate = [[TestFlutterAppLifecycleDelegate alloc] init]; + [registrar addDelegate:delegate]; + + NSNotification* didBecomeActive = + [NSNotification notificationWithName:NSApplicationDidBecomeActiveNotification object:nil]; + [registrar handleDidBecomeActive:didBecomeActive]; + EXPECT_EQ([delegate lastNotification], didBecomeActive); +} + +TEST(FlutterAppLifecycleDelegateTest, RespondsToWillResignActive) { + FlutterAppLifecycleRegistrar* registrar = [[FlutterAppLifecycleRegistrar alloc] init]; + TestFlutterAppLifecycleDelegate* delegate = [[TestFlutterAppLifecycleDelegate alloc] init]; + [registrar addDelegate:delegate]; + + NSNotification* willResignActive = + [NSNotification notificationWithName:NSApplicationWillResignActiveNotification object:nil]; + [registrar handleWillResignActive:willResignActive]; + EXPECT_EQ([delegate lastNotification], willResignActive); +} + +TEST(FlutterAppLifecycleDelegateTest, RespondsToDidResignActive) { + FlutterAppLifecycleRegistrar* registrar = [[FlutterAppLifecycleRegistrar alloc] init]; + TestFlutterAppLifecycleDelegate* delegate = [[TestFlutterAppLifecycleDelegate alloc] init]; + [registrar addDelegate:delegate]; + + NSNotification* didResignActive = + [NSNotification notificationWithName:NSApplicationDidResignActiveNotification object:nil]; + [registrar handleDidResignActive:didResignActive]; + EXPECT_EQ([delegate lastNotification], didResignActive); +} + +TEST(FlutterAppLifecycleDelegateTest, RespondsToWillTerminate) { + FlutterAppLifecycleRegistrar* registrar = [[FlutterAppLifecycleRegistrar alloc] init]; + TestFlutterAppLifecycleDelegate* delegate = [[TestFlutterAppLifecycleDelegate alloc] init]; + [registrar addDelegate:delegate]; + + NSNotification* applicationWillTerminate = + [NSNotification notificationWithName:NSApplicationWillTerminateNotification object:nil]; + [registrar handleWillTerminate:applicationWillTerminate]; + EXPECT_EQ([delegate lastNotification], applicationWillTerminate); +} + +TEST(FlutterAppLifecycleDelegateTest, RespondsToWillHide) { + FlutterAppLifecycleRegistrar* registrar = [[FlutterAppLifecycleRegistrar alloc] init]; + TestFlutterAppLifecycleDelegate* delegate = [[TestFlutterAppLifecycleDelegate alloc] init]; + [registrar addDelegate:delegate]; + + NSNotification* willHide = [NSNotification notificationWithName:NSApplicationWillHideNotification + object:nil]; + [registrar handleWillHide:willHide]; + EXPECT_EQ([delegate lastNotification], willHide); +} + +TEST(FlutterAppLifecycleDelegateTest, RespondsToWillUnhide) { + FlutterAppLifecycleRegistrar* registrar = [[FlutterAppLifecycleRegistrar alloc] init]; + TestFlutterAppLifecycleDelegate* delegate = [[TestFlutterAppLifecycleDelegate alloc] init]; + [registrar addDelegate:delegate]; + + NSNotification* willUnhide = + [NSNotification notificationWithName:NSApplicationWillUnhideNotification object:nil]; + [registrar handleWillUnhide:willUnhide]; + EXPECT_EQ([delegate lastNotification], willUnhide); +} + +TEST(FlutterAppLifecycleDelegateTest, RespondsToDidHide) { + FlutterAppLifecycleRegistrar* registrar = [[FlutterAppLifecycleRegistrar alloc] init]; + TestFlutterAppLifecycleDelegate* delegate = [[TestFlutterAppLifecycleDelegate alloc] init]; + [registrar addDelegate:delegate]; + + NSNotification* didHide = [NSNotification notificationWithName:NSApplicationDidHideNotification + object:nil]; + [registrar handleDidHide:didHide]; + EXPECT_EQ([delegate lastNotification], didHide); +} + +TEST(FlutterAppLifecycleDelegateTest, RespondsToDidUnhide) { + FlutterAppLifecycleRegistrar* registrar = [[FlutterAppLifecycleRegistrar alloc] init]; + TestFlutterAppLifecycleDelegate* delegate = [[TestFlutterAppLifecycleDelegate alloc] init]; + [registrar addDelegate:delegate]; + + NSNotification* didUnhide = + [NSNotification notificationWithName:NSApplicationDidUnhideNotification object:nil]; + [registrar handleDidUnhide:didUnhide]; + EXPECT_EQ([delegate lastNotification], didUnhide); +} + +TEST(FlutterAppLifecycleDelegateTest, RespondsToDidChangeScreenParameters) { + FlutterAppLifecycleRegistrar* registrar = [[FlutterAppLifecycleRegistrar alloc] init]; + TestFlutterAppLifecycleDelegate* delegate = [[TestFlutterAppLifecycleDelegate alloc] init]; + [registrar addDelegate:delegate]; + + NSNotification* didChangeScreenParameters = + [NSNotification notificationWithName:NSApplicationDidChangeScreenParametersNotification + object:nil]; + [registrar handleDidChangeScreenParameters:didChangeScreenParameters]; + EXPECT_EQ([delegate lastNotification], didChangeScreenParameters); +} + +TEST(FlutterAppLifecycleDelegateTest, RespondsToDidChangeOcclusionState) { + FlutterAppLifecycleRegistrar* registrar = [[FlutterAppLifecycleRegistrar alloc] init]; + TestFlutterAppLifecycleDelegate* delegate = [[TestFlutterAppLifecycleDelegate alloc] init]; + [registrar addDelegate:delegate]; + + NSNotification* didChangeOcclusionState = + [NSNotification notificationWithName:NSApplicationDidChangeOcclusionStateNotification + object:nil]; + if ([registrar respondsToSelector:@selector(handleDidChangeOcclusionState:)]) { + [registrar handleDidChangeOcclusionState:didChangeOcclusionState]; + EXPECT_EQ([delegate lastNotification], didChangeOcclusionState); + } +} + +TEST(FlutterAppLifecycleDelegateTest, ReleasesDelegateOnDealloc) { + __weak FlutterAppLifecycleRegistrar* weakRegistrar; + __weak TestFlutterAppLifecycleDelegate* weakDelegate; + @autoreleasepool { + FlutterAppLifecycleRegistrar* registrar = [[FlutterAppLifecycleRegistrar alloc] init]; + weakRegistrar = registrar; + TestFlutterAppLifecycleDelegate* delegate = [[TestFlutterAppLifecycleDelegate alloc] init]; + weakDelegate = delegate; + [registrar addDelegate:delegate]; + } + EXPECT_EQ(weakRegistrar, nil); + EXPECT_EQ(weakDelegate, nil); +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterAppLifecycleDelegate_Internal.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterAppLifecycleDelegate_Internal.h new file mode 100644 index 0000000000000000000000000000000000000000..de55dddbade97487fdb7617ed1d9a18afa9262f1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterAppLifecycleDelegate_Internal.h @@ -0,0 +1,18 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERAPPLIFECYCLEDELEGATE_INTERNAL_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERAPPLIFECYCLEDELEGATE_INTERNAL_H_ + +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppLifecycleDelegate.h" + +@interface FlutterAppLifecycleRegistrar () +/** + * Registered delegates. Exposed to allow FlutterAppDelegate to share the delegate list for + * handling non-notification delegation. + */ +@property(nonatomic, strong) NSPointerArray* delegates; +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERAPPLIFECYCLEDELEGATE_INTERNAL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterBackingStore.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterBackingStore.h new file mode 100644 index 0000000000000000000000000000000000000000..80f8bfe1c75cd53893f18b222bff77ee2d2b38ad --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterBackingStore.h @@ -0,0 +1,29 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERBACKINGSTORE_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERBACKINGSTORE_H_ + +#import +#import + +/** + * Interface for backing store handles. Typically contain references to the buffers that + * are handed by the `FlutterView` to the `FlutterRenderer`. + */ +@interface FlutterRenderBackingStore : NSObject + +/** + * MTLTexture referenced by this backing store instance. + */ +@property(nonnull, nonatomic, readonly) id texture; + +/** + * Initializes a backing store with the specified MTLTexture. + */ +- (nonnull instancetype)initWithTexture:(nonnull id)texture; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERBACKINGSTORE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterBackingStore.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterBackingStore.mm new file mode 100644 index 0000000000000000000000000000000000000000..61404932c9c2d6afc994ec5fe590357c964d9cf1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterBackingStore.mm @@ -0,0 +1,17 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterBackingStore.h" + +@implementation FlutterRenderBackingStore + +- (instancetype)initWithTexture:(id)texture { + self = [super init]; + if (self) { + _texture = texture; + } + return self; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterChannelKeyResponder.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterChannelKeyResponder.h new file mode 100644 index 0000000000000000000000000000000000000000..beccb9de78a9b94b8d6c2866c37f32c2ed4246f1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterChannelKeyResponder.h @@ -0,0 +1,29 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERCHANNELKEYRESPONDER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERCHANNELKEYRESPONDER_H_ + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyPrimaryResponder.h" + +#import + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" + +/** + * A primary responder of |FlutterKeyboardManager| that handles events by + * sending the raw information through the method channel. + * + * This class communicates with the RawKeyboard API in the framework. + */ +@interface FlutterChannelKeyResponder : NSObject + +/** + * Create an instance by specifying the method channel to use. + */ +- (nonnull instancetype)initWithChannel:(nonnull FlutterBasicMessageChannel*)channel; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERCHANNELKEYRESPONDER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterChannelKeyResponder.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterChannelKeyResponder.mm new file mode 100644 index 0000000000000000000000000000000000000000..a2c05767976252296db4981c3756939f5ee459d5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterChannelKeyResponder.mm @@ -0,0 +1,170 @@ +// 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. + +#import + +#import "FlutterChannelKeyResponder.h" +#import "KeyCodeMap_Internal.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" +#import "flutter/shell/platform/embedder/embedder.h" + +@interface FlutterChannelKeyResponder () + +/** + * The channel used to communicate with Flutter. + */ +@property(nonatomic) FlutterBasicMessageChannel* channel; + +/** + * The |NSEvent.modifierFlags| of the last event received. + * + * Used to determine whether a FlagsChanged event should count as a keydown or + * a keyup event. + */ +@property(nonatomic) uint64_t previouslyPressedFlags; + +@end + +@implementation FlutterChannelKeyResponder + +// Synthesize properties declared in FlutterKeyPrimaryResponder protocol. +@synthesize layoutMap; + +- (nonnull instancetype)initWithChannel:(nonnull FlutterBasicMessageChannel*)channel { + self = [super init]; + if (self != nil) { + _channel = channel; + _previouslyPressedFlags = 0; + } + return self; +} + +/// Checks single modifier flag from event flags and sends appropriate key event +/// if it is different from the previous state. +- (void)checkModifierFlag:(NSUInteger)targetMask + forEventFlags:(NSEventModifierFlags)eventFlags + keyCode:(NSUInteger)keyCode + timestamp:(NSTimeInterval)timestamp { + NSAssert((targetMask & (targetMask - 1)) == 0, @"targetMask must only have one bit set"); + if ((eventFlags & targetMask) != (_previouslyPressedFlags & targetMask)) { + uint64_t newFlags = (_previouslyPressedFlags & ~targetMask) | (eventFlags & targetMask); + + // Sets combined flag if either left or right modifier is pressed, unsets otherwise. + auto updateCombinedFlag = [&](uint64_t side1, uint64_t side2, NSEventModifierFlags flag) { + if (newFlags & (side1 | side2)) { + newFlags |= flag; + } else { + newFlags &= ~flag; + } + }; + updateCombinedFlag(flutter::kModifierFlagShiftLeft, flutter::kModifierFlagShiftRight, + NSEventModifierFlagShift); + updateCombinedFlag(flutter::kModifierFlagControlLeft, flutter::kModifierFlagControlRight, + NSEventModifierFlagControl); + updateCombinedFlag(flutter::kModifierFlagAltLeft, flutter::kModifierFlagAltRight, + NSEventModifierFlagOption); + updateCombinedFlag(flutter::kModifierFlagMetaLeft, flutter::kModifierFlagMetaRight, + NSEventModifierFlagCommand); + + NSEvent* event = [NSEvent keyEventWithType:NSEventTypeFlagsChanged + location:NSZeroPoint + modifierFlags:newFlags + timestamp:timestamp + windowNumber:0 + context:nil + characters:@"" + charactersIgnoringModifiers:@"" + isARepeat:NO + keyCode:keyCode]; + [self handleEvent:event + callback:^(BOOL){ + }]; + }; +} + +- (void)syncModifiersIfNeeded:(NSEventModifierFlags)modifierFlags + timestamp:(NSTimeInterval)timestamp { + modifierFlags = modifierFlags & ~0x100; + if (_previouslyPressedFlags == modifierFlags) { + return; + } + + [flutter::modifierFlagToKeyCode + enumerateKeysAndObjectsUsingBlock:^(NSNumber* flag, NSNumber* keyCode, BOOL* stop) { + [self checkModifierFlag:[flag unsignedShortValue] + forEventFlags:modifierFlags + keyCode:[keyCode unsignedShortValue] + timestamp:timestamp]; + }]; + + // Caps lock is not included in the modifierFlagToKeyCode map. + [self checkModifierFlag:NSEventModifierFlagCapsLock + forEventFlags:modifierFlags + keyCode:0x00000039 // kVK_CapsLock + timestamp:timestamp]; +} + +- (void)handleEvent:(NSEvent*)event callback:(FlutterAsyncKeyCallback)callback { + // Remove the modifier bits that Flutter is not interested in. + NSEventModifierFlags modifierFlags = event.modifierFlags & ~0x100; + NSString* type; + switch (event.type) { + case NSEventTypeKeyDown: + type = @"keydown"; + break; + case NSEventTypeKeyUp: + type = @"keyup"; + break; + case NSEventTypeFlagsChanged: + if (modifierFlags < _previouslyPressedFlags) { + type = @"keyup"; + } else if (modifierFlags > _previouslyPressedFlags) { + type = @"keydown"; + } else { + // ignore duplicate modifiers; This can happen in situations like switching + // between application windows when MacOS only sends the up event to new window. + callback(true); + return; + } + break; + default: + [[unlikely]] { + NSAssert(false, @"Unexpected key event type (got %lu).", event.type); + callback(false); + // This should not happen. Return to suppress clang-tidy warning on `type` being nil. + return; + } + } + _previouslyPressedFlags = modifierFlags; + NSMutableDictionary* keyMessage = [@{ + @"keymap" : @"macos", + @"type" : type, + @"keyCode" : @(event.keyCode), + @"modifiers" : @(modifierFlags), + } mutableCopy]; + // Calling these methods on any other type of event + // (e.g NSEventTypeFlagsChanged) will raise an exception. + if (event.type == NSEventTypeKeyDown || event.type == NSEventTypeKeyUp) { + keyMessage[@"characters"] = event.characters; + keyMessage[@"charactersIgnoringModifiers"] = event.charactersIgnoringModifiers; + } + NSNumber* specifiedLogicalKey = layoutMap[@(event.keyCode)]; + if (specifiedLogicalKey != nil) { + keyMessage[@"specifiedLogicalKey"] = specifiedLogicalKey; + } + [self.channel sendMessage:keyMessage + reply:^(id reply) { + if (!reply) { + return callback(true); + } + // Only propagate the event to other responders if the framework didn't + // handle it. + callback([[reply valueForKey:@"handled"] boolValue]); + }]; +} + +#pragma mark - Private + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterChannelKeyResponderTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterChannelKeyResponderTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..004f00799d21d1c3a6818f87005ba3235fb05f87 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterChannelKeyResponderTest.mm @@ -0,0 +1,286 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterChannelKeyResponder.h" + +#include +#import + +#include "flutter/shell/platform/embedder/test_utils/key_codes.g.h" +#include "flutter/testing/autoreleasepool_test.h" +#include "flutter/testing/testing.h" +#include "third_party/googletest/googletest/include/gtest/gtest.h" + +// FlutterBasicMessageChannel fake instance that records Flutter key event messages. +// +// When a sendMessage:reply: callback is specified, it is invoked with the value stored in the +// nextResponse property. +@interface FakeMessageChannel : FlutterBasicMessageChannel +@property(nonatomic, readonly) NSMutableArray* messages; +@property(nonatomic) NSDictionary* nextResponse; + +- (instancetype)init; +- (void)sendMessage:(id _Nullable)message; +- (void)sendMessage:(id _Nullable)message reply:(FlutterReply _Nullable)callback; +@end + +@implementation FakeMessageChannel +- (instancetype)init { + self = [super init]; + if (self != nil) { + _messages = [[NSMutableArray alloc] init]; + } + return self; +} + +- (void)sendMessage:(id _Nullable)message { + [self sendMessage:message reply:nil]; +} + +- (void)sendMessage:(id _Nullable)message reply:(FlutterReply _Nullable)callback { + [_messages addObject:message]; + if (callback) { + callback(_nextResponse); + } +} +@end + +namespace flutter::testing { + +namespace { +using flutter::testing::keycodes::kLogicalKeyQ; + +NSEvent* CreateKeyEvent(NSEventType type, + NSEventModifierFlags modifierFlags, + NSString* characters, + NSString* charactersIgnoringModifiers, + BOOL isARepeat, + unsigned short keyCode) { + return [NSEvent keyEventWithType:type + location:NSZeroPoint + modifierFlags:modifierFlags + timestamp:0 + windowNumber:0 + context:nil + characters:characters + charactersIgnoringModifiers:charactersIgnoringModifiers + isARepeat:isARepeat + keyCode:keyCode]; +} +} // namespace + +using FlutterChannelKeyResponderTest = AutoreleasePoolTest; + +TEST_F(FlutterChannelKeyResponderTest, BasicKeyEvent) { + __block NSMutableArray* responses = [[NSMutableArray alloc] init]; + FakeMessageChannel* channel = [[FakeMessageChannel alloc] init]; + FlutterChannelKeyResponder* responder = + [[FlutterChannelKeyResponder alloc] initWithChannel:channel]; + + // Initial empty modifiers. + // + // This can happen when user opens window while modifier key is pressed and then releases the + // modifier. No events should be sent, but the callback should still be called. + // Regression test for https://github.com/flutter/flutter/issues/87339. + channel.nextResponse = @{@"handled" : @YES}; + [responder handleEvent:CreateKeyEvent(NSEventTypeFlagsChanged, 0x100, @"", @"", NO, 60) + callback:^(BOOL handled) { + [responses addObject:@(handled)]; + }]; + + EXPECT_EQ([channel.messages count], 0u); + ASSERT_EQ([responses count], 1u); + EXPECT_EQ([responses[0] boolValue], YES); + [responses removeAllObjects]; + + // Key down + channel.nextResponse = @{@"handled" : @YES}; + [responder handleEvent:CreateKeyEvent(NSEventTypeKeyDown, 0x100, @"a", @"a", NO, 0) + callback:^(BOOL handled) { + [responses addObject:@(handled)]; + }]; + + ASSERT_EQ([channel.messages count], 1u); + EXPECT_STREQ([[channel.messages lastObject][@"keymap"] UTF8String], "macos"); + EXPECT_STREQ([[channel.messages lastObject][@"type"] UTF8String], "keydown"); + EXPECT_EQ([[channel.messages lastObject][@"keyCode"] intValue], 0); + EXPECT_EQ([[channel.messages lastObject][@"modifiers"] intValue], 0x0); + EXPECT_STREQ([[channel.messages lastObject][@"characters"] UTF8String], "a"); + EXPECT_STREQ([[channel.messages lastObject][@"charactersIgnoringModifiers"] UTF8String], "a"); + + ASSERT_EQ([responses count], 1u); + EXPECT_EQ([[responses lastObject] boolValue], YES); + + [channel.messages removeAllObjects]; + [responses removeAllObjects]; + + // Key up + channel.nextResponse = @{@"handled" : @NO}; + [responder handleEvent:CreateKeyEvent(NSEventTypeKeyUp, 0x100, @"a", @"a", NO, 0) + callback:^(BOOL handled) { + [responses addObject:@(handled)]; + }]; + + ASSERT_EQ([channel.messages count], 1u); + EXPECT_STREQ([[channel.messages lastObject][@"keymap"] UTF8String], "macos"); + EXPECT_STREQ([[channel.messages lastObject][@"type"] UTF8String], "keyup"); + EXPECT_EQ([[channel.messages lastObject][@"keyCode"] intValue], 0); + EXPECT_EQ([[channel.messages lastObject][@"modifiers"] intValue], 0); + EXPECT_STREQ([[channel.messages lastObject][@"characters"] UTF8String], "a"); + EXPECT_STREQ([[channel.messages lastObject][@"charactersIgnoringModifiers"] UTF8String], "a"); + + ASSERT_EQ([responses count], 1u); + EXPECT_EQ([[responses lastObject] boolValue], NO); + + [channel.messages removeAllObjects]; + [responses removeAllObjects]; + + // LShift down + channel.nextResponse = @{@"handled" : @YES}; + [responder handleEvent:CreateKeyEvent(NSEventTypeFlagsChanged, 0x20102, @"", @"", NO, 56) + callback:^(BOOL handled) { + [responses addObject:@(handled)]; + }]; + + ASSERT_EQ([channel.messages count], 1u); + EXPECT_STREQ([[channel.messages lastObject][@"keymap"] UTF8String], "macos"); + EXPECT_STREQ([[channel.messages lastObject][@"type"] UTF8String], "keydown"); + EXPECT_EQ([[channel.messages lastObject][@"keyCode"] intValue], 56); + EXPECT_EQ([[channel.messages lastObject][@"modifiers"] intValue], 0x20002); + + ASSERT_EQ([responses count], 1u); + EXPECT_EQ([[responses lastObject] boolValue], YES); + + [channel.messages removeAllObjects]; + [responses removeAllObjects]; + + // RShift down + channel.nextResponse = @{@"handled" : @NO}; + [responder handleEvent:CreateKeyEvent(NSEventTypeFlagsChanged, 0x20006, @"", @"", NO, 60) + callback:^(BOOL handled) { + [responses addObject:@(handled)]; + }]; + + ASSERT_EQ([channel.messages count], 1u); + EXPECT_STREQ([[channel.messages lastObject][@"keymap"] UTF8String], "macos"); + EXPECT_STREQ([[channel.messages lastObject][@"type"] UTF8String], "keydown"); + EXPECT_EQ([[channel.messages lastObject][@"keyCode"] intValue], 60); + EXPECT_EQ([[channel.messages lastObject][@"modifiers"] intValue], 0x20006); + + ASSERT_EQ([responses count], 1u); + EXPECT_EQ([[responses lastObject] boolValue], NO); + + [channel.messages removeAllObjects]; + [responses removeAllObjects]; + + // LShift up + channel.nextResponse = @{@"handled" : @NO}; + [responder handleEvent:CreateKeyEvent(NSEventTypeFlagsChanged, 0x20104, @"", @"", NO, 56) + callback:^(BOOL handled) { + [responses addObject:@(handled)]; + }]; + + ASSERT_EQ([channel.messages count], 1u); + EXPECT_STREQ([[channel.messages lastObject][@"keymap"] UTF8String], "macos"); + EXPECT_STREQ([[channel.messages lastObject][@"type"] UTF8String], "keyup"); + EXPECT_EQ([[channel.messages lastObject][@"keyCode"] intValue], 56); + EXPECT_EQ([[channel.messages lastObject][@"modifiers"] intValue], 0x20004); + + ASSERT_EQ([responses count], 1u); + EXPECT_EQ([[responses lastObject] boolValue], NO); + + [channel.messages removeAllObjects]; + [responses removeAllObjects]; + + // RShift up + channel.nextResponse = @{@"handled" : @NO}; + [responder handleEvent:CreateKeyEvent(NSEventTypeFlagsChanged, 0, @"", @"", NO, 60) + callback:^(BOOL handled) { + [responses addObject:@(handled)]; + }]; + + ASSERT_EQ([channel.messages count], 1u); + EXPECT_STREQ([[channel.messages lastObject][@"keymap"] UTF8String], "macos"); + EXPECT_STREQ([[channel.messages lastObject][@"type"] UTF8String], "keyup"); + EXPECT_EQ([[channel.messages lastObject][@"keyCode"] intValue], 60); + EXPECT_EQ([[channel.messages lastObject][@"modifiers"] intValue], 0); + + ASSERT_EQ([responses count], 1u); + EXPECT_EQ([[responses lastObject] boolValue], NO); + + [channel.messages removeAllObjects]; + [responses removeAllObjects]; + + // RShift up again, should be ignored and not produce a keydown event, but the + // callback should be called. + channel.nextResponse = @{@"handled" : @NO}; + [responder handleEvent:CreateKeyEvent(NSEventTypeFlagsChanged, 0x100, @"", @"", NO, 60) + callback:^(BOOL handled) { + [responses addObject:@(handled)]; + }]; + + EXPECT_EQ([channel.messages count], 0u); + ASSERT_EQ([responses count], 1u); + EXPECT_EQ([responses[0] boolValue], YES); +} + +TEST_F(FlutterChannelKeyResponderTest, EmptyResponseIsTakenAsHandled) { + __block NSMutableArray* responses = [[NSMutableArray alloc] init]; + FakeMessageChannel* channel = [[FakeMessageChannel alloc] init]; + FlutterChannelKeyResponder* responder = + [[FlutterChannelKeyResponder alloc] initWithChannel:channel]; + + channel.nextResponse = nil; + [responder handleEvent:CreateKeyEvent(NSEventTypeKeyDown, 0x100, @"a", @"a", NO, 0) + callback:^(BOOL handled) { + [responses addObject:@(handled)]; + }]; + + ASSERT_EQ([channel.messages count], 1u); + EXPECT_STREQ([[channel.messages lastObject][@"keymap"] UTF8String], "macos"); + EXPECT_STREQ([[channel.messages lastObject][@"type"] UTF8String], "keydown"); + EXPECT_EQ([[channel.messages lastObject][@"keyCode"] intValue], 0); + EXPECT_EQ([[channel.messages lastObject][@"modifiers"] intValue], 0); + EXPECT_STREQ([[channel.messages lastObject][@"characters"] UTF8String], "a"); + EXPECT_STREQ([[channel.messages lastObject][@"charactersIgnoringModifiers"] UTF8String], "a"); + + ASSERT_EQ([responses count], 1u); + EXPECT_EQ([[responses lastObject] boolValue], YES); +} + +TEST_F(FlutterChannelKeyResponderTest, FollowsLayoutMap) { + __block NSMutableArray* responses = [[NSMutableArray alloc] init]; + FakeMessageChannel* channel = [[FakeMessageChannel alloc] init]; + FlutterChannelKeyResponder* responder = + [[FlutterChannelKeyResponder alloc] initWithChannel:channel]; + + NSMutableDictionary* layoutMap = + [NSMutableDictionary dictionary]; + responder.layoutMap = layoutMap; + // French layout + layoutMap[@(kVK_ANSI_A)] = @(kLogicalKeyQ); + + channel.nextResponse = @{@"handled" : @YES}; + [responder handleEvent:CreateKeyEvent(NSEventTypeKeyDown, kVK_ANSI_A, @"q", @"q", NO, 0) + callback:^(BOOL handled) { + [responses addObject:@(handled)]; + }]; + + ASSERT_EQ([channel.messages count], 1u); + EXPECT_STREQ([[channel.messages lastObject][@"keymap"] UTF8String], "macos"); + EXPECT_STREQ([[channel.messages lastObject][@"type"] UTF8String], "keydown"); + EXPECT_EQ([[channel.messages lastObject][@"keyCode"] intValue], 0); + EXPECT_EQ([[channel.messages lastObject][@"modifiers"] intValue], 0x0); + EXPECT_STREQ([[channel.messages lastObject][@"characters"] UTF8String], "q"); + EXPECT_STREQ([[channel.messages lastObject][@"charactersIgnoringModifiers"] UTF8String], "q"); + EXPECT_EQ([channel.messages lastObject][@"specifiedLogicalKey"], @(kLogicalKeyQ)); + + ASSERT_EQ([responses count], 1u); + EXPECT_EQ([[responses lastObject] boolValue], YES); + + [channel.messages removeAllObjects]; + [responses removeAllObjects]; +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterCompositor.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterCompositor.h new file mode 100644 index 0000000000000000000000000000000000000000..1f756499ac893168f814327459f21e5837caeff7 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterCompositor.h @@ -0,0 +1,131 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERCOMPOSITOR_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERCOMPOSITOR_H_ + +#include +#include +#include +#include + +#include "flutter/fml/macros.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMutatorView.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewController.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTimeConverter.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewProvider.h" +#include "flutter/shell/platform/embedder/embedder.h" + +@class FlutterMutatorView; +@class FlutterCursorCoordinator; + +namespace flutter { + +struct BackingStoreLayer { + std::vector paint_region; +}; + +using LayerVariant = std::variant; + +// FlutterCompositor creates and manages the backing stores used for +// rendering Flutter content and presents Flutter content and Platform views. +// Platform views are not yet supported. +// +// TODO(cbracken): refactor for testability. https://github.com/flutter/flutter/issues/137648 +class FlutterCompositor { + public: + // Create a FlutterCompositor with a view provider. + // + // The view_provider is used to query FlutterViews from view IDs, + // which are used for presenting and creating backing stores. + // It must not be null, and is typically FlutterViewEngineProvider. + FlutterCompositor(id view_provider, + FlutterTimeConverter* time_converter, + FlutterPlatformViewController* platform_views_controller); + + ~FlutterCompositor() = default; + + // Allocate the resources for displaying a view. + // + // This method must be called when a view is added to FlutterEngine, and must be + // called on the main dispatch queue, or an assertion will be thrown. + void AddView(FlutterViewId view_id); + + // Deallocate the resources for displaying a view. + // + // This method must be called when a view is removed from FlutterEngine, and + // must be called on the main dispatch queue, or an assertion will be thrown. + void RemoveView(FlutterViewId view_id); + + // Creates a backing store and saves updates the backing_store_out data with + // the new FlutterBackingStore data. + // + // If the backing store is being requested for the first time for a given + // frame, this compositor does not create a new backing store but rather + // returns the backing store associated with the FlutterView's + // FlutterSurfaceManager. + // + // Any additional state allocated for the backing store and saved as + // user_data in the backing store must be collected in the backing_store's + // destruction_callback field which will be called when the embedder collects + // the backing store. + bool CreateBackingStore(const FlutterBackingStoreConfig* config, + FlutterBackingStore* backing_store_out); + + // Presents the FlutterLayers by updating the FlutterView specified by + // `view_id` using the layer content. + bool Present(FlutterViewIdentifier view_id, const FlutterLayer** layers, size_t layers_count); + + // The number of views that the FlutterCompositor is keeping track of. + // + // This method must only be used in unit tests. + size_t DebugNumViews(); + + private: + // A class that contains the information for a view to be presented. + class ViewPresenter { + public: + ViewPresenter(); + + void PresentPlatformViews(FlutterView* default_base_view, + const std::vector& layers, + const FlutterPlatformViewController* platform_views_controller); + + private: + // Platform view to FlutterMutatorView that contains it. + NSMapTable* mutator_views_; + + // Coordinates mouse cursor changes between platform views and overlays. + FlutterCursorCoordinator* cursor_coordinator_; + + // Presents the platform view layer represented by `layer`. `layer_index` is + // used to position the layer in the z-axis. If the layer does not have a + // superview, it will become subview of `default_base_view`. + FlutterMutatorView* PresentPlatformView( + FlutterView* default_base_view, + const PlatformViewLayer& layer, + size_t layer_position, + const FlutterPlatformViewController* platform_views_controller); + + FML_DISALLOW_COPY_AND_ASSIGN(ViewPresenter); + }; + + // Where the compositor can query FlutterViews. Must not be null. + id const view_provider_; + + // Converts between engine time and core animation media time. + FlutterTimeConverter* const time_converter_; + + // The controller used to manage creation and deletion of platform views. + const FlutterPlatformViewController* platform_view_controller_; + + // The view presenters for views. Each key is a view ID. + std::unordered_map presenters_; + + FML_DISALLOW_COPY_AND_ASSIGN(FlutterCompositor); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERCOMPOSITOR_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterCompositor.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterCompositor.mm new file mode 100644 index 0000000000000000000000000000000000000000..b1cd10ec3a4eb1b583188c433a0cff80383e32b3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterCompositor.mm @@ -0,0 +1,228 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterCompositor.h" + +#include "flutter/common/constants.h" +#include "flutter/fml/logging.h" + +namespace flutter { + +namespace { +std::vector CopyLayers(const FlutterLayer** layers, size_t layer_count) { + std::vector layers_copy; + for (size_t i = 0; i < layer_count; i++) { + const auto& layer = layers[i]; + if (layer->type == kFlutterLayerContentTypePlatformView) { + layers_copy.push_back(PlatformViewLayer(layer)); + } else if (layer->type == kFlutterLayerContentTypeBackingStore) { + std::vector rects; + auto present_info = layer->backing_store_present_info; + if (present_info != nullptr && present_info->paint_region != nullptr) { + rects.reserve(present_info->paint_region->rects_count); + std::copy(present_info->paint_region->rects, + present_info->paint_region->rects + present_info->paint_region->rects_count, + std::back_inserter(rects)); + } + layers_copy.push_back(BackingStoreLayer{rects}); + } + } + return layers_copy; +} +} // namespace + +FlutterCompositor::FlutterCompositor(id view_provider, + FlutterTimeConverter* time_converter, + FlutterPlatformViewController* platform_view_controller) + : view_provider_(view_provider), + time_converter_(time_converter), + platform_view_controller_(platform_view_controller) { + FML_CHECK(view_provider != nullptr) << "view_provider cannot be nullptr"; +} + +void FlutterCompositor::AddView(FlutterViewId view_id) { + dispatch_assert_queue(dispatch_get_main_queue()); + presenters_.try_emplace(view_id); +} + +void FlutterCompositor::RemoveView(FlutterViewId view_id) { + dispatch_assert_queue(dispatch_get_main_queue()); + presenters_.erase(view_id); +} + +bool FlutterCompositor::CreateBackingStore(const FlutterBackingStoreConfig* config, + FlutterBackingStore* backing_store_out) { + FlutterView* view = [view_provider_ viewForIdentifier:config->view_id]; + if (!view) { + return false; + } + + CGSize size = CGSizeMake(config->size.width, config->size.height); + FlutterSurface* surface = [view.surfaceManager surfaceForSize:size]; + memset(backing_store_out, 0, sizeof(FlutterBackingStore)); + backing_store_out->struct_size = sizeof(FlutterBackingStore); + backing_store_out->type = kFlutterBackingStoreTypeMetal; + backing_store_out->metal.struct_size = sizeof(FlutterMetalBackingStore); + backing_store_out->metal.texture = surface.asFlutterMetalTexture; + return true; +} + +bool FlutterCompositor::Present(FlutterViewIdentifier view_id, + const FlutterLayer** layers, + size_t layers_count) { + FlutterView* view = [view_provider_ viewForIdentifier:view_id]; + if (!view) { + return false; + } + + NSMutableArray* surfaces = [NSMutableArray array]; + for (size_t i = 0; i < layers_count; i++) { + const FlutterLayer* layer = layers[i]; + if (layer->type == kFlutterLayerContentTypeBackingStore) { + FlutterSurface* surface = + [FlutterSurface fromFlutterMetalTexture:&layer->backing_store->metal.texture]; + + if (surface) { + FlutterSurfacePresentInfo* info = [[FlutterSurfacePresentInfo alloc] init]; + info.surface = surface; + info.offset = CGPointMake(layer->offset.x, layer->offset.y); + info.zIndex = i; + FlutterBackingStorePresentInfo* present_info = layer->backing_store_present_info; + if (present_info != nullptr && present_info->paint_region != nullptr) { + auto paint_region = present_info->paint_region; + // Safe because the size of FlutterRect is not expected to change. + info.paintRegion = std::vector( + paint_region->rects, paint_region->rects + paint_region->rects_count); + } + [surfaces addObject:info]; + } + } + } + + CFTimeInterval presentation_time = 0; + + if (layers_count > 0 && layers[0]->presentation_time != 0) { + presentation_time = [time_converter_ engineTimeToCAMediaTime:layers[0]->presentation_time]; + } + + // Notify block below may be called asynchronously, hence the need to copy + // the layer information instead of passing the original pointers from embedder. + auto layers_copy = std::make_shared>(CopyLayers(layers, layers_count)); + + [view.surfaceManager presentSurfaces:surfaces + atTime:presentation_time + notify:^{ + // Accessing presenters_ here does not need a + // lock to avoid race condition against + // AddView and RemoveView, since all three + // take place on the platform thread. (The + // macOS API requires platform view presenting + // to take place on the platform thread, + // enforced by `FlutterThreadSynchronizer`.) + dispatch_assert_queue(dispatch_get_main_queue()); + auto found_presenter = presenters_.find(view_id); + if (found_presenter != presenters_.end()) { + found_presenter->second.PresentPlatformViews( + view, *layers_copy, platform_view_controller_); + } + }]; + + return true; +} + +size_t FlutterCompositor::DebugNumViews() { + return presenters_.size(); +} + +FlutterCompositor::ViewPresenter::ViewPresenter() + : mutator_views_([NSMapTable strongToStrongObjectsMapTable]) {} + +void FlutterCompositor::ViewPresenter::PresentPlatformViews( + FlutterView* default_base_view, + const std::vector& layers, + const FlutterPlatformViewController* platform_view_controller) { + FML_DCHECK([[NSThread currentThread] isMainThread]) + << "Must be on the main thread to present platform views"; + + // Active mutator views for this frame. + NSMutableArray* present_mutators = [NSMutableArray array]; + + for (size_t i = 0; i < layers.size(); i++) { + const auto& layer = layers[i]; + if (!std::holds_alternative(layer)) { + continue; + } + const auto& platform_view = std::get(layer); + FlutterMutatorView* mutator_view = + PresentPlatformView(default_base_view, platform_view, i, platform_view_controller); + [present_mutators addObject:mutator_view]; + + // Gather all overlay regions above this mutator view. + [mutator_view resetHitTestRegion]; + for (size_t j = i + 1; j < layers.size(); j++) { + const auto& overlay_layer = layers[j]; + if (!std::holds_alternative(overlay_layer)) { + continue; + } + const auto& backing_store_layer = std::get(overlay_layer); + for (const auto& flutter_rect : backing_store_layer.paint_region) { + double scale = default_base_view.layer.contentsScale; + CGRect rect = CGRectMake(flutter_rect.left / scale, flutter_rect.top / scale, + (flutter_rect.right - flutter_rect.left) / scale, + (flutter_rect.bottom - flutter_rect.top) / scale); + CGRect intersection = CGRectIntersection(rect, mutator_view.frame); + if (!CGRectIsNull(intersection)) { + intersection.origin.x -= mutator_view.frame.origin.x; + intersection.origin.y -= mutator_view.frame.origin.y; + [mutator_view addHitTestIgnoreRegion:intersection]; + } + } + } + } + + NSMutableArray* obsolete_mutators = + [NSMutableArray arrayWithArray:[mutator_views_ objectEnumerator].allObjects]; + [obsolete_mutators removeObjectsInArray:present_mutators]; + + for (FlutterMutatorView* mutator in obsolete_mutators) { + [mutator_views_ removeObjectForKey:mutator.platformView]; + [mutator removeFromSuperview]; + } + + [platform_view_controller disposePlatformViews]; +} + +FlutterMutatorView* FlutterCompositor::ViewPresenter::PresentPlatformView( + FlutterView* default_base_view, + const PlatformViewLayer& layer, + size_t index, + const FlutterPlatformViewController* platform_view_controller) { + FML_DCHECK([[NSThread currentThread] isMainThread]) + << "Must be on the main thread to present platform views"; + + int64_t platform_view_id = layer.identifier(); + NSView* platform_view = [platform_view_controller platformViewWithID:platform_view_id]; + + FML_DCHECK(platform_view) << "Platform view not found for id: " << platform_view_id; + + if (cursor_coordinator_ == nil) { + cursor_coordinator_ = [[FlutterCursorCoordinator alloc] initWithFlutterView:default_base_view]; + } + + FlutterMutatorView* container = [mutator_views_ objectForKey:platform_view]; + + if (!container) { + container = [[FlutterMutatorView alloc] initWithPlatformView:platform_view + cursorCoordiator:cursor_coordinator_]; + [mutator_views_ setObject:container forKey:platform_view]; + [default_base_view addSubview:container]; + } + + container.layer.zPosition = index; + [container applyFlutterLayer:&layer]; + + return container; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject.mm new file mode 100644 index 0000000000000000000000000000000000000000..7d1c06122f34e8b9764035774b380a697d10c746 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject.mm @@ -0,0 +1,140 @@ +// 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. + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterDartProject.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h" + +#include + +#include "flutter/shell/platform/common/engine_switches.h" + +static NSString* const kICUBundlePath = @"icudtl.dat"; +static NSString* const kAppBundleIdentifier = @"io.flutter.flutter.app"; + +#pragma mark - Private interface declaration. +@interface FlutterDartProject () +/** + Get the Flutter assets name path by pass the bundle. If bundle is nil, we use the main bundle as + default. + */ ++ (NSString*)flutterAssetsNameWithBundle:(NSBundle*)bundle; +@end + +@implementation FlutterDartProject { + NSBundle* _dartBundle; + NSString* _assetsPath; + NSString* _ICUDataPath; +} + +- (instancetype)init { + return [self initWithPrecompiledDartBundle:nil]; +} + +- (instancetype)initWithPrecompiledDartBundle:(NSBundle*)bundle { + self = [super init]; + NSAssert(self, @"Super init cannot be nil"); + + _dartBundle = bundle ?: FLTFrameworkBundleWithIdentifier(kAppBundleIdentifier); + if (_dartBundle == nil) { + // The bundle isn't loaded and can't be found by bundle ID. Find it by path. + _dartBundle = [NSBundle bundleWithURL:[NSBundle.mainBundle.privateFrameworksURL + URLByAppendingPathComponent:@"App.framework"]]; + } + if (!_dartBundle.isLoaded) { + [_dartBundle load]; + } + _dartEntrypointArguments = [[NSProcessInfo processInfo] arguments]; + // Remove the first element as it's the binary name + _dartEntrypointArguments = [_dartEntrypointArguments + subarrayWithRange:NSMakeRange(1, _dartEntrypointArguments.count - 1)]; + return self; +} + +- (instancetype)initWithAssetsPath:(NSString*)assets ICUDataPath:(NSString*)icuPath { + self = [super init]; + NSAssert(self, @"Super init cannot be nil"); + _assetsPath = assets; + _ICUDataPath = icuPath; + return self; +} + +- (BOOL)enableImpeller { + NSNumber* enableImpeller = + [[NSBundle mainBundle] objectForInfoDictionaryKey:@"FLTEnableImpeller"]; + if (enableImpeller != nil) { + return enableImpeller.boolValue; + } + return NO; +} + +- (NSString*)assetsPath { + if (_assetsPath) { + return _assetsPath; + } + + // If there's no App.framework, fall back to checking the main bundle for assets. + NSBundle* assetBundle = _dartBundle ?: [NSBundle mainBundle]; + NSString* flutterAssetsName = [assetBundle objectForInfoDictionaryKey:@"FLTAssetsPath"]; + if (flutterAssetsName == nil) { + flutterAssetsName = @"flutter_assets"; + } + NSString* path = [assetBundle pathForResource:flutterAssetsName ofType:@""]; + if (!path) { + NSLog(@"Failed to find path for \"%@\"", flutterAssetsName); + } + return path; +} + +- (NSString*)ICUDataPath { + if (_ICUDataPath) { + return _ICUDataPath; + } + + NSString* path = [[NSBundle bundleForClass:[self class]] pathForResource:kICUBundlePath + ofType:nil]; + if (!path) { + NSLog(@"Failed to find path for \"%@\"", kICUBundlePath); + } + return path; +} + ++ (NSString*)flutterAssetsNameWithBundle:(NSBundle*)bundle { + if (bundle == nil) { + bundle = FLTFrameworkBundleWithIdentifier(kAppBundleIdentifier); + } + if (bundle == nil) { + bundle = [NSBundle mainBundle]; + } + NSString* flutterAssetsName = [bundle objectForInfoDictionaryKey:@"FLTAssetsPath"]; + if (flutterAssetsName == nil) { + flutterAssetsName = @"Contents/Frameworks/App.framework/Resources/flutter_assets"; + } + return flutterAssetsName; +} + ++ (NSString*)lookupKeyForAsset:(NSString*)asset { + return [self lookupKeyForAsset:asset fromBundle:nil]; +} + ++ (NSString*)lookupKeyForAsset:(NSString*)asset fromBundle:(nullable NSBundle*)bundle { + NSString* flutterAssetsName = [FlutterDartProject flutterAssetsNameWithBundle:bundle]; + return [NSString stringWithFormat:@"%@/%@", flutterAssetsName, asset]; +} + ++ (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package { + return [self lookupKeyForAsset:asset fromPackage:package fromBundle:nil]; +} + ++ (NSString*)lookupKeyForAsset:(NSString*)asset + fromPackage:(NSString*)package + fromBundle:(nullable NSBundle*)bundle { + return [self lookupKeyForAsset:[NSString stringWithFormat:@"packages/%@/%@", package, asset] + fromBundle:bundle]; +} + ++ (NSString*)defaultBundleIdentifier { + return kAppBundleIdentifier; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h new file mode 100644 index 0000000000000000000000000000000000000000..a629f5556019a3f87f58d9600cb3309ab112c2bc --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h @@ -0,0 +1,48 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERDARTPROJECT_INTERNAL_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERDARTPROJECT_INTERNAL_H_ + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterDartProject.h" +#import "flutter/shell/platform/darwin/common/framework/Source/FlutterNSBundleUtils.h" + +#include +#include + +/** + * Provides access to data needed to construct a FlutterProjectArgs for the project. + */ +@interface FlutterDartProject () + +/** + * The path to the Flutter assets directory. + */ +@property(nonatomic, readonly, nullable) NSString* assetsPath; + +/** + * The path to the ICU data file. + */ +@property(nonatomic, readonly, nullable) NSString* ICUDataPath; + +/** + * The callback invoked by the engine in root isolate scope. + */ +@property(nonatomic, nullable) void (*rootIsolateCreateCallback)(void* _Nullable); + +/** + * Whether the Impeller rendering backend is enabled + */ +@property(nonatomic, readonly) BOOL enableImpeller; + +/** + * Instead of looking up the assets and ICU data path in the application bundle, this initializer + * allows callers to create a Dart project with custom locations specified for the both. + */ +- (nonnull instancetype)initWithAssetsPath:(nonnull NSString*)assets + ICUDataPath:(nonnull NSString*)icuPath NS_DESIGNATED_INITIALIZER; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERDARTPROJECT_INTERNAL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterDisplayLink.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterDisplayLink.h new file mode 100644 index 0000000000000000000000000000000000000000..f5958174969d0b65a9bad2b8b9e057dc4a69d72c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterDisplayLink.h @@ -0,0 +1,42 @@ +#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERDISPLAYLINK_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERDISPLAYLINK_H_ + +#import + +@protocol FlutterDisplayLinkDelegate +/// This will be called on main thread. +- (void)onDisplayLink:(CFTimeInterval)timestamp targetTimestamp:(CFTimeInterval)targetTimestamp; +@end + +/// Provides notifications of display refresh. +/// +/// Internally FlutterDisplayLink will use at most one CVDisplayLink per +/// screen shared for all views belonging to that screen. This is necessary +/// because each CVDisplayLink comes with its own thread. +/// +/// All methods must be called on main thread. +@interface FlutterDisplayLink : NSObject + +/// Creates new instance tied to provided NSView. FlutterDisplayLink +/// will track view display changes transparently to synchronize +/// update with display refresh. ++ (instancetype)displayLinkWithView:(NSView*)view; + +/// Delegate must be set on main thread. +/// Delegate method will be also called on main thread. +@property(nonatomic, weak) id delegate; + +/// Pauses and resumes the display link. +@property(readwrite) BOOL paused; + +/// Returns the nominal refresh period of the display to which the view +/// currently belongs (in seconds). If view does not belong to any display, +/// returns 0. +@property(readonly) CFTimeInterval nominalOutputRefreshPeriod; + +/// Invalidates the display link. +- (void)invalidate; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERDISPLAYLINK_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterDisplayLink.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterDisplayLink.mm new file mode 100644 index 0000000000000000000000000000000000000000..0fd314ddee37ba1f6c354efb55915a773cd6b2b7 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterDisplayLink.mm @@ -0,0 +1,297 @@ +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDisplayLink.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterRunLoop.h" + +#include "flutter/fml/logging.h" + +#include +#include +#include +#include +#include + +@class _FlutterDisplayLinkView; + +@interface _FlutterDisplayLink : FlutterDisplayLink { + _FlutterDisplayLinkView* _view; + std::optional _display_id; + BOOL _paused; +} + +- (void)didFireWithTimestamp:(CFTimeInterval)timestamp + targetTimestamp:(CFTimeInterval)targetTimestamp; + +@end + +namespace { +class DisplayLinkManager { + public: + static DisplayLinkManager& Instance() { + static DisplayLinkManager instance; + return instance; + } + + void UnregisterDisplayLink(_FlutterDisplayLink* display_link); + void RegisterDisplayLink(_FlutterDisplayLink* display_link, CGDirectDisplayID display_id); + void PausedDidChange(_FlutterDisplayLink* display_link); + CFTimeInterval GetNominalOutputPeriod(CGDirectDisplayID display_id); + + private: + void OnDisplayLink(CVDisplayLinkRef display_link, + const CVTimeStamp* in_now, + const CVTimeStamp* in_output_time, + CVOptionFlags flags_in, + CVOptionFlags* flags_out); + + struct ScreenEntry { + CGDirectDisplayID display_id; + std::vector<_FlutterDisplayLink*> clients; + CVDisplayLinkRef display_link; + + bool ShouldBeRunning() { + return std::any_of(clients.begin(), clients.end(), + [](FlutterDisplayLink* link) { return !link.paused; }); + } + }; + std::vector entries_; +}; + +void RunOrStopDisplayLink(CVDisplayLinkRef display_link, bool should_be_running) { + bool is_running = CVDisplayLinkIsRunning(display_link); + if (should_be_running && !is_running) { + CVDisplayLinkStart(display_link); + } else if (!should_be_running && is_running) { + CVDisplayLinkStop(display_link); + } +} + +void DisplayLinkManager::UnregisterDisplayLink(_FlutterDisplayLink* display_link) { + FML_DCHECK(NSThread.isMainThread); + for (auto entry = entries_.begin(); entry != entries_.end(); ++entry) { + auto it = std::find(entry->clients.begin(), entry->clients.end(), display_link); + if (it != entry->clients.end()) { + entry->clients.erase(it); + if (entry->clients.empty()) { + // Erasing the entry - take the display link instance and stop / release it + // outside of the mutex. + CVDisplayLinkStop(entry->display_link); + CVDisplayLinkRelease(entry->display_link); + entries_.erase(entry); + } else { + // Update the display link state outside of the mutex. + RunOrStopDisplayLink(entry->display_link, entry->ShouldBeRunning()); + } + return; + } + } +} + +void DisplayLinkManager::RegisterDisplayLink(_FlutterDisplayLink* display_link, + CGDirectDisplayID display_id) { + FML_DCHECK(NSThread.isMainThread); + for (ScreenEntry& entry : entries_) { + if (entry.display_id == display_id) { + entry.clients.push_back(display_link); + RunOrStopDisplayLink(entry.display_link, entry.ShouldBeRunning()); + return; + } + } + + ScreenEntry entry; + entry.display_id = display_id; + entry.clients.push_back(display_link); + CVDisplayLinkCreateWithCGDisplay(display_id, &entry.display_link); + + CVDisplayLinkSetOutputHandler( + entry.display_link, + ^(CVDisplayLinkRef display_link, const CVTimeStamp* in_now, const CVTimeStamp* in_output_time, + CVOptionFlags flags_in, CVOptionFlags* flags_out) { + OnDisplayLink(display_link, in_now, in_output_time, flags_in, flags_out); + return 0; + }); + + // This is a new display link so it is safe to start it with mutex held. + RunOrStopDisplayLink(entry.display_link, entry.ShouldBeRunning()); + entries_.push_back(entry); +} + +void DisplayLinkManager::PausedDidChange(_FlutterDisplayLink* display_link) { + for (ScreenEntry& entry : entries_) { + auto it = std::find(entry.clients.begin(), entry.clients.end(), display_link); + if (it != entry.clients.end()) { + RunOrStopDisplayLink(entry.display_link, entry.ShouldBeRunning()); + return; + } + } +} + +CFTimeInterval DisplayLinkManager::GetNominalOutputPeriod(CGDirectDisplayID display_id) { + for (ScreenEntry& entry : entries_) { + if (entry.display_id == display_id) { + CVTime latency = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(entry.display_link); + return (CFTimeInterval)latency.timeValue / (CFTimeInterval)latency.timeScale; + } + } + return 0; +} + +void DisplayLinkManager::OnDisplayLink(CVDisplayLinkRef display_link, + const CVTimeStamp* in_now, + const CVTimeStamp* in_output_time, + CVOptionFlags flags_in, + CVOptionFlags* flags_out) { + CVTimeStamp inNow = *in_now; + CVTimeStamp inOutputTime = *in_output_time; + [FlutterRunLoop.mainRunLoop performBlock:^{ + std::vector<_FlutterDisplayLink*> clients; + for (ScreenEntry& entry : entries_) { + if (entry.display_link == display_link) { + clients = entry.clients; + break; + } + } + + CFTimeInterval timestamp = (CFTimeInterval)inNow.hostTime / CVGetHostClockFrequency(); + CFTimeInterval target_timestamp = + (CFTimeInterval)inOutputTime.hostTime / CVGetHostClockFrequency(); + + for (_FlutterDisplayLink* client : clients) { + [client didFireWithTimestamp:timestamp targetTimestamp:target_timestamp]; + } + }]; +} +} // namespace + +@interface _FlutterDisplayLinkView : NSView { +} + +@end + +static NSString* const kFlutterDisplayLinkViewDidMoveToWindow = + @"FlutterDisplayLinkViewDidMoveToWindow"; + +@implementation _FlutterDisplayLinkView + +- (void)viewDidMoveToWindow { + [super viewDidMoveToWindow]; + [[NSNotificationCenter defaultCenter] postNotificationName:kFlutterDisplayLinkViewDidMoveToWindow + object:self]; +} + +@end + +@implementation _FlutterDisplayLink + +@synthesize delegate = _delegate; + +- (instancetype)initWithView:(NSView*)view { + FML_DCHECK(NSThread.isMainThread); + if (self = [super init]) { + self->_view = [[_FlutterDisplayLinkView alloc] initWithFrame:CGRectZero]; + [view addSubview:self->_view]; + _paused = YES; + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(viewDidChangeWindow:) + name:kFlutterDisplayLinkViewDidMoveToWindow + object:self->_view]; + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(windowDidChangeScreen:) + name:NSWindowDidChangeScreenNotification + object:nil]; + [self updateScreen]; + } + return self; +} + +- (void)invalidate { + FML_DCHECK(NSThread.isMainThread); + // Unregister observer before removing the view to ensure + // that the viewDidChangeWindow notification is not received + // while in @synchronized block. + [[NSNotificationCenter defaultCenter] removeObserver:self]; + [_view removeFromSuperview]; + _view = nil; + _delegate = nil; + DisplayLinkManager::Instance().UnregisterDisplayLink(self); +} + +- (void)updateScreen { + FML_DCHECK(NSThread.isMainThread); + DisplayLinkManager::Instance().UnregisterDisplayLink(self); + std::optional displayId; + NSScreen* screen = _view.window.screen; + if (screen != nil) { + // https://developer.apple.com/documentation/appkit/nsscreen/1388360-devicedescription?language=objc + _display_id = (CGDirectDisplayID)[ + [[screen deviceDescription] objectForKey:@"NSScreenNumber"] unsignedIntValue]; + } else { + _display_id = std::nullopt; + } + displayId = _display_id; + + if (displayId.has_value()) { + DisplayLinkManager::Instance().RegisterDisplayLink(self, *displayId); + } +} + +- (void)viewDidChangeWindow:(NSNotification*)notification { + FML_DCHECK(NSThread.isMainThread); + NSView* view = notification.object; + if (_view == view) { + [self updateScreen]; + } +} + +- (void)windowDidChangeScreen:(NSNotification*)notification { + FML_DCHECK(NSThread.isMainThread); + NSWindow* window = notification.object; + if (_view.window == window) { + [self updateScreen]; + } +} + +- (void)didFireWithTimestamp:(CFTimeInterval)timestamp + targetTimestamp:(CFTimeInterval)targetTimestamp { + FML_DCHECK(NSThread.isMainThread); + if (!_paused) { + id delegate = _delegate; + [delegate onDisplayLink:timestamp targetTimestamp:targetTimestamp]; + } +} + +- (BOOL)paused { + FML_DCHECK(NSThread.isMainThread); + return _paused; +} + +- (void)setPaused:(BOOL)paused { + FML_DCHECK(NSThread.isMainThread); + if (_paused == paused) { + return; + } + _paused = paused; + DisplayLinkManager::Instance().PausedDidChange(self); +} + +- (CFTimeInterval)nominalOutputRefreshPeriod { + FML_DCHECK(NSThread.isMainThread); + CGDirectDisplayID display_id; + if (_display_id.has_value()) { + display_id = *_display_id; + } else { + return 0; + } + return DisplayLinkManager::Instance().GetNominalOutputPeriod(display_id); +} + +@end + +@implementation FlutterDisplayLink ++ (instancetype)displayLinkWithView:(NSView*)view { + return [[_FlutterDisplayLink alloc] initWithView:view]; +} + +- (void)invalidate { + [self doesNotRecognizeSelector:_cmd]; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterDisplayLinkTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterDisplayLinkTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..e0455ded62a9fba51d6a81860a28290f29a231d9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterDisplayLinkTest.mm @@ -0,0 +1,162 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDisplayLink.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterRunLoop.h" + +#import +#include + +#include "flutter/fml/synchronization/waitable_event.h" +#include "flutter/testing/testing.h" + +@interface TestDisplayLinkDelegate : NSObject { + void (^_block)(CFTimeInterval timestamp, CFTimeInterval targetTimestamp); +} + +- (instancetype)initWithBlock:(void (^)(CFTimeInterval timestamp, + CFTimeInterval targetTimestamp))block; + +@end + +@implementation TestDisplayLinkDelegate +- (instancetype)initWithBlock:(void (^__strong)(CFTimeInterval, CFTimeInterval))block { + if (self = [super init]) { + _block = block; + } + return self; +} + +- (void)onDisplayLink:(CFTimeInterval)timestamp targetTimestamp:(CFTimeInterval)targetTimestamp { + _block(timestamp, targetTimestamp); +} + +@end + +class FlutterDisplayLinkTest : public testing::Test { + public: + void SetUp() override { [FlutterRunLoop ensureMainLoopInitialized]; } +}; + +TEST_F(FlutterDisplayLinkTest, ViewAddedToWindowFirst) { + NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 100, 100) + styleMask:NSWindowStyleMaskTitled + backing:NSBackingStoreNonretained + defer:NO]; + NSView* view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)]; + [window setContentView:view]; + + __block BOOL signalled = NO; + + TestDisplayLinkDelegate* delegate = [[TestDisplayLinkDelegate alloc] + initWithBlock:^(CFTimeInterval timestamp, CFTimeInterval targetTimestamp) { + signalled = YES; + }]; + + FlutterDisplayLink* displayLink = [FlutterDisplayLink displayLinkWithView:view]; + displayLink.delegate = delegate; + displayLink.paused = NO; + + while (!signalled) { + [FlutterRunLoop.mainRunLoop pollFlutterMessagesOnce]; + } + + [displayLink invalidate]; +} + +TEST_F(FlutterDisplayLinkTest, ViewAddedToWindowLater) { + NSView* view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)]; + + __block BOOL signalled = NO; + + TestDisplayLinkDelegate* delegate = [[TestDisplayLinkDelegate alloc] + initWithBlock:^(CFTimeInterval timestamp, CFTimeInterval targetTimestamp) { + signalled = YES; + }]; + + FlutterDisplayLink* displayLink = [FlutterDisplayLink displayLinkWithView:view]; + displayLink.delegate = delegate; + displayLink.paused = NO; + + NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 100, 100) + styleMask:NSWindowStyleMaskTitled + backing:NSBackingStoreNonretained + defer:NO]; + [window setContentView:view]; + + while (!signalled) { + [FlutterRunLoop.mainRunLoop pollFlutterMessagesOnce]; + } + + [displayLink invalidate]; +} + +TEST_F(FlutterDisplayLinkTest, ViewRemovedFromWindow) { + NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 100, 100) + styleMask:NSWindowStyleMaskTitled + backing:NSBackingStoreNonretained + defer:NO]; + NSView* view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)]; + [window setContentView:view]; + + __block BOOL signalled = NO; + + TestDisplayLinkDelegate* delegate = [[TestDisplayLinkDelegate alloc] + initWithBlock:^(CFTimeInterval timestamp, CFTimeInterval targetTimestamp) { + signalled = YES; + }]; + + FlutterDisplayLink* displayLink = [FlutterDisplayLink displayLinkWithView:view]; + displayLink.delegate = delegate; + displayLink.paused = NO; + + while (!signalled) { + [FlutterRunLoop.mainRunLoop pollFlutterMessagesOnce]; + } + displayLink.paused = YES; + + signalled = false; + + displayLink.paused = NO; + + [window setContentView:nil]; + + CFTimeInterval start = CACurrentMediaTime(); + while (CACurrentMediaTime() < start + 0.1) { + [FlutterRunLoop.mainRunLoop pollFlutterMessagesOnce]; + } + + EXPECT_FALSE(signalled); + + [displayLink invalidate]; +} + +TEST_F(FlutterDisplayLinkTest, CVDisplayLinkInterval) { + CVDisplayLinkRef link; + CVDisplayLinkCreateWithCGDisplay(CGMainDisplayID(), &link); + __block CFTimeInterval last = 0; + auto intervals = std::make_shared>(); + auto event = std::make_shared(); + CVDisplayLinkSetOutputHandler( + link, ^(CVDisplayLinkRef displayLink, const CVTimeStamp* inNow, + const CVTimeStamp* inOutputTime, CVOptionFlags flagsIn, CVOptionFlags* flagsOut) { + if (last != 0) { + intervals->push_back(CACurrentMediaTime() - last); + } + last = CACurrentMediaTime(); + if (intervals->size() == 10) { + event->Signal(); + } + return 0; + }); + + CVDisplayLinkStart(link); + event->Wait(); + CVDisplayLinkStop(link); + CVDisplayLinkRelease(link); + CFTimeInterval average = std::reduce(intervals->begin(), intervals->end()) / intervals->size(); + CFTimeInterval max = *std::max_element(intervals->begin(), intervals->end()); + CFTimeInterval min = *std::min_element(intervals->begin(), intervals->end()); + NSLog(@"CVDisplayLink Interval: Average: %fs, Max: %fs, Min: %fs", average, max, min); +} diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEmbedderExternalTextureTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEmbedderExternalTextureTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..4159e96627856239c0e15205ad7fc7bd303ceced --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEmbedderExternalTextureTest.mm @@ -0,0 +1,608 @@ +// 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. + +#import +#import + +#include +#include + +#include "flutter/display_list/display_list.h" +#include "flutter/display_list/dl_builder.h" +#import "flutter/display_list/skia/dl_sk_canvas.h" +#include "flutter/fml/synchronization/sync_switch.h" +#include "flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalImpeller.h" +#import "flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalSkia.h" +#import "flutter/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterExternalTexture.h" +#include "flutter/shell/platform/embedder/embedder.h" +#include "flutter/shell/platform/embedder/embedder_external_texture_metal.h" +#include "flutter/testing/autoreleasepool_test.h" +#include "flutter/testing/testing.h" +#include "impeller/display_list/aiks_context.h" // nogncheck +#include "impeller/entity/mtl/entity_shaders.h" // nogncheck +#include "impeller/entity/mtl/framebuffer_blend_shaders.h" // nogncheck +#include "impeller/entity/mtl/modern_shaders.h" // nogncheck +#include "impeller/renderer/backend/metal/context_mtl.h" // nogncheck +#include "third_party/googletest/googletest/include/gtest/gtest.h" +#include "third_party/skia/include/core/SkImage.h" +#include "third_party/skia/include/core/SkSamplingOptions.h" +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" + +static std::shared_ptr CreateImpellerContext() { + std::vector> shader_mappings = { + std::make_shared(impeller_entity_shaders_data, + impeller_entity_shaders_length), + std::make_shared(impeller_modern_shaders_data, + impeller_modern_shaders_length), + std::make_shared(impeller_framebuffer_blend_shaders_data, + impeller_framebuffer_blend_shaders_length), + }; + auto sync_switch = std::make_shared(false); + return impeller::ContextMTL::Create(impeller::Flags{}, shader_mappings, sync_switch, + "Impeller Library"); +} + +@interface TestExternalTexture : NSObject + +- (nonnull instancetype)initWidth:(size_t)width + height:(size_t)height + pixelFormatType:(OSType)pixelFormatType; + +@end + +@implementation TestExternalTexture { + size_t _width; + size_t _height; + OSType _pixelFormatType; +} + +- (nonnull instancetype)initWidth:(size_t)width + height:(size_t)height + pixelFormatType:(OSType)pixelFormatType { + if (self = [super init]) { + _width = width; + _height = height; + _pixelFormatType = pixelFormatType; + } + return self; +} + +- (CVPixelBufferRef)copyPixelBuffer { + return [self pixelBuffer]; +} + +- (CVPixelBufferRef)pixelBuffer { + NSDictionary* options = @{ + // This key is required to generate SKPicture with CVPixelBufferRef in metal. + (NSString*)kCVPixelBufferMetalCompatibilityKey : @YES + }; + CVPixelBufferRef pxbuffer = NULL; + CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault, _width, _width, _pixelFormatType, + (__bridge CFDictionaryRef)options, &pxbuffer); + FML_CHECK(status == kCVReturnSuccess && pxbuffer != nullptr) << "Failed to create pixel buffer"; + return pxbuffer; +} + +@end + +namespace flutter::testing { + +// Test-specific name for AutoreleasePoolTest fixture. +using FlutterEmbedderExternalTextureTest = AutoreleasePoolTest; + +TEST_F(FlutterEmbedderExternalTextureTest, TestTextureResolution) { + // Constants. + const size_t width = 100; + const size_t height = 100; + const int64_t texture_id = 1; + + // Set up the surface. + FlutterDarwinContextMetalSkia* darwinContextMetal = + [[FlutterDarwinContextMetalSkia alloc] initWithDefaultMTLDevice]; + SkImageInfo info = SkImageInfo::MakeN32Premul(width, height); + GrDirectContext* grContext = darwinContextMetal.mainContext.get(); + sk_sp gpuSurface(SkSurfaces::RenderTarget(grContext, skgpu::Budgeted::kNo, info)); + + // Create a texture. + MTLTextureDescriptor* textureDescriptor = [[MTLTextureDescriptor alloc] init]; + textureDescriptor.pixelFormat = MTLPixelFormatBGRA8Unorm; + textureDescriptor.width = width; + textureDescriptor.height = height; + textureDescriptor.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead; + id mtlTexture = + [darwinContextMetal.device newTextureWithDescriptor:textureDescriptor]; + std::vector textures = { + (__bridge FlutterMetalTextureHandle)mtlTexture, + }; + + // Callback to resolve the texture. + EmbedderExternalTextureMetal::ExternalTextureCallback callback = [&](int64_t texture_id, size_t w, + size_t h) { + EXPECT_TRUE(w == width); + EXPECT_TRUE(h == height); + + auto texture = std::make_unique(); + texture->struct_size = sizeof(FlutterMetalExternalTexture); + texture->num_textures = 1; + texture->height = h; + texture->width = w; + texture->pixel_format = FlutterMetalExternalTexturePixelFormat::kRGBA; + texture->textures = textures.data(); + return texture; + }; + + // Render the texture. + std::unique_ptr texture = + std::make_unique(texture_id, callback); + DlRect bounds = DlRect::MakeWH(info.width(), info.height()); + DlImageSampling sampling = DlImageSampling::kNearestNeighbor; + DlSkCanvasAdapter canvas(gpuSurface->getCanvas()); + flutter::Texture::PaintContext context{ + .canvas = &canvas, + .gr_context = grContext, + }; + texture->Paint(context, bounds, /*freeze=*/false, sampling); + + ASSERT_TRUE(mtlTexture != nil); + + gpuSurface->makeImageSnapshot(); +} + +TEST_F(FlutterEmbedderExternalTextureTest, TestPopulateExternalTexture) { + // Constants. + const size_t width = 100; + const size_t height = 100; + const int64_t texture_id = 1; + + // Set up the surface. + FlutterDarwinContextMetalSkia* darwinContextMetal = + [[FlutterDarwinContextMetalSkia alloc] initWithDefaultMTLDevice]; + SkImageInfo info = SkImageInfo::MakeN32Premul(width, height); + GrDirectContext* grContext = darwinContextMetal.mainContext.get(); + sk_sp gpuSurface(SkSurfaces::RenderTarget(grContext, skgpu::Budgeted::kNo, info)); + + // Create a texture. + TestExternalTexture* testExternalTexture = + [[TestExternalTexture alloc] initWidth:width + height:height + pixelFormatType:kCVPixelFormatType_32BGRA]; + FlutterExternalTexture* textureHolder = + [[FlutterExternalTexture alloc] initWithFlutterTexture:testExternalTexture + darwinMetalContext:darwinContextMetal]; + + // Callback to resolve the texture. + EmbedderExternalTextureMetal::ExternalTextureCallback callback = [&](int64_t texture_id, size_t w, + size_t h) { + EXPECT_TRUE(w == width); + EXPECT_TRUE(h == height); + + auto texture = std::make_unique(); + [textureHolder populateTexture:texture.get()]; + + EXPECT_TRUE(texture->num_textures == 1); + EXPECT_TRUE(texture->textures != nullptr); + EXPECT_TRUE(texture->pixel_format == FlutterMetalExternalTexturePixelFormat::kRGBA); + return texture; + }; + + // Render the texture. + std::unique_ptr texture = + std::make_unique(texture_id, callback); + DlRect bounds = DlRect::MakeWH(info.width(), info.height()); + DlImageSampling sampling = DlImageSampling::kNearestNeighbor; + DlSkCanvasAdapter canvas(gpuSurface->getCanvas()); + flutter::Texture::PaintContext context{ + .canvas = &canvas, + .gr_context = grContext, + }; + texture->Paint(context, bounds, /*freeze=*/false, sampling); + + gpuSurface->makeImageSnapshot(); +} + +TEST_F(FlutterEmbedderExternalTextureTest, TestPopulateExternalTextureYUVA) { + // Constants. + const size_t width = 100; + const size_t height = 100; + const int64_t texture_id = 1; + + // Set up the surface. + FlutterDarwinContextMetalSkia* darwinContextMetal = + [[FlutterDarwinContextMetalSkia alloc] initWithDefaultMTLDevice]; + SkImageInfo info = SkImageInfo::MakeN32Premul(width, height); + GrDirectContext* grContext = darwinContextMetal.mainContext.get(); + sk_sp gpuSurface(SkSurfaces::RenderTarget(grContext, skgpu::Budgeted::kNo, info)); + + // Create a texture. + TestExternalTexture* testExternalTexture = + [[TestExternalTexture alloc] initWidth:width + height:height + pixelFormatType:kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange]; + FlutterExternalTexture* textureHolder = + [[FlutterExternalTexture alloc] initWithFlutterTexture:testExternalTexture + darwinMetalContext:darwinContextMetal]; + + // Callback to resolve the texture. + EmbedderExternalTextureMetal::ExternalTextureCallback callback = [&](int64_t texture_id, size_t w, + size_t h) { + EXPECT_TRUE(w == width); + EXPECT_TRUE(h == height); + + auto texture = std::make_unique(); + [textureHolder populateTexture:texture.get()]; + + EXPECT_TRUE(texture->num_textures == 2); + EXPECT_TRUE(texture->textures != nullptr); + EXPECT_TRUE(texture->pixel_format == FlutterMetalExternalTexturePixelFormat::kYUVA); + EXPECT_TRUE(texture->yuv_color_space == + FlutterMetalExternalTextureYUVColorSpace::kBT601LimitedRange); + return texture; + }; + + // Render the texture. + std::unique_ptr texture = + std::make_unique(texture_id, callback); + DlRect bounds = DlRect::MakeWH(info.width(), info.height()); + DlImageSampling sampling = DlImageSampling::kNearestNeighbor; + DlSkCanvasAdapter canvas(gpuSurface->getCanvas()); + flutter::Texture::PaintContext context{ + .canvas = &canvas, + .gr_context = grContext, + }; + texture->Paint(context, bounds, /*freeze=*/false, sampling); + + gpuSurface->makeImageSnapshot(); +} + +TEST_F(FlutterEmbedderExternalTextureTest, TestPopulateExternalTextureYUVA2) { + // Constants. + const size_t width = 100; + const size_t height = 100; + const int64_t texture_id = 1; + + // Set up the surface. + FlutterDarwinContextMetalSkia* darwinContextMetal = + [[FlutterDarwinContextMetalSkia alloc] initWithDefaultMTLDevice]; + SkImageInfo info = SkImageInfo::MakeN32Premul(width, height); + GrDirectContext* grContext = darwinContextMetal.mainContext.get(); + sk_sp gpuSurface(SkSurfaces::RenderTarget(grContext, skgpu::Budgeted::kNo, info)); + + // Create a texture. + TestExternalTexture* testExternalTexture = + [[TestExternalTexture alloc] initWidth:width + height:height + pixelFormatType:kCVPixelFormatType_420YpCbCr8BiPlanarFullRange]; + FlutterExternalTexture* textureHolder = + [[FlutterExternalTexture alloc] initWithFlutterTexture:testExternalTexture + darwinMetalContext:darwinContextMetal]; + + // Callback to resolve the texture. + EmbedderExternalTextureMetal::ExternalTextureCallback callback = [&](int64_t texture_id, size_t w, + size_t h) { + EXPECT_TRUE(w == width); + EXPECT_TRUE(h == height); + + auto texture = std::make_unique(); + [textureHolder populateTexture:texture.get()]; + + EXPECT_TRUE(texture->num_textures == 2); + EXPECT_TRUE(texture->textures != nullptr); + EXPECT_TRUE(texture->pixel_format == FlutterMetalExternalTexturePixelFormat::kYUVA); + EXPECT_TRUE(texture->yuv_color_space == + FlutterMetalExternalTextureYUVColorSpace::kBT601FullRange); + return texture; + }; + + // Render the texture. + std::unique_ptr texture = + std::make_unique(texture_id, callback); + DlRect bounds = DlRect::MakeWH(info.width(), info.height()); + DlImageSampling sampling = DlImageSampling::kNearestNeighbor; + DlSkCanvasAdapter canvas(gpuSurface->getCanvas()); + flutter::Texture::PaintContext context{ + .canvas = &canvas, + .gr_context = grContext, + }; + texture->Paint(context, bounds, /*freeze=*/false, sampling); + + gpuSurface->makeImageSnapshot(); +} + +TEST_F(FlutterEmbedderExternalTextureTest, TestPopulateUnsupportedExternalTexture) { + // Constants. + const size_t width = 100; + const size_t height = 100; + const int64_t texture_id = 1; + + // Set up the surface. + FlutterDarwinContextMetalSkia* darwinContextMetal = + [[FlutterDarwinContextMetalSkia alloc] initWithDefaultMTLDevice]; + SkImageInfo info = SkImageInfo::MakeN32Premul(width, height); + GrDirectContext* grContext = darwinContextMetal.mainContext.get(); + sk_sp gpuSurface(SkSurfaces::RenderTarget(grContext, skgpu::Budgeted::kNo, info)); + + // Create a texture. + TestExternalTexture* testExternalTexture = + [[TestExternalTexture alloc] initWidth:width + height:height + pixelFormatType:kCVPixelFormatType_420YpCbCr8PlanarFullRange]; + FlutterExternalTexture* textureHolder = + [[FlutterExternalTexture alloc] initWithFlutterTexture:testExternalTexture + darwinMetalContext:darwinContextMetal]; + + // Callback to resolve the texture. + EmbedderExternalTextureMetal::ExternalTextureCallback callback = [&](int64_t texture_id, size_t w, + size_t h) { + EXPECT_TRUE(w == width); + EXPECT_TRUE(h == height); + + auto texture = std::make_unique(); + EXPECT_FALSE([textureHolder populateTexture:texture.get()]); + return nullptr; + }; + + // Render the texture. + std::unique_ptr texture = + std::make_unique(texture_id, callback); + DlRect bounds = DlRect::MakeWH(info.width(), info.height()); + DlImageSampling sampling = DlImageSampling::kNearestNeighbor; + DlSkCanvasAdapter canvas(gpuSurface->getCanvas()); + flutter::Texture::PaintContext context{ + .canvas = &canvas, + .gr_context = grContext, + }; + texture->Paint(context, bounds, /*freeze=*/false, sampling); +} + +TEST_F(FlutterEmbedderExternalTextureTest, TestTextureResolutionImpeller) { + // Constants. + const size_t width = 100; + const size_t height = 100; + const int64_t texture_id = 1; + + // Set up the surface. + auto device = ::MTLCreateSystemDefaultDevice(); + impeller::AiksContext aiks_context(CreateImpellerContext(), nullptr); + + SkImageInfo info = SkImageInfo::MakeN32Premul(width, height); + + // Create a texture. + MTLTextureDescriptor* textureDescriptor = [[MTLTextureDescriptor alloc] init]; + textureDescriptor.pixelFormat = MTLPixelFormatBGRA8Unorm; + textureDescriptor.width = width; + textureDescriptor.height = height; + textureDescriptor.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead; + id mtlTexture = [device newTextureWithDescriptor:textureDescriptor]; + std::vector textures = { + (__bridge FlutterMetalTextureHandle)mtlTexture, + }; + + // Callback to resolve the texture. + EmbedderExternalTextureMetal::ExternalTextureCallback callback = [&](int64_t texture_id, size_t w, + size_t h) { + EXPECT_TRUE(w == width); + EXPECT_TRUE(h == height); + + auto texture = std::make_unique(); + texture->struct_size = sizeof(FlutterMetalExternalTexture); + texture->num_textures = 1; + texture->height = h; + texture->width = w; + texture->pixel_format = FlutterMetalExternalTexturePixelFormat::kRGBA; + texture->textures = textures.data(); + return texture; + }; + + // Render the texture. + std::unique_ptr texture = + std::make_unique(texture_id, callback); + DlRect bounds = DlRect::MakeWH(info.width(), info.height()); + DlImageSampling sampling = DlImageSampling::kNearestNeighbor; + + DisplayListBuilder builder; + flutter::Texture::PaintContext context{ + .canvas = &builder, .gr_context = nullptr, .aiks_context = &aiks_context}; + texture->Paint(context, bounds, /*freeze=*/false, sampling); + + ASSERT_TRUE(mtlTexture != nil); +} + +TEST_F(FlutterEmbedderExternalTextureTest, TestPopulateExternalTextureImpeller) { + // Constants. + const size_t width = 100; + const size_t height = 100; + const int64_t texture_id = 1; + + // Set up the surface. + FlutterDarwinContextMetalSkia* darwinContextMetal = + [[FlutterDarwinContextMetalSkia alloc] initWithDefaultMTLDevice]; + impeller::AiksContext aiks_context(CreateImpellerContext(), nullptr); + SkImageInfo info = SkImageInfo::MakeN32Premul(width, height); + + // Create a texture. + TestExternalTexture* testExternalTexture = + [[TestExternalTexture alloc] initWidth:width + height:height + pixelFormatType:kCVPixelFormatType_32BGRA]; + FlutterExternalTexture* textureHolder = + [[FlutterExternalTexture alloc] initWithFlutterTexture:testExternalTexture + darwinMetalContext:darwinContextMetal]; + + // Callback to resolve the texture. + EmbedderExternalTextureMetal::ExternalTextureCallback callback = [&](int64_t texture_id, size_t w, + size_t h) { + EXPECT_TRUE(w == width); + EXPECT_TRUE(h == height); + + auto texture = std::make_unique(); + [textureHolder populateTexture:texture.get()]; + + EXPECT_TRUE(texture->num_textures == 1); + EXPECT_TRUE(texture->textures != nullptr); + EXPECT_TRUE(texture->pixel_format == FlutterMetalExternalTexturePixelFormat::kRGBA); + return texture; + }; + + // Render the texture. + std::unique_ptr texture = + std::make_unique(texture_id, callback); + DlRect bounds = DlRect::MakeWH(info.width(), info.height()); + DlImageSampling sampling = DlImageSampling::kNearestNeighbor; + + DisplayListBuilder builder; + flutter::Texture::PaintContext context{ + .canvas = &builder, + .gr_context = nullptr, + .aiks_context = &aiks_context, + }; + texture->Paint(context, bounds, /*freeze=*/false, sampling); +} + +TEST_F(FlutterEmbedderExternalTextureTest, TestPopulateExternalTextureYUVAImpeller) { + // Constants. + const size_t width = 100; + const size_t height = 100; + const int64_t texture_id = 1; + + // Set up the surface. + FlutterDarwinContextMetalSkia* darwinContextMetal = + [[FlutterDarwinContextMetalSkia alloc] initWithDefaultMTLDevice]; + impeller::AiksContext aiks_context(CreateImpellerContext(), nullptr); + SkImageInfo info = SkImageInfo::MakeN32Premul(width, height); + + // Create a texture. + TestExternalTexture* testExternalTexture = + [[TestExternalTexture alloc] initWidth:width + height:height + pixelFormatType:kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange]; + FlutterExternalTexture* textureHolder = + [[FlutterExternalTexture alloc] initWithFlutterTexture:testExternalTexture + darwinMetalContext:darwinContextMetal]; + + // Callback to resolve the texture. + EmbedderExternalTextureMetal::ExternalTextureCallback callback = [&](int64_t texture_id, size_t w, + size_t h) { + EXPECT_TRUE(w == width); + EXPECT_TRUE(h == height); + + auto texture = std::make_unique(); + [textureHolder populateTexture:texture.get()]; + + EXPECT_TRUE(texture->num_textures == 2); + EXPECT_TRUE(texture->textures != nullptr); + EXPECT_TRUE(texture->pixel_format == FlutterMetalExternalTexturePixelFormat::kYUVA); + EXPECT_TRUE(texture->yuv_color_space == + FlutterMetalExternalTextureYUVColorSpace::kBT601LimitedRange); + return texture; + }; + + // Render the texture. + std::unique_ptr texture = + std::make_unique(texture_id, callback); + DlRect bounds = DlRect::MakeWH(info.width(), info.height()); + DlImageSampling sampling = DlImageSampling::kNearestNeighbor; + + DisplayListBuilder builder; + flutter::Texture::PaintContext context{ + .canvas = &builder, .gr_context = nullptr, .aiks_context = &aiks_context}; + texture->Paint(context, bounds, /*freeze=*/false, sampling); +} + +TEST_F(FlutterEmbedderExternalTextureTest, TestPopulateExternalTextureYUVA2Impeller) { + // Constants. + const size_t width = 100; + const size_t height = 100; + const int64_t texture_id = 1; + + // Set up the surface. + FlutterDarwinContextMetalSkia* darwinContextMetal = + [[FlutterDarwinContextMetalSkia alloc] initWithDefaultMTLDevice]; + impeller::AiksContext aiks_context(CreateImpellerContext(), nullptr); + SkImageInfo info = SkImageInfo::MakeN32Premul(width, height); + + // Create a texture. + TestExternalTexture* testExternalTexture = + [[TestExternalTexture alloc] initWidth:width + height:height + pixelFormatType:kCVPixelFormatType_420YpCbCr8BiPlanarFullRange]; + FlutterExternalTexture* textureHolder = + [[FlutterExternalTexture alloc] initWithFlutterTexture:testExternalTexture + darwinMetalContext:darwinContextMetal]; + + // Callback to resolve the texture. + EmbedderExternalTextureMetal::ExternalTextureCallback callback = [&](int64_t texture_id, size_t w, + size_t h) { + EXPECT_TRUE(w == width); + EXPECT_TRUE(h == height); + + auto texture = std::make_unique(); + [textureHolder populateTexture:texture.get()]; + + EXPECT_TRUE(texture->num_textures == 2); + EXPECT_TRUE(texture->textures != nullptr); + EXPECT_TRUE(texture->pixel_format == FlutterMetalExternalTexturePixelFormat::kYUVA); + EXPECT_TRUE(texture->yuv_color_space == + FlutterMetalExternalTextureYUVColorSpace::kBT601FullRange); + return texture; + }; + + // Render the texture. + std::unique_ptr texture = + std::make_unique(texture_id, callback); + DlRect bounds = DlRect::MakeWH(info.width(), info.height()); + DlImageSampling sampling = DlImageSampling::kNearestNeighbor; + + DisplayListBuilder builder; + flutter::Texture::PaintContext context{ + .canvas = &builder, .gr_context = nullptr, .aiks_context = &aiks_context}; + texture->Paint(context, bounds, /*freeze=*/false, sampling); +} + +TEST_F(FlutterEmbedderExternalTextureTest, TestPopulateUnsupportedExternalTextureImpeller) { + // Constants. + const size_t width = 100; + const size_t height = 100; + const int64_t texture_id = 1; + + // Set up the surface. + FlutterDarwinContextMetalSkia* darwinContextMetal = + [[FlutterDarwinContextMetalSkia alloc] initWithDefaultMTLDevice]; + impeller::AiksContext aiks_context(CreateImpellerContext(), nullptr); + SkImageInfo info = SkImageInfo::MakeN32Premul(width, height); + + // Create a texture. + TestExternalTexture* testExternalTexture = + [[TestExternalTexture alloc] initWidth:width + height:height + pixelFormatType:kCVPixelFormatType_420YpCbCr8PlanarFullRange]; + FlutterExternalTexture* textureHolder = + [[FlutterExternalTexture alloc] initWithFlutterTexture:testExternalTexture + darwinMetalContext:darwinContextMetal]; + + // Callback to resolve the texture. + EmbedderExternalTextureMetal::ExternalTextureCallback callback = [&](int64_t texture_id, size_t w, + size_t h) { + EXPECT_TRUE(w == width); + EXPECT_TRUE(h == height); + + auto texture = std::make_unique(); + EXPECT_FALSE([textureHolder populateTexture:texture.get()]); + return nullptr; + }; + + // Render the texture. + std::unique_ptr texture = + std::make_unique(texture_id, callback); + DlRect bounds = DlRect::MakeWH(info.width(), info.height()); + DlImageSampling sampling = DlImageSampling::kNearestNeighbor; + + DisplayListBuilder builder; + flutter::Texture::PaintContext context{ + .canvas = &builder, .gr_context = nullptr, .aiks_context = &aiks_context}; + texture->Paint(context, bounds, /*freeze=*/false, sampling); +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEmbedderKeyResponder.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEmbedderKeyResponder.h new file mode 100644 index 0000000000000000000000000000000000000000..8600780d675a5e8c17113728432dca15fcec25a1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEmbedderKeyResponder.h @@ -0,0 +1,51 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTEREMBEDDERKEYRESPONDER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTEREMBEDDERKEYRESPONDER_H_ + +#import + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyPrimaryResponder.h" +#include "flutter/shell/platform/embedder/embedder.h" + +typedef void (^FlutterSendEmbedderKeyEvent)(const FlutterKeyEvent& /* event */, + _Nullable FlutterKeyEventCallback /* callback */, + void* _Nullable /* user_data */); + +/** + * A primary responder of |FlutterKeyboardManager| that handles events by + * sending the converted events through the embedder API. + * + * This class communicates with the HardwareKeyboard API in the framework. + */ +@interface FlutterEmbedderKeyResponder : NSObject + +/** + * Create an instance by specifying the function to send converted events to. + * + * The |sendEvent| is typically |FlutterEngine|'s |sendKeyEvent|. + */ +- (nonnull instancetype)initWithSendEvent:(_Nonnull FlutterSendEmbedderKeyEvent)sendEvent; + +/** + * Synthesize modifier keys events. + * + * If needed, synthesize modifier keys up and down events by comparing their + * current pressing states with the given modifier flags. + */ +- (void)syncModifiersIfNeeded:(NSEventModifierFlags)modifierFlags + timestamp:(NSTimeInterval)timestamp; + +/** + * Returns the keyboard pressed state. + * + * Returns the keyboard pressed state. The dictionary contains one entry per + * pressed keys, mapping from the logical key to the physical key. + */ +- (nonnull NSDictionary*)getPressedState; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTEREMBEDDERKEYRESPONDER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEmbedderKeyResponder.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEmbedderKeyResponder.mm new file mode 100644 index 0000000000000000000000000000000000000000..f3c0106e24d02d7e666af1a9f722e6dd31884201 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEmbedderKeyResponder.mm @@ -0,0 +1,810 @@ +// 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. + +#import +#include + +#import "FlutterEmbedderKeyResponder.h" +#import "KeyCodeMap_Internal.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" +#import "flutter/shell/platform/embedder/embedder.h" + +namespace { + +/** + * Isolate the least significant 1-bit. + * + * For example, + * + * * lowestSetBit(0x1010) returns 0x10. + * * lowestSetBit(0) returns 0. + */ +static NSUInteger lowestSetBit(NSUInteger bitmask) { + // This utilizes property of two's complement (negation), which propagates a + // carry bit from LSB to the lowest set bit. + return bitmask & -bitmask; +} + +/** + * Whether a string represents a control character. + */ +static bool IsControlCharacter(uint64_t character) { + return (character <= 0x1f && character >= 0x00) || (character >= 0x7f && character <= 0x9f); +} + +/** + * Whether a string represents an unprintable key. + */ +static bool IsUnprintableKey(uint64_t character) { + return character >= 0xF700 && character <= 0xF8FF; +} + +/** + * Returns a key code composed with a base key and a plane. + * + * Examples of unprintable keys are "NSUpArrowFunctionKey = 0xF700" or + * "NSHomeFunctionKey = 0xF729". + * + * See + * https://developer.apple.com/documentation/appkit/1535851-function-key_unicodes?language=objc + * for more information. + */ +static uint64_t KeyOfPlane(uint64_t baseKey, uint64_t plane) { + return plane | (baseKey & flutter::kValueMask); +} + +/** + * Returns the physical key for a key code. + */ +static uint64_t GetPhysicalKeyForKeyCode(unsigned short keyCode) { + NSNumber* physicalKey = [flutter::keyCodeToPhysicalKey objectForKey:@(keyCode)]; + if (physicalKey == nil) { + return KeyOfPlane(keyCode, flutter::kMacosPlane); + } + return physicalKey.unsignedLongLongValue; +} + +/** + * Returns the logical key for a modifier physical key. + */ +static uint64_t GetLogicalKeyForModifier(unsigned short keyCode, uint64_t hidCode) { + NSNumber* fromKeyCode = [flutter::keyCodeToLogicalKey objectForKey:@(keyCode)]; + if (fromKeyCode != nil) { + return fromKeyCode.unsignedLongLongValue; + } + return KeyOfPlane(hidCode, flutter::kMacosPlane); +} + +/** + * Converts upper letters to lower letters in ASCII, and returns as-is + * otherwise. + * + * Independent of locale. + */ +static uint64_t toLower(uint64_t n) { + constexpr uint64_t lowerA = 0x61; + constexpr uint64_t upperA = 0x41; + constexpr uint64_t upperZ = 0x5a; + + constexpr uint64_t lowerAGrave = 0xe0; + constexpr uint64_t upperAGrave = 0xc0; + constexpr uint64_t upperThorn = 0xde; + constexpr uint64_t division = 0xf7; + + // ASCII range. + if (n >= upperA && n <= upperZ) { + return n - upperA + lowerA; + } + + // EASCII range. + if (n >= upperAGrave && n <= upperThorn && n != division) { + return n - upperAGrave + lowerAGrave; + } + + return n; +} + +// Decode a UTF-16 sequence to an array of char32 (UTF-32). +// +// See https://en.wikipedia.org/wiki/UTF-16#Description for the algorithm. +// +// The returned character array must be deallocated with delete[]. The length of +// the result is stored in `out_length`. +// +// Although NSString has a dataUsingEncoding method, we implement our own +// because dataUsingEncoding outputs redundant characters for unknown reasons. +static uint32_t* DecodeUtf16(NSString* target, size_t* out_length) { + // The result always has a length less or equal to target. + size_t result_pos = 0; + uint32_t* result = new uint32_t[target.length]; + uint16_t high_surrogate = 0; + for (NSUInteger target_pos = 0; target_pos < target.length; target_pos += 1) { + uint16_t codeUnit = [target characterAtIndex:target_pos]; + // BMP + if (codeUnit <= 0xD7FF || codeUnit >= 0xE000) { + result[result_pos] = codeUnit; + result_pos += 1; + // High surrogates + } else if (codeUnit <= 0xDBFF) { + high_surrogate = codeUnit - 0xD800; + // Low surrogates + } else { + uint16_t low_surrogate = codeUnit - 0xDC00; + result[result_pos] = (high_surrogate << 10) + low_surrogate + 0x10000; + result_pos += 1; + } + } + *out_length = result_pos; + return result; +} + +/** + * Returns the logical key of a KeyUp or KeyDown event. + * + * For FlagsChanged event, use GetLogicalKeyForModifier. + */ +static uint64_t GetLogicalKeyForEvent(NSEvent* event, uint64_t physicalKey) { + // Look to see if the keyCode can be mapped from keycode. + NSNumber* fromKeyCode = [flutter::keyCodeToLogicalKey objectForKey:@(event.keyCode)]; + if (fromKeyCode != nil) { + return fromKeyCode.unsignedLongLongValue; + } + + // Convert `charactersIgnoringModifiers` to UTF32. + NSString* keyLabelUtf16 = event.charactersIgnoringModifiers; + + // Check if this key is a single character, which will be used to generate the + // logical key from its Unicode value. + // + // Multi-char keys will be minted onto the macOS plane because there are no + // meaningful values for them. Control keys and unprintable keys have been + // converted by `keyCodeToLogicalKey` earlier. + uint32_t character = 0; + if (keyLabelUtf16.length != 0) { + size_t keyLabelLength; + uint32_t* keyLabel = DecodeUtf16(keyLabelUtf16, &keyLabelLength); + if (keyLabelLength == 1) { + uint32_t keyLabelChar = *keyLabel; + FML_DCHECK(!IsControlCharacter(keyLabelChar) && !IsUnprintableKey(keyLabelChar)) + << "Unexpected control or unprintable keylabel 0x" << std::hex << keyLabelChar; + FML_DCHECK(keyLabelChar <= 0x10FFFF) + << "Out of range keylabel 0x" << std::hex << keyLabelChar; + character = keyLabelChar; + } + delete[] keyLabel; + } + if (character != 0) { + return KeyOfPlane(toLower(character), flutter::kUnicodePlane); + } + + // We can't represent this key with a single printable unicode, so a new code + // is minted to the macOS plane. + return KeyOfPlane(event.keyCode, flutter::kMacosPlane); +} + +/** + * Converts NSEvent.timestamp to the timestamp for Flutter. + */ +static double GetFlutterTimestampFrom(NSTimeInterval timestamp) { + // Timestamp in microseconds. The event.timestamp is in seconds with sub-ms precision. + return timestamp * 1000000.0; +} + +/** + * Compute |modifierFlagOfInterestMask| out of |keyCodeToModifierFlag|. + * + * This is equal to the bitwise-or of all values of |keyCodeToModifierFlag| as + * well as NSEventModifierFlagCapsLock. + */ +static NSUInteger computeModifierFlagOfInterestMask() { + __block NSUInteger modifierFlagOfInterestMask = NSEventModifierFlagCapsLock; + [flutter::keyCodeToModifierFlag + enumerateKeysAndObjectsUsingBlock:^(NSNumber* keyCode, NSNumber* flag, BOOL* stop) { + modifierFlagOfInterestMask = modifierFlagOfInterestMask | [flag unsignedLongValue]; + }]; + return modifierFlagOfInterestMask; +} + +/** + * The C-function sent to the embedder's |SendKeyEvent|, wrapping + * |FlutterEmbedderKeyResponder.handleResponse|. + * + * For the reason of this wrap, see |FlutterKeyPendingResponse|. + */ +void HandleResponse(bool handled, void* user_data); + +/** + * Converts NSEvent.characters to a C-string for FlutterKeyEvent. + */ +const char* getEventString(NSString* characters) { + if ([characters length] == 0) { + return nullptr; + } + unichar utf16Code = [characters characterAtIndex:0]; + if (utf16Code >= 0xf700 && utf16Code <= 0xf7ff) { + // Some function keys are assigned characters with codepoints from the + // private use area. These characters are filtered out since they're + // unprintable. + // + // The official documentation reserves 0xF700-0xF8FF as private use area + // (https://developer.apple.com/documentation/appkit/1535851-function-key_unicodes?language=objc). + // But macOS seems to only use a reduced range of it. The official doc + // defines a few constants, all of which are within 0xF700-0xF747. + // (https://developer.apple.com/documentation/appkit/1535851-function-key_unicodes?language=objc). + // This mostly aligns with the experimentation result, except for 0xF8FF, + // which is used for the "Apple logo" character (Option-Shift-K on a US + // keyboard.) + // + // Assume that non-printable function keys are defined from + // 0xF700 upwards, and printable private keys are defined from 0xF8FF + // downwards. This function filters out 0xF700-0xF7FF in order to keep + // the printable private keys. + return nullptr; + } + return [characters UTF8String]; +} +} // namespace + +/** + * The invocation context for |HandleResponse|, wrapping + * |FlutterEmbedderKeyResponder.handleResponse|. + */ +struct FlutterKeyPendingResponse { + FlutterEmbedderKeyResponder* responder; + uint64_t responseId; +}; + +/** + * Guards a |FlutterAsyncKeyCallback| to make sure it's handled exactly once + * throughout |FlutterEmbedderKeyResponder.handleEvent|. + * + * A callback can either be handled with |pendTo:withId:|, or with |resolveTo:|. + * Either way, the callback cannot be handled again, or an assertion will be + * thrown. + */ +@interface FlutterKeyCallbackGuard : NSObject +- (nonnull instancetype)initWithCallback:(FlutterAsyncKeyCallback)callback; + +/** + * Handle the callback by storing it to pending responses. + */ +- (void)pendTo:(nonnull NSMutableDictionary*)pendingResponses + withId:(uint64_t)responseId; + +/** + * Handle the callback by calling it with a result. + */ +- (void)resolveTo:(BOOL)handled; + +@property(nonatomic) BOOL handled; +@property(nonatomic) BOOL sentAnyEvents; +/** + * A string indicating how the callback is handled. + * + * Only set in debug mode. Nil in release mode, or if the callback has not been + * handled. + */ +@property(nonatomic, copy) NSString* debugHandleSource; +@end + +@implementation FlutterKeyCallbackGuard { + // The callback is declared in the implemnetation block to avoid being + // accessed directly. + FlutterAsyncKeyCallback _callback; +} +- (nonnull instancetype)initWithCallback:(FlutterAsyncKeyCallback)callback { + self = [super init]; + if (self != nil) { + _callback = callback; + _handled = FALSE; + _sentAnyEvents = FALSE; + } + return self; +} + +- (void)pendTo:(nonnull NSMutableDictionary*)pendingResponses + withId:(uint64_t)responseId { + NSAssert(!_handled, @"This callback has been handled by %@.", _debugHandleSource); + if (_handled) { + return; + } + pendingResponses[@(responseId)] = _callback; + _handled = TRUE; + NSAssert( + ((_debugHandleSource = [NSString stringWithFormat:@"pending event %llu", responseId]), TRUE), + @""); +} + +- (void)resolveTo:(BOOL)handled { + NSAssert(!_handled, @"This callback has been handled by %@.", _debugHandleSource); + if (_handled) { + return; + } + _callback(handled); + _handled = TRUE; + NSAssert(((_debugHandleSource = [NSString stringWithFormat:@"resolved with %d", _handled]), TRUE), + @""); +} +@end + +@interface FlutterEmbedderKeyResponder () + +/** + * The function to send converted events to. + * + * Set by the initializer. + */ +@property(nonatomic, copy) FlutterSendEmbedderKeyEvent sendEvent; + +/** + * A map of presessd keys. + * + * The keys of the dictionary are physical keys, while the values are the logical keys + * of the key down event. + */ +@property(nonatomic) NSMutableDictionary* pressingRecords; + +/** + * A constant mask for NSEvent.modifierFlags that Flutter synchronizes with. + * + * Flutter keeps track of the last |modifierFlags| and compares it with the + * incoming one. Any bit within |modifierFlagOfInterestMask| that is different + * (except for the one that corresponds to the event key) indicates that an + * event for this modifier was missed, and Flutter synthesizes an event to make + * up for the state difference. + * + * It is computed by computeModifierFlagOfInterestMask. + */ +@property(nonatomic) NSUInteger modifierFlagOfInterestMask; + +/** + * The modifier flags of the last received key event, excluding uninterested + * bits. + * + * This should be kept synchronized with the last |NSEvent.modifierFlags| + * after masking with |modifierFlagOfInterestMask|. This should also be kept + * synchronized with the corresponding keys of |pressingRecords|. + * + * This is used by |synchronizeModifiers| to quickly find + * out modifier keys that are desynchronized. + */ +@property(nonatomic) NSUInteger lastModifierFlagsOfInterest; + +/** + * A self-incrementing ID used to label key events sent to the framework. + */ +@property(nonatomic) uint64_t responseId; + +/** + * A map of unresponded key events sent to the framework. + * + * Its values are |responseId|s, and keys are the callback that was received + * along with the event. + */ +@property(nonatomic) NSMutableDictionary* pendingResponses; + +/** + * Compare the last modifier flags and the current, and dispatch synthesized + * key events for each different modifier flag bit. + * + * The flags compared are all flags after masking with + * |modifierFlagOfInterestMask| and excluding |ignoringFlags|. + * + * The |guard| is basically a regular guarded callback, but instead of being + * called, it is only used to record whether an event is sent. + */ +- (void)synchronizeModifiers:(NSUInteger)currentFlags + ignoringFlags:(NSUInteger)ignoringFlags + timestamp:(NSTimeInterval)timestamp + guard:(nonnull FlutterKeyCallbackGuard*)guard; + +/** + * Update the pressing state. + * + * If `logicalKey` is not 0, `physicalKey` is pressed as `logicalKey`. + * Otherwise, `physicalKey` is released. + */ +- (void)updateKey:(uint64_t)physicalKey asPressed:(uint64_t)logicalKey; + +/** + * Send an event to the framework, expecting its response. + */ +- (void)sendPrimaryFlutterEvent:(const FlutterKeyEvent&)event + callback:(nonnull FlutterKeyCallbackGuard*)callback; + +/** + * Send a synthesized key event, never expecting its event result. + * + * The |guard| is basically a regular guarded callback, but instead of being + * called, it is only used to record whether an event is sent. + */ +- (void)sendSynthesizedFlutterEvent:(const FlutterKeyEvent&)event + guard:(FlutterKeyCallbackGuard*)guard; + +/** + * Send a CapsLock down event, then a CapsLock up event. + * + * If synthesizeDown is TRUE, then both events will be synthesized. Otherwise, + * the callback will be used as the callback for the down event, which is not + * synthesized, while the up event will always be synthesized. + */ +- (void)sendCapsLockTapWithTimestamp:(NSTimeInterval)timestamp + synthesizeDown:(bool)synthesizeDown + callback:(nonnull FlutterKeyCallbackGuard*)callback; + +/** + * Send a key event for a modifier key. + */ +- (void)sendModifierEventOfType:(BOOL)isDownEvent + timestamp:(NSTimeInterval)timestamp + keyCode:(unsigned short)keyCode + synthesized:(bool)synthesized + callback:(nonnull FlutterKeyCallbackGuard*)callback; + +/** + * Processes a down event from the system. + */ +- (void)handleDownEvent:(nonnull NSEvent*)event callback:(nonnull FlutterKeyCallbackGuard*)callback; + +/** + * Processes an up event from the system. + */ +- (void)handleUpEvent:(nonnull NSEvent*)event callback:(nonnull FlutterKeyCallbackGuard*)callback; + +/** + * Processes an event from the system for the CapsLock key. + */ +- (void)handleCapsLockEvent:(nonnull NSEvent*)event + callback:(nonnull FlutterKeyCallbackGuard*)callback; + +/** + * Processes a flags changed event from the system, where modifier keys are pressed or released. + */ +- (void)handleFlagEvent:(nonnull NSEvent*)event callback:(nonnull FlutterKeyCallbackGuard*)callback; + +/** + * Processes the response from the framework. + */ +- (void)handleResponse:(BOOL)handled forId:(uint64_t)responseId; + +@end + +@implementation FlutterEmbedderKeyResponder + +// Synthesize properties declared in FlutterKeyPrimaryResponder protocol. +@synthesize layoutMap; + +- (nonnull instancetype)initWithSendEvent:(FlutterSendEmbedderKeyEvent)sendEvent { + self = [super init]; + if (self != nil) { + _sendEvent = sendEvent; + _pressingRecords = [NSMutableDictionary dictionary]; + _pendingResponses = [NSMutableDictionary dictionary]; + _responseId = 1; + _lastModifierFlagsOfInterest = 0; + _modifierFlagOfInterestMask = computeModifierFlagOfInterestMask(); + } + return self; +} + +- (void)handleEvent:(NSEvent*)event callback:(FlutterAsyncKeyCallback)callback { + // The conversion algorithm relies on a non-nil callback to properly compute + // `synthesized`. + NSAssert(callback != nil, @"The callback must not be nil."); + FlutterKeyCallbackGuard* guardedCallback = + [[FlutterKeyCallbackGuard alloc] initWithCallback:callback]; + switch (event.type) { + case NSEventTypeKeyDown: + [self handleDownEvent:event callback:guardedCallback]; + break; + case NSEventTypeKeyUp: + [self handleUpEvent:event callback:guardedCallback]; + break; + case NSEventTypeFlagsChanged: + [self handleFlagEvent:event callback:guardedCallback]; + break; + default: + NSAssert(false, @"Unexpected key event type: |%@|.", @(event.type)); + } + NSAssert(guardedCallback.handled, @"The callback is returned without being handled."); + if (!guardedCallback.sentAnyEvents) { + FlutterKeyEvent flutterEvent = { + .struct_size = sizeof(FlutterKeyEvent), + .timestamp = 0, + .type = kFlutterKeyEventTypeDown, + .physical = 0, + .logical = 0, + .character = nil, + .synthesized = false, + }; + _sendEvent(flutterEvent, nullptr, nullptr); + } + NSAssert(_lastModifierFlagsOfInterest == (event.modifierFlags & _modifierFlagOfInterestMask), + @"The modifier flags are not properly updated: recorded 0x%lx, event with mask 0x%lx", + _lastModifierFlagsOfInterest, event.modifierFlags & _modifierFlagOfInterestMask); +} + +#pragma mark - Private + +- (void)synchronizeModifiers:(NSUInteger)currentFlags + ignoringFlags:(NSUInteger)ignoringFlags + timestamp:(NSTimeInterval)timestamp + guard:(FlutterKeyCallbackGuard*)guard { + const NSUInteger updatingMask = _modifierFlagOfInterestMask & ~ignoringFlags; + const NSUInteger currentFlagsOfInterest = currentFlags & updatingMask; + const NSUInteger lastFlagsOfInterest = _lastModifierFlagsOfInterest & updatingMask; + NSUInteger flagDifference = currentFlagsOfInterest ^ lastFlagsOfInterest; + if (flagDifference & NSEventModifierFlagCapsLock) { + [self sendCapsLockTapWithTimestamp:timestamp synthesizeDown:true callback:guard]; + flagDifference = flagDifference & ~NSEventModifierFlagCapsLock; + } + while (true) { + const NSUInteger currentFlag = lowestSetBit(flagDifference); + if (currentFlag == 0) { + break; + } + flagDifference = flagDifference & ~currentFlag; + NSNumber* keyCode = [flutter::modifierFlagToKeyCode objectForKey:@(currentFlag)]; + NSAssert(keyCode != nil, @"Invalid modifier flag 0x%lx", currentFlag); + if (keyCode == nil) { + continue; + } + BOOL isDownEvent = (currentFlagsOfInterest & currentFlag) != 0; + [self sendModifierEventOfType:isDownEvent + timestamp:timestamp + keyCode:[keyCode unsignedShortValue] + synthesized:true + callback:guard]; + } + _lastModifierFlagsOfInterest = + (_lastModifierFlagsOfInterest & ~updatingMask) | currentFlagsOfInterest; +} + +- (void)updateKey:(uint64_t)physicalKey asPressed:(uint64_t)logicalKey { + if (logicalKey == 0) { + [_pressingRecords removeObjectForKey:@(physicalKey)]; + } else { + _pressingRecords[@(physicalKey)] = @(logicalKey); + } +} + +- (void)sendPrimaryFlutterEvent:(const FlutterKeyEvent&)event + callback:(FlutterKeyCallbackGuard*)callback { + _responseId += 1; + uint64_t responseId = _responseId; + // The `pending` is released in `HandleResponse`. + FlutterKeyPendingResponse* pending = new FlutterKeyPendingResponse{self, responseId}; + [callback pendTo:_pendingResponses withId:responseId]; + _sendEvent(event, HandleResponse, pending); + callback.sentAnyEvents = TRUE; +} + +- (void)sendSynthesizedFlutterEvent:(const FlutterKeyEvent&)event + guard:(FlutterKeyCallbackGuard*)guard { + _sendEvent(event, nullptr, nullptr); + guard.sentAnyEvents = TRUE; +} + +- (void)sendCapsLockTapWithTimestamp:(NSTimeInterval)timestamp + synthesizeDown:(bool)synthesizeDown + callback:(FlutterKeyCallbackGuard*)callback { + // MacOS sends a down *or* an up when CapsLock is tapped, alternatively on + // even taps and odd taps. A CapsLock down or CapsLock up should always be + // converted to a down *and* an up, and the up should always be a synthesized + // event, since the FlutterEmbedderKeyResponder will never know when the + // button is released. + FlutterKeyEvent flutterEvent = { + .struct_size = sizeof(FlutterKeyEvent), + .timestamp = GetFlutterTimestampFrom(timestamp), + .type = kFlutterKeyEventTypeDown, + .physical = flutter::kCapsLockPhysicalKey, + .logical = flutter::kCapsLockLogicalKey, + .character = nil, + .synthesized = synthesizeDown, + }; + if (!synthesizeDown) { + [self sendPrimaryFlutterEvent:flutterEvent callback:callback]; + } else { + [self sendSynthesizedFlutterEvent:flutterEvent guard:callback]; + } + + flutterEvent.type = kFlutterKeyEventTypeUp; + flutterEvent.synthesized = true; + [self sendSynthesizedFlutterEvent:flutterEvent guard:callback]; +} + +- (void)sendModifierEventOfType:(BOOL)isDownEvent + timestamp:(NSTimeInterval)timestamp + keyCode:(unsigned short)keyCode + synthesized:(bool)synthesized + callback:(FlutterKeyCallbackGuard*)callback { + uint64_t physicalKey = GetPhysicalKeyForKeyCode(keyCode); + uint64_t logicalKey = GetLogicalKeyForModifier(keyCode, physicalKey); + if (physicalKey == 0 || logicalKey == 0) { + NSLog(@"Unrecognized modifier key: keyCode 0x%hx, physical key 0x%llx", keyCode, physicalKey); + [callback resolveTo:TRUE]; + return; + } + FlutterKeyEvent flutterEvent = { + .struct_size = sizeof(FlutterKeyEvent), + .timestamp = GetFlutterTimestampFrom(timestamp), + .type = isDownEvent ? kFlutterKeyEventTypeDown : kFlutterKeyEventTypeUp, + .physical = physicalKey, + .logical = logicalKey, + .character = nil, + .synthesized = synthesized, + }; + [self updateKey:physicalKey asPressed:isDownEvent ? logicalKey : 0]; + if (!synthesized) { + [self sendPrimaryFlutterEvent:flutterEvent callback:callback]; + } else { + [self sendSynthesizedFlutterEvent:flutterEvent guard:callback]; + } +} + +- (void)handleDownEvent:(NSEvent*)event callback:(FlutterKeyCallbackGuard*)callback { + uint64_t physicalKey = GetPhysicalKeyForKeyCode(event.keyCode); + NSNumber* logicalKeyFromMap = self.layoutMap[@(event.keyCode)]; + uint64_t logicalKey = logicalKeyFromMap != nil ? [logicalKeyFromMap unsignedLongLongValue] + : GetLogicalKeyForEvent(event, physicalKey); + [self synchronizeModifiers:event.modifierFlags + ignoringFlags:0 + timestamp:event.timestamp + guard:callback]; + + bool isARepeat = event.isARepeat; + NSNumber* pressedLogicalKey = _pressingRecords[@(physicalKey)]; + if (pressedLogicalKey != nil && !isARepeat) { + // This might happen in add-to-app scenarios if the focus is changed + // from the native view to the Flutter view amid the key tap. + // + // This might also happen when a key event is forged (such as by an + // IME) using the same keyCode as an unreleased key. See + // https://github.com/flutter/flutter/issues/82673#issuecomment-988661079 + FlutterKeyEvent flutterEvent = { + .struct_size = sizeof(FlutterKeyEvent), + .timestamp = GetFlutterTimestampFrom(event.timestamp), + .type = kFlutterKeyEventTypeUp, + .physical = physicalKey, + .logical = [pressedLogicalKey unsignedLongLongValue], + .character = nil, + .synthesized = true, + }; + [self sendSynthesizedFlutterEvent:flutterEvent guard:callback]; + pressedLogicalKey = nil; + } + + if (pressedLogicalKey == nil) { + [self updateKey:physicalKey asPressed:logicalKey]; + } + + FlutterKeyEvent flutterEvent = { + .struct_size = sizeof(FlutterKeyEvent), + .timestamp = GetFlutterTimestampFrom(event.timestamp), + .type = pressedLogicalKey == nil ? kFlutterKeyEventTypeDown : kFlutterKeyEventTypeRepeat, + .physical = physicalKey, + .logical = pressedLogicalKey == nil ? logicalKey : [pressedLogicalKey unsignedLongLongValue], + .character = getEventString(event.characters), + .synthesized = false, + }; + [self sendPrimaryFlutterEvent:flutterEvent callback:callback]; +} + +- (void)handleUpEvent:(NSEvent*)event callback:(FlutterKeyCallbackGuard*)callback { + NSAssert(!event.isARepeat, @"Unexpected repeated Up event: keyCode %d, char %@, charIM %@", + event.keyCode, event.characters, event.charactersIgnoringModifiers); + [self synchronizeModifiers:event.modifierFlags + ignoringFlags:0 + timestamp:event.timestamp + guard:callback]; + + uint64_t physicalKey = GetPhysicalKeyForKeyCode(event.keyCode); + NSNumber* pressedLogicalKey = _pressingRecords[@(physicalKey)]; + if (pressedLogicalKey == nil) { + // Normally the key up events won't be missed since macOS always sends the + // key up event to the window where the corresponding key down occurred. + // However this might happen in add-to-app scenarios if the focus is changed + // from the native view to the Flutter view amid the key tap. + [callback resolveTo:TRUE]; + return; + } + [self updateKey:physicalKey asPressed:0]; + + FlutterKeyEvent flutterEvent = { + .struct_size = sizeof(FlutterKeyEvent), + .timestamp = GetFlutterTimestampFrom(event.timestamp), + .type = kFlutterKeyEventTypeUp, + .physical = physicalKey, + .logical = [pressedLogicalKey unsignedLongLongValue], + .character = nil, + .synthesized = false, + }; + [self sendPrimaryFlutterEvent:flutterEvent callback:callback]; +} + +- (void)handleCapsLockEvent:(NSEvent*)event callback:(FlutterKeyCallbackGuard*)callback { + [self synchronizeModifiers:event.modifierFlags + ignoringFlags:NSEventModifierFlagCapsLock + timestamp:event.timestamp + guard:callback]; + if ((_lastModifierFlagsOfInterest & NSEventModifierFlagCapsLock) != + (event.modifierFlags & NSEventModifierFlagCapsLock)) { + [self sendCapsLockTapWithTimestamp:event.timestamp synthesizeDown:false callback:callback]; + _lastModifierFlagsOfInterest = _lastModifierFlagsOfInterest ^ NSEventModifierFlagCapsLock; + } else { + [callback resolveTo:TRUE]; + } +} + +- (void)handleFlagEvent:(NSEvent*)event callback:(FlutterKeyCallbackGuard*)callback { + NSNumber* targetModifierFlagObj = flutter::keyCodeToModifierFlag[@(event.keyCode)]; + NSUInteger targetModifierFlag = + targetModifierFlagObj == nil ? 0 : [targetModifierFlagObj unsignedLongValue]; + uint64_t targetKey = GetPhysicalKeyForKeyCode(event.keyCode); + if (targetKey == flutter::kCapsLockPhysicalKey) { + return [self handleCapsLockEvent:event callback:callback]; + } + + [self synchronizeModifiers:event.modifierFlags + ignoringFlags:targetModifierFlag + timestamp:event.timestamp + guard:callback]; + + NSNumber* pressedLogicalKey = [_pressingRecords objectForKey:@(targetKey)]; + BOOL lastTargetPressed = pressedLogicalKey != nil; + NSAssert(targetModifierFlagObj == nil || + (_lastModifierFlagsOfInterest & targetModifierFlag) != 0 == lastTargetPressed, + @"Desynchronized state between lastModifierFlagsOfInterest (0x%lx) on bit 0x%lx " + @"for keyCode 0x%hx, whose pressing state is %@.", + _lastModifierFlagsOfInterest, targetModifierFlag, event.keyCode, + lastTargetPressed + ? [NSString stringWithFormat:@"0x%llx", [pressedLogicalKey unsignedLongLongValue]] + : @"empty"); + + BOOL shouldBePressed = (event.modifierFlags & targetModifierFlag) != 0; + if (lastTargetPressed == shouldBePressed) { + [callback resolveTo:TRUE]; + return; + } + _lastModifierFlagsOfInterest = _lastModifierFlagsOfInterest ^ targetModifierFlag; + [self sendModifierEventOfType:shouldBePressed + timestamp:event.timestamp + keyCode:event.keyCode + synthesized:false + callback:callback]; +} + +- (void)handleResponse:(BOOL)handled forId:(uint64_t)responseId { + FlutterAsyncKeyCallback callback = _pendingResponses[@(responseId)]; + callback(handled); + [_pendingResponses removeObjectForKey:@(responseId)]; +} + +- (void)syncModifiersIfNeeded:(NSEventModifierFlags)modifierFlags + timestamp:(NSTimeInterval)timestamp { + FlutterAsyncKeyCallback replyCallback = ^(BOOL handled) { + // Do nothing. + }; + FlutterKeyCallbackGuard* guardedCallback = + [[FlutterKeyCallbackGuard alloc] initWithCallback:replyCallback]; + [self synchronizeModifiers:modifierFlags + ignoringFlags:0 + timestamp:timestamp + guard:guardedCallback]; +} + +- (nonnull NSDictionary*)getPressedState { + return [NSDictionary dictionaryWithDictionary:_pressingRecords]; +} +@end + +namespace { +void HandleResponse(bool handled, void* user_data) { + // Use unique_ptr to release on leaving. + auto pending = std::unique_ptr( + reinterpret_cast(user_data)); + [pending->responder handleResponse:handled forId:pending->responseId]; +} +} // namespace diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEmbedderKeyResponderTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEmbedderKeyResponderTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..2443c80db37c9bdd1f2de12c010c8eeefb8112bc --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEmbedderKeyResponderTest.mm @@ -0,0 +1,1274 @@ +// 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. + +#import + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEmbedderKeyResponder.h" +#include "flutter/shell/platform/embedder/test_utils/key_codes.g.h" +#import "flutter/testing/testing.h" +#include "third_party/googletest/googletest/include/gtest/gtest.h" + +// A wrap to convert FlutterKeyEvent to a ObjC class. +@interface TestKeyEvent : NSObject +@property(nonatomic) FlutterKeyEvent* data; +@property(nonatomic) FlutterKeyEventCallback callback; +@property(nonatomic) void* userData; +- (nonnull instancetype)initWithEvent:(const FlutterKeyEvent*)event + callback:(nullable FlutterKeyEventCallback)callback + userData:(nullable void*)userData; +- (BOOL)hasCallback; +- (void)respond:(BOOL)handled; +@end + +@implementation TestKeyEvent +- (instancetype)initWithEvent:(const FlutterKeyEvent*)event + callback:(nullable FlutterKeyEventCallback)callback + userData:(nullable void*)userData { + self = [super init]; + _data = new FlutterKeyEvent(*event); + if (event->character != nullptr) { + size_t len = strlen(event->character); + char* character = new char[len + 1]; + strlcpy(character, event->character, sizeof(character)); + _data->character = character; + } + _callback = callback; + _userData = userData; + return self; +} + +- (BOOL)hasCallback { + return _callback != nil; +} + +- (void)respond:(BOOL)handled { + NSAssert( + _callback != nil, + @"Improper call to `respond` that does not have a callback."); // Caller's responsibility + _callback(handled, _userData); +} + +- (void)dealloc { + if (_data->character != nullptr) { + delete[] _data->character; + } + delete _data; +} +@end + +namespace flutter::testing { + +namespace { +constexpr uint64_t kKeyCodeKeyA = 0x00; +constexpr uint64_t kKeyCodeKeyW = 0x0d; +constexpr uint64_t kKeyCodeShiftLeft = 0x38; +constexpr uint64_t kKeyCodeShiftRight = 0x3c; +constexpr uint64_t kKeyCodeCapsLock = 0x39; +constexpr uint64_t kKeyCodeNumpad1 = 0x53; +constexpr uint64_t kKeyCodeF1 = 0x7a; +constexpr uint64_t kKeyCodeAltRight = 0x3d; + +using namespace ::flutter::testing::keycodes; + +typedef void (^ResponseCallback)(bool handled); + +NSEvent* keyEvent(NSEventType type, + NSEventModifierFlags modifierFlags, + NSString* characters, + NSString* charactersIgnoringModifiers, + BOOL isARepeat, + unsigned short keyCode) { + return [NSEvent keyEventWithType:type + location:NSZeroPoint + modifierFlags:modifierFlags + timestamp:0 + windowNumber:0 + context:nil + characters:characters + charactersIgnoringModifiers:charactersIgnoringModifiers + isARepeat:isARepeat + keyCode:keyCode]; +} + +NSEvent* keyEvent(NSEventType type, + NSTimeInterval timestamp, + NSEventModifierFlags modifierFlags, + NSString* characters, + NSString* charactersIgnoringModifiers, + BOOL isARepeat, + unsigned short keyCode) { + return [NSEvent keyEventWithType:type + location:NSZeroPoint + modifierFlags:modifierFlags + timestamp:timestamp + windowNumber:0 + context:nil + characters:characters + charactersIgnoringModifiers:charactersIgnoringModifiers + isARepeat:isARepeat + keyCode:keyCode]; +} + +} // namespace + +// Test the most basic key events. +// +// Press, hold, and release key A on an US keyboard. +TEST(FlutterEmbedderKeyResponderUnittests, BasicKeyEvent) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + __block BOOL last_handled = TRUE; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + void* _Nullable user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + last_handled = FALSE; + [responder handleEvent:keyEvent(NSEventTypeKeyDown, 123.0f, 0x100, @"a", @"a", FALSE, 0) + callback:^(BOOL handled) { + last_handled = handled; + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->timestamp, 123000000.0f); + EXPECT_EQ(event->physical, kPhysicalKeyA); + EXPECT_EQ(event->logical, kLogicalKeyA); + EXPECT_STREQ(event->character, "a"); + EXPECT_EQ(event->synthesized, false); + + EXPECT_EQ(last_handled, FALSE); + EXPECT_TRUE([[events lastObject] hasCallback]); + [[events lastObject] respond:TRUE]; + EXPECT_EQ(last_handled, TRUE); + + [events removeAllObjects]; + + last_handled = FALSE; + [responder handleEvent:keyEvent(NSEventTypeKeyDown, 0x100, @"a", @"a", TRUE, kKeyCodeKeyA) + callback:^(BOOL handled) { + last_handled = handled; + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeRepeat); + EXPECT_EQ(event->physical, kPhysicalKeyA); + EXPECT_EQ(event->logical, kLogicalKeyA); + EXPECT_STREQ(event->character, "a"); + EXPECT_EQ(event->synthesized, false); + + EXPECT_EQ(last_handled, FALSE); + EXPECT_TRUE([[events lastObject] hasCallback]); + [[events lastObject] respond:TRUE]; + EXPECT_EQ(last_handled, TRUE); + + [events removeAllObjects]; + + last_handled = TRUE; + [responder handleEvent:keyEvent(NSEventTypeKeyUp, 124.0f, 0x100, @"a", @"a", FALSE, kKeyCodeKeyA) + callback:^(BOOL handled) { + last_handled = handled; + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeUp); + EXPECT_EQ(event->timestamp, 124000000.0f); + EXPECT_EQ(event->physical, kPhysicalKeyA); + EXPECT_EQ(event->logical, kLogicalKeyA); + EXPECT_EQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + + EXPECT_EQ(last_handled, TRUE); + EXPECT_TRUE([[events lastObject] hasCallback]); + [[events lastObject] respond:FALSE]; // Check if responding FALSE works + EXPECT_EQ(last_handled, FALSE); + + [events removeAllObjects]; +} + +TEST(FlutterEmbedderKeyResponderUnittests, NonAsciiCharacters) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + void* _Nullable user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + [responder + handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x80140, @"", @"", FALSE, kKeyCodeAltRight) + callback:^(BOOL handled){ + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->physical, kPhysicalAltRight); + EXPECT_EQ(event->logical, kLogicalAltRight); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + + [events removeAllObjects]; + + [responder handleEvent:keyEvent(NSEventTypeKeyDown, 0x80140, @"∑", @"w", FALSE, kKeyCodeKeyW) + callback:^(BOOL handled){ + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->physical, kPhysicalKeyW); + EXPECT_EQ(event->logical, kLogicalKeyW); + EXPECT_STREQ(event->character, "∑"); + EXPECT_EQ(event->synthesized, false); + + [events removeAllObjects]; + + [responder handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x100, @"", @"", FALSE, kKeyCodeAltRight) + callback:^(BOOL handled){ + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeUp); + EXPECT_EQ(event->physical, kPhysicalAltRight); + EXPECT_EQ(event->logical, kLogicalAltRight); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + + [events removeAllObjects]; + + [responder handleEvent:keyEvent(NSEventTypeKeyUp, 0x100, @"w", @"w", FALSE, kKeyCodeKeyW) + callback:^(BOOL handled){ + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeUp); + EXPECT_EQ(event->physical, kPhysicalKeyW); + EXPECT_EQ(event->logical, kLogicalKeyW); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + + [events removeAllObjects]; +} + +TEST(FlutterEmbedderKeyResponderUnittests, MultipleCharacters) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + void* _Nullable user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + [responder handleEvent:keyEvent(NSEventTypeKeyDown, 0, @"àn", @"àn", FALSE, kKeyCodeKeyA) + callback:^(BOOL handled){ + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->physical, kPhysicalKeyA); + EXPECT_EQ(event->logical, 0x1400000000ull); + EXPECT_STREQ(event->character, "àn"); + EXPECT_EQ(event->synthesized, false); + + [events removeAllObjects]; + + [responder handleEvent:keyEvent(NSEventTypeKeyUp, 0, @"a", @"a", FALSE, kKeyCodeKeyA) + callback:^(BOOL handled){ + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeUp); + EXPECT_EQ(event->physical, kPhysicalKeyA); + EXPECT_EQ(event->logical, 0x1400000000ull); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + + [events removeAllObjects]; +} + +TEST(FlutterEmbedderKeyResponderUnittests, SynthesizeForDuplicateDownEvent) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + __block BOOL last_handled = TRUE; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + void* _Nullable user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + last_handled = TRUE; + [responder handleEvent:keyEvent(NSEventTypeKeyDown, 0x100, @"a", @"a", FALSE, kKeyCodeKeyA) + callback:^(BOOL handled) { + last_handled = handled; + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->physical, kPhysicalKeyA); + EXPECT_EQ(event->logical, kLogicalKeyA); + EXPECT_STREQ(event->character, "a"); + EXPECT_EQ(event->synthesized, false); + EXPECT_EQ(last_handled, TRUE); + [[events lastObject] respond:FALSE]; + EXPECT_EQ(last_handled, FALSE); + + [events removeAllObjects]; + + last_handled = TRUE; + [responder handleEvent:keyEvent(NSEventTypeKeyDown, 0x100, @"à", @"à", FALSE, kKeyCodeKeyA) + callback:^(BOOL handled) { + last_handled = handled; + }]; + + EXPECT_EQ([events count], 2u); + + event = [events firstObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeUp); + EXPECT_EQ(event->physical, kPhysicalKeyA); + EXPECT_EQ(event->logical, kLogicalKeyA); + EXPECT_STREQ(event->character, NULL); + EXPECT_EQ(event->synthesized, true); + + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->physical, kPhysicalKeyA); + EXPECT_EQ(event->logical, 0xE0ull /* à */); + EXPECT_STREQ(event->character, "à"); + EXPECT_EQ(event->synthesized, false); + [[events lastObject] respond:FALSE]; + EXPECT_EQ(last_handled, FALSE); + + [events removeAllObjects]; +} + +TEST(FlutterEmbedderKeyResponderUnittests, IgnoreDuplicateUpEvent) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + FlutterKeyEvent* event; + __block BOOL last_handled = TRUE; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + void* _Nullable user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + last_handled = FALSE; + [responder handleEvent:keyEvent(NSEventTypeKeyUp, 0x100, @"a", @"a", FALSE, kKeyCodeKeyA) + callback:^(BOOL handled) { + last_handled = handled; + }]; + + EXPECT_EQ([events count], 1u); + EXPECT_EQ(last_handled, TRUE); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->physical, 0ull); + EXPECT_EQ(event->logical, 0ull); + EXPECT_FALSE([[events lastObject] hasCallback]); + EXPECT_EQ(last_handled, TRUE); + + [events removeAllObjects]; +} + +TEST(FlutterEmbedderKeyResponderUnittests, ConvertAbruptRepeatEventsToDown) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + __block BOOL last_handled = TRUE; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + void* _Nullable user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + last_handled = TRUE; + [responder handleEvent:keyEvent(NSEventTypeKeyDown, 0x100, @"a", @"a", TRUE, kKeyCodeKeyA) + callback:^(BOOL handled) { + last_handled = handled; + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->physical, kPhysicalKeyA); + EXPECT_EQ(event->logical, kLogicalKeyA); + EXPECT_STREQ(event->character, "a"); + EXPECT_EQ(event->synthesized, false); + EXPECT_EQ(last_handled, TRUE); + [[events lastObject] respond:FALSE]; + EXPECT_EQ(last_handled, FALSE); + + [events removeAllObjects]; +} + +// Press L shift, A, then release L shift then A, on an US keyboard. +// +// This is special because the characters for the A key will change in this +// process. +TEST(FlutterEmbedderKeyResponderUnittests, ToggleModifiersDuringKeyTap) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + void* _Nullable user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + [responder handleEvent:keyEvent(NSEventTypeFlagsChanged, 123.0f, 0x20104, @"", @"", FALSE, + kKeyCodeShiftRight) + callback:^(BOOL handled){ + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->timestamp, 123000000.0f); + EXPECT_EQ(event->physical, kPhysicalShiftRight); + EXPECT_EQ(event->logical, kLogicalShiftRight); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + [responder handleEvent:keyEvent(NSEventTypeKeyDown, 0x20104, @"A", @"A", FALSE, kKeyCodeKeyA) + callback:^(BOOL handled){ + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->physical, kPhysicalKeyA); + EXPECT_EQ(event->logical, kLogicalKeyA); + EXPECT_STREQ(event->character, "A"); + EXPECT_EQ(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + [responder handleEvent:keyEvent(NSEventTypeKeyDown, 0x20104, @"A", @"A", TRUE, kKeyCodeKeyA) + callback:^(BOOL handled){ + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeRepeat); + EXPECT_EQ(event->physical, kPhysicalKeyA); + EXPECT_EQ(event->logical, kLogicalKeyA); + EXPECT_STREQ(event->character, "A"); + EXPECT_EQ(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + [responder + handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x100, @"", @"", FALSE, kKeyCodeShiftRight) + callback:^(BOOL handled){ + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeUp); + EXPECT_EQ(event->physical, kPhysicalShiftRight); + EXPECT_EQ(event->logical, kLogicalShiftRight); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + [responder handleEvent:keyEvent(NSEventTypeKeyDown, 0x100, @"a", @"a", TRUE, kKeyCodeKeyA) + callback:^(BOOL handled){ + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeRepeat); + EXPECT_EQ(event->physical, kPhysicalKeyA); + EXPECT_EQ(event->logical, kLogicalKeyA); + EXPECT_STREQ(event->character, "a"); + EXPECT_EQ(event->synthesized, false); + + [events removeAllObjects]; + + [responder handleEvent:keyEvent(NSEventTypeKeyUp, 0x100, @"a", @"a", FALSE, kKeyCodeKeyA) + callback:^(BOOL handled){ + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeUp); + EXPECT_EQ(event->physical, kPhysicalKeyA); + EXPECT_EQ(event->logical, kLogicalKeyA); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; +} + +// Special modifier flags. +// +// Some keys in modifierFlags are not to indicate modifier state, but to mark +// the key area that the key belongs to, such as numpad keys or function keys. +// Ensure these flags do not obstruct other keys. +TEST(FlutterEmbedderKeyResponderUnittests, SpecialModiferFlags) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + void* _Nullable user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + // Keydown: Numpad1, F1, KeyA, ShiftLeft + // Then KeyUp: Numpad1, F1, KeyA, ShiftLeft + + // Numpad 1 + [responder handleEvent:keyEvent(NSEventTypeKeyDown, 0x200100, @"1", @"1", FALSE, kKeyCodeNumpad1) + callback:^(BOOL handled){ + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->physical, kPhysicalNumpad1); + EXPECT_EQ(event->logical, kLogicalNumpad1); + EXPECT_STREQ(event->character, "1"); + EXPECT_EQ(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + // F1 + [responder + handleEvent:keyEvent(NSEventTypeKeyDown, 0x800100, @"\uf704", @"\uf704", FALSE, kKeyCodeF1) + callback:^(BOOL handled){ + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->physical, kPhysicalF1); + EXPECT_EQ(event->logical, kLogicalF1); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + // KeyA + [responder handleEvent:keyEvent(NSEventTypeKeyDown, 0x100, @"a", @"a", FALSE, kKeyCodeKeyA) + callback:^(BOOL handled){ + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->physical, kPhysicalKeyA); + EXPECT_EQ(event->logical, kLogicalKeyA); + EXPECT_STREQ(event->character, "a"); + EXPECT_EQ(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + // ShiftLeft + [responder + handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x20102, @"", @"", FALSE, kKeyCodeShiftLeft) + callback:^(BOOL handled){ + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->physical, kPhysicalShiftLeft); + EXPECT_EQ(event->logical, kLogicalShiftLeft); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + // Numpad 1 + [responder handleEvent:keyEvent(NSEventTypeKeyUp, 0x220102, @"1", @"1", FALSE, kKeyCodeNumpad1) + callback:^(BOOL handled){ + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeUp); + EXPECT_EQ(event->physical, kPhysicalNumpad1); + EXPECT_EQ(event->logical, kLogicalNumpad1); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + // F1 + [responder + handleEvent:keyEvent(NSEventTypeKeyUp, 0x820102, @"\uF704", @"\uF704", FALSE, kKeyCodeF1) + callback:^(BOOL handled){ + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeUp); + EXPECT_EQ(event->physical, kPhysicalF1); + EXPECT_EQ(event->logical, kLogicalF1); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + // KeyA + [responder handleEvent:keyEvent(NSEventTypeKeyUp, 0x20102, @"a", @"a", FALSE, kKeyCodeKeyA) + callback:^(BOOL handled){ + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeUp); + EXPECT_EQ(event->physical, kPhysicalKeyA); + EXPECT_EQ(event->logical, kLogicalKeyA); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + // ShiftLeft + [responder + handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x100, @"", @"", FALSE, kKeyCodeShiftLeft) + callback:^(BOOL handled){ + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeUp); + EXPECT_EQ(event->physical, kPhysicalShiftLeft); + EXPECT_EQ(event->logical, kLogicalShiftLeft); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; +} + +TEST(FlutterEmbedderKeyResponderUnittests, IdentifyLeftAndRightModifiers) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + void* _Nullable user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + [responder + handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x20102, @"", @"", FALSE, kKeyCodeShiftLeft) + callback:^(BOOL handled){ + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->physical, kPhysicalShiftLeft); + EXPECT_EQ(event->logical, kLogicalShiftLeft); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + [responder + handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x20106, @"", @"", FALSE, kKeyCodeShiftRight) + callback:^(BOOL handled){ + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->physical, kPhysicalShiftRight); + EXPECT_EQ(event->logical, kLogicalShiftRight); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + [responder + handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x20104, @"", @"", FALSE, kKeyCodeShiftLeft) + callback:^(BOOL handled){ + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeUp); + EXPECT_EQ(event->physical, kPhysicalShiftLeft); + EXPECT_EQ(event->logical, kLogicalShiftLeft); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + [responder + handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x100, @"", @"", FALSE, kKeyCodeShiftRight) + callback:^(BOOL handled){ + }]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeUp); + EXPECT_EQ(event->physical, kPhysicalShiftRight); + EXPECT_EQ(event->logical, kLogicalShiftRight); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; +} + +// Process various cases where pair modifier key events are missed, and the +// responder has to "guess" how to synchronize states. +// +// In the following comments, parentheses indicate missed events, while +// asterisks indicate synthesized events. +TEST(FlutterEmbedderKeyResponderUnittests, SynthesizeMissedModifierEvents) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + __block BOOL last_handled = TRUE; + id keyEventCallback = ^(BOOL handled) { + last_handled = handled; + }; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + void* _Nullable user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + // Case 1: + // In: L down, (L up), L down, L up + // Out: L down, L up + last_handled = FALSE; + [responder + handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x20102, @"", @"", FALSE, kKeyCodeShiftLeft) + callback:keyEventCallback]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->physical, kPhysicalShiftLeft); + EXPECT_EQ(event->logical, kLogicalShiftLeft); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + + EXPECT_EQ(last_handled, FALSE); + EXPECT_TRUE([[events lastObject] hasCallback]); + [[events lastObject] respond:TRUE]; + EXPECT_EQ(last_handled, TRUE); + + [events removeAllObjects]; + + last_handled = FALSE; + [responder + handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x20102, @"", @"", FALSE, kKeyCodeShiftLeft) + callback:keyEventCallback]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->physical, 0u); + EXPECT_EQ(event->logical, 0u); + EXPECT_FALSE([[events lastObject] hasCallback]); + EXPECT_EQ(last_handled, TRUE); + [events removeAllObjects]; + + last_handled = FALSE; + [responder + handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x100, @"", @"", FALSE, kKeyCodeShiftLeft) + callback:keyEventCallback]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeUp); + EXPECT_EQ(event->physical, kPhysicalShiftLeft); + EXPECT_EQ(event->logical, kLogicalShiftLeft); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + + EXPECT_EQ(last_handled, FALSE); + EXPECT_TRUE([[events lastObject] hasCallback]); + [[events lastObject] respond:TRUE]; + EXPECT_EQ(last_handled, TRUE); + + [events removeAllObjects]; + + // Case 2: + // In: (L down), L up + // Out: + + last_handled = FALSE; + [responder + handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x100, @"", @"", FALSE, kKeyCodeShiftLeft) + callback:keyEventCallback]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->physical, 0u); + EXPECT_EQ(event->logical, 0u); + EXPECT_FALSE([[events lastObject] hasCallback]); + EXPECT_EQ(last_handled, TRUE); + [events removeAllObjects]; + + // Case 3: + // In: L down, (L up), (R down), R up + // Out: L down, *L up + + last_handled = FALSE; + [responder + handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x20102, @"", @"", FALSE, kKeyCodeShiftLeft) + callback:keyEventCallback]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->physical, kPhysicalShiftLeft); + EXPECT_EQ(event->logical, kLogicalShiftLeft); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + + EXPECT_EQ(last_handled, FALSE); + EXPECT_TRUE([[events lastObject] hasCallback]); + [[events lastObject] respond:TRUE]; + EXPECT_EQ(last_handled, TRUE); + + [events removeAllObjects]; + + last_handled = FALSE; + [responder + handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x100, @"", @"", FALSE, kKeyCodeShiftRight) + callback:keyEventCallback]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeUp); + EXPECT_EQ(event->physical, kPhysicalShiftLeft); + EXPECT_EQ(event->logical, kLogicalShiftLeft); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, true); + + // The primary event is automatically replied with TRUE, unrelated to the received event. + EXPECT_EQ(last_handled, TRUE); + EXPECT_FALSE([[events lastObject] hasCallback]); + + [events removeAllObjects]; + + // Case 4: + // In: L down, R down, (L up), R up + // Out: L down, R down *L up & R up + + last_handled = FALSE; + [responder + handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x20102, @"", @"", FALSE, kKeyCodeShiftLeft) + callback:keyEventCallback]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->physical, kPhysicalShiftLeft); + EXPECT_EQ(event->logical, kLogicalShiftLeft); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + + EXPECT_EQ(last_handled, FALSE); + EXPECT_TRUE([[events lastObject] hasCallback]); + [[events lastObject] respond:TRUE]; + EXPECT_EQ(last_handled, TRUE); + + [events removeAllObjects]; + + last_handled = FALSE; + [responder + handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x20106, @"", @"", FALSE, kKeyCodeShiftRight) + callback:keyEventCallback]; + + EXPECT_EQ([events count], 1u); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->physical, kPhysicalShiftRight); + EXPECT_EQ(event->logical, kLogicalShiftRight); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + + EXPECT_EQ(last_handled, FALSE); + EXPECT_TRUE([[events lastObject] hasCallback]); + [[events lastObject] respond:TRUE]; + EXPECT_EQ(last_handled, TRUE); + + [events removeAllObjects]; + + last_handled = FALSE; + [responder + handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x100, @"", @"", FALSE, kKeyCodeShiftRight) + callback:keyEventCallback]; + + EXPECT_EQ([events count], 2u); + event = [events firstObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeUp); + EXPECT_EQ(event->physical, kPhysicalShiftLeft); + EXPECT_EQ(event->logical, kLogicalShiftLeft); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, true); + + EXPECT_FALSE([[events firstObject] hasCallback]); + + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeUp); + EXPECT_EQ(event->physical, kPhysicalShiftRight); + EXPECT_EQ(event->logical, kLogicalShiftRight); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + + EXPECT_EQ(last_handled, FALSE); + EXPECT_TRUE([[events lastObject] hasCallback]); + [[events lastObject] respond:TRUE]; + EXPECT_EQ(last_handled, TRUE); + + [events removeAllObjects]; +} + +TEST(FlutterEmbedderKeyResponderUnittests, SynthesizeMissedModifierEventsInNormalEvents) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + __block BOOL last_handled = TRUE; + id keyEventCallback = ^(BOOL handled) { + last_handled = handled; + }; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + void* _Nullable user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + // In: (LShift down), A down, (LShift up), A up + // Out: *LS down & A down, *LS up & A up + + last_handled = FALSE; + [responder handleEvent:keyEvent(NSEventTypeKeyDown, 0x20102, @"A", @"A", FALSE, kKeyCodeKeyA) + callback:keyEventCallback]; + + EXPECT_EQ([events count], 2u); + event = [events firstObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->physical, kPhysicalShiftLeft); + EXPECT_EQ(event->logical, kLogicalShiftLeft); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, true); + EXPECT_FALSE([[events firstObject] hasCallback]); + + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->physical, kPhysicalKeyA); + EXPECT_EQ(event->logical, kLogicalKeyA); + EXPECT_STREQ(event->character, "A"); + EXPECT_EQ(event->synthesized, false); + EXPECT_TRUE([[events lastObject] hasCallback]); + + EXPECT_EQ(last_handled, FALSE); + [[events lastObject] respond:TRUE]; + EXPECT_EQ(last_handled, TRUE); + + [events removeAllObjects]; + + last_handled = FALSE; + [responder handleEvent:keyEvent(NSEventTypeKeyUp, 0x100, @"a", @"a", FALSE, kKeyCodeKeyA) + callback:keyEventCallback]; + + EXPECT_EQ([events count], 2u); + event = [events firstObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeUp); + EXPECT_EQ(event->physical, kPhysicalShiftLeft); + EXPECT_EQ(event->logical, kLogicalShiftLeft); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, true); + EXPECT_FALSE([[events firstObject] hasCallback]); + + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeUp); + EXPECT_EQ(event->physical, kPhysicalKeyA); + EXPECT_EQ(event->logical, kLogicalKeyA); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + EXPECT_TRUE([[events lastObject] hasCallback]); + + EXPECT_EQ(last_handled, FALSE); + [[events lastObject] respond:TRUE]; + EXPECT_EQ(last_handled, TRUE); + + [events removeAllObjects]; +} + +TEST(FlutterEmbedderKeyResponderUnittests, ConvertCapsLockEvents) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + __block BOOL last_handled = TRUE; + id keyEventCallback = ^(BOOL handled) { + last_handled = handled; + }; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + void* _Nullable user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + // In: CapsLock down + // Out: CapsLock down & *CapsLock Up + last_handled = FALSE; + [responder + handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x10100, @"", @"", FALSE, kKeyCodeCapsLock) + callback:keyEventCallback]; + + EXPECT_EQ([events count], 2u); + + event = [events firstObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->physical, kPhysicalCapsLock); + EXPECT_EQ(event->logical, kLogicalCapsLock); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + EXPECT_TRUE([[events firstObject] hasCallback]); + + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeUp); + EXPECT_EQ(event->physical, kPhysicalCapsLock); + EXPECT_EQ(event->logical, kLogicalCapsLock); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, true); + EXPECT_FALSE([[events lastObject] hasCallback]); + + EXPECT_EQ(last_handled, FALSE); + [[events firstObject] respond:TRUE]; + EXPECT_EQ(last_handled, TRUE); + + [events removeAllObjects]; + + // In: CapsLock up + // Out: CapsLock down & *CapsLock Up + last_handled = FALSE; + [responder handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x100, @"", @"", FALSE, kKeyCodeCapsLock) + callback:keyEventCallback]; + + EXPECT_EQ([events count], 2u); + + event = [events firstObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->physical, kPhysicalCapsLock); + EXPECT_EQ(event->logical, kLogicalCapsLock); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, false); + EXPECT_TRUE([[events firstObject] hasCallback]); + + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeUp); + EXPECT_EQ(event->physical, kPhysicalCapsLock); + EXPECT_EQ(event->logical, kLogicalCapsLock); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, true); + EXPECT_FALSE([[events lastObject] hasCallback]); + + EXPECT_EQ(last_handled, FALSE); + [[events firstObject] respond:TRUE]; + EXPECT_EQ(last_handled, TRUE); + + [events removeAllObjects]; +} + +// Press the CapsLock key when CapsLock state is desynchronized +TEST(FlutterEmbedderKeyResponderUnittests, SynchronizeCapsLockStateOnCapsLock) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + FlutterKeyEvent* event; + __block BOOL last_handled = TRUE; + id keyEventCallback = ^(BOOL handled) { + last_handled = handled; + }; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + void* _Nullable user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + // In: CapsLock down + // Out: (empty) + last_handled = FALSE; + [responder handleEvent:keyEvent(NSEventTypeFlagsChanged, 0x100, @"", @"", FALSE, kKeyCodeCapsLock) + callback:keyEventCallback]; + + EXPECT_EQ([events count], 1u); + EXPECT_EQ(last_handled, TRUE); + event = [events lastObject].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->physical, 0ull); + EXPECT_EQ(event->logical, 0ull); + EXPECT_FALSE([[events lastObject] hasCallback]); + EXPECT_EQ(last_handled, TRUE); + + [events removeAllObjects]; +} + +// Press the CapsLock key when CapsLock state is desynchronized +TEST(FlutterEmbedderKeyResponderUnittests, SynchronizeCapsLockStateOnNormalKey) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + __block BOOL last_handled = TRUE; + id keyEventCallback = ^(BOOL handled) { + last_handled = handled; + }; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + void* _Nullable user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + last_handled = FALSE; + [responder handleEvent:keyEvent(NSEventTypeKeyDown, 0x10100, @"A", @"a", FALSE, kKeyCodeKeyA) + callback:keyEventCallback]; + + EXPECT_EQ([events count], 3u); + + event = events[0].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->physical, kPhysicalCapsLock); + EXPECT_EQ(event->logical, kLogicalCapsLock); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, true); + EXPECT_FALSE([events[0] hasCallback]); + + event = events[1].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeUp); + EXPECT_EQ(event->physical, kPhysicalCapsLock); + EXPECT_EQ(event->logical, kLogicalCapsLock); + EXPECT_STREQ(event->character, nullptr); + EXPECT_EQ(event->synthesized, true); + EXPECT_FALSE([events[1] hasCallback]); + + event = events[2].data; + ASSERT_NE(event, nullptr); + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->physical, kPhysicalKeyA); + EXPECT_EQ(event->logical, kLogicalKeyA); + EXPECT_STREQ(event->character, "A"); + EXPECT_EQ(event->synthesized, false); + EXPECT_TRUE([events[2] hasCallback]); + + EXPECT_EQ(last_handled, FALSE); + [[events lastObject] respond:TRUE]; + EXPECT_EQ(last_handled, TRUE); + + [events removeAllObjects]; +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine.mm new file mode 100644 index 0000000000000000000000000000000000000000..a6fb4de0993e3efa8c417f95cac48c873e84e62b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine.mm @@ -0,0 +1,1596 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" + +#include +#include +#include + +#include "flutter/common/constants.h" +#include "flutter/shell/platform/common/app_lifecycle_state.h" +#include "flutter/shell/platform/common/engine_switches.h" +#include "flutter/shell/platform/embedder/embedder.h" + +#import "flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.h" +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppDelegate.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterAppDelegate_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterCompositor.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDisplayLink.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMouseCursorPlugin.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewController.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderer.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterRunLoop.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTimeConverter.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterVSyncWaiter.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewEngineProvider.h" + +@class FlutterEngineRegistrar; + +NSString* const kFlutterPlatformChannel = @"flutter/platform"; +NSString* const kFlutterSettingsChannel = @"flutter/settings"; +NSString* const kFlutterLifecycleChannel = @"flutter/lifecycle"; + +using flutter::kFlutterImplicitViewId; + +/** + * Constructs and returns a FlutterLocale struct corresponding to |locale|, which must outlive + * the returned struct. + */ +static FlutterLocale FlutterLocaleFromNSLocale(NSLocale* locale) { + FlutterLocale flutterLocale = {}; + flutterLocale.struct_size = sizeof(FlutterLocale); + flutterLocale.language_code = [[locale objectForKey:NSLocaleLanguageCode] UTF8String]; + flutterLocale.country_code = [[locale objectForKey:NSLocaleCountryCode] UTF8String]; + flutterLocale.script_code = [[locale objectForKey:NSLocaleScriptCode] UTF8String]; + flutterLocale.variant_code = [[locale objectForKey:NSLocaleVariantCode] UTF8String]; + return flutterLocale; +} + +/// The private notification for voice over. +static NSString* const kEnhancedUserInterfaceNotification = + @"NSApplicationDidChangeAccessibilityEnhancedUserInterfaceNotification"; +static NSString* const kEnhancedUserInterfaceKey = @"AXEnhancedUserInterface"; + +/// Clipboard plain text format. +constexpr char kTextPlainFormat[] = "text/plain"; + +#pragma mark - + +// Records an active handler of the messenger (FlutterEngine) that listens to +// platform messages on a given channel. +@interface FlutterEngineHandlerInfo : NSObject + +- (instancetype)initWithConnection:(NSNumber*)connection + handler:(FlutterBinaryMessageHandler)handler; + +@property(nonatomic, readonly) FlutterBinaryMessageHandler handler; +@property(nonatomic, readonly) NSNumber* connection; + +@end + +@implementation FlutterEngineHandlerInfo +- (instancetype)initWithConnection:(NSNumber*)connection + handler:(FlutterBinaryMessageHandler)handler { + self = [super init]; + NSAssert(self, @"Super init cannot be nil"); + _connection = connection; + _handler = handler; + return self; +} +@end + +#pragma mark - + +/** + * Private interface declaration for FlutterEngine. + */ +@interface FlutterEngine () + +/** + * A mutable array that holds one bool value that determines if responses to platform messages are + * clear to execute. This value should be read or written only inside of a synchronized block and + * will return `NO` after the FlutterEngine has been dealloc'd. + */ +@property(nonatomic, strong) NSMutableArray* isResponseValid; + +/** + * All delegates added via plugin calls to addApplicationDelegate. + */ +@property(nonatomic, strong) NSPointerArray* pluginAppDelegates; + +/** + * All registrars returned from registrarForPlugin: + */ +@property(nonatomic, readonly) + NSMutableDictionary* pluginRegistrars; + +- (nullable FlutterViewController*)viewControllerForIdentifier: + (FlutterViewIdentifier)viewIdentifier; + +/** + * An internal method that adds the view controller with the given ID. + * + * This method assigns the controller with the ID, puts the controller into the + * map, and does assertions related to the implicit view ID. + */ +- (void)registerViewController:(FlutterViewController*)controller + forIdentifier:(FlutterViewIdentifier)viewIdentifier; + +/** + * An internal method that removes the view controller with the given ID. + * + * This method clears the ID of the controller, removes the controller from the + * map. This is an no-op if the view ID is not associated with any view + * controllers. + */ +- (void)deregisterViewControllerForIdentifier:(FlutterViewIdentifier)viewIdentifier; + +/** + * Shuts down the engine if view requirement is not met, and headless execution + * is not allowed. + */ +- (void)shutDownIfNeeded; + +/** + * Sends the list of user-preferred locales to the Flutter engine. + */ +- (void)sendUserLocales; + +/** + * Handles a platform message from the engine. + */ +- (void)engineCallbackOnPlatformMessage:(const FlutterPlatformMessage*)message; + +/** + * Invoked right before the engine is restarted. + * + * This should reset states to as if the application has just started. It + * usually indicates a hot restart (Shift-R in Flutter CLI.) + */ +- (void)engineCallbackOnPreEngineRestart; + +/** + * Requests that the task be posted back the to the Flutter engine at the target time. The target + * time is in the clock used by the Flutter engine. + */ +- (void)postMainThreadTask:(FlutterTask)task targetTimeInNanoseconds:(uint64_t)targetTime; + +/** + * Loads the AOT snapshots and instructions from the elf bundle (app_elf_snapshot.so) into _aotData, + * if it is present in the assets directory. + */ +- (void)loadAOTData:(NSString*)assetsDir; + +/** + * Creates a platform view channel and sets up the method handler. + */ +- (void)setUpPlatformViewChannel; + +/** + * Creates an accessibility channel and sets up the message handler. + */ +- (void)setUpAccessibilityChannel; + +/** + * Handles messages received from the Flutter engine on the _*Channel channels. + */ +- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result; + +@end + +#pragma mark - + +@implementation FlutterEngineTerminationHandler { + __weak FlutterEngine* _engine; + FlutterTerminationCallback _terminator; +} + +- (instancetype)initWithEngine:(FlutterEngine*)engine + terminator:(FlutterTerminationCallback)terminator { + self = [super init]; + _acceptingRequests = NO; + _engine = engine; + _terminator = terminator ? terminator : ^(id sender) { + // Default to actually terminating the application. The terminator exists to + // allow tests to override it so that an actual exit doesn't occur. + [[NSApplication sharedApplication] terminate:sender]; + }; + id appDelegate = [[NSApplication sharedApplication] delegate]; + if ([appDelegate respondsToSelector:@selector(setTerminationHandler:)]) { + FlutterAppDelegate* flutterAppDelegate = reinterpret_cast(appDelegate); + flutterAppDelegate.terminationHandler = self; + } + return self; +} + +// This is called by the method call handler in the engine when the application +// requests termination itself. +- (void)handleRequestAppExitMethodCall:(NSDictionary*)arguments + result:(FlutterResult)result { + NSString* type = arguments[@"type"]; + // Ignore the "exitCode" value in the arguments because AppKit doesn't have + // any good way to set the process exit code other than calling exit(), and + // that bypasses all of the native applicationShouldExit shutdown events, + // etc., which we don't want to skip. + + FlutterAppExitType exitType = + [type isEqualTo:@"cancelable"] ? kFlutterAppExitTypeCancelable : kFlutterAppExitTypeRequired; + + [self requestApplicationTermination:[NSApplication sharedApplication] + exitType:exitType + result:result]; +} + +// This is called by the FlutterAppDelegate whenever any termination request is +// received. +- (void)requestApplicationTermination:(id)sender + exitType:(FlutterAppExitType)type + result:(nullable FlutterResult)result { + _shouldTerminate = YES; + if (![self acceptingRequests]) { + // Until the Dart application has signaled that it is ready to handle + // termination requests, the app will just terminate when asked. + type = kFlutterAppExitTypeRequired; + } + switch (type) { + case kFlutterAppExitTypeCancelable: { + FlutterJSONMethodCodec* codec = [FlutterJSONMethodCodec sharedInstance]; + FlutterMethodCall* methodCall = + [FlutterMethodCall methodCallWithMethodName:@"System.requestAppExit" arguments:nil]; + [_engine sendOnChannel:kFlutterPlatformChannel + message:[codec encodeMethodCall:methodCall] + binaryReply:^(NSData* _Nullable reply) { + NSAssert(_terminator, @"terminator shouldn't be nil"); + id decoded_reply = [codec decodeEnvelope:reply]; + if ([decoded_reply isKindOfClass:[FlutterError class]]) { + FlutterError* error = (FlutterError*)decoded_reply; + NSLog(@"Method call returned error[%@]: %@ %@", [error code], [error message], + [error details]); + _terminator(sender); + return; + } + if (![decoded_reply isKindOfClass:[NSDictionary class]]) { + NSLog(@"Call to System.requestAppExit returned an unexpected object: %@", + decoded_reply); + _terminator(sender); + return; + } + NSDictionary* replyArgs = (NSDictionary*)decoded_reply; + if ([replyArgs[@"response"] isEqual:@"exit"]) { + _terminator(sender); + } else if ([replyArgs[@"response"] isEqual:@"cancel"]) { + _shouldTerminate = NO; + } + if (result != nil) { + result(replyArgs); + } + }]; + break; + } + case kFlutterAppExitTypeRequired: + NSAssert(_terminator, @"terminator shouldn't be nil"); + _terminator(sender); + break; + } +} + +@end + +#pragma mark - + +@implementation FlutterPasteboard + +- (NSInteger)clearContents { + return [[NSPasteboard generalPasteboard] clearContents]; +} + +- (NSString*)stringForType:(NSPasteboardType)dataType { + return [[NSPasteboard generalPasteboard] stringForType:dataType]; +} + +- (BOOL)setString:(nonnull NSString*)string forType:(nonnull NSPasteboardType)dataType { + return [[NSPasteboard generalPasteboard] setString:string forType:dataType]; +} + +@end + +#pragma mark - + +/** + * `FlutterPluginRegistrar` implementation handling a single plugin. + */ +@interface FlutterEngineRegistrar : NSObject +- (instancetype)initWithPlugin:(nonnull NSString*)pluginKey + flutterEngine:(nonnull FlutterEngine*)flutterEngine; + +- (nullable NSView*)viewForIdentifier:(FlutterViewIdentifier)viewIdentifier; + +/** + * The value published by this plugin, or NSNull if nothing has been published. + * + * The unusual NSNull is for the documented behavior of valuePublishedByPlugin:. + */ +@property(nonatomic, readonly, nonnull) NSObject* publishedValue; +@end + +@implementation FlutterEngineRegistrar { + NSString* _pluginKey; + __weak FlutterEngine* _flutterEngine; +} + +@dynamic view; + +- (instancetype)initWithPlugin:(NSString*)pluginKey flutterEngine:(FlutterEngine*)flutterEngine { + self = [super init]; + if (self) { + _pluginKey = [pluginKey copy]; + _flutterEngine = flutterEngine; + _publishedValue = [NSNull null]; + } + return self; +} + +#pragma mark - FlutterPluginRegistrar + +- (id)messenger { + return _flutterEngine.binaryMessenger; +} + +- (id)textures { + return _flutterEngine.renderer; +} + +- (NSView*)view { + return [self viewForIdentifier:kFlutterImplicitViewId]; +} + +- (NSView*)viewForIdentifier:(FlutterViewIdentifier)viewIdentifier { + FlutterViewController* controller = [_flutterEngine viewControllerForIdentifier:viewIdentifier]; + if (controller == nil) { + return nil; + } + if (!controller.viewLoaded) { + [controller loadView]; + } + return controller.flutterView; +} + +- (void)addMethodCallDelegate:(nonnull id)delegate + channel:(nonnull FlutterMethodChannel*)channel { + [channel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { + [delegate handleMethodCall:call result:result]; + }]; +} + +- (void)addApplicationDelegate:(NSObject*)delegate { + id appDelegate = [[NSApplication sharedApplication] delegate]; + if ([appDelegate conformsToProtocol:@protocol(FlutterAppLifecycleProvider)]) { + id lifeCycleProvider = + static_cast>(appDelegate); + [lifeCycleProvider addApplicationLifecycleDelegate:delegate]; + [_flutterEngine.pluginAppDelegates addPointer:(__bridge void*)delegate]; + } +} + +- (void)registerViewFactory:(nonnull NSObject*)factory + withId:(nonnull NSString*)factoryId { + [[_flutterEngine platformViewController] registerViewFactory:factory withId:factoryId]; +} + +- (void)publish:(NSObject*)value { + _publishedValue = value; +} + +- (NSString*)lookupKeyForAsset:(NSString*)asset { + return [FlutterDartProject lookupKeyForAsset:asset]; +} + +- (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package { + return [FlutterDartProject lookupKeyForAsset:asset fromPackage:package]; +} + +@end + +// Callbacks provided to the engine. See the called methods for documentation. +#pragma mark - Static methods provided to engine configuration + +static void OnPlatformMessage(const FlutterPlatformMessage* message, void* user_data) { + FlutterEngine* engine = (__bridge FlutterEngine*)user_data; + [engine engineCallbackOnPlatformMessage:message]; +} + +#pragma mark - + +@implementation FlutterEngine { + // The embedding-API-level engine object. + FLUTTER_API_SYMBOL(FlutterEngine) _engine; + + // The project being run by this engine. + FlutterDartProject* _project; + + // A mapping of channel names to the registered information for those channels. + NSMutableDictionary* _messengerHandlers; + + // A self-incremental integer to assign to newly assigned channels as + // identification. + FlutterBinaryMessengerConnection _currentMessengerConnection; + + // Whether the engine can continue running after the view controller is removed. + BOOL _allowHeadlessExecution; + + // Pointer to the Dart AOT snapshot and instruction data. + _FlutterEngineAOTData* _aotData; + + // _macOSCompositor is created when the engine is created and its destruction is handled by ARC + // when the engine is destroyed. + std::unique_ptr _macOSCompositor; + + // The information of all views attached to this engine mapped from IDs. + // + // It can't use NSDictionary, because the values need to be weak references. + NSMapTable* _viewControllers; + + // FlutterCompositor is copied and used in embedder.cc. + FlutterCompositor _compositor; + + // Method channel for platform view functions. These functions include creating, disposing and + // mutating a platform view. + FlutterMethodChannel* _platformViewsChannel; + + // Used to support creation and deletion of platform views and registering platform view + // factories. Lifecycle is tied to the engine. + FlutterPlatformViewController* _platformViewController; + + // A message channel for sending user settings to the flutter engine. + FlutterBasicMessageChannel* _settingsChannel; + + // A message channel for accessibility. + FlutterBasicMessageChannel* _accessibilityChannel; + + // A method channel for miscellaneous platform functionality. + FlutterMethodChannel* _platformChannel; + + // Whether the application is currently the active application. + BOOL _active; + + // Whether any portion of the application is currently visible. + BOOL _visible; + + // Proxy to allow plugins, channels to hold a weak reference to the binary messenger (self). + FlutterBinaryMessengerRelay* _binaryMessenger; + + // Map from ViewId to vsync waiter. Note that this is modified on main thread + // but accessed on UI thread, so access must be @synchronized. + NSMapTable* _vsyncWaiters; + + // Weak reference to last view that received a pointer event. This is used to + // pair cursor change with a view. + __weak FlutterView* _lastViewWithPointerEvent; + + // Pointer to a keyboard manager. + FlutterKeyboardManager* _keyboardManager; + + // The text input plugin that handles text editing state for text fields. + FlutterTextInputPlugin* _textInputPlugin; +} + +- (instancetype)initWithName:(NSString*)labelPrefix project:(FlutterDartProject*)project { + return [self initWithName:labelPrefix project:project allowHeadlessExecution:YES]; +} + +static const int kMainThreadPriority = 47; + +static void SetThreadPriority(FlutterThreadPriority priority) { + if (priority == kDisplay || priority == kRaster) { + pthread_t thread = pthread_self(); + sched_param param; + int policy; + if (!pthread_getschedparam(thread, &policy, ¶m)) { + param.sched_priority = kMainThreadPriority; + pthread_setschedparam(thread, policy, ¶m); + } + pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0); + } +} + +- (instancetype)initWithName:(NSString*)labelPrefix + project:(FlutterDartProject*)project + allowHeadlessExecution:(BOOL)allowHeadlessExecution { + self = [super init]; + NSAssert(self, @"Super init cannot be nil"); + + [FlutterRunLoop ensureMainLoopInitialized]; + + _pasteboard = [[FlutterPasteboard alloc] init]; + _active = NO; + _visible = NO; + _project = project ?: [[FlutterDartProject alloc] init]; + _messengerHandlers = [[NSMutableDictionary alloc] init]; + _binaryMessenger = [[FlutterBinaryMessengerRelay alloc] initWithParent:self]; + _pluginAppDelegates = [NSPointerArray weakObjectsPointerArray]; + _pluginRegistrars = [[NSMutableDictionary alloc] init]; + _currentMessengerConnection = 1; + _allowHeadlessExecution = allowHeadlessExecution; + _semanticsEnabled = NO; + _binaryMessenger = [[FlutterBinaryMessengerRelay alloc] initWithParent:self]; + _isResponseValid = [[NSMutableArray alloc] initWithCapacity:1]; + [_isResponseValid addObject:@YES]; + _keyboardManager = [[FlutterKeyboardManager alloc] initWithDelegate:self]; + _textInputPlugin = [[FlutterTextInputPlugin alloc] initWithDelegate:self]; + + _embedderAPI.struct_size = sizeof(FlutterEngineProcTable); + FlutterEngineGetProcAddresses(&_embedderAPI); + + _viewControllers = [NSMapTable weakToWeakObjectsMapTable]; + _renderer = [[FlutterRenderer alloc] initWithFlutterEngine:self]; + + NSNotificationCenter* notificationCenter = [NSNotificationCenter defaultCenter]; + [notificationCenter addObserver:self + selector:@selector(sendUserLocales) + name:NSCurrentLocaleDidChangeNotification + object:nil]; + + _platformViewController = [[FlutterPlatformViewController alloc] init]; + // The macOS compositor must be initialized in the initializer because it is + // used when adding views, which might happen before runWithEntrypoint. + _macOSCompositor = std::make_unique( + [[FlutterViewEngineProvider alloc] initWithEngine:self], + [[FlutterTimeConverter alloc] initWithEngine:self], _platformViewController); + + [self setUpPlatformViewChannel]; + [self setUpAccessibilityChannel]; + [self setUpNotificationCenterListeners]; + id appDelegate = [[NSApplication sharedApplication] delegate]; + if ([appDelegate conformsToProtocol:@protocol(FlutterAppLifecycleProvider)]) { + _terminationHandler = [[FlutterEngineTerminationHandler alloc] initWithEngine:self + terminator:nil]; + id lifecycleProvider = + static_cast>(appDelegate); + [lifecycleProvider addApplicationLifecycleDelegate:self]; + } else { + _terminationHandler = nil; + } + + _vsyncWaiters = [NSMapTable strongToStrongObjectsMapTable]; + + return self; +} + +- (void)dealloc { + id appDelegate = [[NSApplication sharedApplication] delegate]; + if ([appDelegate conformsToProtocol:@protocol(FlutterAppLifecycleProvider)]) { + id lifecycleProvider = + static_cast>(appDelegate); + [lifecycleProvider removeApplicationLifecycleDelegate:self]; + + // Unregister any plugins that registered as app delegates, since they are not guaranteed to + // live after the engine is destroyed, and their delegation registration is intended to be bound + // to the engine and its lifetime. + for (id delegate in _pluginAppDelegates) { + if (delegate) { + [lifecycleProvider removeApplicationLifecycleDelegate:delegate]; + } + } + } + // Clear any published values, just in case a plugin has created a retain cycle with the + // registrar. + for (NSString* pluginName in _pluginRegistrars) { + [_pluginRegistrars[pluginName] publish:[NSNull null]]; + } + @synchronized(_isResponseValid) { + [_isResponseValid removeAllObjects]; + [_isResponseValid addObject:@NO]; + } + [self shutDownEngine]; + if (_aotData) { + _embedderAPI.CollectAOTData(_aotData); + } +} + +- (FlutterTaskRunnerDescription)createPlatformThreadTaskDescription { + static size_t sTaskRunnerIdentifiers = 0; + FlutterTaskRunnerDescription cocoa_task_runner_description = { + .struct_size = sizeof(FlutterTaskRunnerDescription), + // Retain for use in post_task_callback. Released in destruction_callback. + .user_data = (__bridge_retained void*)self, + .runs_task_on_current_thread_callback = [](void* user_data) -> bool { + return [[NSThread currentThread] isMainThread]; + }, + .post_task_callback = [](FlutterTask task, uint64_t target_time_nanos, + void* user_data) -> void { + FlutterEngine* engine = (__bridge FlutterEngine*)user_data; + [engine postMainThreadTask:task targetTimeInNanoseconds:target_time_nanos]; + }, + .identifier = ++sTaskRunnerIdentifiers, + .destruction_callback = + [](void* user_data) { + // Balancing release for the retain when setting user_data above. + FlutterEngine* engine = (__bridge_transfer FlutterEngine*)user_data; + engine = nil; + }, + }; + return cocoa_task_runner_description; +} + +- (BOOL)runWithEntrypoint:(NSString*)entrypoint { + if (self.running) { + return NO; + } + + if (!_allowHeadlessExecution && [_viewControllers count] == 0) { + NSLog(@"Attempted to run an engine with no view controller without headless mode enabled."); + return NO; + } + + [self addInternalPlugins]; + + // The first argument of argv is required to be the executable name. + std::vector argv = {[self.executableName UTF8String]}; + std::vector switches = self.switches; + + // Enable Impeller only if specifically asked for from the project or cmdline arguments. + if (_project.enableImpeller || + std::find(switches.begin(), switches.end(), "--enable-impeller=true") != switches.end()) { + switches.push_back("--enable-impeller=true"); + } + + std::transform(switches.begin(), switches.end(), std::back_inserter(argv), + [](const std::string& arg) -> const char* { return arg.c_str(); }); + + std::vector dartEntrypointArgs; + for (NSString* argument in [_project dartEntrypointArguments]) { + dartEntrypointArgs.push_back([argument UTF8String]); + } + + FlutterProjectArgs flutterArguments = {}; + flutterArguments.struct_size = sizeof(FlutterProjectArgs); + flutterArguments.assets_path = _project.assetsPath.UTF8String; + flutterArguments.icu_data_path = _project.ICUDataPath.UTF8String; + flutterArguments.command_line_argc = static_cast(argv.size()); + flutterArguments.command_line_argv = argv.empty() ? nullptr : argv.data(); + flutterArguments.platform_message_callback = (FlutterPlatformMessageCallback)OnPlatformMessage; + flutterArguments.update_semantics_callback2 = [](const FlutterSemanticsUpdate2* update, + void* user_data) { + // TODO(dkwingsmt): This callback only supports single-view, therefore it + // only operates on the implicit view. To support multi-view, we need a + // way to pass in the ID (probably through FlutterSemanticsUpdate). + FlutterEngine* engine = (__bridge FlutterEngine*)user_data; + [[engine viewControllerForIdentifier:kFlutterImplicitViewId] updateSemantics:update]; + }; + flutterArguments.custom_dart_entrypoint = entrypoint.UTF8String; + flutterArguments.shutdown_dart_vm_when_done = true; + flutterArguments.dart_entrypoint_argc = dartEntrypointArgs.size(); + flutterArguments.dart_entrypoint_argv = dartEntrypointArgs.data(); + flutterArguments.root_isolate_create_callback = _project.rootIsolateCreateCallback; + flutterArguments.log_message_callback = [](const char* tag, const char* message, + void* user_data) { + if (tag && tag[0]) { + std::cout << tag << ": "; + } + std::cout << message << std::endl; + }; + + flutterArguments.engine_id = reinterpret_cast((__bridge void*)self); + + BOOL mergedPlatformUIThread = NO; + NSNumber* enableMergedPlatformUIThread = + [[NSBundle mainBundle] objectForInfoDictionaryKey:@"FLTEnableMergedPlatformUIThread"]; + if (enableMergedPlatformUIThread != nil) { + mergedPlatformUIThread = enableMergedPlatformUIThread.boolValue; + } + + if (mergedPlatformUIThread) { + NSLog(@"Running with merged UI and platform thread. Experimental."); + } + + // The task description needs to be created separately for platform task + // runner and UI task runner because each one has their own __bridge_retained + // engine user data. + FlutterTaskRunnerDescription platformTaskRunnerDescription = + [self createPlatformThreadTaskDescription]; + std::optional uiTaskRunnerDescription; + if (mergedPlatformUIThread) { + uiTaskRunnerDescription = [self createPlatformThreadTaskDescription]; + } + + const FlutterCustomTaskRunners custom_task_runners = { + .struct_size = sizeof(FlutterCustomTaskRunners), + .platform_task_runner = &platformTaskRunnerDescription, + .thread_priority_setter = SetThreadPriority, + .ui_task_runner = uiTaskRunnerDescription ? &uiTaskRunnerDescription.value() : nullptr, + }; + flutterArguments.custom_task_runners = &custom_task_runners; + + [self loadAOTData:_project.assetsPath]; + if (_aotData) { + flutterArguments.aot_data = _aotData; + } + + flutterArguments.compositor = [self createFlutterCompositor]; + + flutterArguments.on_pre_engine_restart_callback = [](void* user_data) { + FlutterEngine* engine = (__bridge FlutterEngine*)user_data; + [engine engineCallbackOnPreEngineRestart]; + }; + + flutterArguments.vsync_callback = [](void* user_data, intptr_t baton) { + FlutterEngine* engine = (__bridge FlutterEngine*)user_data; + [engine onVSync:baton]; + }; + + FlutterRendererConfig rendererConfig = [_renderer createRendererConfig]; + FlutterEngineResult result = _embedderAPI.Initialize( + FLUTTER_ENGINE_VERSION, &rendererConfig, &flutterArguments, (__bridge void*)(self), &_engine); + if (result != kSuccess) { + NSLog(@"Failed to initialize Flutter engine: error %d", result); + return NO; + } + + result = _embedderAPI.RunInitialized(_engine); + if (result != kSuccess) { + NSLog(@"Failed to run an initialized engine: error %d", result); + return NO; + } + + [self sendUserLocales]; + + // Update window metric for all view controllers. + NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator]; + FlutterViewController* nextViewController; + while ((nextViewController = [viewControllerEnumerator nextObject])) { + [self updateWindowMetricsForViewController:nextViewController]; + } + + [self updateDisplayConfig]; + // Send the initial user settings such as brightness and text scale factor + // to the engine. + [self sendInitialSettings]; + return YES; +} + +- (void)loadAOTData:(NSString*)assetsDir { + if (!_embedderAPI.RunsAOTCompiledDartCode()) { + return; + } + + BOOL isDirOut = false; // required for NSFileManager fileExistsAtPath. + NSFileManager* fileManager = [NSFileManager defaultManager]; + + // This is the location where the test fixture places the snapshot file. + // For applications built by Flutter tool, this is in "App.framework". + NSString* elfPath = [NSString pathWithComponents:@[ assetsDir, @"app_elf_snapshot.so" ]]; + + if (![fileManager fileExistsAtPath:elfPath isDirectory:&isDirOut]) { + return; + } + + FlutterEngineAOTDataSource source = {}; + source.type = kFlutterEngineAOTDataSourceTypeElfPath; + source.elf_path = [elfPath cStringUsingEncoding:NSUTF8StringEncoding]; + + auto result = _embedderAPI.CreateAOTData(&source, &_aotData); + if (result != kSuccess) { + NSLog(@"Failed to load AOT data from: %@", elfPath); + } +} + +- (void)registerViewController:(FlutterViewController*)controller + forIdentifier:(FlutterViewIdentifier)viewIdentifier { + _macOSCompositor->AddView(viewIdentifier); + NSAssert(controller != nil, @"The controller must not be nil."); + NSAssert(controller.engine == nil, + @"The FlutterViewController is unexpectedly attached to " + @"engine %@ before initialization.", + controller.engine); + NSAssert([_viewControllers objectForKey:@(viewIdentifier)] == nil, + @"The requested view ID is occupied."); + [_viewControllers setObject:controller forKey:@(viewIdentifier)]; + [controller setUpWithEngine:self viewIdentifier:viewIdentifier]; + NSAssert(controller.viewIdentifier == viewIdentifier, @"Failed to assign view ID."); + // Verify that the controller's property are updated accordingly. Failing the + // assertions is likely because either the FlutterViewController or the + // FlutterEngine is mocked. Please subclass these classes instead. + NSAssert(controller.attached, @"The FlutterViewController should switch to the attached mode " + @"after it is added to a FlutterEngine."); + NSAssert(controller.engine == self, + @"The FlutterViewController was added to %@, but its engine unexpectedly became %@.", + self, controller.engine); + + if (controller.viewLoaded) { + [self viewControllerViewDidLoad:controller]; + } +} + +- (void)viewControllerViewDidLoad:(FlutterViewController*)viewController { + __weak FlutterEngine* weakSelf = self; + FlutterTimeConverter* timeConverter = [[FlutterTimeConverter alloc] initWithEngine:self]; + FlutterVSyncWaiter* waiter = [[FlutterVSyncWaiter alloc] + initWithDisplayLink:[FlutterDisplayLink displayLinkWithView:viewController.view] + block:^(CFTimeInterval timestamp, CFTimeInterval targetTimestamp, + uintptr_t baton) { + uint64_t timeNanos = [timeConverter CAMediaTimeToEngineTime:timestamp]; + uint64_t targetTimeNanos = + [timeConverter CAMediaTimeToEngineTime:targetTimestamp]; + FlutterEngine* engine = weakSelf; + if (engine) { + engine->_embedderAPI.OnVsync(_engine, baton, timeNanos, targetTimeNanos); + } + }]; + FML_DCHECK([_vsyncWaiters objectForKey:@(viewController.viewIdentifier)] == nil); + @synchronized(_vsyncWaiters) { + [_vsyncWaiters setObject:waiter forKey:@(viewController.viewIdentifier)]; + } +} + +- (void)deregisterViewControllerForIdentifier:(FlutterViewIdentifier)viewIdentifier { + _macOSCompositor->RemoveView(viewIdentifier); + FlutterViewController* controller = [self viewControllerForIdentifier:viewIdentifier]; + // The controller can be nil. The engine stores only a weak ref, and this + // method could have been called from the controller's dealloc. + if (controller != nil) { + [controller detachFromEngine]; + NSAssert(!controller.attached, + @"The FlutterViewController unexpectedly stays attached after being removed. " + @"In unit tests, this is likely because either the FlutterViewController or " + @"the FlutterEngine is mocked. Please subclass these classes instead."); + } + [_viewControllers removeObjectForKey:@(viewIdentifier)]; + @synchronized(_vsyncWaiters) { + [_vsyncWaiters removeObjectForKey:@(viewIdentifier)]; + } +} + +- (void)shutDownIfNeeded { + if ([_viewControllers count] == 0 && !_allowHeadlessExecution) { + [self shutDownEngine]; + } +} + +- (FlutterViewController*)viewControllerForIdentifier:(FlutterViewIdentifier)viewIdentifier { + FlutterViewController* controller = [_viewControllers objectForKey:@(viewIdentifier)]; + NSAssert(controller == nil || controller.viewIdentifier == viewIdentifier, + @"The stored controller has unexpected view ID."); + return controller; +} + +- (void)setViewController:(FlutterViewController*)controller { + FlutterViewController* currentController = + [_viewControllers objectForKey:@(kFlutterImplicitViewId)]; + if (currentController == controller) { + // From nil to nil, or from non-nil to the same controller. + return; + } + if (currentController == nil && controller != nil) { + // From nil to non-nil. + NSAssert(controller.engine == nil, + @"Failed to set view controller to the engine: " + @"The given FlutterViewController is already attached to an engine %@. " + @"If you wanted to create an FlutterViewController and set it to an existing engine, " + @"you should use FlutterViewController#init(engine:, nibName, bundle:) instead.", + controller.engine); + [self registerViewController:controller forIdentifier:kFlutterImplicitViewId]; + } else if (currentController != nil && controller == nil) { + NSAssert(currentController.viewIdentifier == kFlutterImplicitViewId, + @"The default controller has an unexpected ID %llu", currentController.viewIdentifier); + // From non-nil to nil. + [self deregisterViewControllerForIdentifier:kFlutterImplicitViewId]; + [self shutDownIfNeeded]; + } else { + // From non-nil to a different non-nil view controller. + NSAssert(NO, + @"Failed to set view controller to the engine: " + @"The engine already has an implicit view controller %@. " + @"If you wanted to make the implicit view render in a different window, " + @"you should attach the current view controller to the window instead.", + [_viewControllers objectForKey:@(kFlutterImplicitViewId)]); + } +} + +- (FlutterViewController*)viewController { + return [self viewControllerForIdentifier:kFlutterImplicitViewId]; +} + +- (FlutterCompositor*)createFlutterCompositor { + _compositor = {}; + _compositor.struct_size = sizeof(FlutterCompositor); + _compositor.user_data = _macOSCompositor.get(); + + _compositor.create_backing_store_callback = [](const FlutterBackingStoreConfig* config, // + FlutterBackingStore* backing_store_out, // + void* user_data // + ) { + return reinterpret_cast(user_data)->CreateBackingStore( + config, backing_store_out); + }; + + _compositor.collect_backing_store_callback = [](const FlutterBackingStore* backing_store, // + void* user_data // + ) { return true; }; + + _compositor.present_view_callback = [](const FlutterPresentViewInfo* info) { + return reinterpret_cast(info->user_data) + ->Present(info->view_id, info->layers, info->layers_count); + }; + + _compositor.avoid_backing_store_cache = true; + + return &_compositor; +} + +- (id)binaryMessenger { + return _binaryMessenger; +} + +#pragma mark - Framework-internal methods + +- (void)addViewController:(FlutterViewController*)controller { + // FlutterEngine can only handle the implicit view for now. Adding more views + // throws an assertion. + NSAssert(self.viewController == nil, + @"The engine already has a view controller for the implicit view."); + self.viewController = controller; +} + +- (void)removeViewController:(nonnull FlutterViewController*)viewController { + [self deregisterViewControllerForIdentifier:viewController.viewIdentifier]; + [self shutDownIfNeeded]; +} + +- (BOOL)running { + return _engine != nullptr; +} + +- (void)updateDisplayConfig:(NSNotification*)notification { + [self updateDisplayConfig]; +} + +- (NSArray*)screens { + return [NSScreen screens]; +} + +- (void)updateDisplayConfig { + if (!_engine) { + return; + } + + std::vector displays; + for (NSScreen* screen : [self screens]) { + CGDirectDisplayID displayID = + static_cast([screen.deviceDescription[@"NSScreenNumber"] integerValue]); + + double devicePixelRatio = screen.backingScaleFactor; + FlutterEngineDisplay display; + display.struct_size = sizeof(display); + display.display_id = displayID; + display.single_display = false; + display.width = static_cast(screen.frame.size.width) * devicePixelRatio; + display.height = static_cast(screen.frame.size.height) * devicePixelRatio; + display.device_pixel_ratio = devicePixelRatio; + + CVDisplayLinkRef displayLinkRef = nil; + CVReturn error = CVDisplayLinkCreateWithCGDisplay(displayID, &displayLinkRef); + + if (error == 0) { + CVTime nominal = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(displayLinkRef); + if (!(nominal.flags & kCVTimeIsIndefinite)) { + double refreshRate = static_cast(nominal.timeScale) / nominal.timeValue; + display.refresh_rate = round(refreshRate); + } + CVDisplayLinkRelease(displayLinkRef); + } else { + display.refresh_rate = 0; + } + + displays.push_back(display); + } + _embedderAPI.NotifyDisplayUpdate(_engine, kFlutterEngineDisplaysUpdateTypeStartup, + displays.data(), displays.size()); +} + +- (void)onSettingsChanged:(NSNotification*)notification { + // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/32015. + NSString* brightness = + [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"]; + [_settingsChannel sendMessage:@{ + @"platformBrightness" : [brightness isEqualToString:@"Dark"] ? @"dark" : @"light", + // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/32006. + @"textScaleFactor" : @1.0, + @"alwaysUse24HourFormat" : @([FlutterHourFormat isAlwaysUse24HourFormat]), + }]; +} + +- (void)sendInitialSettings { + // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/32015. + [[NSDistributedNotificationCenter defaultCenter] + addObserver:self + selector:@selector(onSettingsChanged:) + name:@"AppleInterfaceThemeChangedNotification" + object:nil]; + [self onSettingsChanged:nil]; +} + +- (FlutterEngineProcTable&)embedderAPI { + return _embedderAPI; +} + +- (nonnull NSString*)executableName { + return [[[NSProcessInfo processInfo] arguments] firstObject] ?: @"Flutter"; +} + +- (void)updateWindowMetricsForViewController:(FlutterViewController*)viewController { + if (!_engine || !viewController || !viewController.viewLoaded) { + return; + } + NSAssert([self viewControllerForIdentifier:viewController.viewIdentifier] == viewController, + @"The provided view controller is not attached to this engine."); + NSView* view = viewController.flutterView; + CGRect scaledBounds = [view convertRectToBacking:view.bounds]; + CGSize scaledSize = scaledBounds.size; + double pixelRatio = view.bounds.size.width == 0 ? 1 : scaledSize.width / view.bounds.size.width; + auto displayId = [view.window.screen.deviceDescription[@"NSScreenNumber"] integerValue]; + const FlutterWindowMetricsEvent windowMetricsEvent = { + .struct_size = sizeof(windowMetricsEvent), + .width = static_cast(scaledSize.width), + .height = static_cast(scaledSize.height), + .pixel_ratio = pixelRatio, + .left = static_cast(scaledBounds.origin.x), + .top = static_cast(scaledBounds.origin.y), + .display_id = static_cast(displayId), + .view_id = viewController.viewIdentifier, + }; + _embedderAPI.SendWindowMetricsEvent(_engine, &windowMetricsEvent); +} + +- (void)sendPointerEvent:(const FlutterPointerEvent&)event { + _embedderAPI.SendPointerEvent(_engine, &event, 1); + _lastViewWithPointerEvent = [self viewControllerForIdentifier:kFlutterImplicitViewId].flutterView; +} + +- (void)setSemanticsEnabled:(BOOL)enabled { + if (_semanticsEnabled == enabled) { + return; + } + _semanticsEnabled = enabled; + + // Update all view controllers' bridges. + NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator]; + FlutterViewController* nextViewController; + while ((nextViewController = [viewControllerEnumerator nextObject])) { + [nextViewController notifySemanticsEnabledChanged]; + } + + _embedderAPI.UpdateSemanticsEnabled(_engine, _semanticsEnabled); +} + +- (void)dispatchSemanticsAction:(FlutterSemanticsAction)action + toTarget:(uint16_t)target + withData:(fml::MallocMapping)data { + _embedderAPI.DispatchSemanticsAction(_engine, target, action, data.GetMapping(), data.GetSize()); +} + +- (FlutterPlatformViewController*)platformViewController { + return _platformViewController; +} + +#pragma mark - Private methods + +- (void)sendUserLocales { + if (!self.running) { + return; + } + + // Create a list of FlutterLocales corresponding to the preferred languages. + NSMutableArray* locales = [NSMutableArray array]; + std::vector flutterLocales; + flutterLocales.reserve(locales.count); + for (NSString* localeID in [NSLocale preferredLanguages]) { + NSLocale* locale = [[NSLocale alloc] initWithLocaleIdentifier:localeID]; + [locales addObject:locale]; + flutterLocales.push_back(FlutterLocaleFromNSLocale(locale)); + } + // Convert to a list of pointers, and send to the engine. + std::vector flutterLocaleList; + flutterLocaleList.reserve(flutterLocales.size()); + std::transform(flutterLocales.begin(), flutterLocales.end(), + std::back_inserter(flutterLocaleList), + [](const auto& arg) -> const auto* { return &arg; }); + _embedderAPI.UpdateLocales(_engine, flutterLocaleList.data(), flutterLocaleList.size()); +} + +- (void)engineCallbackOnPlatformMessage:(const FlutterPlatformMessage*)message { + NSData* messageData = nil; + if (message->message_size > 0) { + messageData = [NSData dataWithBytesNoCopy:(void*)message->message + length:message->message_size + freeWhenDone:NO]; + } + NSString* channel = @(message->channel); + __block const FlutterPlatformMessageResponseHandle* responseHandle = message->response_handle; + __block FlutterEngine* weakSelf = self; + NSMutableArray* isResponseValid = self.isResponseValid; + FlutterEngineSendPlatformMessageResponseFnPtr sendPlatformMessageResponse = + _embedderAPI.SendPlatformMessageResponse; + FlutterBinaryReply binaryResponseHandler = ^(NSData* response) { + @synchronized(isResponseValid) { + if (![isResponseValid[0] boolValue]) { + // Ignore, engine was killed. + return; + } + if (responseHandle) { + sendPlatformMessageResponse(weakSelf->_engine, responseHandle, + static_cast(response.bytes), response.length); + responseHandle = NULL; + } else { + NSLog(@"Error: Message responses can be sent only once. Ignoring duplicate response " + "on channel '%@'.", + channel); + } + } + }; + + FlutterEngineHandlerInfo* handlerInfo = _messengerHandlers[channel]; + if (handlerInfo) { + handlerInfo.handler(messageData, binaryResponseHandler); + } else { + binaryResponseHandler(nil); + } +} + +- (void)engineCallbackOnPreEngineRestart { + NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator]; + FlutterViewController* nextViewController; + while ((nextViewController = [viewControllerEnumerator nextObject])) { + [nextViewController onPreEngineRestart]; + } + [_platformViewController reset]; + _keyboardManager = [[FlutterKeyboardManager alloc] initWithDelegate:self]; +} + +// This will be called on UI thread, which maybe or may not be platform thread, +// depending on the configuration. +- (void)onVSync:(uintptr_t)baton { + auto block = ^{ + // TODO(knopp): Use vsync waiter for correct view. + // https://github.com/flutter/flutter/issues/142845 + FlutterVSyncWaiter* waiter = [_vsyncWaiters objectForKey:@(kFlutterImplicitViewId)]; + [waiter waitForVSync:baton]; + }; + if ([NSThread isMainThread]) { + block(); + } else { + [FlutterRunLoop.mainRunLoop performBlock:block]; + } +} + +/** + * Note: Called from dealloc. Should not use accessors or other methods. + */ +- (void)shutDownEngine { + if (_engine == nullptr) { + return; + } + + FlutterEngineResult result = _embedderAPI.Deinitialize(_engine); + if (result != kSuccess) { + NSLog(@"Could not de-initialize the Flutter engine: error %d", result); + } + + result = _embedderAPI.Shutdown(_engine); + if (result != kSuccess) { + NSLog(@"Failed to shut down Flutter engine: error %d", result); + } + _engine = nullptr; +} + ++ (FlutterEngine*)engineForIdentifier:(int64_t)identifier { + NSAssert([[NSThread currentThread] isMainThread], @"Must be called on the main thread."); + return (__bridge FlutterEngine*)reinterpret_cast(identifier); +} + +- (void)setUpPlatformViewChannel { + _platformViewsChannel = + [FlutterMethodChannel methodChannelWithName:@"flutter/platform_views" + binaryMessenger:self.binaryMessenger + codec:[FlutterStandardMethodCodec sharedInstance]]; + + __weak FlutterEngine* weakSelf = self; + [_platformViewsChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { + [[weakSelf platformViewController] handleMethodCall:call result:result]; + }]; +} + +- (void)setUpAccessibilityChannel { + _accessibilityChannel = [FlutterBasicMessageChannel + messageChannelWithName:@"flutter/accessibility" + binaryMessenger:self.binaryMessenger + codec:[FlutterStandardMessageCodec sharedInstance]]; + __weak FlutterEngine* weakSelf = self; + [_accessibilityChannel setMessageHandler:^(id message, FlutterReply reply) { + [weakSelf handleAccessibilityEvent:message]; + }]; +} +- (void)setUpNotificationCenterListeners { + NSNotificationCenter* center = [NSNotificationCenter defaultCenter]; + // macOS fires this private message when VoiceOver turns on or off. + [center addObserver:self + selector:@selector(onAccessibilityStatusChanged:) + name:kEnhancedUserInterfaceNotification + object:nil]; + [center addObserver:self + selector:@selector(applicationWillTerminate:) + name:NSApplicationWillTerminateNotification + object:nil]; + [center addObserver:self + selector:@selector(windowDidChangeScreen:) + name:NSWindowDidChangeScreenNotification + object:nil]; + [center addObserver:self + selector:@selector(updateDisplayConfig:) + name:NSApplicationDidChangeScreenParametersNotification + object:nil]; +} + +- (void)addInternalPlugins { + __weak FlutterEngine* weakSelf = self; + [FlutterMouseCursorPlugin registerWithRegistrar:[self registrarForPlugin:@"mousecursor"] + delegate:self]; + [FlutterMenuPlugin registerWithRegistrar:[self registrarForPlugin:@"menu"]]; + _settingsChannel = + [FlutterBasicMessageChannel messageChannelWithName:kFlutterSettingsChannel + binaryMessenger:self.binaryMessenger + codec:[FlutterJSONMessageCodec sharedInstance]]; + _platformChannel = + [FlutterMethodChannel methodChannelWithName:kFlutterPlatformChannel + binaryMessenger:self.binaryMessenger + codec:[FlutterJSONMethodCodec sharedInstance]]; + [_platformChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { + [weakSelf handleMethodCall:call result:result]; + }]; +} + +- (void)didUpdateMouseCursor:(NSCursor*)cursor { + // Mouse cursor plugin does not specify which view is responsible for changing the cursor, + // so the reasonable assumption here is that cursor change is a result of a mouse movement + // and thus the cursor will be paired with last Flutter view that reveived mouse event. + [_lastViewWithPointerEvent didUpdateMouseCursor:cursor]; +} + +- (void)applicationWillTerminate:(NSNotification*)notification { + [self shutDownEngine]; +} + +- (void)windowDidChangeScreen:(NSNotification*)notification { + // Update window metric for all view controllers since the display_id has + // changed. + NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator]; + FlutterViewController* nextViewController; + while ((nextViewController = [viewControllerEnumerator nextObject])) { + [self updateWindowMetricsForViewController:nextViewController]; + } +} + +- (void)onAccessibilityStatusChanged:(NSNotification*)notification { + BOOL enabled = [notification.userInfo[kEnhancedUserInterfaceKey] boolValue]; + NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator]; + FlutterViewController* nextViewController; + while ((nextViewController = [viewControllerEnumerator nextObject])) { + [nextViewController onAccessibilityStatusChanged:enabled]; + } + + self.semanticsEnabled = enabled; +} +- (void)handleAccessibilityEvent:(NSDictionary*)annotatedEvent { + NSString* type = annotatedEvent[@"type"]; + if ([type isEqualToString:@"announce"]) { + NSString* message = annotatedEvent[@"data"][@"message"]; + NSNumber* assertiveness = annotatedEvent[@"data"][@"assertiveness"]; + if (message == nil) { + return; + } + + NSAccessibilityPriorityLevel priority = [assertiveness isEqualToNumber:@1] + ? NSAccessibilityPriorityHigh + : NSAccessibilityPriorityMedium; + + [self announceAccessibilityMessage:message withPriority:priority]; + } +} + +- (void)announceAccessibilityMessage:(NSString*)message + withPriority:(NSAccessibilityPriorityLevel)priority { + NSAccessibilityPostNotificationWithUserInfo( + [self viewControllerForIdentifier:kFlutterImplicitViewId].flutterView, + NSAccessibilityAnnouncementRequestedNotification, + @{NSAccessibilityAnnouncementKey : message, NSAccessibilityPriorityKey : @(priority)}); +} +- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { + if ([call.method isEqualToString:@"SystemNavigator.pop"]) { + [[NSApplication sharedApplication] terminate:self]; + result(nil); + } else if ([call.method isEqualToString:@"SystemSound.play"]) { + [self playSystemSound:call.arguments]; + result(nil); + } else if ([call.method isEqualToString:@"Clipboard.getData"]) { + result([self getClipboardData:call.arguments]); + } else if ([call.method isEqualToString:@"Clipboard.setData"]) { + [self setClipboardData:call.arguments]; + result(nil); + } else if ([call.method isEqualToString:@"Clipboard.hasStrings"]) { + result(@{@"value" : @([self clipboardHasStrings])}); + } else if ([call.method isEqualToString:@"System.exitApplication"]) { + if ([self terminationHandler] == nil) { + // If the termination handler isn't set, then either we haven't + // initialized it yet, or (more likely) the NSApp delegate isn't a + // FlutterAppDelegate, so it can't cancel requests to exit. So, in that + // case, just terminate when requested. + [NSApp terminate:self]; + result(nil); + } else { + [[self terminationHandler] handleRequestAppExitMethodCall:call.arguments result:result]; + } + } else if ([call.method isEqualToString:@"System.initializationComplete"]) { + if ([self terminationHandler] != nil) { + [self terminationHandler].acceptingRequests = YES; + } + result(nil); + } else { + result(FlutterMethodNotImplemented); + } +} + +- (void)playSystemSound:(NSString*)soundType { + if ([soundType isEqualToString:@"SystemSoundType.alert"]) { + NSBeep(); + } +} + +- (NSDictionary*)getClipboardData:(NSString*)format { + if ([format isEqualToString:@(kTextPlainFormat)]) { + NSString* stringInPasteboard = [self.pasteboard stringForType:NSPasteboardTypeString]; + return stringInPasteboard == nil ? nil : @{@"text" : stringInPasteboard}; + } + return nil; +} + +- (void)setClipboardData:(NSDictionary*)data { + NSString* text = data[@"text"]; + [self.pasteboard clearContents]; + if (text && ![text isEqual:[NSNull null]]) { + [self.pasteboard setString:text forType:NSPasteboardTypeString]; + } +} + +- (BOOL)clipboardHasStrings { + return [self.pasteboard stringForType:NSPasteboardTypeString].length > 0; +} + +- (std::vector)switches { + return flutter::GetSwitchesFromEnvironment(); +} + +#pragma mark - FlutterAppLifecycleDelegate + +- (void)setApplicationState:(flutter::AppLifecycleState)state { + NSString* nextState = + [[NSString alloc] initWithCString:flutter::AppLifecycleStateToString(state)]; + [self sendOnChannel:kFlutterLifecycleChannel + message:[nextState dataUsingEncoding:NSUTF8StringEncoding]]; +} + +/** + * Called when the |FlutterAppDelegate| gets the applicationWillBecomeActive + * notification. + */ +- (void)handleWillBecomeActive:(NSNotification*)notification { + _active = YES; + if (!_visible) { + [self setApplicationState:flutter::AppLifecycleState::kHidden]; + } else { + [self setApplicationState:flutter::AppLifecycleState::kResumed]; + } +} + +/** + * Called when the |FlutterAppDelegate| gets the applicationWillResignActive + * notification. + */ +- (void)handleWillResignActive:(NSNotification*)notification { + _active = NO; + if (!_visible) { + [self setApplicationState:flutter::AppLifecycleState::kHidden]; + } else { + [self setApplicationState:flutter::AppLifecycleState::kInactive]; + } +} + +/** + * Called when the |FlutterAppDelegate| gets the applicationDidUnhide + * notification. + */ +- (void)handleDidChangeOcclusionState:(NSNotification*)notification { + NSApplicationOcclusionState occlusionState = [[NSApplication sharedApplication] occlusionState]; + if (occlusionState & NSApplicationOcclusionStateVisible) { + _visible = YES; + if (_active) { + [self setApplicationState:flutter::AppLifecycleState::kResumed]; + } else { + [self setApplicationState:flutter::AppLifecycleState::kInactive]; + } + } else { + _visible = NO; + [self setApplicationState:flutter::AppLifecycleState::kHidden]; + } +} + +#pragma mark - FlutterBinaryMessenger + +- (void)sendOnChannel:(nonnull NSString*)channel message:(nullable NSData*)message { + [self sendOnChannel:channel message:message binaryReply:nil]; +} + +- (void)sendOnChannel:(NSString*)channel + message:(NSData* _Nullable)message + binaryReply:(FlutterBinaryReply _Nullable)callback { + FlutterPlatformMessageResponseHandle* response_handle = nullptr; + if (callback) { + struct Captures { + FlutterBinaryReply reply; + }; + auto captures = std::make_unique(); + captures->reply = callback; + auto message_reply = [](const uint8_t* data, size_t data_size, void* user_data) { + auto captures = reinterpret_cast(user_data); + NSData* reply_data = nil; + if (data != nullptr && data_size > 0) { + reply_data = [NSData dataWithBytes:static_cast(data) length:data_size]; + } + captures->reply(reply_data); + delete captures; + }; + + FlutterEngineResult create_result = _embedderAPI.PlatformMessageCreateResponseHandle( + _engine, message_reply, captures.get(), &response_handle); + if (create_result != kSuccess) { + NSLog(@"Failed to create a FlutterPlatformMessageResponseHandle (%d)", create_result); + return; + } + captures.release(); + } + + FlutterPlatformMessage platformMessage = { + .struct_size = sizeof(FlutterPlatformMessage), + .channel = [channel UTF8String], + .message = static_cast(message.bytes), + .message_size = message.length, + .response_handle = response_handle, + }; + + FlutterEngineResult message_result = _embedderAPI.SendPlatformMessage(_engine, &platformMessage); + if (message_result != kSuccess) { + NSLog(@"Failed to send message to Flutter engine on channel '%@' (%d).", channel, + message_result); + } + + if (response_handle != nullptr) { + FlutterEngineResult release_result = + _embedderAPI.PlatformMessageReleaseResponseHandle(_engine, response_handle); + if (release_result != kSuccess) { + NSLog(@"Failed to release the response handle (%d).", release_result); + }; + } +} + +- (FlutterBinaryMessengerConnection)setMessageHandlerOnChannel:(nonnull NSString*)channel + binaryMessageHandler: + (nullable FlutterBinaryMessageHandler)handler { + _currentMessengerConnection += 1; + _messengerHandlers[channel] = + [[FlutterEngineHandlerInfo alloc] initWithConnection:@(_currentMessengerConnection) + handler:[handler copy]]; + return _currentMessengerConnection; +} + +- (void)cleanUpConnection:(FlutterBinaryMessengerConnection)connection { + // Find the _messengerHandlers that has the required connection, and record its + // channel. + NSString* foundChannel = nil; + for (NSString* key in [_messengerHandlers allKeys]) { + FlutterEngineHandlerInfo* handlerInfo = [_messengerHandlers objectForKey:key]; + if ([handlerInfo.connection isEqual:@(connection)]) { + foundChannel = key; + break; + } + } + if (foundChannel) { + [_messengerHandlers removeObjectForKey:foundChannel]; + } +} + +#pragma mark - FlutterPluginRegistry + +- (id)registrarForPlugin:(NSString*)pluginName { + id registrar = self.pluginRegistrars[pluginName]; + if (!registrar) { + FlutterEngineRegistrar* registrarImpl = + [[FlutterEngineRegistrar alloc] initWithPlugin:pluginName flutterEngine:self]; + self.pluginRegistrars[pluginName] = registrarImpl; + registrar = registrarImpl; + } + return registrar; +} + +- (nullable NSObject*)valuePublishedByPlugin:(NSString*)pluginName { + return self.pluginRegistrars[pluginName].publishedValue; +} + +#pragma mark - FlutterTextureRegistrar + +- (int64_t)registerTexture:(id)texture { + return [_renderer registerTexture:texture]; +} + +- (BOOL)registerTextureWithID:(int64_t)textureId { + return _embedderAPI.RegisterExternalTexture(_engine, textureId) == kSuccess; +} + +- (void)textureFrameAvailable:(int64_t)textureID { + [_renderer textureFrameAvailable:textureID]; +} + +- (BOOL)markTextureFrameAvailable:(int64_t)textureID { + return _embedderAPI.MarkExternalTextureFrameAvailable(_engine, textureID) == kSuccess; +} + +- (void)unregisterTexture:(int64_t)textureID { + [_renderer unregisterTexture:textureID]; +} + +- (BOOL)unregisterTextureWithID:(int64_t)textureID { + return _embedderAPI.UnregisterExternalTexture(_engine, textureID) == kSuccess; +} + +#pragma mark - Task runner integration + +- (void)postMainThreadTask:(FlutterTask)task targetTimeInNanoseconds:(uint64_t)targetTime { + __weak FlutterEngine* weakSelf = self; + + const auto engine_time = _embedderAPI.GetCurrentTime(); + [FlutterRunLoop.mainRunLoop + performBlock:^{ + FlutterEngine* self = weakSelf; + if (self != nil && self->_engine != nil) { + auto result = _embedderAPI.RunTask(self->_engine, &task); + if (result != kSuccess) { + NSLog(@"Could not post a task to the Flutter engine."); + } + } + } + afterDelay:(targetTime - (double)engine_time) / NSEC_PER_SEC]; +} + +// Getter used by test harness, only exposed through the FlutterEngine(Test) category +- (flutter::FlutterCompositor*)macOSCompositor { + return _macOSCompositor.get(); +} + +#pragma mark - FlutterKeyboardManagerDelegate + +/** + * Dispatches the given pointer event data to engine. + */ +- (void)sendKeyEvent:(const FlutterKeyEvent&)event + callback:(FlutterKeyEventCallback)callback + userData:(void*)userData { + _embedderAPI.SendKeyEvent(_engine, &event, callback, userData); +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..4c3d7ed6acab7f969fbb08612e97f1b88fce3307 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTest.mm @@ -0,0 +1,1350 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" +#include "shell/platform/darwin/macos/framework/Source/FlutterResizeSynchronizer.h" + +#include + +#include +#include +#include +#include + +#include "flutter/fml/synchronization/waitable_event.h" +#include "flutter/lib/ui/window/platform_message.h" +#include "flutter/shell/platform/common/accessibility_bridge.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" +#import "flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.h" +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppDelegate.h" +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppLifecycleDelegate.h" +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginMacOS.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterCompositor.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.h" +#include "flutter/shell/platform/embedder/embedder.h" +#include "flutter/shell/platform/embedder/embedder_engine.h" +#include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h" +#include "flutter/testing/stream_capture.h" +#include "flutter/testing/test_dart_native_resolver.h" +#include "gtest/gtest.h" + +// CREATE_NATIVE_ENTRY and MOCK_ENGINE_PROC are leaky by design +// NOLINTBEGIN(clang-analyzer-core.StackAddressEscape) + +@interface FlutterEngine (Test) +/** + * The FlutterCompositor object currently in use by the FlutterEngine. + * + * May be nil if the compositor has not been initialized yet. + */ +@property(nonatomic, readonly, nullable) flutter::FlutterCompositor* macOSCompositor; + +@end + +@interface TestPlatformViewFactory : NSObject +@end + +@implementation TestPlatformViewFactory +- (nonnull NSView*)createWithViewIdentifier:(FlutterViewIdentifier)viewIdentifier + arguments:(nullable id)args { + return viewIdentifier == 42 ? [[NSView alloc] init] : nil; +} + +@end + +@interface PlainAppDelegate : NSObject +@end + +@implementation PlainAppDelegate +- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication* _Nonnull)sender { + // Always cancel, so that the test doesn't exit. + return NSTerminateCancel; +} +@end + +#pragma mark - + +@interface FakeLifecycleProvider : NSObject + +@property(nonatomic, strong, readonly) NSPointerArray* registeredDelegates; + +// True if the given delegate is currently registered. +- (BOOL)hasDelegate:(nonnull NSObject*)delegate; +@end + +@implementation FakeLifecycleProvider { + /** + * All currently registered delegates. + * + * This does not use NSPointerArray or any other weak-pointer + * system, because a weak pointer will be nil'd out at the start of dealloc, which will break + * queries. E.g., if a delegate is dealloc'd without being unregistered, a weak pointer array + * would no longer contain that pointer even though removeApplicationLifecycleDelegate: was never + * called, causing tests to pass incorrectly. + */ + std::vector _delegates; +} + +- (void)addApplicationLifecycleDelegate:(nonnull NSObject*)delegate { + _delegates.push_back((__bridge void*)delegate); +} + +- (void)removeApplicationLifecycleDelegate: + (nonnull NSObject*)delegate { + auto delegateIndex = std::find(_delegates.begin(), _delegates.end(), (__bridge void*)delegate); + NSAssert(delegateIndex != _delegates.end(), + @"Attempting to unregister a delegate that was not registered."); + _delegates.erase(delegateIndex); +} + +- (BOOL)hasDelegate:(nonnull NSObject*)delegate { + return std::find(_delegates.begin(), _delegates.end(), (__bridge void*)delegate) != + _delegates.end(); +} + +@end + +#pragma mark - + +@interface FakeAppDelegatePlugin : NSObject +@end + +@implementation FakeAppDelegatePlugin ++ (void)registerWithRegistrar:(id)registrar { +} +@end + +#pragma mark - + +@interface MockableFlutterEngine : FlutterEngine +@end + +@implementation MockableFlutterEngine +- (NSArray*)screens { + id mockScreen = OCMClassMock([NSScreen class]); + OCMStub([mockScreen backingScaleFactor]).andReturn(2.0); + OCMStub([mockScreen deviceDescription]).andReturn(@{ + @"NSScreenNumber" : [NSNumber numberWithInt:10] + }); + OCMStub([mockScreen frame]).andReturn(NSMakeRect(10, 20, 30, 40)); + return [NSArray arrayWithObject:mockScreen]; +} +@end + +#pragma mark - + +namespace flutter::testing { + +TEST_F(FlutterEngineTest, CanLaunch) { + FlutterEngine* engine = GetFlutterEngine(); + EXPECT_TRUE([engine runWithEntrypoint:@"main"]); + ASSERT_TRUE(engine.running); +} + +TEST_F(FlutterEngineTest, HasNonNullExecutableName) { + FlutterEngine* engine = GetFlutterEngine(); + std::string executable_name = [[engine executableName] UTF8String]; + ASSERT_FALSE(executable_name.empty()); + + // Block until notified by the Dart test of the value of Platform.executable. + fml::AutoResetWaitableEvent latch; + AddNativeCallback("NotifyStringValue", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + const auto dart_string = tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + EXPECT_EQ(executable_name, dart_string); + latch.Signal(); + })); + + // Launch the test entrypoint. + EXPECT_TRUE([engine runWithEntrypoint:@"executableNameNotNull"]); + + latch.Wait(); +} + +#ifndef FLUTTER_RELEASE +TEST_F(FlutterEngineTest, Switches) { + setenv("FLUTTER_ENGINE_SWITCHES", "2", 1); + setenv("FLUTTER_ENGINE_SWITCH_1", "abc", 1); + setenv("FLUTTER_ENGINE_SWITCH_2", "foo=\"bar, baz\"", 1); + + FlutterEngine* engine = GetFlutterEngine(); + std::vector switches = engine.switches; + ASSERT_EQ(switches.size(), 2UL); + EXPECT_EQ(switches[0], "--abc"); + EXPECT_EQ(switches[1], "--foo=\"bar, baz\""); + + unsetenv("FLUTTER_ENGINE_SWITCHES"); + unsetenv("FLUTTER_ENGINE_SWITCH_1"); + unsetenv("FLUTTER_ENGINE_SWITCH_2"); +} +#endif // !FLUTTER_RELEASE + +TEST_F(FlutterEngineTest, MessengerSend) { + FlutterEngine* engine = GetFlutterEngine(); + EXPECT_TRUE([engine runWithEntrypoint:@"main"]); + + NSData* test_message = [@"a message" dataUsingEncoding:NSUTF8StringEncoding]; + bool called = false; + + engine.embedderAPI.SendPlatformMessage = MOCK_ENGINE_PROC( + SendPlatformMessage, ([&called, test_message](auto engine, auto message) { + called = true; + EXPECT_STREQ(message->channel, "test"); + EXPECT_EQ(memcmp(message->message, test_message.bytes, message->message_size), 0); + return kSuccess; + })); + + [engine.binaryMessenger sendOnChannel:@"test" message:test_message]; + EXPECT_TRUE(called); +} + +TEST_F(FlutterEngineTest, CanLogToStdout) { + // Block until completion of print statement. + fml::AutoResetWaitableEvent latch; + AddNativeCallback("SignalNativeTest", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch.Signal(); })); + + // Replace stdout stream buffer with our own. + StreamCapture stdout_capture(&std::cout); + + // Launch the test entrypoint. + FlutterEngine* engine = GetFlutterEngine(); + EXPECT_TRUE([engine runWithEntrypoint:@"canLogToStdout"]); + ASSERT_TRUE(engine.running); + + latch.Wait(); + + stdout_capture.Stop(); + + // Verify hello world was written to stdout. + EXPECT_TRUE(stdout_capture.GetOutput().find("Hello logging") != std::string::npos); +} + +TEST_F(FlutterEngineTest, DISABLED_BackgroundIsBlack) { + FlutterEngine* engine = GetFlutterEngine(); + + // Latch to ensure the entire layer tree has been generated and presented. + fml::AutoResetWaitableEvent latch; + AddNativeCallback("SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + CALayer* rootLayer = engine.viewController.flutterView.layer; + EXPECT_TRUE(rootLayer.backgroundColor != nil); + if (rootLayer.backgroundColor != nil) { + NSColor* actualBackgroundColor = + [NSColor colorWithCGColor:rootLayer.backgroundColor]; + EXPECT_EQ(actualBackgroundColor, [NSColor blackColor]); + } + latch.Signal(); + })); + + // Launch the test entrypoint. + EXPECT_TRUE([engine runWithEntrypoint:@"backgroundTest"]); + ASSERT_TRUE(engine.running); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + [viewController loadView]; + viewController.flutterView.frame = CGRectMake(0, 0, 800, 600); + + latch.Wait(); +} + +TEST_F(FlutterEngineTest, DISABLED_CanOverrideBackgroundColor) { + FlutterEngine* engine = GetFlutterEngine(); + + // Latch to ensure the entire layer tree has been generated and presented. + fml::AutoResetWaitableEvent latch; + AddNativeCallback("SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + CALayer* rootLayer = engine.viewController.flutterView.layer; + EXPECT_TRUE(rootLayer.backgroundColor != nil); + if (rootLayer.backgroundColor != nil) { + NSColor* actualBackgroundColor = + [NSColor colorWithCGColor:rootLayer.backgroundColor]; + EXPECT_EQ(actualBackgroundColor, [NSColor whiteColor]); + } + latch.Signal(); + })); + + // Launch the test entrypoint. + EXPECT_TRUE([engine runWithEntrypoint:@"backgroundTest"]); + ASSERT_TRUE(engine.running); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + [viewController loadView]; + viewController.flutterView.frame = CGRectMake(0, 0, 800, 600); + viewController.flutterView.backgroundColor = [NSColor whiteColor]; + + latch.Wait(); +} + +TEST_F(FlutterEngineTest, CanToggleAccessibility) { + FlutterEngine* engine = GetFlutterEngine(); + // Capture the update callbacks before the embedder API initializes. + auto original_init = engine.embedderAPI.Initialize; + std::function update_semantics_callback; + engine.embedderAPI.Initialize = MOCK_ENGINE_PROC( + Initialize, ([&update_semantics_callback, &original_init]( + size_t version, const FlutterRendererConfig* config, + const FlutterProjectArgs* args, void* user_data, auto engine_out) { + update_semantics_callback = args->update_semantics_callback2; + return original_init(version, config, args, user_data, engine_out); + })); + EXPECT_TRUE([engine runWithEntrypoint:@"main"]); + // Set up view controller. + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + [viewController loadView]; + // Enable the semantics. + bool enabled_called = false; + engine.embedderAPI.UpdateSemanticsEnabled = + MOCK_ENGINE_PROC(UpdateSemanticsEnabled, ([&enabled_called](auto engine, bool enabled) { + enabled_called = enabled; + return kSuccess; + })); + engine.semanticsEnabled = YES; + EXPECT_TRUE(enabled_called); + // Send flutter semantics updates. + FlutterSemanticsNode2 root; + root.id = 0; + root.flags = static_cast(0); + root.actions = static_cast(0); + root.text_selection_base = -1; + root.text_selection_extent = -1; + root.label = "root"; + root.hint = ""; + root.value = ""; + root.increased_value = ""; + root.decreased_value = ""; + root.tooltip = ""; + root.child_count = 1; + int32_t children[] = {1}; + root.children_in_traversal_order = children; + root.custom_accessibility_actions_count = 0; + + FlutterSemanticsNode2 child1; + child1.id = 1; + child1.flags = static_cast(0); + child1.actions = static_cast(0); + child1.text_selection_base = -1; + child1.text_selection_extent = -1; + child1.label = "child 1"; + child1.hint = ""; + child1.value = ""; + child1.increased_value = ""; + child1.decreased_value = ""; + child1.tooltip = ""; + child1.child_count = 0; + child1.custom_accessibility_actions_count = 0; + + FlutterSemanticsUpdate2 update; + update.node_count = 2; + FlutterSemanticsNode2* nodes[] = {&root, &child1}; + update.nodes = nodes; + update.custom_action_count = 0; + update_semantics_callback(&update, (__bridge void*)engine); + + // Verify the accessibility tree is attached to the flutter view. + EXPECT_EQ([engine.viewController.flutterView.accessibilityChildren count], 1u); + NSAccessibilityElement* native_root = engine.viewController.flutterView.accessibilityChildren[0]; + std::string root_label = [native_root.accessibilityLabel UTF8String]; + EXPECT_TRUE(root_label == "root"); + EXPECT_EQ(native_root.accessibilityRole, NSAccessibilityGroupRole); + EXPECT_EQ([native_root.accessibilityChildren count], 1u); + NSAccessibilityElement* native_child1 = native_root.accessibilityChildren[0]; + std::string child1_value = [native_child1.accessibilityValue UTF8String]; + EXPECT_TRUE(child1_value == "child 1"); + EXPECT_EQ(native_child1.accessibilityRole, NSAccessibilityStaticTextRole); + EXPECT_EQ([native_child1.accessibilityChildren count], 0u); + // Disable the semantics. + bool semanticsEnabled = true; + engine.embedderAPI.UpdateSemanticsEnabled = + MOCK_ENGINE_PROC(UpdateSemanticsEnabled, ([&semanticsEnabled](auto engine, bool enabled) { + semanticsEnabled = enabled; + return kSuccess; + })); + engine.semanticsEnabled = NO; + EXPECT_FALSE(semanticsEnabled); + // Verify the accessibility tree is removed from the view. + EXPECT_EQ([engine.viewController.flutterView.accessibilityChildren count], 0u); + + [engine setViewController:nil]; +} + +TEST_F(FlutterEngineTest, CanToggleAccessibilityWhenHeadless) { + FlutterEngine* engine = GetFlutterEngine(); + // Capture the update callbacks before the embedder API initializes. + auto original_init = engine.embedderAPI.Initialize; + std::function update_semantics_callback; + engine.embedderAPI.Initialize = MOCK_ENGINE_PROC( + Initialize, ([&update_semantics_callback, &original_init]( + size_t version, const FlutterRendererConfig* config, + const FlutterProjectArgs* args, void* user_data, auto engine_out) { + update_semantics_callback = args->update_semantics_callback2; + return original_init(version, config, args, user_data, engine_out); + })); + EXPECT_TRUE([engine runWithEntrypoint:@"main"]); + + // Enable the semantics without attaching a view controller. + bool enabled_called = false; + engine.embedderAPI.UpdateSemanticsEnabled = + MOCK_ENGINE_PROC(UpdateSemanticsEnabled, ([&enabled_called](auto engine, bool enabled) { + enabled_called = enabled; + return kSuccess; + })); + engine.semanticsEnabled = YES; + EXPECT_TRUE(enabled_called); + // Send flutter semantics updates. + FlutterSemanticsNode2 root; + root.id = 0; + root.flags = static_cast(0); + root.actions = static_cast(0); + root.text_selection_base = -1; + root.text_selection_extent = -1; + root.label = "root"; + root.hint = ""; + root.value = ""; + root.increased_value = ""; + root.decreased_value = ""; + root.tooltip = ""; + root.child_count = 1; + int32_t children[] = {1}; + root.children_in_traversal_order = children; + root.custom_accessibility_actions_count = 0; + + FlutterSemanticsNode2 child1; + child1.id = 1; + child1.flags = static_cast(0); + child1.actions = static_cast(0); + child1.text_selection_base = -1; + child1.text_selection_extent = -1; + child1.label = "child 1"; + child1.hint = ""; + child1.value = ""; + child1.increased_value = ""; + child1.decreased_value = ""; + child1.tooltip = ""; + child1.child_count = 0; + child1.custom_accessibility_actions_count = 0; + + FlutterSemanticsUpdate2 update; + update.node_count = 2; + FlutterSemanticsNode2* nodes[] = {&root, &child1}; + update.nodes = nodes; + update.custom_action_count = 0; + // This call updates semantics for the implicit view, which does not exist, + // and therefore this call is invalid. But the engine should not crash. + update_semantics_callback(&update, (__bridge void*)engine); + + // No crashes. + EXPECT_EQ(engine.viewController, nil); + + // Disable the semantics. + bool semanticsEnabled = true; + engine.embedderAPI.UpdateSemanticsEnabled = + MOCK_ENGINE_PROC(UpdateSemanticsEnabled, ([&semanticsEnabled](auto engine, bool enabled) { + semanticsEnabled = enabled; + return kSuccess; + })); + engine.semanticsEnabled = NO; + EXPECT_FALSE(semanticsEnabled); + // Still no crashes + EXPECT_EQ(engine.viewController, nil); +} + +TEST_F(FlutterEngineTest, ProducesAccessibilityTreeWhenAddingViews) { + FlutterEngine* engine = GetFlutterEngine(); + EXPECT_TRUE([engine runWithEntrypoint:@"main"]); + + // Enable the semantics without attaching a view controller. + bool enabled_called = false; + engine.embedderAPI.UpdateSemanticsEnabled = + MOCK_ENGINE_PROC(UpdateSemanticsEnabled, ([&enabled_called](auto engine, bool enabled) { + enabled_called = enabled; + return kSuccess; + })); + engine.semanticsEnabled = YES; + EXPECT_TRUE(enabled_called); + + EXPECT_EQ(engine.viewController, nil); + + // Assign the view controller after enabling semantics + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + engine.viewController = viewController; + + EXPECT_NE(viewController.accessibilityBridge.lock(), nullptr); +} + +TEST_F(FlutterEngineTest, NativeCallbacks) { + fml::AutoResetWaitableEvent latch; + bool latch_called = false; + AddNativeCallback("SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + latch_called = true; + latch.Signal(); + })); + + FlutterEngine* engine = GetFlutterEngine(); + EXPECT_TRUE([engine runWithEntrypoint:@"nativeCallback"]); + ASSERT_TRUE(engine.running); + + latch.Wait(); + ASSERT_TRUE(latch_called); +} + +TEST_F(FlutterEngineTest, Compositor) { + NSString* fixtures = @(flutter::testing::GetFixturesPath()); + FlutterDartProject* project = [[FlutterDartProject alloc] + initWithAssetsPath:fixtures + ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:project]; + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + [viewController loadView]; + [viewController viewDidLoad]; + viewController.flutterView.frame = CGRectMake(0, 0, 800, 600); + + EXPECT_TRUE([engine runWithEntrypoint:@"canCompositePlatformViews"]); + + [engine.platformViewController registerViewFactory:[[TestPlatformViewFactory alloc] init] + withId:@"factory_id"]; + [engine.platformViewController + handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @(42), + @"viewType" : @"factory_id", + }] + result:^(id result){ + }]; + + // Wait up to 1 second for Flutter to emit a frame. + CFAbsoluteTime start = CFAbsoluteTimeGetCurrent(); + CALayer* rootLayer = viewController.flutterView.layer; + while (rootLayer.sublayers.count == 0) { + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, YES); + if (CFAbsoluteTimeGetCurrent() - start > 1) { + break; + } + } + + // There are two layers with Flutter contents and one view + EXPECT_EQ(rootLayer.sublayers.count, 2u); + EXPECT_EQ(viewController.flutterView.subviews.count, 1u); + + // TODO(gw280): add support for screenshot tests in this test harness + + [engine shutDownEngine]; +} + +TEST_F(FlutterEngineTest, CompositorIgnoresUnknownView) { + FlutterEngine* engine = GetFlutterEngine(); + auto original_init = engine.embedderAPI.Initialize; + ::FlutterCompositor compositor; + engine.embedderAPI.Initialize = MOCK_ENGINE_PROC( + Initialize, ([&compositor, &original_init]( + size_t version, const FlutterRendererConfig* config, + const FlutterProjectArgs* args, void* user_data, auto engine_out) { + compositor = *args->compositor; + return original_init(version, config, args, user_data, engine_out); + })); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + [viewController loadView]; + + EXPECT_TRUE([engine runWithEntrypoint:@"empty"]); + + FlutterBackingStoreConfig config = { + .struct_size = sizeof(FlutterBackingStoreConfig), + .size = FlutterSize{10, 10}, + }; + FlutterBackingStore backing_store = {}; + EXPECT_NE(compositor.create_backing_store_callback, nullptr); + EXPECT_TRUE( + compositor.create_backing_store_callback(&config, &backing_store, compositor.user_data)); + + FlutterLayer layer{ + .type = kFlutterLayerContentTypeBackingStore, + .backing_store = &backing_store, + }; + std::vector layers = {&layer}; + + FlutterPresentViewInfo info = { + .struct_size = sizeof(FlutterPresentViewInfo), + .view_id = 123, + .layers = const_cast(layers.data()), + .layers_count = 1, + .user_data = compositor.user_data, + }; + EXPECT_NE(compositor.present_view_callback, nullptr); + EXPECT_FALSE(compositor.present_view_callback(&info)); + EXPECT_TRUE(compositor.collect_backing_store_callback(&backing_store, compositor.user_data)); + + (void)viewController; + [engine shutDownEngine]; +} + +TEST_F(FlutterEngineTest, DartEntrypointArguments) { + NSString* fixtures = @(flutter::testing::GetFixturesPath()); + FlutterDartProject* project = [[FlutterDartProject alloc] + initWithAssetsPath:fixtures + ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; + + project.dartEntrypointArguments = @[ @"arg1", @"arg2" ]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:project]; + + bool called = false; + auto original_init = engine.embedderAPI.Initialize; + engine.embedderAPI.Initialize = MOCK_ENGINE_PROC( + Initialize, ([&called, &original_init](size_t version, const FlutterRendererConfig* config, + const FlutterProjectArgs* args, void* user_data, + FLUTTER_API_SYMBOL(FlutterEngine) * engine_out) { + called = true; + EXPECT_EQ(args->dart_entrypoint_argc, 2); + NSString* arg1 = [[NSString alloc] initWithCString:args->dart_entrypoint_argv[0] + encoding:NSUTF8StringEncoding]; + NSString* arg2 = [[NSString alloc] initWithCString:args->dart_entrypoint_argv[1] + encoding:NSUTF8StringEncoding]; + + EXPECT_TRUE([arg1 isEqualToString:@"arg1"]); + EXPECT_TRUE([arg2 isEqualToString:@"arg2"]); + + return original_init(version, config, args, user_data, engine_out); + })); + + EXPECT_TRUE([engine runWithEntrypoint:@"main"]); + EXPECT_TRUE(called); + [engine shutDownEngine]; +} + +// Verify that the engine is not retained indirectly via the binary messenger held by channels and +// plugins. Previously, FlutterEngine.binaryMessenger returned the engine itself, and thus plugins +// could cause a retain cycle, preventing the engine from being deallocated. +// FlutterEngine.binaryMessenger now returns a FlutterBinaryMessengerRelay whose weak pointer back +// to the engine is cleared when the engine is deallocated. +// Issue: https://github.com/flutter/flutter/issues/116445 +TEST_F(FlutterEngineTest, FlutterBinaryMessengerDoesNotRetainEngine) { + __weak FlutterEngine* weakEngine; + id binaryMessenger = nil; + @autoreleasepool { + // Create a test engine. + NSString* fixtures = @(flutter::testing::GetFixturesPath()); + FlutterDartProject* project = [[FlutterDartProject alloc] + initWithAssetsPath:fixtures + ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" + project:project + allowHeadlessExecution:YES]; + weakEngine = engine; + binaryMessenger = engine.binaryMessenger; + } + + // Once the engine has been deallocated, verify the weak engine pointer is nil, and thus not + // retained by the relay. + EXPECT_NE(binaryMessenger, nil); + EXPECT_EQ(weakEngine, nil); +} + +// Verify that the engine is not retained indirectly via the texture registry held by plugins. +// Issue: https://github.com/flutter/flutter/issues/116445 +TEST_F(FlutterEngineTest, FlutterTextureRegistryDoesNotReturnEngine) { + __weak FlutterEngine* weakEngine; + id textureRegistry; + @autoreleasepool { + // Create a test engine. + NSString* fixtures = @(flutter::testing::GetFixturesPath()); + FlutterDartProject* project = [[FlutterDartProject alloc] + initWithAssetsPath:fixtures + ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" + project:project + allowHeadlessExecution:YES]; + id registrar = [engine registrarForPlugin:@"MyPlugin"]; + textureRegistry = registrar.textures; + } + + // Once the engine has been deallocated, verify the weak engine pointer is nil, and thus not + // retained via the texture registry. + EXPECT_NE(textureRegistry, nil); + EXPECT_EQ(weakEngine, nil); +} + +TEST_F(FlutterEngineTest, PublishedValueNilForUnknownPlugin) { + NSString* fixtures = @(flutter::testing::GetFixturesPath()); + FlutterDartProject* project = [[FlutterDartProject alloc] + initWithAssetsPath:fixtures + ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" + project:project + allowHeadlessExecution:YES]; + + EXPECT_EQ([engine valuePublishedByPlugin:@"NoSuchPlugin"], nil); +} + +TEST_F(FlutterEngineTest, PublishedValueNSNullIfNoPublishedValue) { + NSString* fixtures = @(flutter::testing::GetFixturesPath()); + FlutterDartProject* project = [[FlutterDartProject alloc] + initWithAssetsPath:fixtures + ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" + project:project + allowHeadlessExecution:YES]; + NSString* pluginName = @"MyPlugin"; + // Request the registarar to register the plugin as existing. + [engine registrarForPlugin:pluginName]; + + // The documented behavior is that a plugin that exists but hasn't published + // anything returns NSNull, rather than nil, as on iOS. + EXPECT_EQ([engine valuePublishedByPlugin:pluginName], [NSNull null]); +} + +TEST_F(FlutterEngineTest, PublishedValueReturnsLastPublished) { + NSString* fixtures = @(flutter::testing::GetFixturesPath()); + FlutterDartProject* project = [[FlutterDartProject alloc] + initWithAssetsPath:fixtures + ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" + project:project + allowHeadlessExecution:YES]; + NSString* pluginName = @"MyPlugin"; + id registrar = [engine registrarForPlugin:pluginName]; + + NSString* firstValue = @"A published value"; + NSArray* secondValue = @[ @"A different published value" ]; + + [registrar publish:firstValue]; + EXPECT_EQ([engine valuePublishedByPlugin:pluginName], firstValue); + + [registrar publish:secondValue]; + EXPECT_EQ([engine valuePublishedByPlugin:pluginName], secondValue); +} + +// If a channel overrides a previous channel with the same name, cleaning +// the previous channel should not affect the new channel. +// +// This is important when recreating classes that uses a channel, because the +// new instance would create the channel before the first class is deallocated +// and clears the channel. +TEST_F(FlutterEngineTest, MessengerCleanupConnectionWorks) { + FlutterEngine* engine = GetFlutterEngine(); + EXPECT_TRUE([engine runWithEntrypoint:@"main"]); + + NSString* channel = @"_test_"; + NSData* channel_data = [channel dataUsingEncoding:NSUTF8StringEncoding]; + + // Mock SendPlatformMessage so that if a message is sent to + // "test/send_message", act as if the framework has sent an empty message to + // the channel marked by the `sendOnChannel:message:` call's message. + engine.embedderAPI.SendPlatformMessage = MOCK_ENGINE_PROC( + SendPlatformMessage, ([](auto engine_, auto message_) { + if (strcmp(message_->channel, "test/send_message") == 0) { + // The simplest message that is acceptable to a method channel. + std::string message = R"|({"method": "a"})|"; + std::string channel(reinterpret_cast(message_->message), + message_->message_size); + reinterpret_cast(engine_) + ->GetShell() + .GetPlatformView() + ->HandlePlatformMessage(std::make_unique( + channel.c_str(), fml::MallocMapping::Copy(message.c_str(), message.length()), + fml::RefPtr())); + } + return kSuccess; + })); + + __block int record = 0; + + FlutterMethodChannel* channel1 = + [FlutterMethodChannel methodChannelWithName:channel + binaryMessenger:engine.binaryMessenger + codec:[FlutterJSONMethodCodec sharedInstance]]; + [channel1 setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { + record += 1; + }]; + + [engine.binaryMessenger sendOnChannel:@"test/send_message" message:channel_data]; + EXPECT_EQ(record, 1); + + FlutterMethodChannel* channel2 = + [FlutterMethodChannel methodChannelWithName:channel + binaryMessenger:engine.binaryMessenger + codec:[FlutterJSONMethodCodec sharedInstance]]; + [channel2 setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { + record += 10; + }]; + + [engine.binaryMessenger sendOnChannel:@"test/send_message" message:channel_data]; + EXPECT_EQ(record, 11); + + [channel1 setMethodCallHandler:nil]; + + [engine.binaryMessenger sendOnChannel:@"test/send_message" message:channel_data]; + EXPECT_EQ(record, 21); +} + +TEST_F(FlutterEngineTest, HasStringsWhenPasteboardEmpty) { + id engineMock = CreateMockFlutterEngine(nil); + + // Call hasStrings and expect it to be false. + __block bool calledAfterClear = false; + __block bool valueAfterClear; + FlutterResult resultAfterClear = ^(id result) { + calledAfterClear = true; + NSNumber* valueNumber = [result valueForKey:@"value"]; + valueAfterClear = [valueNumber boolValue]; + }; + FlutterMethodCall* methodCallAfterClear = + [FlutterMethodCall methodCallWithMethodName:@"Clipboard.hasStrings" arguments:nil]; + [engineMock handleMethodCall:methodCallAfterClear result:resultAfterClear]; + EXPECT_TRUE(calledAfterClear); + EXPECT_FALSE(valueAfterClear); +} + +TEST_F(FlutterEngineTest, HasStringsWhenPasteboardFull) { + id engineMock = CreateMockFlutterEngine(@"some string"); + + // Call hasStrings and expect it to be true. + __block bool called = false; + __block bool value; + FlutterResult result = ^(id result) { + called = true; + NSNumber* valueNumber = [result valueForKey:@"value"]; + value = [valueNumber boolValue]; + }; + FlutterMethodCall* methodCall = + [FlutterMethodCall methodCallWithMethodName:@"Clipboard.hasStrings" arguments:nil]; + [engineMock handleMethodCall:methodCall result:result]; + EXPECT_TRUE(called); + EXPECT_TRUE(value); +} + +TEST_F(FlutterEngineTest, ResponseAfterEngineDied) { + FlutterEngine* engine = GetFlutterEngine(); + FlutterBasicMessageChannel* channel = [[FlutterBasicMessageChannel alloc] + initWithName:@"foo" + binaryMessenger:engine.binaryMessenger + codec:[FlutterStandardMessageCodec sharedInstance]]; + __block BOOL didCallCallback = NO; + [channel setMessageHandler:^(id message, FlutterReply callback) { + ShutDownEngine(); + callback(nil); + didCallCallback = YES; + }]; + EXPECT_TRUE([engine runWithEntrypoint:@"sendFooMessage"]); + engine = nil; + + while (!didCallCallback) { + [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; + } +} + +TEST_F(FlutterEngineTest, ResponseFromBackgroundThread) { + FlutterEngine* engine = GetFlutterEngine(); + FlutterBasicMessageChannel* channel = [[FlutterBasicMessageChannel alloc] + initWithName:@"foo" + binaryMessenger:engine.binaryMessenger + codec:[FlutterStandardMessageCodec sharedInstance]]; + __block BOOL didCallCallback = NO; + [channel setMessageHandler:^(id message, FlutterReply callback) { + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + callback(nil); + dispatch_async(dispatch_get_main_queue(), ^{ + didCallCallback = YES; + }); + }); + }]; + EXPECT_TRUE([engine runWithEntrypoint:@"sendFooMessage"]); + + while (!didCallCallback) { + [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; + } +} + +TEST_F(FlutterEngineTest, CanGetEngineForId) { + FlutterEngine* engine = GetFlutterEngine(); + + fml::AutoResetWaitableEvent latch; + std::optional engineId; + AddNativeCallback("NotifyEngineId", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + const auto argument = Dart_GetNativeArgument(args, 0); + if (!Dart_IsNull(argument)) { + const auto id = tonic::DartConverter::FromDart(argument); + engineId = id; + } + latch.Signal(); + })); + + EXPECT_TRUE([engine runWithEntrypoint:@"testEngineId"]); + latch.Wait(); + + EXPECT_TRUE(engineId.has_value()); + if (!engineId.has_value()) { + return; + } + EXPECT_EQ(engine, [FlutterEngine engineForIdentifier:*engineId]); + ShutDownEngine(); +} + +TEST_F(FlutterEngineTest, ResizeSynchronizerNotBlockingRasterThreadAfterShutdown) { + FlutterResizeSynchronizer* threadSynchronizer = [[FlutterResizeSynchronizer alloc] init]; + [threadSynchronizer shutDown]; + + std::thread rasterThread([&threadSynchronizer] { + [threadSynchronizer performCommitForSize:CGSizeMake(100, 100) + notify:^{ + } + delay:0]; + }); + + rasterThread.join(); +} + +TEST_F(FlutterEngineTest, ManageControllersIfInitiatedByController) { + NSString* fixtures = @(flutter::testing::GetFixturesPath()); + FlutterDartProject* project = [[FlutterDartProject alloc] + initWithAssetsPath:fixtures + ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; + + FlutterEngine* engine; + FlutterViewController* viewController1; + + @autoreleasepool { + // Create FVC1. + viewController1 = [[FlutterViewController alloc] initWithProject:project]; + EXPECT_EQ(viewController1.viewIdentifier, 0ll); + + engine = viewController1.engine; + engine.viewController = nil; + + // Create FVC2 based on the same engine. + FlutterViewController* viewController2 = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + EXPECT_EQ(engine.viewController, viewController2); + } + // FVC2 is deallocated but FVC1 is retained. + + EXPECT_EQ(engine.viewController, nil); + + engine.viewController = viewController1; + EXPECT_EQ(engine.viewController, viewController1); + EXPECT_EQ(viewController1.viewIdentifier, 0ll); +} + +TEST_F(FlutterEngineTest, ManageControllersIfInitiatedByEngine) { + // Don't create the engine with `CreateMockFlutterEngine`, because it adds + // additional references to FlutterViewControllers, which is crucial to this + // test case. + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"io.flutter" + project:nil + allowHeadlessExecution:NO]; + FlutterViewController* viewController1; + + @autoreleasepool { + viewController1 = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; + EXPECT_EQ(viewController1.viewIdentifier, 0ll); + EXPECT_EQ(engine.viewController, viewController1); + + engine.viewController = nil; + + FlutterViewController* viewController2 = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + EXPECT_EQ(viewController2.viewIdentifier, 0ll); + EXPECT_EQ(engine.viewController, viewController2); + } + // FVC2 is deallocated but FVC1 is retained. + + EXPECT_EQ(engine.viewController, nil); + + engine.viewController = viewController1; + EXPECT_EQ(engine.viewController, viewController1); + EXPECT_EQ(viewController1.viewIdentifier, 0ll); +} + +TEST_F(FlutterEngineTest, RemovingViewDisposesCompositorResources) { + NSString* fixtures = @(flutter::testing::GetFixturesPath()); + FlutterDartProject* project = [[FlutterDartProject alloc] + initWithAssetsPath:fixtures + ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:project]; + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + [viewController loadView]; + [viewController viewDidLoad]; + viewController.flutterView.frame = CGRectMake(0, 0, 800, 600); + + EXPECT_TRUE([engine runWithEntrypoint:@"drawIntoAllViews"]); + // Wait up to 1 second for Flutter to emit a frame. + CFTimeInterval start = CACurrentMediaTime(); + while (engine.macOSCompositor->DebugNumViews() == 0) { + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, YES); + if (CACurrentMediaTime() - start > 1) { + break; + } + } + + EXPECT_EQ(engine.macOSCompositor->DebugNumViews(), 1u); + + engine.viewController = nil; + EXPECT_EQ(engine.macOSCompositor->DebugNumViews(), 0u); + + [engine shutDownEngine]; + engine = nil; +} + +TEST_F(FlutterEngineTest, HandlesTerminationRequest) { + id engineMock = CreateMockFlutterEngine(nil); + __block NSString* nextResponse = @"exit"; + __block BOOL triedToTerminate = NO; + FlutterEngineTerminationHandler* terminationHandler = + [[FlutterEngineTerminationHandler alloc] initWithEngine:engineMock + terminator:^(id sender) { + triedToTerminate = TRUE; + // Don't actually terminate, of course. + }]; + OCMStub([engineMock terminationHandler]).andReturn(terminationHandler); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + OCMStub([engineMock sendOnChannel:@"flutter/platform" + message:[OCMArg any] + binaryReply:[OCMArg any]]) + .andDo((^(NSInvocation* invocation) { + [invocation retainArguments]; + FlutterBinaryReply callback; + NSData* returnedMessage; + [invocation getArgument:&callback atIndex:4]; + if ([nextResponse isEqualToString:@"error"]) { + FlutterError* errorResponse = [FlutterError errorWithCode:@"Error" + message:@"Failed" + details:@"Details"]; + returnedMessage = + [[FlutterJSONMethodCodec sharedInstance] encodeErrorEnvelope:errorResponse]; + } else { + NSDictionary* responseDict = @{@"response" : nextResponse}; + returnedMessage = + [[FlutterJSONMethodCodec sharedInstance] encodeSuccessEnvelope:responseDict]; + } + callback(returnedMessage); + })); + __block NSString* calledAfterTerminate = @""; + FlutterResult appExitResult = ^(id result) { + NSDictionary* resultDict = result; + calledAfterTerminate = resultDict[@"response"]; + }; + FlutterMethodCall* methodExitApplication = + [FlutterMethodCall methodCallWithMethodName:@"System.exitApplication" + arguments:@{@"type" : @"cancelable"}]; + + // Always terminate when the binding isn't ready (which is the default). + triedToTerminate = NO; + calledAfterTerminate = @""; + nextResponse = @"cancel"; + [engineMock handleMethodCall:methodExitApplication result:appExitResult]; + EXPECT_STREQ([calledAfterTerminate UTF8String], ""); + EXPECT_TRUE(triedToTerminate); + + // Once the binding is ready, handle the request. + terminationHandler.acceptingRequests = YES; + triedToTerminate = NO; + calledAfterTerminate = @""; + nextResponse = @"exit"; + [engineMock handleMethodCall:methodExitApplication result:appExitResult]; + EXPECT_STREQ([calledAfterTerminate UTF8String], "exit"); + EXPECT_TRUE(triedToTerminate); + + triedToTerminate = NO; + calledAfterTerminate = @""; + nextResponse = @"cancel"; + [engineMock handleMethodCall:methodExitApplication result:appExitResult]; + EXPECT_STREQ([calledAfterTerminate UTF8String], "cancel"); + EXPECT_FALSE(triedToTerminate); + + // Check that it doesn't crash on error. + triedToTerminate = NO; + calledAfterTerminate = @""; + nextResponse = @"error"; + [engineMock handleMethodCall:methodExitApplication result:appExitResult]; + EXPECT_STREQ([calledAfterTerminate UTF8String], ""); + EXPECT_TRUE(triedToTerminate); +} + +TEST_F(FlutterEngineTest, IgnoresTerminationRequestIfNotFlutterAppDelegate) { + id previousDelegate = [[NSApplication sharedApplication] delegate]; + id plainDelegate = [[PlainAppDelegate alloc] init]; + [NSApplication sharedApplication].delegate = plainDelegate; + + // Creating the engine shouldn't fail here, even though the delegate isn't a + // FlutterAppDelegate. + CreateMockFlutterEngine(nil); + + // Asking to terminate the app should cancel. + EXPECT_EQ([[[NSApplication sharedApplication] delegate] applicationShouldTerminate:NSApp], + NSTerminateCancel); + + [NSApplication sharedApplication].delegate = previousDelegate; +} + +TEST_F(FlutterEngineTest, HandleAccessibilityEvent) { + __block BOOL announced = NO; + id engineMock = CreateMockFlutterEngine(nil); + + OCMStub([engineMock announceAccessibilityMessage:[OCMArg any] + withPriority:NSAccessibilityPriorityMedium]) + .andDo((^(NSInvocation* invocation) { + announced = TRUE; + [invocation retainArguments]; + NSString* message; + [invocation getArgument:&message atIndex:2]; + EXPECT_EQ(message, @"error message"); + })); + + NSDictionary* annotatedEvent = + @{@"type" : @"announce", + @"data" : @{@"message" : @"error message"}}; + + [engineMock handleAccessibilityEvent:annotatedEvent]; + + EXPECT_TRUE(announced); +} + +TEST_F(FlutterEngineTest, HandleLifecycleStates) API_AVAILABLE(macos(10.9)) { + __block flutter::AppLifecycleState sentState; + id engineMock = CreateMockFlutterEngine(nil); + + // Have to enumerate all the values because OCMStub can't capture + // non-Objective-C object arguments. + OCMStub([engineMock setApplicationState:flutter::AppLifecycleState::kDetached]) + .andDo((^(NSInvocation* invocation) { + sentState = flutter::AppLifecycleState::kDetached; + })); + OCMStub([engineMock setApplicationState:flutter::AppLifecycleState::kResumed]) + .andDo((^(NSInvocation* invocation) { + sentState = flutter::AppLifecycleState::kResumed; + })); + OCMStub([engineMock setApplicationState:flutter::AppLifecycleState::kInactive]) + .andDo((^(NSInvocation* invocation) { + sentState = flutter::AppLifecycleState::kInactive; + })); + OCMStub([engineMock setApplicationState:flutter::AppLifecycleState::kHidden]) + .andDo((^(NSInvocation* invocation) { + sentState = flutter::AppLifecycleState::kHidden; + })); + OCMStub([engineMock setApplicationState:flutter::AppLifecycleState::kPaused]) + .andDo((^(NSInvocation* invocation) { + sentState = flutter::AppLifecycleState::kPaused; + })); + + __block NSApplicationOcclusionState visibility = NSApplicationOcclusionStateVisible; + id mockApplication = OCMPartialMock([NSApplication sharedApplication]); + OCMStub((NSApplicationOcclusionState)[mockApplication occlusionState]) + .andDo(^(NSInvocation* invocation) { + [invocation setReturnValue:&visibility]; + }); + + NSNotification* willBecomeActive = + [[NSNotification alloc] initWithName:NSApplicationWillBecomeActiveNotification + object:nil + userInfo:nil]; + NSNotification* willResignActive = + [[NSNotification alloc] initWithName:NSApplicationWillResignActiveNotification + object:nil + userInfo:nil]; + + NSNotification* didChangeOcclusionState; + didChangeOcclusionState = + [[NSNotification alloc] initWithName:NSApplicationDidChangeOcclusionStateNotification + object:nil + userInfo:nil]; + + [engineMock handleDidChangeOcclusionState:didChangeOcclusionState]; + EXPECT_EQ(sentState, flutter::AppLifecycleState::kInactive); + + [engineMock handleWillBecomeActive:willBecomeActive]; + EXPECT_EQ(sentState, flutter::AppLifecycleState::kResumed); + + [engineMock handleWillResignActive:willResignActive]; + EXPECT_EQ(sentState, flutter::AppLifecycleState::kInactive); + + visibility = 0; + [engineMock handleDidChangeOcclusionState:didChangeOcclusionState]; + EXPECT_EQ(sentState, flutter::AppLifecycleState::kHidden); + + [engineMock handleWillBecomeActive:willBecomeActive]; + EXPECT_EQ(sentState, flutter::AppLifecycleState::kHidden); + + [engineMock handleWillResignActive:willResignActive]; + EXPECT_EQ(sentState, flutter::AppLifecycleState::kHidden); + + [mockApplication stopMocking]; +} + +TEST_F(FlutterEngineTest, ForwardsPluginDelegateRegistration) { + id previousDelegate = [[NSApplication sharedApplication] delegate]; + FakeLifecycleProvider* fakeAppDelegate = [[FakeLifecycleProvider alloc] init]; + [NSApplication sharedApplication].delegate = fakeAppDelegate; + + FakeAppDelegatePlugin* plugin = [[FakeAppDelegatePlugin alloc] init]; + FlutterEngine* engine = CreateMockFlutterEngine(nil); + + [[engine registrarForPlugin:@"TestPlugin"] addApplicationDelegate:plugin]; + + EXPECT_TRUE([fakeAppDelegate hasDelegate:plugin]); + + [NSApplication sharedApplication].delegate = previousDelegate; +} + +TEST_F(FlutterEngineTest, UnregistersPluginsOnEngineDestruction) { + id previousDelegate = [[NSApplication sharedApplication] delegate]; + FakeLifecycleProvider* fakeAppDelegate = [[FakeLifecycleProvider alloc] init]; + [NSApplication sharedApplication].delegate = fakeAppDelegate; + + FakeAppDelegatePlugin* plugin = [[FakeAppDelegatePlugin alloc] init]; + + @autoreleasepool { + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil]; + + [[engine registrarForPlugin:@"TestPlugin"] addApplicationDelegate:plugin]; + EXPECT_TRUE([fakeAppDelegate hasDelegate:plugin]); + } + + // When the engine is released, it should unregister any plugins it had + // registered on its behalf. + EXPECT_FALSE([fakeAppDelegate hasDelegate:plugin]); + + [NSApplication sharedApplication].delegate = previousDelegate; +} + +TEST_F(FlutterEngineTest, RunWithEntrypointUpdatesDisplayConfig) { + BOOL updated = NO; + FlutterEngine* engine = GetFlutterEngine(); + auto original_update_displays = engine.embedderAPI.NotifyDisplayUpdate; + engine.embedderAPI.NotifyDisplayUpdate = MOCK_ENGINE_PROC( + NotifyDisplayUpdate, ([&updated, &original_update_displays]( + auto engine, auto update_type, auto* displays, auto display_count) { + updated = YES; + return original_update_displays(engine, update_type, displays, display_count); + })); + + EXPECT_TRUE([engine runWithEntrypoint:@"main"]); + EXPECT_TRUE(updated); + + updated = NO; + [[NSNotificationCenter defaultCenter] + postNotificationName:NSApplicationDidChangeScreenParametersNotification + object:nil]; + EXPECT_TRUE(updated); +} + +TEST_F(FlutterEngineTest, NotificationsUpdateDisplays) { + BOOL updated = NO; + FlutterEngine* engine = GetFlutterEngine(); + auto original_set_viewport_metrics = engine.embedderAPI.SendWindowMetricsEvent; + engine.embedderAPI.SendWindowMetricsEvent = MOCK_ENGINE_PROC( + SendWindowMetricsEvent, + ([&updated, &original_set_viewport_metrics](auto engine, auto* window_metrics) { + updated = YES; + return original_set_viewport_metrics(engine, window_metrics); + })); + + EXPECT_TRUE([engine runWithEntrypoint:@"main"]); + + updated = NO; + [[NSNotificationCenter defaultCenter] postNotificationName:NSWindowDidChangeScreenNotification + object:nil]; + // No VC. + EXPECT_FALSE(updated); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + [viewController loadView]; + viewController.flutterView.frame = CGRectMake(0, 0, 800, 600); + + [[NSNotificationCenter defaultCenter] postNotificationName:NSWindowDidChangeScreenNotification + object:nil]; + EXPECT_TRUE(updated); +} + +TEST_F(FlutterEngineTest, DisplaySizeIsInPhysicalPixel) { + NSString* fixtures = @(testing::GetFixturesPath()); + FlutterDartProject* project = [[FlutterDartProject alloc] + initWithAssetsPath:fixtures + ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; + project.rootIsolateCreateCallback = FlutterEngineTest::IsolateCreateCallback; + MockableFlutterEngine* engine = [[MockableFlutterEngine alloc] initWithName:@"foobar" + project:project + allowHeadlessExecution:true]; + BOOL updated = NO; + auto original_update_displays = engine.embedderAPI.NotifyDisplayUpdate; + engine.embedderAPI.NotifyDisplayUpdate = MOCK_ENGINE_PROC( + NotifyDisplayUpdate, ([&updated, &original_update_displays]( + auto engine, auto update_type, auto* displays, auto display_count) { + EXPECT_EQ(display_count, 1UL); + EXPECT_EQ(displays->display_id, 10UL); + EXPECT_EQ(displays->width, 60UL); + EXPECT_EQ(displays->height, 80UL); + EXPECT_EQ(displays->device_pixel_ratio, 2UL); + updated = YES; + return original_update_displays(engine, update_type, displays, display_count); + })); + EXPECT_TRUE([engine runWithEntrypoint:@"main"]); + EXPECT_TRUE(updated); + [engine shutDownEngine]; + engine = nil; +} + +TEST_F(FlutterEngineTest, ReportsHourFormat) { + __block BOOL expectedValue; + + // Set up mocks. + id channelMock = OCMClassMock([FlutterBasicMessageChannel class]); + OCMStub([channelMock messageChannelWithName:@"flutter/settings" + binaryMessenger:[OCMArg any] + codec:[OCMArg any]]) + .andReturn(channelMock); + OCMStub([channelMock sendMessage:[OCMArg any]]).andDo((^(NSInvocation* invocation) { + __weak id message; + [invocation getArgument:&message atIndex:2]; + EXPECT_EQ(message[@"alwaysUse24HourFormat"], @(expectedValue)); + })); + + id mockHourFormat = OCMClassMock([FlutterHourFormat class]); + OCMStub([mockHourFormat isAlwaysUse24HourFormat]).andDo((^(NSInvocation* invocation) { + [invocation setReturnValue:&expectedValue]; + })); + + id engineMock = CreateMockFlutterEngine(nil); + + // Verify the YES case. + expectedValue = YES; + EXPECT_TRUE([engineMock runWithEntrypoint:@"main"]); + [engineMock shutDownEngine]; + + // Verify the NO case. + expectedValue = NO; + EXPECT_TRUE([engineMock runWithEntrypoint:@"main"]); + [engineMock shutDownEngine]; + + // Clean up mocks. + [mockHourFormat stopMocking]; + [engineMock stopMocking]; + [channelMock stopMocking]; +} + +} // namespace flutter::testing + +// NOLINTEND(clang-analyzer-core.StackAddressEscape) diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..d9d78f88d10720f41674858dfbe817ff8eae0856 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.h @@ -0,0 +1,72 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERENGINETESTUTILS_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERENGINETESTUTILS_H_ + +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h" + +#import + +#include "flutter/testing/autoreleasepool_test.h" +#include "flutter/testing/test_dart_native_resolver.h" +#include "gtest/gtest.h" + +namespace flutter::testing { + +class FlutterEngineTest : public AutoreleasePoolTest { + public: + FlutterEngineTest(); + + FlutterEngine* GetFlutterEngine() { return engine_; }; + + void SetUp() override; + void TearDown() override; + + void AddNativeCallback(const char* name, Dart_NativeFunction function); + + static void IsolateCreateCallback(void* user_data); + + void ShutDownEngine(); + + private: + inline static std::shared_ptr native_resolver_; + + FlutterDartProject* project_; + FlutterEngine* engine_; + + FML_DISALLOW_COPY_AND_ASSIGN(FlutterEngineTest); +}; + +// Returns a mock FlutterEngine that is able to work in environments +// without a real pasteboard. +// +// Callers MUST call [mockEngine shutDownEngine] when finished with the returned engine. +id CreateMockFlutterEngine(NSString* pasteboardString); + +class MockFlutterEngineTest : public AutoreleasePoolTest { + public: + MockFlutterEngineTest(); + + void SetUp() override; + void TearDown() override; + + id GetMockEngine() { return engine_mock_; } + + void ShutDownEngine(); + + ~MockFlutterEngineTest() { + [engine_mock_ shutDownEngine]; + [engine_mock_ stopMocking]; + } + + private: + id engine_mock_; + + FML_DISALLOW_COPY_AND_ASSIGN(MockFlutterEngineTest); +}; + +} // namespace flutter::testing + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERENGINETESTUTILS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.mm new file mode 100644 index 0000000000000000000000000000000000000000..b2ff26cab0d607c080ee9e411045febb9bb2e391 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.mm @@ -0,0 +1,109 @@ + +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.h" + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" + +#include "flutter/testing/testing.h" + +/** + * Fake pasteboard implementation to allow tests to work in environments without a real + * pasteboard. + */ +@interface FakePasteboard : FlutterPasteboard +@end + +@implementation FakePasteboard { + NSString* _result; +} + +- (NSInteger)clearContents { + size_t changeCount = (_result != nil) ? 1 : 0; + _result = nil; + return changeCount; +} + +- (NSString*)stringForType:(NSPasteboardType)dataType { + return _result; +} + +- (BOOL)setString:(NSString*)string forType:(NSPasteboardType)dataType { + _result = string; + return YES; +} + +@end + +namespace flutter::testing { + +FlutterEngineTest::FlutterEngineTest() = default; + +void FlutterEngineTest::SetUp() { + native_resolver_ = std::make_shared(); + NSString* fixtures = @(testing::GetFixturesPath()); + project_ = [[FlutterDartProject alloc] + initWithAssetsPath:fixtures + ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; + project_.rootIsolateCreateCallback = FlutterEngineTest::IsolateCreateCallback; + engine_ = [[FlutterEngine alloc] initWithName:@"test" + project:project_ + allowHeadlessExecution:true]; +} + +void FlutterEngineTest::TearDown() { + [engine_ shutDownEngine]; + engine_ = nil; + native_resolver_.reset(); +} + +void FlutterEngineTest::ShutDownEngine() { + [engine_ shutDownEngine]; + engine_ = nil; +} + +void FlutterEngineTest::IsolateCreateCallback(void* user_data) { + native_resolver_->SetNativeResolverForIsolate(); +} + +void FlutterEngineTest::AddNativeCallback(const char* name, Dart_NativeFunction function) { + native_resolver_->AddNativeCallback({name}, function); +} + +id CreateMockFlutterEngine(NSString* pasteboardString) { + NSString* fixtures = @(testing::GetFixturesPath()); + FlutterDartProject* project = [[FlutterDartProject alloc] + initWithAssetsPath:fixtures + ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" + project:project + allowHeadlessExecution:true]; + + FakePasteboard* pasteboardMock = [[FakePasteboard alloc] init]; + [pasteboardMock setString:pasteboardString forType:NSPasteboardTypeString]; + engine.pasteboard = pasteboardMock; + id engineMock = OCMPartialMock(engine); + return engineMock; +} + +MockFlutterEngineTest::MockFlutterEngineTest() = default; + +void MockFlutterEngineTest::SetUp() { + engine_mock_ = CreateMockFlutterEngine(@""); +} + +void MockFlutterEngineTest::TearDown() { + [engine_mock_ shutDownEngine]; + [engine_mock_ stopMocking]; + engine_mock_ = nil; +} + +void MockFlutterEngineTest::ShutDownEngine() { + [engine_mock_ shutDownEngine]; + engine_mock_ = nil; +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h new file mode 100644 index 0000000000000000000000000000000000000000..ec34b267a9246e42f32ee1000f1fb8d1aca60cf3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h @@ -0,0 +1,245 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERENGINE_INTERNAL_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERENGINE_INTERNAL_H_ + +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h" + +#import + +#include + +#include "flutter/shell/platform/common/app_lifecycle_state.h" + +#import "flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMac.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewController.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderer.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.h" + +NS_ASSUME_NONNULL_BEGIN + +#pragma mark - Typedefs + +typedef void (^FlutterTerminationCallback)(id _Nullable sender); + +#pragma mark - Enumerations + +/** + * An enum for defining the different request types allowed when requesting an + * application exit. + * + * Must match the entries in the `AppExitType` enum in the Dart code. + */ +typedef NS_ENUM(NSInteger, FlutterAppExitType) { + kFlutterAppExitTypeCancelable = 0, + kFlutterAppExitTypeRequired = 1, +}; + +/** + * An enum for defining the different responses the framework can give to an + * application exit request from the engine. + * + * Must match the entries in the `AppExitResponse` enum in the Dart code. + */ +typedef NS_ENUM(NSInteger, FlutterAppExitResponse) { + kFlutterAppExitResponseCancel = 0, + kFlutterAppExitResponseExit = 1, +}; + +#pragma mark - FlutterEngineTerminationHandler + +/** + * A handler interface for handling application termination that the + * FlutterAppDelegate can use to coordinate an application exit by sending + * messages through the platform channel managed by the engine. + */ +@interface FlutterEngineTerminationHandler : NSObject + +@property(nonatomic, readonly) BOOL shouldTerminate; +@property(nonatomic, readwrite) BOOL acceptingRequests; + +- (instancetype)initWithEngine:(FlutterEngine*)engine + terminator:(nullable FlutterTerminationCallback)terminator; +- (void)handleRequestAppExitMethodCall:(NSDictionary*)data + result:(FlutterResult)result; +- (void)requestApplicationTermination:(NSApplication*)sender + exitType:(FlutterAppExitType)type + result:(nullable FlutterResult)result; +@end + +/** + * An NSPasteboard wrapper object to allow for substitution of a fake in unit tests. + */ +@interface FlutterPasteboard : NSObject +- (NSInteger)clearContents; +- (NSString*)stringForType:(NSPasteboardType)dataType; +- (BOOL)setString:(NSString*)string forType:(NSPasteboardType)dataType; +@end + +@interface FlutterEngine () + +/** + * True if the engine is currently running. + */ +@property(nonatomic, readonly) BOOL running; + +/** + * Provides the renderer config needed to initialize the engine and also handles external + * texture management. + */ +@property(nonatomic, readonly, nullable) FlutterRenderer* renderer; + +/** + * Function pointers for interacting with the embedder.h API. + */ +@property(nonatomic) FlutterEngineProcTable& embedderAPI; + +/** + * True if the semantics is enabled. The Flutter framework starts sending + * semantics update through the embedder as soon as it is set to YES. + */ +@property(nonatomic) BOOL semanticsEnabled; + +/** + * The executable name for the current process. + */ +@property(nonatomic, readonly, nonnull) NSString* executableName; + +/** + * This just returns the NSPasteboard so that it can be mocked in the tests. + */ +@property(nonatomic, nonnull) FlutterPasteboard* pasteboard; + +/** + * The command line arguments array for the engine. + */ +@property(nonatomic, readonly) std::vector switches; + +/** + * Provides the |FlutterEngineTerminationHandler| to be used for this engine. + */ +@property(nonatomic, readonly) FlutterEngineTerminationHandler* terminationHandler; + +/** + * Attach a view controller to the engine as its default controller. + * + * Since FlutterEngine can only handle the implicit view for now, the given + * controller will always be assigned to the implicit view, if there isn't an + * implicit view yet. If the engine already has an implicit view, this call + * throws an assertion. + * + * The engine holds a weak reference to the attached view controller. + * + * If the given view controller is already attached to an engine, this call + * throws an assertion. + */ +- (void)addViewController:(FlutterViewController*)viewController; + +/** + * Notify the engine that a view for the given view controller has been loaded. + */ +- (void)viewControllerViewDidLoad:(FlutterViewController*)viewController; + +/** + * Dissociate the given view controller from this engine. + * + * If the view controller is not associated with this engine, this call throws an + * assertion. + */ +- (void)removeViewController:(FlutterViewController*)viewController; + +/** + * The |FlutterViewController| associated with the given view ID, if any. + */ +- (nullable FlutterViewController*)viewControllerForIdentifier: + (FlutterViewIdentifier)viewIdentifier; + +/** + * Informs the engine that the specified view controller's window metrics have changed. + */ +- (void)updateWindowMetricsForViewController:(FlutterViewController*)viewController; + +/** + * Dispatches the given pointer event data to engine. + */ +- (void)sendPointerEvent:(const FlutterPointerEvent&)event; + +/** + * Registers an external texture with the given id. Returns YES on success. + */ +- (BOOL)registerTextureWithID:(int64_t)textureId; + +/** + * Marks texture with the given id as available. Returns YES on success. + */ +- (BOOL)markTextureFrameAvailable:(int64_t)textureID; + +/** + * Unregisters an external texture with the given id. Returns YES on success. + */ +- (BOOL)unregisterTextureWithID:(int64_t)textureID; + +- (nonnull FlutterPlatformViewController*)platformViewController; + +/** + * Handles changes to the application state, sending them to the framework. + * + * @param state One of the lifecycle constants in app_lifecycle_state.h, + * corresponding to the Dart enum AppLifecycleState. + */ +- (void)setApplicationState:(flutter::AppLifecycleState)state; + +// Accessibility API. + +/** + * Dispatches semantics action back to the framework. The semantics must be enabled by calling + * the updateSemanticsEnabled before dispatching semantics actions. + */ +- (void)dispatchSemanticsAction:(FlutterSemanticsAction)action + toTarget:(uint16_t)target + withData:(fml::MallocMapping)data; + +/** + * Handles accessibility events. + */ +- (void)handleAccessibilityEvent:(NSDictionary*)annotatedEvent; + +/** + * Announces accessibility messages. + */ +- (void)announceAccessibilityMessage:(NSString*)message + withPriority:(NSAccessibilityPriorityLevel)priority; + +/** + * Returns keyboard manager for the engine. + */ +@property(nonatomic, readonly) FlutterKeyboardManager* keyboardManager; + +/** + * Returns text input plugin for the engine. + */ +@property(nonatomic, readonly) FlutterTextInputPlugin* textInputPlugin; + +/** + * Returns an array of screen objects representing all of the screens available on the system. + */ +- (NSArray*)screens; + +/** + * Returns engine for the identifier. The identifier must be valid for an engine + * that is currently running, otherwise the behavior is undefined. + * + * The identifier can be obtained in Dart code through + * `PlatformDispatcher.instance.engineId`. + * + * This function must be called on the main thread. + */ ++ (nullable FlutterEngine*)engineForIdentifier:(int64_t)identifier; +@end + +NS_ASSUME_NONNULL_END + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERENGINE_INTERNAL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterExternalTexture.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterExternalTexture.h new file mode 100644 index 0000000000000000000000000000000000000000..b2aa481aade140c74e69137bb4fd0ac65054c8f3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterExternalTexture.h @@ -0,0 +1,41 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTEREXTERNALTEXTURE_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTEREXTERNALTEXTURE_H_ + +#import + +#import "flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalSkia.h" +#include "flutter/shell/platform/embedder/embedder.h" + +/** + * Embedding side texture wrappers for Metal external textures. + * Used to bridge FlutterTexture object and handle the texture copy request the + * Flutter engine. + */ +@interface FlutterExternalTexture : NSObject + +/** + * Initializes a texture adapter with |texture|. + */ +- (nonnull instancetype)initWithFlutterTexture:(nonnull id)texture + darwinMetalContext:(nonnull FlutterDarwinContextMetalSkia*)context; + +/** + * Returns the ID for the FlutterExternalTexture instance. + */ +- (int64_t)textureID; + +/** + * Accepts texture buffer copy request from the Flutter engine. + * When the user side marks the textureID as available, the Flutter engine will + * callback to this method and ask for populate the |metalTexture| object, + * such as the texture type and the format of the pixel buffer and the texture object. + */ +- (BOOL)populateTexture:(nonnull FlutterMetalExternalTexture*)metalTexture; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTEREXTERNALTEXTURE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterExternalTexture.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterExternalTexture.mm new file mode 100644 index 0000000000000000000000000000000000000000..e15cd4e1e2d36cd93a96ff1a382c6bda9cdf6dd9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterExternalTexture.mm @@ -0,0 +1,146 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterExternalTexture.h" + +#include "flutter/fml/platform/darwin/cf_utils.h" + +@implementation FlutterExternalTexture { + FlutterDarwinContextMetalSkia* _darwinMetalContext; + + int64_t _textureID; + + id _texture; + + std::vector _textures; +} + +- (instancetype)initWithFlutterTexture:(id)texture + darwinMetalContext:(FlutterDarwinContextMetalSkia*)context { + self = [super init]; + if (self) { + _texture = texture; + _textureID = reinterpret_cast(_texture); + _darwinMetalContext = context; + } + return self; +} + +- (int64_t)textureID { + return _textureID; +} + +- (BOOL)populateTexture:(FlutterMetalExternalTexture*)textureOut { + // Copy the pixel buffer from the FlutterTexture instance implemented on the user side. + fml::CFRef pixelBuffer([_texture copyPixelBuffer]); + + if (!pixelBuffer) { + return NO; + } + + OSType pixel_format = CVPixelBufferGetPixelFormatType(pixelBuffer); + if (pixel_format == kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange || + pixel_format == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) { + return [self populateTextureFromYUVAPixelBuffer:pixelBuffer textureOut:textureOut]; + } else if (pixel_format == kCVPixelFormatType_32BGRA) { + return [self populateTextureFromRGBAPixelBuffer:pixelBuffer textureOut:textureOut]; + } else { + NSLog(@"Unsupported pixel format: %d", pixel_format); + return NO; + } +} + +- (BOOL)populateTextureFromYUVAPixelBuffer:(nonnull CVPixelBufferRef)pixelBuffer + textureOut:(nonnull FlutterMetalExternalTexture*)textureOut { + CVMetalTextureRef yCVMetalTexture = nullptr; + CVMetalTextureRef uvCVMetalTextureRef = nullptr; + SkISize textureSize = + SkISize::Make(CVPixelBufferGetWidth(pixelBuffer), CVPixelBufferGetHeight(pixelBuffer)); + + CVReturn yCVReturn = CVMetalTextureCacheCreateTextureFromImage( + /*allocator=*/kCFAllocatorDefault, + /*textureCache=*/_darwinMetalContext.textureCache, + /*sourceImage=*/pixelBuffer, + /*textureAttributes=*/nullptr, + /*pixelFormat=*/MTLPixelFormatR8Unorm, + /*width=*/CVPixelBufferGetWidthOfPlane(pixelBuffer, 0u), + /*height=*/CVPixelBufferGetHeightOfPlane(pixelBuffer, 0u), + /*planeIndex=*/0u, + /*texture=*/&yCVMetalTexture); + + if (yCVReturn != kCVReturnSuccess) { + NSLog(@"Could not create Metal texture from pixel buffer: CVReturn %d", yCVReturn); + return NO; + } + + CVReturn uvCVReturn = CVMetalTextureCacheCreateTextureFromImage( + /*allocator=*/kCFAllocatorDefault, + /*textureCache=*/_darwinMetalContext.textureCache, + /*sourceImage=*/pixelBuffer, + /*textureAttributes=*/nullptr, + /*pixelFormat=*/MTLPixelFormatRG8Unorm, + /*width=*/CVPixelBufferGetWidthOfPlane(pixelBuffer, 1u), + /*height=*/CVPixelBufferGetHeightOfPlane(pixelBuffer, 1u), + /*planeIndex=*/1u, + /*texture=*/&uvCVMetalTextureRef); + + if (uvCVReturn != kCVReturnSuccess) { + CVBufferRelease(yCVMetalTexture); + NSLog(@"Could not create Metal texture from pixel buffer: CVReturn %d", uvCVReturn); + return NO; + } + + _textures = {(__bridge FlutterMetalTextureHandle)CVMetalTextureGetTexture(yCVMetalTexture), + (__bridge FlutterMetalTextureHandle)CVMetalTextureGetTexture(uvCVMetalTextureRef)}; + CVBufferRelease(yCVMetalTexture); + CVBufferRelease(uvCVMetalTextureRef); + + textureOut->num_textures = 2; + textureOut->height = textureSize.height(); + textureOut->width = textureSize.width(); + textureOut->pixel_format = FlutterMetalExternalTexturePixelFormat::kYUVA; + textureOut->textures = _textures.data(); + OSType pixel_format = CVPixelBufferGetPixelFormatType(pixelBuffer); + textureOut->yuv_color_space = pixel_format == kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange + ? FlutterMetalExternalTextureYUVColorSpace::kBT601LimitedRange + : FlutterMetalExternalTextureYUVColorSpace::kBT601FullRange; + + return YES; +} + +- (BOOL)populateTextureFromRGBAPixelBuffer:(nonnull CVPixelBufferRef)pixelBuffer + textureOut:(nonnull FlutterMetalExternalTexture*)textureOut { + SkISize textureSize = + SkISize::Make(CVPixelBufferGetWidth(pixelBuffer), CVPixelBufferGetHeight(pixelBuffer)); + + CVMetalTextureRef cvMetalTexture = nullptr; + CVReturn cvReturn = + CVMetalTextureCacheCreateTextureFromImage(/*allocator=*/kCFAllocatorDefault, + /*textureCache=*/_darwinMetalContext.textureCache, + /*sourceImage=*/pixelBuffer, + /*textureAttributes=*/nullptr, + /*pixelFormat=*/MTLPixelFormatBGRA8Unorm, + /*width=*/textureSize.width(), + /*height=*/textureSize.height(), + /*planeIndex=*/0u, + /*texture=*/&cvMetalTexture); + + if (cvReturn != kCVReturnSuccess) { + NSLog(@"Could not create Metal texture from pixel buffer: CVReturn %d", cvReturn); + return NO; + } + + _textures = {(__bridge FlutterMetalTextureHandle)CVMetalTextureGetTexture(cvMetalTexture)}; + CVBufferRelease(cvMetalTexture); + + textureOut->num_textures = 1; + textureOut->height = textureSize.height(); + textureOut->width = textureSize.width(); + textureOut->pixel_format = FlutterMetalExternalTexturePixelFormat::kRGBA; + textureOut->textures = _textures.data(); + + return YES; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyPrimaryResponder.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyPrimaryResponder.h new file mode 100644 index 0000000000000000000000000000000000000000..5a2e18d3a4ab363a9c1602c76ca8f2179f573d61 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyPrimaryResponder.h @@ -0,0 +1,50 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERKEYPRIMARYRESPONDER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERKEYPRIMARYRESPONDER_H_ + +#import + +typedef void (^FlutterAsyncKeyCallback)(BOOL handled); + +/** + * An interface for a responder that can process a key event and decides whether + * to handle an event asynchronously. + * + * To use this class, add it to a |FlutterKeyboardManager| with |addPrimaryResponder|. + */ +@protocol FlutterKeyPrimaryResponder + +/** + * Process the event. + * + * The |callback| should be called with a value that indicates whether the + * responder has handled the given event. The |callback| must be called exactly + * once, and can be called before the return of this method, or after. + */ +@required +- (void)handleEvent:(nonnull NSEvent*)event callback:(nonnull FlutterAsyncKeyCallback)callback; + +/** + * Synchronize the modifier flags if necessary. The new modifier flag would usually come from mouse + * event and may be out of sync with current keyboard state if the modifier flags have changed while + * window was not key. + */ +@required +- (void)syncModifiersIfNeeded:(NSEventModifierFlags)modifierFlags + timestamp:(NSTimeInterval)timestamp; + +/* A map from macOS key code to logical keyboard. + * + * The map is assigned on initialization, and updated when the user changes + * keyboard type or layout. The responder should prioritize this map when + * deriving logical keys. + */ +@required +@property(nonatomic, nullable, strong) NSMutableDictionary* layoutMap; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERKEYPRIMARYRESPONDER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardLayout.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardLayout.h new file mode 100644 index 0000000000000000000000000000000000000000..6b7539f01aeb742713bfd8750849dabb877e5971 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardLayout.h @@ -0,0 +1,61 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERKEYBOARDLAYOUT_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERKEYBOARDLAYOUT_H_ + +#import + +namespace flutter { + +// The printable result of a key under certain modifiers, used to derive key +// mapping. +typedef struct { + // The printable character. + // + // If `isDeadKey` is true, then this is the character when pressing the same + // dead key twice. + uint32_t character; + + // Whether this character is a dead key. + // + // A dead key is a key that is not counted as text per se, but holds a + // diacritics to be added to the next key. + bool isDeadKey; +} LayoutClue; + +} // namespace flutter + +/** + * A delegate protocol for FlutterKeyboardLayout. Implemented by FlutterKeyboardManager. + */ +@protocol FlutterKeyboardLayoutDelegate + +/** + * Called when the active keyboard input source changes. + * + * Input sources may be simple keyboard layouts, or more complex input methods involving an IME, + * such as Chinese, Japanese, and Korean. + */ +- (void)keyboardLayoutDidChange; + +@end + +/** + * A class that allows querying the printable result of a key with a modifier state according to the + * current keyboard layout. It also provides a delegate protocol for clients interested in + * listening to keyboard layout changes. + */ +@interface FlutterKeyboardLayout : NSObject + +@property(readwrite, nonatomic, weak) id delegate; + +/** + * Querying the printable result of a key under the given modifier state. + */ +- (flutter::LayoutClue)lookUpLayoutForKeyCode:(uint16_t)keyCode shift:(BOOL)shift; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERKEYBOARDLAYOUT_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardLayout.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardLayout.mm new file mode 100644 index 0000000000000000000000000000000000000000..ee6858d5245f8cdb952fd20efa8c6a4d700f754e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardLayout.mm @@ -0,0 +1,107 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardLayout.h" + +#include +#include +#include "flutter/fml/platform/darwin/cf_utils.h" + +@implementation FlutterKeyboardLayout { + NSData* _keyboardLayoutData; +} + +@synthesize delegate = _delegate; + +/** + * Returns the current Unicode layout data (kTISPropertyUnicodeKeyLayoutData). + * + * To use the returned data, convert it to CFDataRef first, finds its bytes + * with CFDataGetBytePtr, then reinterpret it into const UCKeyboardLayout*. + * It's returned in NSData* to enable auto reference count. + */ +static NSData* CurrentKeyboardLayoutData() { + fml::CFRef source(TISCopyCurrentKeyboardInputSource()); + CFTypeRef layout_data = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData); + if (layout_data == nil) { + // TISGetInputSourceProperty returns null with Japanese keyboard layout. + // Using TISCopyCurrentKeyboardLayoutInputSource to fix NULL return. + // https://github.com/microsoft/node-native-keymap/blob/5f0699ded00179410a14c0e1b0e089fe4df8e130/src/keyboard_mac.mm#L91 + source.Reset(TISCopyCurrentKeyboardLayoutInputSource()); + layout_data = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData); + } + return (__bridge NSData*)layout_data; +} + +/** + * NotificationCenter callback invoked on kTISNotifySelectedKeyboardInputSourceChanged events. + */ +static void OnKeyboardLayoutChanged(CFNotificationCenterRef center, + void* observer, + CFStringRef name, + const void* object, + CFDictionaryRef userInfo) { + FlutterKeyboardLayout* controller = (__bridge FlutterKeyboardLayout*)observer; + if (controller != nil) { + [controller onKeyboardLayoutChanged]; + } +} + +- (instancetype)initWithDelegate:(id)delegate { + self = [super init]; + if (self) { + _delegate = delegate; + // macOS fires this message when changing IMEs. + CFNotificationCenterRef cfCenter = CFNotificationCenterGetDistributedCenter(); + __weak FlutterKeyboardLayout* weakSelf = self; + CFNotificationCenterAddObserver(cfCenter, (__bridge void*)weakSelf, OnKeyboardLayoutChanged, + kTISNotifySelectedKeyboardInputSourceChanged, NULL, + CFNotificationSuspensionBehaviorDeliverImmediately); + } + return self; +} + +- (void)dealloc { + CFNotificationCenterRef cfCenter = CFNotificationCenterGetDistributedCenter(); + CFNotificationCenterRemoveEveryObserver(cfCenter, (__bridge void*)self); +} + +- (void)onKeyboardLayoutChanged { + _keyboardLayoutData = nil; + [_delegate keyboardLayoutDidChange]; +} + +- (flutter::LayoutClue)lookUpLayoutForKeyCode:(uint16_t)keyCode shift:(BOOL)shift { + if (_keyboardLayoutData == nil) { + _keyboardLayoutData = CurrentKeyboardLayoutData(); + } + const UCKeyboardLayout* layout = reinterpret_cast( + CFDataGetBytePtr((__bridge CFDataRef)_keyboardLayoutData)); + + UInt32 deadKeyState = 0; + UniCharCount stringLength = 0; + UniChar resultChar; + + UInt32 modifierState = ((shift ? shiftKey : 0) >> 8) & 0xFF; + UInt32 keyboardType = LMGetKbdLast(); + + bool isDeadKey = false; + OSStatus status = + UCKeyTranslate(layout, keyCode, kUCKeyActionDown, modifierState, keyboardType, + kUCKeyTranslateNoDeadKeysBit, &deadKeyState, 1, &stringLength, &resultChar); + // For dead keys, press the same key again to get the printable representation of the key. + if (status == noErr && stringLength == 0 && deadKeyState != 0) { + isDeadKey = true; + status = + UCKeyTranslate(layout, keyCode, kUCKeyActionDown, modifierState, keyboardType, + kUCKeyTranslateNoDeadKeysBit, &deadKeyState, 1, &stringLength, &resultChar); + } + + if (status == noErr && stringLength == 1 && !std::iscntrl(resultChar)) { + return flutter::LayoutClue{resultChar, isDeadKey}; + } + return flutter::LayoutClue{0, false}; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.h new file mode 100644 index 0000000000000000000000000000000000000000..5e5339772ac70f6ed2b451c87a786d84028152e8 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.h @@ -0,0 +1,132 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERKEYBOARDMANAGER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERKEYBOARDMANAGER_H_ + +#import + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h" +#import "flutter/shell/platform/embedder/embedder.h" + +@protocol FlutterKeyboardManagerDelegate + +@required + +/** + * Dispatch events to the framework to be processed by |HardwareKeyboard|. + * + * This method typically forwards events to + * |FlutterEngine.sendKeyEvent:callback:userData:|. + */ +- (void)sendKeyEvent:(const FlutterKeyEvent&)event + callback:(nullable FlutterKeyEventCallback)callback + userData:(nullable void*)userData; + +/** + * Get a binary messenger to send channel messages with. + * + * This method is used to create the key data channel and typically + * forwards to |FlutterEngine.binaryMessenger|. + */ +- (nonnull id)binaryMessenger; + +@end + +/** + * Provides context for a keyboard event. Implemented by FlutterViewController. + */ +@protocol FlutterKeyboardManagerEventContext + +@required +/** + * Get the next responder to dispatch events that the keyboard system + * (including text input) do not handle. + * + * If the |nextResponder| is null, then those events will be discarded. + */ +@property(nonatomic, readonly, nullable) NSResponder* nextResponder; + +/** + * Dispatch events that are not handled by the keyboard event handlers + * to the text input handler. + * + * This method typically forwards events to |TextInputPlugin.handleKeyEvent|. + */ +- (BOOL)onTextInputKeyEvent:(nonnull NSEvent*)event; + +@end + +/** + * A hub that manages how key events are dispatched to various Flutter key + * responders, and whether the event is propagated to the next NSResponder. + * Cooperates with |TextInputPlugin| to handle text + * + * A keyboard event goes through a few sections, each can choose to handled the + * event, and only unhandled events can move to the next section: + * + * - Pre-filtering: Events during IME are sent to the system immediately. + * - Keyboard: Dispatch to the embedder responder and the channel responder + * simultaneously. After both responders have responded (asynchronously), the + * event is considered handled if either responder handles. + * - Text input: Events are sent to |TextInputPlugin| and are handled + * synchronously. + * - Next responder: Events are sent to the next responder as specified by + * |viewDelegate|. + */ +@interface FlutterKeyboardManager : NSObject + +/** + * Create a keyboard manager. + * + * The |viewDelegate| is a weak reference, typically implemented by + * |FlutterViewController|. + */ +- (nonnull instancetype)initWithDelegate:(nonnull id)delegate; + +/** + * Processes a key event. + * + * Unhandled events will be dispatched to the text input system, and possibly + * the next responder afterwards. + */ +- (void)handleEvent:(nonnull NSEvent*)event + withContext:(nonnull id)eventContext; + +/** + * Returns yes if is event currently being redispatched. + * + * In some instances (i.e. emoji shortcut) the event may be redelivered by cocoa + * as key equivalent to FlutterTextInput, in which case it shouldn't be + * processed again. + */ +- (BOOL)isDispatchingKeyEvent:(nonnull NSEvent*)event; + +/** + * Synthesize modifier keys events. + * + * If needed, synthesize modifier keys up and down events by comparing their + * current pressing states with the given modifier flags. + */ +- (void)syncModifiersIfNeeded:(NSEventModifierFlags)modifierFlags + timestamp:(NSTimeInterval)timestamp; + +/** + * Returns the keyboard pressed state. + * + * Returns the keyboard pressed state. The dictionary contains one entry per + * pressed keys, mapping from the logical key to the physical key. + */ +- (nonnull NSDictionary*)getPressedState; + +@end + +@class FlutterKeyboardLayout; + +@interface FlutterKeyboardManager (Testing) +- (nonnull instancetype)initWithDelegate:(nonnull id)delegate + keyboardLayout:(nonnull FlutterKeyboardLayout*)keyboardLayout; +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERKEYBOARDMANAGER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.mm new file mode 100644 index 0000000000000000000000000000000000000000..960cf4b0bb678dd3984df6fbef83ee535554b1b9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.mm @@ -0,0 +1,406 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.h" + +#include +#include + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterChannelKeyResponder.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEmbedderKeyResponder.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyPrimaryResponder.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardLayout.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/KeyCodeMap_Internal.h" + +// Turn on this flag to print complete layout data when switching IMEs. The data +// is used in unit tests. +// #define DEBUG_PRINT_LAYOUT + +namespace { +using flutter::LayoutClue; +using flutter::LayoutGoal; + +#ifdef DEBUG_PRINT_LAYOUT +// Prints layout entries that will be parsed by `MockLayoutData`. +NSString* debugFormatLayoutData(NSString* debugLayoutData, + uint16_t keyCode, + LayoutClue clue1, + LayoutClue clue2) { + return [NSString + stringWithFormat:@" %@%@0x%d%04x, 0x%d%04x,", debugLayoutData, + keyCode % 4 == 0 ? [NSString stringWithFormat:@"\n/* 0x%02x */ ", keyCode] + : @" ", + clue1.isDeadKey, clue1.character, clue2.isDeadKey, clue2.character]; +} +#endif + +bool isEascii(const LayoutClue& clue) { + return clue.character < 256 && !clue.isDeadKey; +} + +typedef void (^VoidBlock)(); + +} // namespace + +@interface FlutterEventWithContext : NSObject + +@property(nonatomic, readonly) NSEvent* event; +@property(nonatomic, readonly) id context; + +- (instancetype)initWithEvent:(NSEvent*)event + context:(nonnull id)context; + +@end + +@implementation FlutterEventWithContext { + NSEvent* _event; + id _context; +} + +- (instancetype)initWithEvent:(NSEvent*)event + context:(id)context { + self = [super init]; + if (self) { + _event = event; + _context = context; + } + return self; +} + +@end + +@interface FlutterKeyboardManager () + +/** + * The text input plugin set by initialization. + */ +@property(nonatomic, weak) id delegate; + +/** + * The primary responders added by addPrimaryResponder. + */ +@property(nonatomic) NSMutableArray>* primaryResponders; + +@property(nonatomic) NSMutableArray* pendingEvents; + +@property(nonatomic) BOOL processingEvent; + +@property(nonatomic) NSMutableDictionary* layoutMap; + +@property(nonatomic, nullable) NSEvent* eventBeingDispatched; + +/** + * Add a primary responder, which asynchronously decides whether to handle an + * event. + */ +- (void)addPrimaryResponder:(nonnull id)responder; + +/** + * Start processing the next event if not started already. + * + * This function might initiate an async process, whose callback calls this + * function again. + */ +- (void)processNextEvent; + +/** + * Implement how to process an event. + * + * The `onFinish` must be called eventually, either during this function or + * asynchronously later, otherwise the event queue will be stuck. + * + * This function is called by processNextEvent. + */ +- (void)performProcessEvent:(NSEvent*)event + withContext:(nonnull id)context + onFinish:(nonnull VoidBlock)onFinish; + +/** + * Dispatch an event that's not hadled by the responders to text input plugin, + * and potentially to the next responder. + */ +- (void)dispatchTextEvent:(nonnull NSEvent*)pendingEvent + withContext:(nonnull id)context; + +/** + * Clears the current layout and build a new one based on the current layout. + */ +- (void)buildLayout; + +@end + +@implementation FlutterKeyboardManager { + FlutterKeyboardLayout* _keyboardLayout; +} + +- (nonnull instancetype)initWithDelegate:(nonnull id)delegate { + return [self initWithDelegate:delegate keyboardLayout:[[FlutterKeyboardLayout alloc] init]]; +} + +- (nonnull instancetype)initWithDelegate:(nonnull id)delegate + keyboardLayout:(nonnull FlutterKeyboardLayout*)keyboardLayout { + self = [super init]; + if (self != nil) { + _processingEvent = FALSE; + _delegate = delegate; + + FlutterMethodChannel* keyboardChannel = + [FlutterMethodChannel methodChannelWithName:@"flutter/keyboard" + binaryMessenger:_delegate.binaryMessenger + codec:[FlutterStandardMethodCodec sharedInstance]]; + + [keyboardChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { + [self handleKeyboardMethodCall:call result:result]; + }]; + + _primaryResponders = [[NSMutableArray alloc] init]; + + __weak __typeof__(self) weakSelf = self; + [self addPrimaryResponder:[[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, + FlutterKeyEventCallback callback, + void* userData) { + __strong __typeof__(weakSelf) strongSelf = weakSelf; + [strongSelf.delegate sendKeyEvent:event + callback:callback + userData:userData]; + }]]; + + [self + addPrimaryResponder:[[FlutterChannelKeyResponder alloc] + initWithChannel:[FlutterBasicMessageChannel + messageChannelWithName:@"flutter/keyevent" + binaryMessenger:_delegate.binaryMessenger + codec:[FlutterJSONMessageCodec + sharedInstance]]]]; + + _pendingEvents = [[NSMutableArray alloc] init]; + _layoutMap = [NSMutableDictionary dictionary]; + + _keyboardLayout = keyboardLayout; + _keyboardLayout.delegate = self; + [self buildLayout]; + for (id responder in _primaryResponders) { + responder.layoutMap = _layoutMap; + } + } + return self; +} + +- (void)handleKeyboardMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { + if ([[call method] isEqualToString:@"getKeyboardState"]) { + result([self getPressedState]); + } else { + result(FlutterMethodNotImplemented); + } +} + +- (void)addPrimaryResponder:(nonnull id)responder { + [_primaryResponders addObject:responder]; +} + +- (void)handleEvent:(nonnull NSEvent*)event + withContext:(nonnull id)context { + // The `handleEvent` does not process the event immediately, but instead put + // events into a queue. Events are processed one by one by `processNextEvent`. + + // Be sure to add a handling method in propagateKeyEvent when allowing more + // event types here. + if (event.type != NSEventTypeKeyDown && event.type != NSEventTypeKeyUp && + event.type != NSEventTypeFlagsChanged) { + return; + } + + [_pendingEvents addObject:[[FlutterEventWithContext alloc] initWithEvent:event context:context]]; + [self processNextEvent]; +} + +- (BOOL)isDispatchingKeyEvent:(NSEvent*)event { + return _eventBeingDispatched == event; +} + +#pragma mark - Private + +- (void)processNextEvent { + @synchronized(self) { + if (_processingEvent || [_pendingEvents count] == 0) { + return; + } + _processingEvent = TRUE; + } + + FlutterEventWithContext* pendingEvent = [_pendingEvents firstObject]; + [_pendingEvents removeObjectAtIndex:0]; + + __weak __typeof__(self) weakSelf = self; + VoidBlock onFinish = ^() { + weakSelf.processingEvent = FALSE; + [weakSelf processNextEvent]; + }; + [self performProcessEvent:pendingEvent.event withContext:pendingEvent.context onFinish:onFinish]; +} + +- (void)performProcessEvent:(NSEvent*)event + withContext:(id)context + onFinish:(VoidBlock)onFinish { + // Having no primary responders require extra logic, but Flutter hard-codes + // all primary responders, so this is a situation that Flutter will never + // encounter. + NSAssert([_primaryResponders count] >= 0, @"At least one primary responder must be added."); + + __weak __typeof__(self) weakSelf = self; + __block int unreplied = [_primaryResponders count]; + __block BOOL anyHandled = false; + + FlutterAsyncKeyCallback replyCallback = ^(BOOL handled) { + unreplied -= 1; + NSAssert(unreplied >= 0, @"More primary responders replied than possible."); + anyHandled = anyHandled || handled; + if (unreplied == 0) { + if (!anyHandled) { + [weakSelf dispatchTextEvent:event withContext:context]; + } + onFinish(); + } + }; + + for (id responder in _primaryResponders) { + [responder handleEvent:event callback:replyCallback]; + } +} + +- (void)dispatchTextEvent:(NSEvent*)event + withContext:(id)context { + if ([context onTextInputKeyEvent:event]) { + return; + } + NSResponder* nextResponder = context.nextResponder; + if (nextResponder == nil) { + return; + } + NSAssert(_eventBeingDispatched == nil, @"An event is already being dispached."); + _eventBeingDispatched = event; + switch (event.type) { + case NSEventTypeKeyDown: + if ([nextResponder respondsToSelector:@selector(keyDown:)]) { + [nextResponder keyDown:event]; + } + break; + case NSEventTypeKeyUp: + if ([nextResponder respondsToSelector:@selector(keyUp:)]) { + [nextResponder keyUp:event]; + } + break; + case NSEventTypeFlagsChanged: + if ([nextResponder respondsToSelector:@selector(flagsChanged:)]) { + [nextResponder flagsChanged:event]; + } + break; + default: + NSAssert(false, @"Unexpected key event type (got %lu).", event.type); + } + NSAssert(_eventBeingDispatched != nil, @"_eventBeingDispatched was cleared unexpectedly."); + _eventBeingDispatched = nil; +} + +- (void)buildLayout { + [_layoutMap removeAllObjects]; + + std::map mandatoryGoalsByChar; + std::map usLayoutGoalsByKeyCode; + for (const LayoutGoal& goal : flutter::kLayoutGoals) { + if (goal.mandatory) { + mandatoryGoalsByChar[goal.keyChar] = goal; + } else { + usLayoutGoalsByKeyCode[goal.keyCode] = goal; + } + } + + // Derive key mapping for each key code based on their layout clues. + // Key code 0x00 - 0x32 are typewriter keys (letters, digits, and symbols.) + // See keyCodeToPhysicalKey. + const uint16_t kMaxKeyCode = 0x32; +#ifdef DEBUG_PRINT_LAYOUT + NSString* debugLayoutData = @""; +#endif + for (uint16_t keyCode = 0; keyCode <= kMaxKeyCode; keyCode += 1) { + std::vector thisKeyClues = { + [_keyboardLayout lookUpLayoutForKeyCode:keyCode shift:false], + [_keyboardLayout lookUpLayoutForKeyCode:keyCode shift:true]}; +#ifdef DEBUG_PRINT_LAYOUT + debugLayoutData = + debugFormatLayoutData(debugLayoutData, keyCode, thisKeyClues[0], thisKeyClues[1]); +#endif + // The logical key should be the first available clue from below: + // + // - Mandatory goal, if it matches any clue. This ensures that all alnum + // keys can be found somewhere. + // - US layout, if neither clue of the key is EASCII. This ensures that + // there are no non-latin logical keys. + // - Derived on the fly from keyCode & characters. + for (const LayoutClue& clue : thisKeyClues) { + uint32_t keyChar = clue.isDeadKey ? 0 : clue.character; + auto matchingGoal = mandatoryGoalsByChar.find(keyChar); + if (matchingGoal != mandatoryGoalsByChar.end()) { + // Found a key that produces a mandatory char. Use it. + NSAssert(_layoutMap[@(keyCode)] == nil, @"Attempting to assign an assigned key code."); + _layoutMap[@(keyCode)] = @(keyChar); + mandatoryGoalsByChar.erase(matchingGoal); + break; + } + } + bool hasAnyEascii = isEascii(thisKeyClues[0]) || isEascii(thisKeyClues[1]); + // See if any produced char meets the requirement as a logical key. + auto foundUsLayoutGoal = usLayoutGoalsByKeyCode.find(keyCode); + if (foundUsLayoutGoal != usLayoutGoalsByKeyCode.end() && _layoutMap[@(keyCode)] == nil && + !hasAnyEascii) { + _layoutMap[@(keyCode)] = @(foundUsLayoutGoal->second.keyChar); + } + } +#ifdef DEBUG_PRINT_LAYOUT + NSLog(@"%@", debugLayoutData); +#endif + + // Ensure all mandatory goals are assigned. + for (auto mandatoryGoalIter : mandatoryGoalsByChar) { + const LayoutGoal& goal = mandatoryGoalIter.second; + _layoutMap[@(goal.keyCode)] = @(goal.keyChar); + } +} + +- (void)syncModifiersIfNeeded:(NSEventModifierFlags)modifierFlags + timestamp:(NSTimeInterval)timestamp { + for (id responder in _primaryResponders) { + [responder syncModifiersIfNeeded:modifierFlags timestamp:timestamp]; + } +} + +- (void)reset { + _processingEvent = FALSE; + [_pendingEvents removeAllObjects]; +} + +/** + * Returns the keyboard pressed state. + * + * Returns the keyboard pressed state. The dictionary contains one entry per + * pressed keys, mapping from the logical key to the physical key. + */ +- (nonnull NSDictionary*)getPressedState { + // The embedder responder is the first element in _primaryResponders. + FlutterEmbedderKeyResponder* embedderResponder = + (FlutterEmbedderKeyResponder*)_primaryResponders[0]; + return [embedderResponder getPressedState]; +} + +- (void)keyboardLayoutDidChange { + [self buildLayout]; +} + +- (void)replaceKeyboardLayout:(nonnull FlutterKeyboardLayout*)keyboardLayout { + _keyboardLayout = keyboardLayout; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManagerTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManagerTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..773af4afb9cb39ce6e130226732ecfd494f6afcf --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManagerTest.mm @@ -0,0 +1,849 @@ +// 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 +#import +#import + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyPrimaryResponder.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardLayout.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.h" +#include "flutter/shell/platform/embedder/test_utils/key_codes.g.h" +#import "flutter/testing/testing.h" +#include "third_party/googletest/googletest/include/gtest/gtest.h" + +namespace { + +using flutter::testing::keycodes::kLogicalBracketLeft; +using flutter::testing::keycodes::kLogicalDigit1; +using flutter::testing::keycodes::kLogicalDigit2; +using flutter::testing::keycodes::kLogicalKeyA; +using flutter::testing::keycodes::kLogicalKeyM; +using flutter::testing::keycodes::kLogicalKeyQ; +using flutter::testing::keycodes::kLogicalKeyT; +using flutter::testing::keycodes::kPhysicalKeyA; + +using flutter::LayoutClue; + +typedef BOOL (^BoolGetter)(); +typedef void (^AsyncKeyCallbackHandler)(FlutterAsyncKeyCallback callback); +typedef void (^AsyncEmbedderCallbackHandler)(const FlutterKeyEvent* event, + FlutterAsyncKeyCallback callback); +typedef BOOL (^TextInputCallback)(NSEvent*); + +// When the Vietnamese IME converts messages into "pure text" messages, their +// key codes are set to "empty". +// +// The 0 also happens to be the key code for key A. +constexpr uint16_t kKeyCodeEmpty = 0x00; + +// Constants used for `recordCallTypesTo:forTypes:`. +constexpr uint32_t kEmbedderCall = 0x1; +constexpr uint32_t kChannelCall = 0x2; +constexpr uint32_t kTextCall = 0x4; + +// All key clues for a keyboard layout. +// +// The index is (keyCode * 2 + hasShift). The value is 0xMNNNN, where: +// +// - M is whether the key is a dead key (0x1 for true, 0x0 for false). +// - N is the character for this key. (It only supports UTF-16, but we don't +// need full UTF-32 support for unit tests. Moreover, Carbon's UCKeyTranslate +// only returns UniChar (UInt16) anyway.) +typedef const std::array MockLayoutData; + +// The following layout data is generated using DEBUG_PRINT_LAYOUT. + +MockLayoutData kUsLayout = { + // +0x0 Shift +0x1 Shift +0x2 Shift +0x3 Shift + /* 0x00 */ 0x00061, 0x00041, 0x00073, 0x00053, 0x00064, 0x00044, 0x00066, 0x00046, + /* 0x04 */ 0x00068, 0x00048, 0x00067, 0x00047, 0x0007a, 0x0005a, 0x00078, 0x00058, + /* 0x08 */ 0x00063, 0x00043, 0x00076, 0x00056, 0x000a7, 0x000b1, 0x00062, 0x00042, + /* 0x0c */ 0x00071, 0x00051, 0x00077, 0x00057, 0x00065, 0x00045, 0x00072, 0x00052, + /* 0x10 */ 0x00079, 0x00059, 0x00074, 0x00054, 0x00031, 0x00021, 0x00032, 0x00040, + /* 0x14 */ 0x00033, 0x00023, 0x00034, 0x00024, 0x00036, 0x0005e, 0x00035, 0x00025, + /* 0x18 */ 0x0003d, 0x0002b, 0x00039, 0x00028, 0x00037, 0x00026, 0x0002d, 0x0005f, + /* 0x1c */ 0x00038, 0x0002a, 0x00030, 0x00029, 0x0005d, 0x0007d, 0x0006f, 0x0004f, + /* 0x20 */ 0x00075, 0x00055, 0x0005b, 0x0007b, 0x00069, 0x00049, 0x00070, 0x00050, + /* 0x24 */ 0x00000, 0x00000, 0x0006c, 0x0004c, 0x0006a, 0x0004a, 0x00027, 0x00022, + /* 0x28 */ 0x0006b, 0x0004b, 0x0003b, 0x0003a, 0x0005c, 0x0007c, 0x0002c, 0x0003c, + /* 0x2c */ 0x0002f, 0x0003f, 0x0006e, 0x0004e, 0x0006d, 0x0004d, 0x0002e, 0x0003e, + /* 0x30 */ 0x00000, 0x00000, 0x00020, 0x00020, 0x00060, 0x0007e, +}; + +MockLayoutData kFrenchLayout = { + // +0x0 Shift +0x1 Shift +0x2 Shift +0x3 Shift + /* 0x00 */ 0x00071, 0x00051, 0x00073, 0x00053, 0x00064, 0x00044, 0x00066, 0x00046, + /* 0x04 */ 0x00068, 0x00048, 0x00067, 0x00047, 0x00077, 0x00057, 0x00078, 0x00058, + /* 0x08 */ 0x00063, 0x00043, 0x00076, 0x00056, 0x00040, 0x00023, 0x00062, 0x00042, + /* 0x0c */ 0x00061, 0x00041, 0x0007a, 0x0005a, 0x00065, 0x00045, 0x00072, 0x00052, + /* 0x10 */ 0x00079, 0x00059, 0x00074, 0x00054, 0x00026, 0x00031, 0x000e9, 0x00032, + /* 0x14 */ 0x00022, 0x00033, 0x00027, 0x00034, 0x000a7, 0x00036, 0x00028, 0x00035, + /* 0x18 */ 0x0002d, 0x0005f, 0x000e7, 0x00039, 0x000e8, 0x00037, 0x00029, 0x000b0, + /* 0x1c */ 0x00021, 0x00038, 0x000e0, 0x00030, 0x00024, 0x0002a, 0x0006f, 0x0004f, + /* 0x20 */ 0x00075, 0x00055, 0x1005e, 0x100a8, 0x00069, 0x00049, 0x00070, 0x00050, + /* 0x24 */ 0x00000, 0x00000, 0x0006c, 0x0004c, 0x0006a, 0x0004a, 0x000f9, 0x00025, + /* 0x28 */ 0x0006b, 0x0004b, 0x0006d, 0x0004d, 0x10060, 0x000a3, 0x0003b, 0x0002e, + /* 0x2c */ 0x0003d, 0x0002b, 0x0006e, 0x0004e, 0x0002c, 0x0003f, 0x0003a, 0x0002f, + /* 0x30 */ 0x00000, 0x00000, 0x00020, 0x00020, 0x0003c, 0x0003e, +}; + +MockLayoutData kRussianLayout = { + // +0x0 Shift +0x1 Shift +0x2 Shift +0x3 Shift + /* 0x00 */ 0x00444, 0x00424, 0x0044b, 0x0042b, 0x00432, 0x00412, 0x00430, 0x00410, + /* 0x04 */ 0x00440, 0x00420, 0x0043f, 0x0041f, 0x0044f, 0x0042f, 0x00447, 0x00427, + /* 0x08 */ 0x00441, 0x00421, 0x0043c, 0x0041c, 0x0003e, 0x0003c, 0x00438, 0x00418, + /* 0x0c */ 0x00439, 0x00419, 0x00446, 0x00426, 0x00443, 0x00423, 0x0043a, 0x0041a, + /* 0x10 */ 0x0043d, 0x0041d, 0x00435, 0x00415, 0x00031, 0x00021, 0x00032, 0x00022, + /* 0x14 */ 0x00033, 0x02116, 0x00034, 0x00025, 0x00036, 0x0002c, 0x00035, 0x0003a, + /* 0x18 */ 0x0003d, 0x0002b, 0x00039, 0x00028, 0x00037, 0x0002e, 0x0002d, 0x0005f, + /* 0x1c */ 0x00038, 0x0003b, 0x00030, 0x00029, 0x0044a, 0x0042a, 0x00449, 0x00429, + /* 0x20 */ 0x00433, 0x00413, 0x00445, 0x00425, 0x00448, 0x00428, 0x00437, 0x00417, + /* 0x24 */ 0x00000, 0x00000, 0x00434, 0x00414, 0x0043e, 0x0041e, 0x0044d, 0x0042d, + /* 0x28 */ 0x0043b, 0x0041b, 0x00436, 0x00416, 0x00451, 0x00401, 0x00431, 0x00411, + /* 0x2c */ 0x0002f, 0x0003f, 0x00442, 0x00422, 0x0044c, 0x0042c, 0x0044e, 0x0042e, + /* 0x30 */ 0x00000, 0x00000, 0x00020, 0x00020, 0x0005d, 0x0005b, +}; + +MockLayoutData kKhmerLayout = { + // +0x0 Shift +0x1 Shift +0x2 Shift +0x3 Shift + /* 0x00 */ 0x017b6, 0x017ab, 0x0179f, 0x017c3, 0x0178a, 0x0178c, 0x01790, 0x01792, + /* 0x04 */ 0x017a0, 0x017c7, 0x01784, 0x017a2, 0x0178b, 0x0178d, 0x01781, 0x01783, + /* 0x08 */ 0x01785, 0x01787, 0x0179c, 0x017c8, 0x00000, 0x00000, 0x01794, 0x01796, + /* 0x0c */ 0x01786, 0x01788, 0x017b9, 0x017ba, 0x017c1, 0x017c2, 0x0179a, 0x017ac, + /* 0x10 */ 0x01799, 0x017bd, 0x0178f, 0x01791, 0x017e1, 0x00021, 0x017e2, 0x017d7, + /* 0x14 */ 0x017e3, 0x00022, 0x017e4, 0x017db, 0x017e6, 0x017cd, 0x017e5, 0x00025, + /* 0x18 */ 0x017b2, 0x017ce, 0x017e9, 0x017b0, 0x017e7, 0x017d0, 0x017a5, 0x017cc, + /* 0x1c */ 0x017e8, 0x017cf, 0x017e0, 0x017b3, 0x017aa, 0x017a7, 0x017c4, 0x017c5, + /* 0x20 */ 0x017bb, 0x017bc, 0x017c0, 0x017bf, 0x017b7, 0x017b8, 0x01795, 0x01797, + /* 0x24 */ 0x00000, 0x00000, 0x0179b, 0x017a1, 0x017d2, 0x01789, 0x017cb, 0x017c9, + /* 0x28 */ 0x01780, 0x01782, 0x017be, 0x017d6, 0x017ad, 0x017ae, 0x017a6, 0x017b1, + /* 0x2c */ 0x017ca, 0x017af, 0x01793, 0x0178e, 0x01798, 0x017c6, 0x017d4, 0x017d5, + /* 0x30 */ 0x00000, 0x00000, 0x00020, 0x0200b, 0x000ab, 0x000bb, +}; + +NSEvent* keyDownEvent(unsigned short keyCode, NSString* chars = @"", NSString* charsUnmod = @"") { + return [NSEvent keyEventWithType:NSEventTypeKeyDown + location:NSZeroPoint + modifierFlags:0x100 + timestamp:0 + windowNumber:0 + context:nil + characters:chars + charactersIgnoringModifiers:charsUnmod + isARepeat:NO + keyCode:keyCode]; +} + +NSEvent* keyUpEvent(unsigned short keyCode) { + return [NSEvent keyEventWithType:NSEventTypeKeyUp + location:NSZeroPoint + modifierFlags:0x100 + timestamp:0 + windowNumber:0 + context:nil + characters:@"" + charactersIgnoringModifiers:@"" + isARepeat:NO + keyCode:keyCode]; +} + +id checkKeyDownEvent(unsigned short keyCode) { + return [OCMArg checkWithBlock:^BOOL(id value) { + if (![value isKindOfClass:[NSEvent class]]) { + return NO; + } + NSEvent* event = value; + return event.keyCode == keyCode; + }]; +} + +// Clear a list of `FlutterKeyEvent` whose `character` is dynamically allocated. +void clearEvents(std::vector& events) { + for (FlutterKeyEvent& event : events) { + if (event.character != nullptr) { + delete[] event.character; + } + } + events.clear(); +} + +#define VERIFY_DOWN(OUT_LOGICAL, OUT_CHAR) \ + EXPECT_EQ(events[0].type, kFlutterKeyEventTypeDown); \ + EXPECT_EQ(events[0].logical, static_cast(OUT_LOGICAL)); \ + EXPECT_STREQ(events[0].character, (OUT_CHAR)); \ + clearEvents(events); + +} // namespace + +@interface KeyboardTester : NSObject +- (nonnull instancetype)init; + +// Set embedder calls to respond immediately with the given response. +- (void)respondEmbedderCallsWith:(BOOL)response; + +// Record embedder calls to the given storage. +// +// They are not responded to until the stored callbacks are manually called. +- (void)recordEmbedderCallsTo:(nonnull NSMutableArray*)storage; + +- (void)recordEmbedderEventsTo:(nonnull std::vector*)storage + returning:(bool)handled; + +// Set channel calls to respond immediately with the given response. +- (void)respondChannelCallsWith:(BOOL)response; + +// Record channel calls to the given storage. +// +// They are not responded to until the stored callbacks are manually called. +- (void)recordChannelCallsTo:(nonnull NSMutableArray*)storage; + +// Set text calls to respond with the given response. +- (void)respondTextInputWith:(BOOL)response; + +// At the start of any kind of call, record the call type to the given storage. +// +// Only calls that are included in `typeMask` will be added. Options are +// kEmbedderCall, kChannelCall, and kTextCall. +// +// This method does not conflict with other call settings, and the recording +// takes place before the callbacks are (or are not) invoked. +- (void)recordCallTypesTo:(nonnull NSMutableArray*)typeStorage + forTypes:(uint32_t)typeMask; + +- (id)lastKeyboardChannelResult; + +- (void)sendKeyboardChannelMessage:(NSData* _Nullable)message; + +@property(readonly, nonatomic, strong) FlutterKeyboardManager* manager; +@property(readonly, nonatomic, strong) id eventContextMock; +@property(nonatomic, nullable, strong) NSResponder* nextResponder; + +#pragma mark - Private + +- (void)handleEmbedderEvent:(const FlutterKeyEvent&)event + callback:(nullable FlutterKeyEventCallback)callback + userData:(nullable void*)userData; + +- (void)handleChannelMessage:(NSString*)channel + message:(NSData* _Nullable)message + binaryReply:(FlutterBinaryReply _Nullable)callback; + +- (BOOL)handleTextInputKeyEvent:(NSEvent*)event; +@end + +@implementation KeyboardTester { + AsyncEmbedderCallbackHandler _embedderHandler; + AsyncKeyCallbackHandler _channelHandler; + TextInputCallback _textCallback; + + NSMutableArray* _typeStorage; + uint32_t _typeStorageMask; + + __weak id _keyboardLayoutDelegate; + const MockLayoutData* _currentLayout; + + id _keyboardChannelResult; + NSObject* _messengerMock; + FlutterBinaryMessageHandler _keyboardHandler; + + NSObject* _eventContextMock; +} + +- (nonnull instancetype)init { + self = [super init]; + if (self == nil) { + return nil; + } + + _nextResponder = OCMClassMock([NSResponder class]); + [self respondChannelCallsWith:FALSE]; + [self respondEmbedderCallsWith:FALSE]; + [self respondTextInputWith:FALSE]; + + _currentLayout = &kUsLayout; + + _messengerMock = OCMStrictProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub([_messengerMock sendOnChannel:@"flutter/keyevent" + message:[OCMArg any] + binaryReply:[OCMArg any]]) + .andCall(self, @selector(handleChannelMessage:message:binaryReply:)); + OCMStub([_messengerMock setMessageHandlerOnChannel:@"flutter/keyboard" + binaryMessageHandler:[OCMArg any]]) + .andCall(self, @selector(setKeyboardChannelHandler:handler:)); + OCMStub([_messengerMock sendOnChannel:@"flutter/keyboard" message:[OCMArg any]]) + .andCall(self, @selector(handleKeyboardChannelMessage:message:)); + id managerDelegateMock = OCMStrictProtocolMock(@protocol(FlutterKeyboardManagerDelegate)); + OCMStub([managerDelegateMock binaryMessenger]).andReturn(_messengerMock); + OCMStub([managerDelegateMock sendKeyEvent:*(const FlutterKeyEvent*)[OCMArg anyPointer] + callback:nil + userData:nil]) + .ignoringNonObjectArgs() + .andCall(self, @selector(handleEmbedderEvent:callback:userData:)); + + _eventContextMock = OCMStrictProtocolMock(@protocol(FlutterKeyboardManagerEventContext)); + OCMStub([_eventContextMock nextResponder]).andReturn(_nextResponder); + OCMStub([_eventContextMock onTextInputKeyEvent:[OCMArg any]]) + .andCall(self, @selector(handleTextInputKeyEvent:)); + + id keyboardLayoutMock = OCMStrictClassMock([FlutterKeyboardLayout class]); + OCMStub([keyboardLayoutMock lookUpLayoutForKeyCode:0 shift:false]) + .ignoringNonObjectArgs() + .andCall(self, @selector(lookUpLayoutForKeyCode:shift:)); + OCMStub([keyboardLayoutMock setDelegate:[OCMArg any]]) + .andCall(self, @selector(onSetKeyboardLayoutDelegate:)); + + _manager = [[FlutterKeyboardManager alloc] initWithDelegate:managerDelegateMock + keyboardLayout:keyboardLayoutMock]; + return self; +} + +- (id)lastKeyboardChannelResult { + return _keyboardChannelResult; +} + +- (void)respondEmbedderCallsWith:(BOOL)response { + _embedderHandler = ^(const FlutterKeyEvent* event, FlutterAsyncKeyCallback callback) { + callback(response); + }; +} + +- (void)recordEmbedderCallsTo:(nonnull NSMutableArray*)storage { + _embedderHandler = ^(const FlutterKeyEvent* event, FlutterAsyncKeyCallback callback) { + [storage addObject:callback]; + }; +} + +- (void)recordEmbedderEventsTo:(nonnull std::vector*)storage + returning:(bool)handled { + _embedderHandler = ^(const FlutterKeyEvent* event, FlutterAsyncKeyCallback callback) { + FlutterKeyEvent newEvent = *event; + if (event->character != nullptr) { + size_t charLen = strlen(event->character); + char* newCharacter = new char[charLen + 1]; + strlcpy(newCharacter, event->character, charLen + 1); + newEvent.character = newCharacter; + } + storage->push_back(newEvent); + callback(handled); + }; +} + +- (void)respondChannelCallsWith:(BOOL)response { + _channelHandler = ^(FlutterAsyncKeyCallback callback) { + callback(response); + }; +} + +- (void)recordChannelCallsTo:(nonnull NSMutableArray*)storage { + _channelHandler = ^(FlutterAsyncKeyCallback callback) { + [storage addObject:callback]; + }; +} + +- (void)respondTextInputWith:(BOOL)response { + _textCallback = ^(NSEvent* event) { + return response; + }; +} + +- (void)recordCallTypesTo:(nonnull NSMutableArray*)typeStorage + forTypes:(uint32_t)typeMask { + _typeStorage = typeStorage; + _typeStorageMask = typeMask; +} + +- (void)sendKeyboardChannelMessage:(NSData* _Nullable)message { + [_messengerMock sendOnChannel:@"flutter/keyboard" message:message]; +} + +- (void)setLayout:(const MockLayoutData&)layout { + _currentLayout = &layout; + [_keyboardLayoutDelegate keyboardLayoutDidChange]; +} + +#pragma mark - Private + +- (void)handleEmbedderEvent:(const FlutterKeyEvent&)event + callback:(nullable FlutterKeyEventCallback)callback + userData:(nullable void*)userData { + if (_typeStorage != nil && (_typeStorageMask & kEmbedderCall) != 0) { + [_typeStorage addObject:@(kEmbedderCall)]; + } + if (callback != nullptr) { + _embedderHandler(&event, ^(BOOL handled) { + callback(handled, userData); + }); + } +} + +- (void)handleChannelMessage:(NSString*)channel + message:(NSData* _Nullable)message + binaryReply:(FlutterBinaryReply _Nullable)callback { + if (_typeStorage != nil && (_typeStorageMask & kChannelCall) != 0) { + [_typeStorage addObject:@(kChannelCall)]; + } + _channelHandler(^(BOOL handled) { + NSDictionary* result = @{ + @"handled" : @(handled), + }; + NSData* encodedKeyEvent = [[FlutterJSONMessageCodec sharedInstance] encode:result]; + callback(encodedKeyEvent); + }); +} + +- (void)handleKeyboardChannelMessage:(NSString*)channel message:(NSData* _Nullable)message { + _keyboardHandler(message, ^(id result) { + _keyboardChannelResult = result; + }); +} + +- (BOOL)handleTextInputKeyEvent:(NSEvent*)event { + if (_typeStorage != nil && (_typeStorageMask & kTextCall) != 0) { + [_typeStorage addObject:@(kTextCall)]; + } + return _textCallback(event); +} + +- (void)onSetKeyboardLayoutDelegate:(id)delegate { + _keyboardLayoutDelegate = delegate; +} + +- (LayoutClue)lookUpLayoutForKeyCode:(uint16_t)keyCode shift:(BOOL)shift { + uint32_t cluePair = (*_currentLayout)[(keyCode * 2) + (shift ? 1 : 0)]; + const uint32_t kCharMask = 0xffff; + const uint32_t kDeadKeyMask = 0x10000; + return LayoutClue{cluePair & kCharMask, (cluePair & kDeadKeyMask) != 0}; +} + +- (void)setKeyboardChannelHandler:(NSString*)channel handler:(FlutterBinaryMessageHandler)handler { + _keyboardHandler = handler; +} + +@end + +@interface FlutterKeyboardManagerUnittestsObjC : NSObject +- (bool)singlePrimaryResponder; +- (bool)doublePrimaryResponder; +- (bool)textInputPlugin; +- (bool)emptyNextResponder; +- (bool)getPressedState; +- (bool)keyboardChannelGetPressedState; +- (bool)racingConditionBetweenKeyAndText; +- (bool)correctLogicalKeyForLayouts; +- (bool)shouldNotHoldStrongReferenceToDelegate; +@end + +namespace flutter::testing { + +TEST(FlutterKeyboardManagerUnittests, SinglePrimaryResponder) { + ASSERT_TRUE([[FlutterKeyboardManagerUnittestsObjC alloc] singlePrimaryResponder]); +} + +TEST(FlutterKeyboardManagerUnittests, DoublePrimaryResponder) { + ASSERT_TRUE([[FlutterKeyboardManagerUnittestsObjC alloc] doublePrimaryResponder]); +} + +TEST(FlutterKeyboardManagerUnittests, SingleFinalResponder) { + ASSERT_TRUE([[FlutterKeyboardManagerUnittestsObjC alloc] textInputPlugin]); +} + +TEST(FlutterKeyboardManagerUnittests, EmptyNextResponder) { + ASSERT_TRUE([[FlutterKeyboardManagerUnittestsObjC alloc] emptyNextResponder]); +} + +TEST(FlutterKeyboardManagerUnittests, GetPressedState) { + ASSERT_TRUE([[FlutterKeyboardManagerUnittestsObjC alloc] getPressedState]); +} + +TEST(FlutterKeyboardManagerUnittests, KeyboardChannelGetPressedState) { + ASSERT_TRUE([[FlutterKeyboardManagerUnittestsObjC alloc] keyboardChannelGetPressedState]); +} + +TEST(FlutterKeyboardManagerUnittests, RacingConditionBetweenKeyAndText) { + ASSERT_TRUE([[FlutterKeyboardManagerUnittestsObjC alloc] racingConditionBetweenKeyAndText]); +} + +TEST(FlutterKeyboardManagerUnittests, CorrectLogicalKeyForLayouts) { + ASSERT_TRUE([[FlutterKeyboardManagerUnittestsObjC alloc] correctLogicalKeyForLayouts]); +} + +TEST(FlutterKeyboardManagerUnittests, ShouldNotHoldStrongReferenceToDelegate) { + ASSERT_TRUE([[FlutterKeyboardManagerUnittestsObjC alloc] shouldNotHoldStrongReferenceToDelegate]); +} + +} // namespace flutter::testing + +@implementation FlutterKeyboardManagerUnittestsObjC + +- (bool)singlePrimaryResponder { + KeyboardTester* tester = [[KeyboardTester alloc] init]; + NSMutableArray* embedderCallbacks = + [NSMutableArray array]; + [tester recordEmbedderCallsTo:embedderCallbacks]; + + // Case: The responder reports FALSE + [tester.manager handleEvent:keyDownEvent(0x50) withContext:tester.eventContextMock]; + EXPECT_EQ([embedderCallbacks count], 1u); + embedderCallbacks[0](FALSE); + OCMVerify([tester.nextResponder keyDown:checkKeyDownEvent(0x50)]); + [embedderCallbacks removeAllObjects]; + + // Case: The responder reports TRUE + [tester.manager handleEvent:keyUpEvent(0x50) withContext:tester.eventContextMock]; + EXPECT_EQ([embedderCallbacks count], 1u); + embedderCallbacks[0](TRUE); + // [owner.nextResponder keyUp:] should not be called, otherwise an error will be thrown. + + return true; +} + +- (bool)doublePrimaryResponder { + KeyboardTester* tester = [[KeyboardTester alloc] init]; + + // Send a down event first so we can send an up event later. + [tester respondEmbedderCallsWith:false]; + [tester respondChannelCallsWith:false]; + [tester.manager handleEvent:keyDownEvent(0x50) withContext:tester.eventContextMock]; + + NSMutableArray* embedderCallbacks = + [NSMutableArray array]; + NSMutableArray* channelCallbacks = + [NSMutableArray array]; + [tester recordEmbedderCallsTo:embedderCallbacks]; + [tester recordChannelCallsTo:channelCallbacks]; + + // Case: Both responders report TRUE. + [tester.manager handleEvent:keyUpEvent(0x50) withContext:tester.eventContextMock]; + EXPECT_EQ([embedderCallbacks count], 1u); + EXPECT_EQ([channelCallbacks count], 1u); + embedderCallbacks[0](TRUE); + channelCallbacks[0](TRUE); + EXPECT_EQ([embedderCallbacks count], 1u); + EXPECT_EQ([channelCallbacks count], 1u); + // [tester.nextResponder keyUp:] should not be called, otherwise an error will be thrown. + [embedderCallbacks removeAllObjects]; + [channelCallbacks removeAllObjects]; + + // Case: One responder reports TRUE. + [tester respondEmbedderCallsWith:false]; + [tester respondChannelCallsWith:false]; + [tester.manager handleEvent:keyDownEvent(0x50) withContext:tester.eventContextMock]; + + [tester recordEmbedderCallsTo:embedderCallbacks]; + [tester recordChannelCallsTo:channelCallbacks]; + [tester.manager handleEvent:keyUpEvent(0x50) withContext:tester.eventContextMock]; + EXPECT_EQ([embedderCallbacks count], 1u); + EXPECT_EQ([channelCallbacks count], 1u); + embedderCallbacks[0](FALSE); + channelCallbacks[0](TRUE); + EXPECT_EQ([embedderCallbacks count], 1u); + EXPECT_EQ([channelCallbacks count], 1u); + // [tester.nextResponder keyUp:] should not be called, otherwise an error will be thrown. + [embedderCallbacks removeAllObjects]; + [channelCallbacks removeAllObjects]; + + // Case: Both responders report FALSE. + [tester.manager handleEvent:keyDownEvent(0x53) withContext:tester.eventContextMock]; + EXPECT_EQ([embedderCallbacks count], 1u); + EXPECT_EQ([channelCallbacks count], 1u); + embedderCallbacks[0](FALSE); + channelCallbacks[0](FALSE); + EXPECT_EQ([embedderCallbacks count], 1u); + EXPECT_EQ([channelCallbacks count], 1u); + OCMVerify([tester.nextResponder keyDown:checkKeyDownEvent(0x53)]); + [embedderCallbacks removeAllObjects]; + [channelCallbacks removeAllObjects]; + + return true; +} + +- (bool)textInputPlugin { + KeyboardTester* tester = [[KeyboardTester alloc] init]; + + // Send a down event first so we can send an up event later. + [tester respondEmbedderCallsWith:false]; + [tester respondChannelCallsWith:false]; + [tester.manager handleEvent:keyDownEvent(0x50) withContext:tester.eventContextMock]; + + NSMutableArray* callbacks = + [NSMutableArray array]; + [tester recordEmbedderCallsTo:callbacks]; + + // Case: Primary responder responds TRUE. The event shouldn't be handled by + // the secondary responder. + [tester respondTextInputWith:FALSE]; + [tester.manager handleEvent:keyUpEvent(0x50) withContext:tester.eventContextMock]; + EXPECT_EQ([callbacks count], 1u); + callbacks[0](TRUE); + // [owner.nextResponder keyUp:] should not be called, otherwise an error will be thrown. + [callbacks removeAllObjects]; + + // Send a down event first so we can send an up event later. + [tester respondEmbedderCallsWith:false]; + [tester.manager handleEvent:keyDownEvent(0x50) withContext:tester.eventContextMock]; + + // Case: Primary responder responds FALSE. The secondary responder returns + // TRUE. + [tester recordEmbedderCallsTo:callbacks]; + [tester respondTextInputWith:TRUE]; + [tester.manager handleEvent:keyUpEvent(0x50) withContext:tester.eventContextMock]; + EXPECT_EQ([callbacks count], 1u); + callbacks[0](FALSE); + // [owner.nextResponder keyUp:] should not be called, otherwise an error will be thrown. + [callbacks removeAllObjects]; + + // Case: Primary responder responds FALSE. The secondary responder returns FALSE. + [tester respondTextInputWith:FALSE]; + [tester.manager handleEvent:keyDownEvent(0x50) withContext:tester.eventContextMock]; + EXPECT_EQ([callbacks count], 1u); + callbacks[0](FALSE); + OCMVerify([tester.nextResponder keyDown:checkKeyDownEvent(0x50)]); + [callbacks removeAllObjects]; + + return true; +} + +- (bool)emptyNextResponder { + KeyboardTester* tester = [[KeyboardTester alloc] init]; + tester.nextResponder = nil; + + [tester respondEmbedderCallsWith:false]; + [tester respondChannelCallsWith:false]; + [tester respondTextInputWith:false]; + [tester.manager handleEvent:keyDownEvent(0x50) withContext:tester.eventContextMock]; + + // Passes if no error is thrown. + return true; +} + +- (bool)getPressedState { + KeyboardTester* tester = [[KeyboardTester alloc] init]; + + [tester respondEmbedderCallsWith:false]; + [tester respondChannelCallsWith:false]; + [tester respondTextInputWith:false]; + [tester.manager handleEvent:keyDownEvent(kVK_ANSI_A) withContext:tester.eventContextMock]; + + NSDictionary* pressingRecords = [tester.manager getPressedState]; + EXPECT_EQ([pressingRecords count], 1u); + EXPECT_EQ(pressingRecords[@(kPhysicalKeyA)], @(kLogicalKeyA)); + + return true; +} + +- (bool)keyboardChannelGetPressedState { + KeyboardTester* tester = [[KeyboardTester alloc] init]; + + [tester respondEmbedderCallsWith:false]; + [tester respondChannelCallsWith:false]; + [tester respondTextInputWith:false]; + [tester.manager handleEvent:keyDownEvent(kVK_ANSI_A) withContext:tester.eventContextMock]; + + FlutterMethodCall* getKeyboardStateMethodCall = + [FlutterMethodCall methodCallWithMethodName:@"getKeyboardState" arguments:nil]; + NSData* getKeyboardStateMessage = + [[FlutterStandardMethodCodec sharedInstance] encodeMethodCall:getKeyboardStateMethodCall]; + [tester sendKeyboardChannelMessage:getKeyboardStateMessage]; + + id encodedResult = [tester lastKeyboardChannelResult]; + id decoded = [[FlutterStandardMethodCodec sharedInstance] decodeEnvelope:encodedResult]; + + EXPECT_EQ([decoded count], 1u); + EXPECT_EQ(decoded[@(kPhysicalKeyA)], @(kLogicalKeyA)); + + return true; +} + +// Regression test for https://github.com/flutter/flutter/issues/82673. +- (bool)racingConditionBetweenKeyAndText { + KeyboardTester* tester = [[KeyboardTester alloc] init]; + + // Use Vietnamese IME (GoTiengViet, Telex mode) to type "uco". + + // The events received by the framework. The engine might receive + // a channel message "setEditingState" from the framework. + NSMutableArray* keyCallbacks = + [NSMutableArray array]; + [tester recordEmbedderCallsTo:keyCallbacks]; + + NSMutableArray* allCalls = [NSMutableArray array]; + [tester recordCallTypesTo:allCalls forTypes:(kEmbedderCall | kTextCall)]; + + // Tap key U, which is converted by IME into a pure text message "ư". + + [tester.manager handleEvent:keyDownEvent(kKeyCodeEmpty, @"ư", @"ư") + withContext:tester.eventContextMock]; + EXPECT_EQ([keyCallbacks count], 1u); + EXPECT_EQ([allCalls count], 1u); + EXPECT_EQ(allCalls[0], @(kEmbedderCall)); + keyCallbacks[0](false); + EXPECT_EQ([keyCallbacks count], 1u); + EXPECT_EQ([allCalls count], 2u); + EXPECT_EQ(allCalls[1], @(kTextCall)); + [keyCallbacks removeAllObjects]; + [allCalls removeAllObjects]; + + [tester.manager handleEvent:keyUpEvent(kKeyCodeEmpty) withContext:tester.eventContextMock]; + EXPECT_EQ([keyCallbacks count], 1u); + keyCallbacks[0](false); + EXPECT_EQ([keyCallbacks count], 1u); + EXPECT_EQ([allCalls count], 2u); + [keyCallbacks removeAllObjects]; + [allCalls removeAllObjects]; + + // Tap key O, which is converted to normal KeyO events, but the responses are + // slow. + + [tester.manager handleEvent:keyDownEvent(kVK_ANSI_O, @"o", @"o") + withContext:tester.eventContextMock]; + [tester.manager handleEvent:keyUpEvent(kVK_ANSI_O) withContext:tester.eventContextMock]; + EXPECT_EQ([keyCallbacks count], 1u); + EXPECT_EQ([allCalls count], 1u); + EXPECT_EQ(allCalls[0], @(kEmbedderCall)); + + // Tap key C, which results in two Backspace messages first - and here they + // arrive before the key O messages are responded. + + [tester.manager handleEvent:keyDownEvent(kVK_Delete) withContext:tester.eventContextMock]; + [tester.manager handleEvent:keyUpEvent(kVK_Delete) withContext:tester.eventContextMock]; + EXPECT_EQ([keyCallbacks count], 1u); + EXPECT_EQ([allCalls count], 1u); + + // The key O down is responded, which releases a text call (for KeyO down) and + // an embedder call (for KeyO up) immediately. + keyCallbacks[0](false); + EXPECT_EQ([keyCallbacks count], 2u); + EXPECT_EQ([allCalls count], 3u); + EXPECT_EQ(allCalls[1], @(kTextCall)); // The order is important! + EXPECT_EQ(allCalls[2], @(kEmbedderCall)); + + // The key O up is responded, which releases a text call (for KeyO up) and + // an embedder call (for Backspace down) immediately. + keyCallbacks[1](false); + EXPECT_EQ([keyCallbacks count], 3u); + EXPECT_EQ([allCalls count], 5u); + EXPECT_EQ(allCalls[3], @(kTextCall)); // The order is important! + EXPECT_EQ(allCalls[4], @(kEmbedderCall)); + + // Finish up callbacks. + keyCallbacks[2](false); + keyCallbacks[3](false); + + return true; +} + +- (bool)correctLogicalKeyForLayouts { + KeyboardTester* tester = [[KeyboardTester alloc] init]; + tester.nextResponder = nil; + + std::vector events; + [tester recordEmbedderEventsTo:&events returning:true]; + [tester respondChannelCallsWith:false]; + [tester respondTextInputWith:false]; + + auto sendTap = [&](uint16_t keyCode, NSString* chars, NSString* charsUnmod) { + [tester.manager handleEvent:keyDownEvent(keyCode, chars, charsUnmod) + withContext:tester.eventContextMock]; + [tester.manager handleEvent:keyUpEvent(keyCode) withContext:tester.eventContextMock]; + }; + + /* US keyboard layout */ + + sendTap(kVK_ANSI_A, @"a", @"a"); // KeyA + VERIFY_DOWN(kLogicalKeyA, "a"); + + sendTap(kVK_ANSI_A, @"A", @"A"); // Shift-KeyA + VERIFY_DOWN(kLogicalKeyA, "A"); + + sendTap(kVK_ANSI_A, @"å", @"a"); // Option-KeyA + VERIFY_DOWN(kLogicalKeyA, "å"); + + sendTap(kVK_ANSI_T, @"t", @"t"); // KeyT + VERIFY_DOWN(kLogicalKeyT, "t"); + + sendTap(kVK_ANSI_1, @"1", @"1"); // Digit1 + VERIFY_DOWN(kLogicalDigit1, "1"); + + sendTap(kVK_ANSI_1, @"!", @"!"); // Shift-Digit1 + VERIFY_DOWN(kLogicalDigit1, "!"); + + sendTap(kVK_ANSI_Minus, @"-", @"-"); // Minus + VERIFY_DOWN('-', "-"); + + sendTap(kVK_ANSI_Minus, @"=", @"="); // Shift-Minus + VERIFY_DOWN('=', "="); + + /* French keyboard layout */ + [tester setLayout:kFrenchLayout]; + + sendTap(kVK_ANSI_A, @"q", @"q"); // KeyA + VERIFY_DOWN(kLogicalKeyQ, "q"); + + sendTap(kVK_ANSI_A, @"Q", @"Q"); // Shift-KeyA + VERIFY_DOWN(kLogicalKeyQ, "Q"); + + sendTap(kVK_ANSI_Semicolon, @"m", @"m"); // ; but prints M + VERIFY_DOWN(kLogicalKeyM, "m"); + + sendTap(kVK_ANSI_M, @",", @","); // M but prints , + VERIFY_DOWN(',', ","); + + sendTap(kVK_ANSI_1, @"&", @"&"); // Digit1 + VERIFY_DOWN(kLogicalDigit1, "&"); + + sendTap(kVK_ANSI_1, @"1", @"1"); // Shift-Digit1 + VERIFY_DOWN(kLogicalDigit1, "1"); + + sendTap(kVK_ANSI_Minus, @")", @")"); // Minus + VERIFY_DOWN(')', ")"); + + sendTap(kVK_ANSI_Minus, @"°", @"°"); // Shift-Minus + VERIFY_DOWN(L'°', "°"); + + /* Russian keyboard layout */ + [tester setLayout:kRussianLayout]; + + sendTap(kVK_ANSI_A, @"ф", @"ф"); // KeyA + VERIFY_DOWN(kLogicalKeyA, "ф"); + + sendTap(kVK_ANSI_1, @"1", @"1"); // Digit1 + VERIFY_DOWN(kLogicalDigit1, "1"); + + sendTap(kVK_ANSI_LeftBracket, @"х", @"х"); + VERIFY_DOWN(kLogicalBracketLeft, "х"); + + /* Khmer keyboard layout */ + // Regression test for https://github.com/flutter/flutter/issues/108729 + [tester setLayout:kKhmerLayout]; + + sendTap(kVK_ANSI_2, @"២", @"២"); // Digit2 + VERIFY_DOWN(kLogicalDigit2, "២"); + + return TRUE; +} + +- (bool)shouldNotHoldStrongReferenceToDelegate { + __strong FlutterKeyboardManager* strongKeyboardManager; + __weak id weakDelegate; + + @autoreleasepool { + id binaryMessengerMock = OCMStrictProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub([binaryMessengerMock setMessageHandlerOnChannel:[OCMArg any] + binaryMessageHandler:[OCMArg any]]); + + id delegateMock = OCMStrictProtocolMock(@protocol(FlutterKeyboardManagerDelegate)); + OCMStub([delegateMock binaryMessenger]).andReturn(binaryMessengerMock); + + FlutterKeyboardManager* keyboardManager = + [[FlutterKeyboardManager alloc] initWithDelegate:delegateMock]; + strongKeyboardManager = keyboardManager; + weakDelegate = delegateMock; + } + + return weakDelegate == nil; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin.h new file mode 100644 index 0000000000000000000000000000000000000000..d4f3df4264ba17f8391ec4d96730e918b79e89f9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin.h @@ -0,0 +1,28 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERMENUPLUGIN_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERMENUPLUGIN_H_ + +#import + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h" +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginMacOS.h" +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h" + +/** + * A plugin to configure and control the native system menu. + * + * Responsible for bridging the native macOS menu system with the Flutter + * framework's PlatformMenuBar class, via method channels. + */ +@interface FlutterMenuPlugin : NSObject + +/** + * Registers a FlutterMenuPlugin with the given registrar. + */ ++ (void)registerWithRegistrar:(nonnull id)registrar; +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERMENUPLUGIN_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin.mm new file mode 100644 index 0000000000000000000000000000000000000000..b9ba7fd4bd8aa89328ad1d8b09d8f71122050a27 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin.mm @@ -0,0 +1,419 @@ +// 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. + +#import "FlutterMenuPlugin.h" + +#include + +#import "flutter/shell/platform/common/platform_provided_menu.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h" + +// Channel constants +static NSString* const kChannelName = @"flutter/menu"; +static NSString* const kIsPluginAvailableMethod = @"Menu.isPluginAvailable"; +static NSString* const kMenuSetMenusMethod = @"Menu.setMenus"; +static NSString* const kMenuSelectedCallbackMethod = @"Menu.selectedCallback"; +static NSString* const kMenuOpenedMethod = @"Menu.opened"; +static NSString* const kMenuClosedMethod = @"Menu.closed"; + +// Serialization keys for menu objects +static NSString* const kIdKey = @"id"; +static NSString* const kLabelKey = @"label"; +static NSString* const kEnabledKey = @"enabled"; +static NSString* const kChildrenKey = @"children"; +static NSString* const kDividerKey = @"isDivider"; +static NSString* const kShortcutCharacterKey = @"shortcutCharacter"; +static NSString* const kShortcutTriggerKey = @"shortcutTrigger"; +static NSString* const kShortcutModifiersKey = @"shortcutModifiers"; +static NSString* const kPlatformProvidedMenuKey = @"platformProvidedMenu"; + +// Key shortcut constants +constexpr int kFlutterShortcutModifierMeta = 1 << 0; +constexpr int kFlutterShortcutModifierShift = 1 << 1; +constexpr int kFlutterShortcutModifierAlt = 1 << 2; +constexpr int kFlutterShortcutModifierControl = 1 << 3; + +constexpr uint64_t kFlutterKeyIdPlaneMask = 0xff00000000l; +constexpr uint64_t kFlutterKeyIdUnicodePlane = 0x0000000000l; +constexpr uint64_t kFlutterKeyIdValueMask = 0x00ffffffffl; + +static const NSDictionary* logicalKeyToKeyCode = {}; + +// What to look for in menu titles to replace with the application name. +static NSString* const kAppName = @"APP_NAME"; + +// Odd facts about AppKit key equivalents: +// +// 1) ⌃⇧1 and ⇧1 cannot exist in the same app, or the former triggers the latter’s +// action. +// 2) ⌃⌥⇧1 and ⇧1 cannot exist in the same app, or the former triggers the latter’s +// action. +// 3) ⌃⌥⇧1 and ⌃⇧1 cannot exist in the same app, or the former triggers the latter’s +// action. +// 4) ⌃⇧a is equivalent to ⌃A: If a keyEquivalent is a capitalized alphabetical +// letter and keyEquivalentModifierMask does not include +// NSEventModifierFlagShift, AppKit will add ⇧ automatically in the UI. + +/** + * Maps the string used by NSMenuItem for the given special key equivalent. + * Keys are the logical key ids of matching trigger keys. + */ +static NSDictionary* GetMacOsSpecialKeys() { + return @{ + @0x00100000008 : [NSNumber numberWithInt:NSBackspaceCharacter], + @0x00100000009 : [NSNumber numberWithInt:NSTabCharacter], + @0x0010000000a : [NSNumber numberWithInt:NSNewlineCharacter], + @0x0010000000c : [NSNumber numberWithInt:NSFormFeedCharacter], + @0x0010000000d : [NSNumber numberWithInt:NSCarriageReturnCharacter], + @0x0010000007f : [NSNumber numberWithInt:NSDeleteCharacter], + @0x00100000801 : [NSNumber numberWithInt:NSF1FunctionKey], + @0x00100000802 : [NSNumber numberWithInt:NSF2FunctionKey], + @0x00100000803 : [NSNumber numberWithInt:NSF3FunctionKey], + @0x00100000804 : [NSNumber numberWithInt:NSF4FunctionKey], + @0x00100000805 : [NSNumber numberWithInt:NSF5FunctionKey], + @0x00100000806 : [NSNumber numberWithInt:NSF6FunctionKey], + @0x00100000807 : [NSNumber numberWithInt:NSF7FunctionKey], + @0x00100000808 : [NSNumber numberWithInt:NSF8FunctionKey], + @0x00100000809 : [NSNumber numberWithInt:NSF9FunctionKey], + @0x0010000080a : [NSNumber numberWithInt:NSF10FunctionKey], + @0x0010000080b : [NSNumber numberWithInt:NSF11FunctionKey], + @0x0010000080c : [NSNumber numberWithInt:NSF12FunctionKey], + @0x0010000080d : [NSNumber numberWithInt:NSF13FunctionKey], + @0x0010000080e : [NSNumber numberWithInt:NSF14FunctionKey], + @0x0010000080f : [NSNumber numberWithInt:NSF15FunctionKey], + @0x00100000810 : [NSNumber numberWithInt:NSF16FunctionKey], + @0x00100000811 : [NSNumber numberWithInt:NSF17FunctionKey], + @0x00100000812 : [NSNumber numberWithInt:NSF18FunctionKey], + @0x00100000813 : [NSNumber numberWithInt:NSF19FunctionKey], + @0x00100000814 : [NSNumber numberWithInt:NSF20FunctionKey], + + // For some reason, there don't appear to be constants for these in ObjC. In + // Swift, there is a class with static members for these: KeyEquivalent. The + // values below are taken from that (where they don't already appear above). + @0x00100000302 : @0xf702, // ArrowLeft + @0x00100000303 : @0xf703, // ArrowRight + @0x00100000304 : @0xf700, // ArrowUp + @0x00100000301 : @0xf701, // ArrowDown + @0x00100000306 : @0xf729, // Home + @0x00100000305 : @0xf72B, // End + @0x00100000308 : @0xf72c, // PageUp + @0x00100000307 : @0xf72d, // PageDown + @0x0010000001b : @0x001B, // Escape + }; +} + +/** + * The mapping from the PlatformProvidedMenu enum to the macOS selectors for the provided + * menus. + */ +static const std::map GetMacOSProvidedMenus() { + return { + {flutter::PlatformProvidedMenu::kAbout, @selector(orderFrontStandardAboutPanel:)}, + {flutter::PlatformProvidedMenu::kQuit, @selector(terminate:)}, + // servicesSubmenu is handled specially below: it is assumed to be the first + // submenu in the preserved platform provided menus, since it doesn't have a + // definitive selector like the rest. + {flutter::PlatformProvidedMenu::kServicesSubmenu, @selector(submenuAction:)}, + {flutter::PlatformProvidedMenu::kHide, @selector(hide:)}, + {flutter::PlatformProvidedMenu::kHideOtherApplications, @selector(hideOtherApplications:)}, + {flutter::PlatformProvidedMenu::kShowAllApplications, @selector(unhideAllApplications:)}, + {flutter::PlatformProvidedMenu::kStartSpeaking, @selector(startSpeaking:)}, + {flutter::PlatformProvidedMenu::kStopSpeaking, @selector(stopSpeaking:)}, + {flutter::PlatformProvidedMenu::kToggleFullScreen, @selector(toggleFullScreen:)}, + {flutter::PlatformProvidedMenu::kMinimizeWindow, @selector(performMiniaturize:)}, + {flutter::PlatformProvidedMenu::kZoomWindow, @selector(performZoom:)}, + {flutter::PlatformProvidedMenu::kArrangeWindowsInFront, @selector(arrangeInFront:)}, + }; +} + +/** + * Returns the NSEventModifierFlags of |modifiers|, a value from + * kShortcutKeyModifiers. + */ +static NSEventModifierFlags KeyEquivalentModifierMaskForModifiers(NSNumber* modifiers) { + int flutterModifierFlags = modifiers.intValue; + NSEventModifierFlags flags = 0; + if (flutterModifierFlags & kFlutterShortcutModifierMeta) { + flags |= NSEventModifierFlagCommand; + } + if (flutterModifierFlags & kFlutterShortcutModifierShift) { + flags |= NSEventModifierFlagShift; + } + if (flutterModifierFlags & kFlutterShortcutModifierAlt) { + flags |= NSEventModifierFlagOption; + } + if (flutterModifierFlags & kFlutterShortcutModifierControl) { + flags |= NSEventModifierFlagControl; + } + // There are also modifier flags for things like the function (Fn) key, but + // the framework doesn't support those. + return flags; +} + +/** + * An NSMenuDelegate used to listen for changes in the menu when it opens and + * closes. + */ +@interface FlutterMenuDelegate : NSObject +/** + * When this delegate receives notification that the menu opened or closed, it + * will send a message on the given channel to that effect for the menu item + * with the given id (the ID comes from the data supplied by the framework to + * |FlutterMenuPlugin.setMenus|). + */ +- (instancetype)initWithIdentifier:(int64_t)identifier channel:(FlutterMethodChannel*)channel; +@end + +@implementation FlutterMenuDelegate { + FlutterMethodChannel* _channel; + int64_t _identifier; +} + +- (instancetype)initWithIdentifier:(int64_t)identifier channel:(FlutterMethodChannel*)channel { + self = [super init]; + if (self) { + _identifier = identifier; + _channel = channel; + } + return self; +} + +- (void)menuWillOpen:(NSMenu*)menu { + [_channel invokeMethod:kMenuOpenedMethod arguments:@(_identifier)]; +} + +- (void)menuDidClose:(NSMenu*)menu { + [_channel invokeMethod:kMenuClosedMethod arguments:@(_identifier)]; +} +@end + +@interface FlutterMenuPlugin () +// Initialize the plugin with the given method channel. +- (instancetype)initWithChannel:(FlutterMethodChannel*)channel; + +// Iterates through the given menu hierarchy, and replaces "APP_NAME" +// with the localized running application name. +- (void)replaceAppName:(NSArray*)items; + +// Look up the menu item with the given selector in the list of provided menus +// and return it. +- (NSMenuItem*)findProvidedMenuItem:(NSMenu*)menu ofType:(SEL)selector; + +// Create a platform-provided menu from the given enum type. +- (NSMenuItem*)createPlatformProvidedMenu:(flutter::PlatformProvidedMenu)type; + +// Create an NSMenuItem from information in the dictionary sent by the framework. +- (NSMenuItem*)menuItemFromFlutterRepresentation:(NSDictionary*)representation; + +// Invokes kMenuSelectedCallbackMethod with the senders ID. +// +// Used as the callback for all Flutter-created menu items that have IDs. +- (void)flutterMenuItemSelected:(id)sender; + +// Replaces the NSApp.mainMenu with menus created from an array of top level +// menus sent by the framework. +- (void)setMenus:(nonnull NSDictionary*)representation; +@end + +@implementation FlutterMenuPlugin { + // The channel used to communicate with Flutter. + FlutterMethodChannel* _channel; + + // This contains a copy of the default platform provided items. + NSArray* _platformProvidedItems; + // These are the menu delegates that will listen to open/close events for menu + // items. This array is holding them so that we can deallocate them when + // rebuilding the menus. + NSMutableArray* _menuDelegates; +} + +#pragma mark - Private Methods + +- (instancetype)initWithChannel:(FlutterMethodChannel*)channel { + self = [super init]; + if (self) { + _channel = channel; + _platformProvidedItems = @[]; + _menuDelegates = [[NSMutableArray alloc] init]; + + // Make a copy of all the platform provided menus for later use. + _platformProvidedItems = [[NSApp.mainMenu itemArray] mutableCopy]; + + // As copied, these platform provided menu items don't yet have the APP_NAME + // string replaced in them, so this rectifies that. + [self replaceAppName:_platformProvidedItems]; + } + return self; +} + +/** + * Iterates through the given menu hierarchy, and replaces "APP_NAME" + * with the localized running application name. + */ +- (void)replaceAppName:(NSArray*)items { + NSString* appName = [NSRunningApplication currentApplication].localizedName; + for (NSMenuItem* item in items) { + if ([[item title] containsString:kAppName]) { + [item setTitle:[[item title] stringByReplacingOccurrencesOfString:kAppName + withString:appName]]; + } + if ([item hasSubmenu]) { + [self replaceAppName:[[item submenu] itemArray]]; + } + } +} + +- (NSMenuItem*)findProvidedMenuItem:(NSMenu*)menu ofType:(SEL)selector { + const NSArray* items = menu ? menu.itemArray : _platformProvidedItems; + for (NSMenuItem* item in items) { + if ([item action] == selector) { + return item; + } + if ([[item submenu] numberOfItems] > 0) { + NSMenuItem* foundChild = [self findProvidedMenuItem:[item submenu] ofType:selector]; + if (foundChild) { + return foundChild; + } + } + } + return nil; +} + +- (NSMenuItem*)createPlatformProvidedMenu:(flutter::PlatformProvidedMenu)type { + const std::map providedMenus = GetMacOSProvidedMenus(); + auto found_type = providedMenus.find(type); + if (found_type == providedMenus.end()) { + return nil; + } + SEL selectorTarget = found_type->second; + // Since it doesn't have a definitive selector, the Services submenu is + // assumed to be the first item with a submenu action in the first menu item + // of the default menu set. We can't just get the title to check, since that + // is localized, and the contents of the menu aren't fixed (or even available). + NSMenu* startingMenu = type == flutter::PlatformProvidedMenu::kServicesSubmenu + ? [_platformProvidedItems[0] submenu] + : nil; + NSMenuItem* found = [self findProvidedMenuItem:startingMenu ofType:selectorTarget]; + // Return a copy because the original menu item might not have been removed + // from the main menu yet, and AppKit doesn't like menu items that exist in + // more than one menu at a time. + return [found copy]; +} + +- (NSMenuItem*)menuItemFromFlutterRepresentation:(NSDictionary*)representation { + if ([(NSNumber*)([representation valueForKey:kDividerKey]) intValue] == YES) { + return [NSMenuItem separatorItem]; + } + NSNumber* platformProvidedMenuId = representation[kPlatformProvidedMenuKey]; + NSString* keyEquivalent = @""; + + if (platformProvidedMenuId) { + return [self + createPlatformProvidedMenu:(flutter::PlatformProvidedMenu)platformProvidedMenuId.intValue]; + } else { + if (representation[kShortcutCharacterKey]) { + keyEquivalent = representation[kShortcutCharacterKey]; + } else { + NSNumber* triggerKeyId = representation[kShortcutTriggerKey]; + const NSDictionary* specialKeys = GetMacOsSpecialKeys(); + NSNumber* trigger = specialKeys[triggerKeyId]; + if (trigger) { + keyEquivalent = [NSString stringWithFormat:@"%C", [trigger unsignedShortValue]]; + } else { + if (([triggerKeyId unsignedLongLongValue] & kFlutterKeyIdPlaneMask) == + kFlutterKeyIdUnicodePlane) { + keyEquivalent = [[NSString + stringWithFormat:@"%C", (unichar)([triggerKeyId unsignedLongLongValue] & + kFlutterKeyIdValueMask)] lowercaseString]; + } + } + } + } + + NSNumber* identifier = representation[kIdKey]; + SEL action = (identifier ? @selector(flutterMenuItemSelected:) : NULL); + NSString* appName = [NSRunningApplication currentApplication].localizedName; + NSString* title = [representation[kLabelKey] stringByReplacingOccurrencesOfString:kAppName + withString:appName]; + NSMenuItem* item = [[NSMenuItem alloc] initWithTitle:title + action:action + keyEquivalent:keyEquivalent]; + if ([keyEquivalent length] > 0) { + item.keyEquivalentModifierMask = + KeyEquivalentModifierMaskForModifiers(representation[kShortcutModifiersKey]); + } + if (identifier) { + item.tag = identifier.longLongValue; + item.target = self; + } + NSNumber* enabled = representation[kEnabledKey]; + if (enabled) { + item.enabled = enabled.boolValue; + } + + NSArray* children = representation[kChildrenKey]; + if (children && children.count > 0) { + NSMenu* submenu = [[NSMenu alloc] initWithTitle:title]; + FlutterMenuDelegate* delegate = [[FlutterMenuDelegate alloc] initWithIdentifier:item.tag + channel:_channel]; + [_menuDelegates addObject:delegate]; + submenu.delegate = delegate; + submenu.autoenablesItems = NO; + for (NSDictionary* child in children) { + NSMenuItem* newItem = [self menuItemFromFlutterRepresentation:child]; + if (newItem) { + [submenu addItem:newItem]; + } + } + item.submenu = submenu; + } + return item; +} + +- (void)flutterMenuItemSelected:(id)sender { + NSMenuItem* item = sender; + [_channel invokeMethod:kMenuSelectedCallbackMethod arguments:@(item.tag)]; +} + +- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { + if ([call.method isEqualToString:kIsPluginAvailableMethod]) { + result(@YES); + } else if ([call.method isEqualToString:kMenuSetMenusMethod]) { + NSDictionary* menus = call.arguments; + [self setMenus:menus]; + result(nil); + } else { + result(FlutterMethodNotImplemented); + } +} + +- (void)setMenus:(NSDictionary*)representation { + [_menuDelegates removeAllObjects]; + NSMenu* newMenu = [[NSMenu alloc] init]; + // There's currently only one window, named "0", but there could be other + // eventually, with different menu configurations. + for (NSDictionary* item in representation[@"0"]) { + NSMenuItem* menuItem = [self menuItemFromFlutterRepresentation:item]; + menuItem.representedObject = self; + NSNumber* identifier = item[kIdKey]; + FlutterMenuDelegate* delegate = + [[FlutterMenuDelegate alloc] initWithIdentifier:identifier.longLongValue channel:_channel]; + [_menuDelegates addObject:delegate]; + [menuItem submenu].delegate = delegate; + [newMenu addItem:menuItem]; + } + NSApp.mainMenu = newMenu; +} + +#pragma mark - Public Class Methods + ++ (void)registerWithRegistrar:(nonnull id)registrar { + FlutterMethodChannel* channel = [FlutterMethodChannel methodChannelWithName:kChannelName + binaryMessenger:registrar.messenger]; + FlutterMenuPlugin* instance = [[FlutterMenuPlugin alloc] initWithChannel:channel]; + [registrar addMethodCallDelegate:instance channel:channel]; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPluginTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPluginTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..127bc5d5f29f16cea59b2852dfea4f9e11eb7b16 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPluginTest.mm @@ -0,0 +1,216 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin_Internal.h" + +#import "flutter/shell/platform/common/platform_provided_menu.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginMacOS.h" +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginRegistrarMacOS.h" +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" +#include "flutter/testing/autoreleasepool_test.h" +#include "flutter/testing/testing.h" +#include "gtest/gtest.h" + +@interface FakePluginRegistrar : NSObject +@property(nonatomic, readonly) id plugin; +@property(nonatomic, readonly) FlutterMethodChannel* channel; +@end + +@implementation FakePluginRegistrar + +// Synthesize properties declared in FlutterPluginRegistrar protocol. +@synthesize messenger; +@synthesize textures; +@synthesize view; + +- (void)addMethodCallDelegate:(nonnull id)delegate + channel:(nonnull FlutterMethodChannel*)channel { + _plugin = delegate; + _channel = channel; + [_channel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { + [delegate handleMethodCall:call result:result]; + }]; +} + +- (void)addApplicationDelegate:(nonnull NSObject*)delegate { +} + +- (void)registerViewFactory:(nonnull NSObject*)factory + withId:(nonnull NSString*)factoryId { +} + +- (void)publish:(nonnull NSObject*)value { +} + +- (nonnull NSString*)lookupKeyForAsset:(nonnull NSString*)asset { + return @""; +} + +- (nonnull NSString*)lookupKeyForAsset:(nonnull NSString*)asset + fromPackage:(nonnull NSString*)package { + return @""; +} +@end + +namespace flutter::testing { + +// FlutterMenuPluginTest is an AutoreleasePoolTest that allocates an NSView. +// +// This supports the use of NSApplication features that rely on the assumption of a view, such as +// when modifying the application menu bar, or even accessing the NSApplication.localizedName +// property. +// +// See: https://github.com/flutter/flutter/issues/104748#issuecomment-1159336728 +class FlutterMenuPluginTest : public AutoreleasePoolTest { + public: + FlutterMenuPluginTest(); + ~FlutterMenuPluginTest() = default; + + private: + NSView* view_; +}; + +FlutterMenuPluginTest::FlutterMenuPluginTest() { + view_ = [[NSView alloc] initWithFrame:NSZeroRect]; + view_.wantsLayer = YES; +} + +TEST_F(FlutterMenuPluginTest, TestSetMenu) { + // Build a simulation of the default main menu. + NSMenu* mainMenu = [[NSMenu alloc] init]; + NSMenuItem* appNameMenu = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"APP_NAME", nil) + action:nil + keyEquivalent:@""]; + NSMenu* submenu = + [[NSMenu alloc] initWithTitle:NSLocalizedString(@"Prexisting APP_NAME menu", nil)]; + [submenu addItem:[[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"About APP_NAME", nil) + action:nil + keyEquivalent:@""]]; + appNameMenu.submenu = submenu; + [mainMenu addItem:appNameMenu]; + [NSApp setMainMenu:mainMenu]; + + FakePluginRegistrar* registrar = [[FakePluginRegistrar alloc] init]; + [FlutterMenuPlugin registerWithRegistrar:registrar]; + FlutterMenuPlugin* plugin = [registrar plugin]; + + NSDictionary* testMenus = @{ + @"0" : @[ + @{ + @"id" : [NSNumber numberWithInt:1], + @"label" : @"APP_NAME", + @"enabled" : @(YES), + @"children" : @[ + @{ + @"id" : [NSNumber numberWithInt:3], + @"platformProvidedMenu" : @(static_cast(flutter::PlatformProvidedMenu::kQuit)), + @"enabled" : @(YES), + }, + @{ + @"id" : [NSNumber numberWithInt:2], + @"label" : @"APP_NAME Info", + @"enabled" : @(YES), + @"shortcutTrigger" : [NSNumber numberWithUnsignedLongLong:0x61], + @"shortcutModifiers" : [NSNumber numberWithUnsignedInt:0], + }, + ], + }, + @{ + @"id" : [NSNumber numberWithInt:4], + @"label" : @"Help for APP_NAME", + @"enabled" : @(YES), + @"children" : @[ + @{ + @"id" : [NSNumber numberWithInt:5], + @"label" : @"Help me!", + @"enabled" : @(YES), + }, + @{ + @"id" : [NSNumber numberWithInt:6], + @"label" : @"", + @"enabled" : @(NO), + @"isDivider" : @(YES), + }, + @{ + @"id" : [NSNumber numberWithInt:7], + @"label" : @"Search help", + @"enabled" : @(NO), + }, + ], + }, + ], + }; + + __block id available = @NO; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"Menu.isPluginAvailable" + arguments:nil] + result:^(id _Nullable result) { + available = result; + }]; + + EXPECT_TRUE(available); + + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"Menu.setMenus" + arguments:testMenus] + result:^(id _Nullable result){ + }]; + + EXPECT_EQ([NSApp.mainMenu numberOfItems], 2); + NSMenuItem* firstMenu = [NSApp.mainMenu itemAtIndex:0]; + EXPECT_TRUE([[firstMenu title] isEqualToString:@"flutter_desktop_darwin_unittests"]); + EXPECT_EQ([firstMenu tag], 1); + EXPECT_TRUE([firstMenu isEnabled]); + EXPECT_FALSE([firstMenu isHidden]); + EXPECT_TRUE([[firstMenu keyEquivalent] isEqualToString:@"\0"]); + + EXPECT_EQ([[firstMenu submenu] numberOfItems], 1); + NSMenuItem* firstItem = [[firstMenu submenu] itemAtIndex:0]; + EXPECT_TRUE([[firstItem title] isEqualToString:@"flutter_desktop_darwin_unittests Info"]); + EXPECT_TRUE([[firstItem keyEquivalent] isEqualToString:@"a"]); + EXPECT_TRUE([firstItem isEnabled]); + EXPECT_FALSE([firstItem isHidden]); + EXPECT_TRUE( + [NSStringFromSelector([firstItem action]) isEqualToString:@"flutterMenuItemSelected:"]); + EXPECT_EQ([firstItem tag], 2); + + NSMenuItem* secondMenu = [NSApp.mainMenu itemAtIndex:1]; + EXPECT_TRUE([[secondMenu title] isEqualToString:@"Help for flutter_desktop_darwin_unittests"]); + EXPECT_EQ([secondMenu tag], 4); + EXPECT_TRUE([secondMenu isEnabled]); + EXPECT_FALSE([secondMenu isHidden]); + + EXPECT_EQ([[secondMenu submenu] numberOfItems], 3); + NSMenuItem* secondMenuFirst = [[secondMenu submenu] itemAtIndex:0]; + EXPECT_TRUE([[secondMenuFirst title] isEqualToString:@"Help me!"]); + EXPECT_TRUE([secondMenuFirst isEnabled]); + EXPECT_FALSE([secondMenuFirst isHidden]); + EXPECT_TRUE( + [NSStringFromSelector([secondMenuFirst action]) isEqualToString:@"flutterMenuItemSelected:"]); + EXPECT_EQ([secondMenuFirst tag], 5); + + NSMenuItem* secondMenuDivider = [[secondMenu submenu] itemAtIndex:1]; + EXPECT_TRUE([[secondMenuDivider title] isEqualToString:@""]); + EXPECT_TRUE([[secondMenuDivider keyEquivalent] isEqualToString:@""]); + EXPECT_FALSE([secondMenuDivider isEnabled]); + EXPECT_FALSE([secondMenuDivider isHidden]); + EXPECT_EQ([secondMenuDivider action], nil); + EXPECT_EQ([secondMenuDivider tag], 0); + + NSMenuItem* secondMenuLast = [[secondMenu submenu] itemAtIndex:2]; + EXPECT_TRUE([[secondMenuLast title] isEqualToString:@"Search help"]); + EXPECT_FALSE([secondMenuLast isEnabled]); + EXPECT_FALSE([secondMenuLast isHidden]); + EXPECT_TRUE( + [NSStringFromSelector([secondMenuLast action]) isEqualToString:@"flutterMenuItemSelected:"]); + EXPECT_EQ([secondMenuLast tag], 7); +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin_Internal.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin_Internal.h new file mode 100644 index 0000000000000000000000000000000000000000..f7dfdd87c96191fc5e851173a875865e58ca7652 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin_Internal.h @@ -0,0 +1,20 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERMENUPLUGIN_INTERNAL_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERMENUPLUGIN_INTERNAL_H_ + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin.h" + +/** + * Internal methods used in testing. + */ +@interface FlutterMenuPlugin () + +// Handles method calls received from the framework. +- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERMENUPLUGIN_INTERNAL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMouseCursorPlugin.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMouseCursorPlugin.h new file mode 100644 index 0000000000000000000000000000000000000000..4cc4790a1e0a75fe1e595327ddce6603b03eec58 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMouseCursorPlugin.h @@ -0,0 +1,30 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERMOUSECURSORPLUGIN_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERMOUSECURSORPLUGIN_H_ + +#import + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h" +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h" + +@protocol FlutterMouseCursorPluginDelegate +- (void)didUpdateMouseCursor:(nonnull NSCursor*)cursor; +@end + +/** + * A plugin to handle mouse cursor. + * + * Responsible for bridging the native macOS mouse cursor system with the + * Flutter framework mouse cursor classes, via system channels. + */ +@interface FlutterMouseCursorPlugin : NSObject + ++ (void)registerWithRegistrar:(nonnull id)registrar + delegate:(nullable id)delegate; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERMOUSECURSORPLUGIN_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMouseCursorPlugin.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMouseCursorPlugin.mm new file mode 100644 index 0000000000000000000000000000000000000000..a108b7078a493b00445872337d78eac9745d512a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMouseCursorPlugin.mm @@ -0,0 +1,157 @@ +// 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. + +#import + +#import "FlutterMouseCursorPlugin.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h" + +static NSString* const kMouseCursorChannel = @"flutter/mousecursor"; + +static NSString* const kActivateSystemCursorMethod = @"activateSystemCursor"; +static NSString* const kKindKey = @"kind"; + +static NSString* const kKindValueNone = @"none"; + +static NSDictionary* systemCursors; + +/** + * Maps a Flutter's constant to a platform's cursor object. + * + * Returns the arrow cursor for unknown constants, including kSystemShapeNone. + */ +static NSCursor* GetCursorForKind(NSString* kind) { + // The following mapping must be kept in sync with Flutter framework's + // mouse_cursor.dart + + if ([kind isEqualToString:kKindValueNone]) { + NSImage* image = [[NSImage alloc] initWithSize:NSMakeSize(1, 1)]; + return [[NSCursor alloc] initWithImage:image hotSpot:NSMakePoint(0, 0)]; + } + + if (systemCursors == nil) { + systemCursors = @{ + @"alias" : [NSCursor dragLinkCursor], + @"basic" : [NSCursor arrowCursor], + @"click" : [NSCursor pointingHandCursor], + @"contextMenu" : [NSCursor contextualMenuCursor], + @"copy" : [NSCursor dragCopyCursor], + @"disappearing" : [NSCursor disappearingItemCursor], + @"forbidden" : [NSCursor operationNotAllowedCursor], + @"grab" : [NSCursor openHandCursor], + @"grabbing" : [NSCursor closedHandCursor], + @"noDrop" : [NSCursor operationNotAllowedCursor], + @"precise" : [NSCursor crosshairCursor], + @"text" : [NSCursor IBeamCursor], + @"resizeColumn" : [NSCursor resizeLeftRightCursor], + @"resizeDown" : [NSCursor resizeDownCursor], + @"resizeLeft" : [NSCursor resizeLeftCursor], + @"resizeLeftRight" : [NSCursor resizeLeftRightCursor], + @"resizeRight" : [NSCursor resizeRightCursor], + @"resizeRow" : [NSCursor resizeUpDownCursor], + @"resizeUp" : [NSCursor resizeUpCursor], + @"resizeUpDown" : [NSCursor resizeUpDownCursor], + @"verticalText" : [NSCursor IBeamCursorForVerticalLayout], + }; + } + NSCursor* result = [systemCursors objectForKey:kind]; + if (result == nil) { + return [NSCursor arrowCursor]; + } + return result; +} + +@interface FlutterMouseCursorPlugin () + +@property(nonatomic, weak) id delegate; + +/** + * Handles the method call that activates a system cursor. + * + * Returns a FlutterError if the arguments can not be recognized. Otherwise + * returns nil. + */ +- (FlutterError*)activateSystemCursor:(nonnull NSDictionary*)arguments; + +/** + * Displays the specified cursor. + * + * Unhides the cursor before displaying the cursor, and updates + * internal states. + */ +- (void)displayCursorObject:(nonnull NSCursor*)cursorObject; + +/** + * Handles all method calls from Flutter. + */ +- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result; + +@end + +@implementation FlutterMouseCursorPlugin + +#pragma mark - Private + +NSMutableDictionary* cachedSystemCursors; + +- (instancetype)init { + self = [super init]; + if (self) { + cachedSystemCursors = [NSMutableDictionary dictionary]; + } + return self; +} + +- (FlutterError*)activateSystemCursor:(nonnull NSDictionary*)arguments { + NSString* kindArg = arguments[kKindKey]; + if (!kindArg) { + return [FlutterError errorWithCode:@"error" + message:@"Missing argument" + details:@"Missing argument while trying to activate system cursor"]; + } + + NSCursor* cursorObject = [FlutterMouseCursorPlugin cursorFromKind:kindArg]; + [self displayCursorObject:cursorObject]; + return nil; +} + +- (void)displayCursorObject:(nonnull NSCursor*)cursorObject { + [cursorObject set]; + [self.delegate didUpdateMouseCursor:cursorObject]; +} + ++ (NSCursor*)cursorFromKind:(NSString*)kind { + NSCursor* cachedValue = [cachedSystemCursors objectForKey:kind]; + if (!cachedValue) { + cachedValue = GetCursorForKind(kind); + [cachedSystemCursors setValue:cachedValue forKey:kind]; + } + return cachedValue; +} + +#pragma mark - FlutterPlugin implementation + ++ (void)registerWithRegistrar:(id)registrar { + [self registerWithRegistrar:registrar delegate:nil]; +} + ++ (void)registerWithRegistrar:(id)registrar + delegate:(id)delegate { + FlutterMethodChannel* channel = [FlutterMethodChannel methodChannelWithName:kMouseCursorChannel + binaryMessenger:registrar.messenger]; + FlutterMouseCursorPlugin* instance = [[FlutterMouseCursorPlugin alloc] init]; + instance.delegate = delegate; + [registrar addMethodCallDelegate:instance channel:channel]; +} + +- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { + NSString* method = call.method; + if ([method isEqualToString:kActivateSystemCursorMethod]) { + result([self activateSystemCursor:call.arguments]); + } else { + result(FlutterMethodNotImplemented); + } +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMutatorView.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMutatorView.h new file mode 100644 index 0000000000000000000000000000000000000000..390da0e5830ba19d6f2a5c9ad7d1187d306d8086 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMutatorView.h @@ -0,0 +1,88 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERMUTATORVIEW_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERMUTATORVIEW_H_ + +#import +#include + +#include "flutter/shell/platform/embedder/embedder.h" + +namespace flutter { + +/// Represents a platform view layer, including all mutations. +class PlatformViewLayer { + public: + /// Creates platform view from provided FlutterLayer, which must be + /// of type kFlutterLayerContentTypePlatformView. + explicit PlatformViewLayer(const FlutterLayer* _Nonnull layer); + + PlatformViewLayer(FlutterPlatformViewIdentifier identifier, + const std::vector& mutations, + FlutterPoint offset, + FlutterSize size); + + FlutterPlatformViewIdentifier identifier() const { return identifier_; } + const std::vector& mutations() const { return mutations_; } + FlutterPoint offset() const { return offset_; } + FlutterSize size() const { return size_; } + + private: + FlutterPlatformViewIdentifier identifier_; + std::vector mutations_; + FlutterPoint offset_; + FlutterSize size_; +}; +} // namespace flutter + +@class FlutterView; +@class FlutterMutatorView; + +/// FlutterCursorCoordinator is responsible for coordinating cursor changes between +/// platform views and overlays of single FlutterView. +@interface FlutterCursorCoordinator : NSObject + +- (nonnull FlutterCursorCoordinator*)initWithFlutterView:(nonnull FlutterView*)flutterView; + +@end + +/// Exposed methods for testing. +@interface FlutterCursorCoordinator (Private) + +@property(readonly, nonatomic) BOOL cleanupScheduled; + +- (void)processMouseMoveEvent:(nonnull NSEvent*)event + forMutatorView:(nonnull FlutterMutatorView*)view + overlayRegion:(const std::vector&)region; +@end + +/// FlutterMutatorView contains platform view and is responsible for applying +/// FlutterLayer mutations to it. +@interface FlutterMutatorView : NSView + +/// Designated initializer. +- (nonnull instancetype)initWithPlatformView:(nonnull NSView*)platformView + cursorCoordiator:(nullable FlutterCursorCoordinator*)coordinator; + +- (nonnull instancetype)initWithPlatformView:(nonnull NSView*)platformView; + +/// Returns wrapped platform view. +@property(readonly, nonnull) NSView* platformView; + +/// Applies mutations from FlutterLayer to the platform view. This may involve +/// creating or removing intermediate subviews depending on current state and +/// requested mutations. +- (void)applyFlutterLayer:(nonnull const flutter::PlatformViewLayer*)layer; + +/// Resets hit hit testing region for this mutator view. +- (void)resetHitTestRegion; + +/// Adds rectangle (in local vie coordinates) to hit test ignore region +/// (part of view obscured by Flutter contents). +- (void)addHitTestIgnoreRegion:(CGRect)region; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERMUTATORVIEW_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMutatorView.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMutatorView.mm new file mode 100644 index 0000000000000000000000000000000000000000..c9036ecb8ffd0b415060bbe67514b2dd08bc1a32 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMutatorView.mm @@ -0,0 +1,683 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMutatorView.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterView.h" + +#include + +#include "flutter/fml/logging.h" +#include "flutter/shell/platform/embedder/embedder.h" + +#import "flutter/shell/platform/darwin/macos/framework/Source/NSView+ClipsToBounds.h" + +namespace flutter { +PlatformViewLayer::PlatformViewLayer(const FlutterLayer* layer) { + FML_CHECK(layer->type == kFlutterLayerContentTypePlatformView); + const auto* platform_view = layer->platform_view; + identifier_ = platform_view->identifier; + for (size_t i = 0; i < platform_view->mutations_count; i++) { + mutations_.push_back(*platform_view->mutations[i]); + } + offset_ = layer->offset; + size_ = layer->size; +} +PlatformViewLayer::PlatformViewLayer(FlutterPlatformViewIdentifier identifier, + const std::vector& mutations, + FlutterPoint offset, + FlutterSize size) + : identifier_(identifier), mutations_(mutations), offset_(offset), size_(size) {} +} // namespace flutter + +@implementation FlutterCursorCoordinator { + __weak FlutterView* _flutterView; + BOOL _cleanupScheduled; + BOOL _mouseMoveHandled; +} + +- (FlutterCursorCoordinator*)initWithFlutterView:(FlutterView*)flutterView { + if (self = [super init]) { + _flutterView = flutterView; + } + return self; +} + +- (void)frameCleanup { + _cleanupScheduled = NO; + _mouseMoveHandled = NO; +} + +- (BOOL)cleanupScheduled { + return _cleanupScheduled; +} + +// Processes the mouse event from given mutator view. This is called for each mutator view, in +// z-order, from the top most down. +- (void)processMouseMoveEvent:(NSEvent*)event + forMutatorView:(FlutterMutatorView*)view + overlayRegion:(const std::vector&)region { + // [self frameCleanup] will be called once after current run loop turn. + if (!_cleanupScheduled) { + [[NSRunLoop mainRunLoop] performBlock:^{ + [self frameCleanup]; + }]; + _cleanupScheduled = YES; + } + + // Mouse move was already handled by a mutator view above. + if (_mouseMoveHandled) { + return; + } + + NSPoint point = [view convertPoint:event.locationInWindow fromView:nil]; + + // If the mouse is above overlay region restore current Flutter cursor. + for (const auto& r : region) { + if (CGRectContainsPoint(r, point)) { + [_flutterView cursorUpdate:event]; + _mouseMoveHandled = YES; + return; + } + } + NSView* platformView = view.platformView; + // It is possible that Flutter changed mouse cursor while the mouse was inside + // cursor rect. Unfocused NSTextField uses legacy cursor rects for changing + // its cursor. + [platformView.window invalidateCursorRectsForView:platformView]; + _mouseMoveHandled = YES; +} +@end + +@interface FlutterMutatorView () { + // Each of these views clips to a CGPathRef. These views, if present, + // are nested (first is child of FlutterMutatorView and last is parent of + // _platformView). + NSMutableArray* _pathClipViews; + + // View right above the platform view. Used to apply the final transform + // (sans the translation) to the platform view. + NSView* _platformViewContainer; + + NSView* _platformView; + + FlutterCursorCoordinator* _cursorCoordinator; + + // Container view that hosts the tracking area. Must be above platform view + // so that it gets the mouseMove event first. + NSView* _trackingAreaContainer; + + // Tracking area used to update cursor when moving over overlay region. + NSTrackingArea* _trackingArea; + + // Region of the overlay that should be ignored for hit testing. + std::vector _hitTestIgnoreRegion; +} + +@end + +/// Superview container for platform views, to which sublayer transforms are applied. +@interface FlutterPlatformViewContainer : NSView +@end + +@implementation FlutterPlatformViewContainer + +- (NSView*)hitTest:(NSPoint)point { + NSView* res = [super hitTest:point]; + return res != self ? res : nil; +} + +- (BOOL)isFlipped { + // Flutter transforms assume a coordinate system with an upper-left corner origin, with y + // coordinate values increasing downwards. This affects the view, view transforms, and + // sublayerTransforms. + return YES; +} + +@end + +/// View that clips that content to a specific CGPathRef. +/// Clipping is done through a CAShapeLayer mask, which avoids the need to +/// rasterize the mask. +@interface FlutterPathClipView : NSView + +@end + +@implementation FlutterPathClipView + +- (instancetype)initWithFrame:(NSRect)frameRect { + if (self = [super initWithFrame:frameRect]) { + self.wantsLayer = YES; + } + return self; +} + +- (BOOL)isFlipped { + // Flutter transforms assume a coordinate system with an upper-left corner origin, with y + // coordinate values increasing downwards. This affects the view, view transforms, and + // sublayerTransforms. + return YES; +} + +- (NSView*)hitTest:(NSPoint)point { + NSView* res = [super hitTest:point]; + return res != self ? res : nil; +} + +/// Clip the view to the given path. Offset top left corner of platform view +/// in global logical coordinates. +- (void)maskToPath:(CGPathRef)path withOrigin:(CGPoint)origin { + CAShapeLayer* maskLayer = self.layer.mask; + if (maskLayer == nil) { + maskLayer = [CAShapeLayer layer]; + self.layer.mask = maskLayer; + } + maskLayer.path = path; + maskLayer.transform = CATransform3DMakeTranslation(-origin.x, -origin.y, 0); +} + +@end + +namespace { +CATransform3D ToCATransform3D(const FlutterTransformation& t) { + CATransform3D transform = CATransform3DIdentity; + transform.m11 = t.scaleX; + transform.m21 = t.skewX; + transform.m41 = t.transX; + transform.m14 = t.pers0; + transform.m12 = t.skewY; + transform.m22 = t.scaleY; + transform.m42 = t.transY; + transform.m24 = t.pers1; + return transform; +} + +bool AffineTransformIsOnlyScaleOrTranslate(const CGAffineTransform& transform) { + return transform.b == 0 && transform.c == 0; +} + +bool IsZeroSize(const FlutterSize size) { + return size.width == 0 && size.height == 0; +} + +CGRect FromFlutterRect(const FlutterRect& rect) { + return CGRectMake(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top); +} + +FlutterRect ToFlutterRect(const CGRect& rect) { + return FlutterRect{ + .left = rect.origin.x, + .top = rect.origin.y, + .right = rect.origin.x + rect.size.width, + .bottom = rect.origin.y + rect.size.height, + + }; +} + +/// Returns whether the point is inside ellipse with given radius (centered at 0, 0). +bool PointInsideEllipse(const CGPoint& point, const FlutterSize& radius) { + return (point.x * point.x) / (radius.width * radius.width) + + (point.y * point.y) / (radius.height * radius.height) < + 1.0; +} + +bool RoundRectCornerIntersects(const FlutterRoundedRect& roundRect, const FlutterRect& rect) { + // Inner coordinate of the top left corner of the round rect. + CGPoint inner_top_left = + CGPointMake(roundRect.rect.left + roundRect.upper_left_corner_radius.width, + roundRect.rect.top + roundRect.upper_left_corner_radius.height); + + // Position of `rect` corner relative to inner_top_left. + CGPoint relative_top_left = + CGPointMake(rect.left - inner_top_left.x, rect.top - inner_top_left.y); + + // `relative_top_left` is in upper left quadrant. + if (relative_top_left.x < 0 && relative_top_left.y < 0) { + if (!PointInsideEllipse(relative_top_left, roundRect.upper_left_corner_radius)) { + return true; + } + } + + // Inner coordinate of the top right corner of the round rect. + CGPoint inner_top_right = + CGPointMake(roundRect.rect.right - roundRect.upper_right_corner_radius.width, + roundRect.rect.top + roundRect.upper_right_corner_radius.height); + + // Positon of `rect` corner relative to inner_top_right. + CGPoint relative_top_right = + CGPointMake(rect.right - inner_top_right.x, rect.top - inner_top_right.y); + + // `relative_top_right` is in top right quadrant. + if (relative_top_right.x > 0 && relative_top_right.y < 0) { + if (!PointInsideEllipse(relative_top_right, roundRect.upper_right_corner_radius)) { + return true; + } + } + + // Inner coordinate of the bottom left corner of the round rect. + CGPoint inner_bottom_left = + CGPointMake(roundRect.rect.left + roundRect.lower_left_corner_radius.width, + roundRect.rect.bottom - roundRect.lower_left_corner_radius.height); + + // Position of `rect` corner relative to inner_bottom_left. + CGPoint relative_bottom_left = + CGPointMake(rect.left - inner_bottom_left.x, rect.bottom - inner_bottom_left.y); + + // `relative_bottom_left` is in bottom left quadrant. + if (relative_bottom_left.x < 0 && relative_bottom_left.y > 0) { + if (!PointInsideEllipse(relative_bottom_left, roundRect.lower_left_corner_radius)) { + return true; + } + } + + // Inner coordinate of the bottom right corner of the round rect. + CGPoint inner_bottom_right = + CGPointMake(roundRect.rect.right - roundRect.lower_right_corner_radius.width, + roundRect.rect.bottom - roundRect.lower_right_corner_radius.height); + + // Position of `rect` corner relative to inner_bottom_right. + CGPoint relative_bottom_right = + CGPointMake(rect.right - inner_bottom_right.x, rect.bottom - inner_bottom_right.y); + + // `relative_bottom_right` is in bottom right quadrant. + if (relative_bottom_right.x > 0 && relative_bottom_right.y > 0) { + if (!PointInsideEllipse(relative_bottom_right, roundRect.lower_right_corner_radius)) { + return true; + } + } + + return false; +} + +CGPathRef PathFromRoundedRect(const FlutterRoundedRect& roundedRect) { + if (IsZeroSize(roundedRect.lower_left_corner_radius) && + IsZeroSize(roundedRect.lower_right_corner_radius) && + IsZeroSize(roundedRect.upper_left_corner_radius) && + IsZeroSize(roundedRect.upper_right_corner_radius)) { + return CGPathCreateWithRect(FromFlutterRect(roundedRect.rect), nullptr); + } + + CGMutablePathRef path = CGPathCreateMutable(); + + const auto& rect = roundedRect.rect; + const auto& topLeft = roundedRect.upper_left_corner_radius; + const auto& topRight = roundedRect.upper_right_corner_radius; + const auto& bottomLeft = roundedRect.lower_left_corner_radius; + const auto& bottomRight = roundedRect.lower_right_corner_radius; + + CGPathMoveToPoint(path, nullptr, rect.left + topLeft.width, rect.top); + CGPathAddLineToPoint(path, nullptr, rect.right - topRight.width, rect.top); + CGPathAddCurveToPoint(path, nullptr, rect.right, rect.top, rect.right, rect.top + topRight.height, + rect.right, rect.top + topRight.height); + CGPathAddLineToPoint(path, nullptr, rect.right, rect.bottom - bottomRight.height); + CGPathAddCurveToPoint(path, nullptr, rect.right, rect.bottom, rect.right - bottomRight.width, + rect.bottom, rect.right - bottomRight.width, rect.bottom); + CGPathAddLineToPoint(path, nullptr, rect.left + bottomLeft.width, rect.bottom); + CGPathAddCurveToPoint(path, nullptr, rect.left, rect.bottom, rect.left, + rect.bottom - bottomLeft.height, rect.left, + rect.bottom - bottomLeft.height); + CGPathAddLineToPoint(path, nullptr, rect.left, rect.top + topLeft.height); + CGPathAddCurveToPoint(path, nullptr, rect.left, rect.top, rect.left + topLeft.width, rect.top, + rect.left + topLeft.width, rect.top); + CGPathCloseSubpath(path); + return path; +} + +using MutationVector = std::vector; + +/// Returns a vector of FlutterPlatformViewMutation object pointers associated with a platform view. +/// The transforms sent from the engine include a transform from logical to physical coordinates. +/// Since Cocoa deals only in logical points, this function prepends a scale transform that scales +/// back from physical to logical coordinates to compensate. +MutationVector MutationsForPlatformView(const MutationVector& mutationsIn, float scale) { + MutationVector mutations(mutationsIn); + + mutations.insert(mutations.begin(), { + .type = kFlutterPlatformViewMutationTypeTransformation, + .transformation{ + .scaleX = 1.0 / scale, + .scaleY = 1.0 / scale, + }, + }); + return mutations; +} + +/// Returns the composition of all transformation mutations in the mutations vector. +CATransform3D CATransformFromMutations(const MutationVector& mutations) { + CATransform3D transform = CATransform3DIdentity; + for (auto mutation : mutations) { + switch (mutation.type) { + case kFlutterPlatformViewMutationTypeTransformation: { + CATransform3D mutationTransform = ToCATransform3D(mutation.transformation); + transform = CATransform3DConcat(mutationTransform, transform); + break; + } + case kFlutterPlatformViewMutationTypeClipRect: + case kFlutterPlatformViewMutationTypeClipRoundedRect: + case kFlutterPlatformViewMutationTypeOpacity: + break; + } + } + return transform; +} + +/// Returns the opacity for all opacity mutations in the mutations vector. +float OpacityFromMutations(const MutationVector& mutations) { + float opacity = 1.0; + for (auto mutation : mutations) { + switch (mutation.type) { + case kFlutterPlatformViewMutationTypeOpacity: + opacity *= mutation.opacity; + break; + case kFlutterPlatformViewMutationTypeClipRect: + case kFlutterPlatformViewMutationTypeClipRoundedRect: + case kFlutterPlatformViewMutationTypeTransformation: + break; + } + } + return opacity; +} + +/// Returns the clip rect generated by the intersection of clips in the mutations vector. +CGRect MasterClipFromMutations(CGRect bounds, const MutationVector& mutations) { + // Master clip in global logical coordinates. This is intersection of all clip rectangles + // present in mutators. + CGRect master_clip = bounds; + + // Create the initial transform. + CATransform3D transform = CATransform3DIdentity; + for (auto mutation : mutations) { + switch (mutation.type) { + case kFlutterPlatformViewMutationTypeClipRect: { + CGRect rect = CGRectApplyAffineTransform(FromFlutterRect(mutation.clip_rect), + CATransform3DGetAffineTransform(transform)); + master_clip = CGRectIntersection(rect, master_clip); + break; + } + case kFlutterPlatformViewMutationTypeClipRoundedRect: { + CGAffineTransform affineTransform = CATransform3DGetAffineTransform(transform); + CGRect rect = CGRectApplyAffineTransform(FromFlutterRect(mutation.clip_rounded_rect.rect), + affineTransform); + master_clip = CGRectIntersection(rect, master_clip); + break; + } + case kFlutterPlatformViewMutationTypeTransformation: + transform = CATransform3DConcat(ToCATransform3D(mutation.transformation), transform); + break; + case kFlutterPlatformViewMutationTypeOpacity: + break; + } + } + return master_clip; +} + +/// A rounded rectangle and transform associated with it. +typedef struct { + FlutterRoundedRect rrect; + CGAffineTransform transform; +} ClipRoundedRect; + +/// Returns the set of all rounded rect paths generated by clips in the mutations vector. +NSMutableArray* ClipPathFromMutations(CGRect master_clip, const MutationVector& mutations) { + std::vector rounded_rects; + + CATransform3D transform = CATransform3DIdentity; + for (auto mutation : mutations) { + switch (mutation.type) { + case kFlutterPlatformViewMutationTypeClipRoundedRect: { + CGAffineTransform affineTransform = CATransform3DGetAffineTransform(transform); + rounded_rects.push_back({mutation.clip_rounded_rect, affineTransform}); + break; + } + case kFlutterPlatformViewMutationTypeTransformation: + transform = CATransform3DConcat(ToCATransform3D(mutation.transformation), transform); + break; + case kFlutterPlatformViewMutationTypeClipRect: { + CGAffineTransform affineTransform = CATransform3DGetAffineTransform(transform); + // Shearing or rotation requires path clipping. + if (!AffineTransformIsOnlyScaleOrTranslate(affineTransform)) { + rounded_rects.push_back( + {FlutterRoundedRect{mutation.clip_rect, FlutterSize{0, 0}, FlutterSize{0, 0}, + FlutterSize{0, 0}, FlutterSize{0, 0}}, + affineTransform}); + } + break; + } + case kFlutterPlatformViewMutationTypeOpacity: + break; + } + } + + NSMutableArray* paths = [NSMutableArray array]; + for (const auto& r : rounded_rects) { + bool requiresPath = !AffineTransformIsOnlyScaleOrTranslate(r.transform); + if (!requiresPath) { + CGAffineTransform inverse = CGAffineTransformInvert(r.transform); + // Transform master clip to clip rect coordinates and check if this view intersects one of the + // corners, which means we need to use path clipping. + CGRect localMasterClip = CGRectApplyAffineTransform(master_clip, inverse); + requiresPath = RoundRectCornerIntersects(r.rrect, ToFlutterRect(localMasterClip)); + } + + // Only clip to rounded rectangle path if the view intersects some of the round corners. If + // not, clipping to masterClip is enough. + if (requiresPath) { + CGPathRef path = PathFromRoundedRect(r.rrect); + CGPathRef transformedPath = CGPathCreateCopyByTransformingPath(path, &r.transform); + [paths addObject:(__bridge id)transformedPath]; + CGPathRelease(transformedPath); + CGPathRelease(path); + } + } + return paths; +} +} // namespace + +@interface FlutterTrackingAreaContainer : NSView +@end + +@implementation FlutterTrackingAreaContainer +- (NSView*)hitTest:(NSPoint)point { + return nil; +} +@end + +@implementation FlutterMutatorView + +- (NSView*)platformView { + return _platformView; +} + +- (NSMutableArray*)pathClipViews { + return _pathClipViews; +} + +- (NSView*)platformViewContainer { + return _platformViewContainer; +} + +- (instancetype)initWithPlatformView:(NSView*)platformView { + return [self initWithPlatformView:platformView cursorCoordiator:nil]; +} + +- (instancetype)initWithPlatformView:(NSView*)platformView + cursorCoordiator:(FlutterCursorCoordinator*)coordinator { + if (self = [super initWithFrame:NSZeroRect]) { + _platformView = platformView; + _pathClipViews = [NSMutableArray array]; + _cursorCoordinator = coordinator; + self.wantsLayer = YES; + self.clipsToBounds = YES; + + _trackingAreaContainer = [[FlutterTrackingAreaContainer alloc] initWithFrame:NSZeroRect]; + [self addSubview:_trackingAreaContainer]; + + NSTrackingAreaOptions options = NSTrackingMouseMoved | NSTrackingInVisibleRect | + NSTrackingEnabledDuringMouseDrag | NSTrackingActiveAlways; + _trackingArea = [[NSTrackingArea alloc] initWithRect:NSZeroRect + options:options + owner:self + userInfo:nil]; + [_trackingAreaContainer addTrackingArea:_trackingArea]; + } + return self; +} + +- (void)resetHitTestRegion { + self->_hitTestIgnoreRegion.clear(); +} + +- (void)addHitTestIgnoreRegion:(CGRect)region { + self->_hitTestIgnoreRegion.push_back(region); +} + +- (void)mouseMoved:(NSEvent*)event { + [_cursorCoordinator processMouseMoveEvent:event + forMutatorView:self + overlayRegion:_hitTestIgnoreRegion]; +} + +- (NSView*)hitTest:(NSPoint)point { + CGPoint localPoint = point; + localPoint.x -= self.frame.origin.x; + localPoint.y -= self.frame.origin.y; + for (const auto& region : _hitTestIgnoreRegion) { + if (CGRectContainsPoint(region, localPoint)) { + return nil; + } + } + return [super hitTest:point]; +} + +- (BOOL)isFlipped { + return YES; +} + +/// Returns the scale factor to translate logical pixels to physical pixels for this view. +- (CGFloat)contentsScale { + return self.superview != nil ? self.superview.layer.contentsScale : 1.0; +} + +/// Updates the nested stack of clip views that host the platform view. +- (void)updatePathClipViewsWithPaths:(NSArray*)paths { + // Remove path clip views depending on the number of paths. + while (_pathClipViews.count > paths.count) { + NSView* view = _pathClipViews.lastObject; + [view removeFromSuperview]; + [_pathClipViews removeLastObject]; + } + // Otherwise, add path clip views to the end. + for (size_t i = _pathClipViews.count; i < paths.count; ++i) { + NSView* superView = _pathClipViews.count == 0 ? self : _pathClipViews.lastObject; + FlutterPathClipView* pathClipView = [[FlutterPathClipView alloc] initWithFrame:self.bounds]; + [_pathClipViews addObject:pathClipView]; + [superView addSubview:pathClipView]; + } + // Update bounds and apply clip paths. + for (size_t i = 0; i < _pathClipViews.count; ++i) { + FlutterPathClipView* pathClipView = _pathClipViews[i]; + pathClipView.frame = self.bounds; + [pathClipView maskToPath:(__bridge CGPathRef)[paths objectAtIndex:i] + withOrigin:self.frame.origin]; + } +} + +/// Updates the PlatformView and PlatformView container views. +/// +/// Re-nests _platformViewContainer in the innermost clip view, applies transforms to the underlying +/// CALayer, adds the platform view as a subview of the container, and sets the axis-aligned clip +/// rect around the tranformed view. +- (void)updatePlatformViewWithBounds:(CGRect)untransformedBounds + transformedBounds:(CGRect)transformedBounds + transform:(CATransform3D)transform + clipRect:(CGRect)clipRect { + // Create the PlatformViewContainer view if necessary. + if (_platformViewContainer == nil) { + _platformViewContainer = [[FlutterPlatformViewContainer alloc] initWithFrame:self.bounds]; + _platformViewContainer.wantsLayer = YES; + } + + // Nest the PlatformViewContainer view in the innermost path clip view. + NSView* containerSuperview = _pathClipViews.count == 0 ? self : _pathClipViews.lastObject; + [containerSuperview addSubview:_platformViewContainer]; + _platformViewContainer.frame = self.bounds; + + // Nest the platform view in the PlatformViewContainer, but only if the view doesn't have a + // superview yet. Sometimes the platform view reparents itself (WKWebView entering FullScreen) + // in which case do not forcefully move it back. + if (_platformView.superview == nil) { + [_platformViewContainer addSubview:_platformView]; + } + + // Originally first subview would be the _platformView. However during WKWebView full screen + // the platform view gets replaced with a placeholder. Given that _platformViewContainer does + // not contain any other views it is safe to assume that any subview found can be treated + // as the platform view. + _platformViewContainer.subviews.firstObject.frame = untransformedBounds; + + // Transform for the platform view is finalTransform adjusted for bounding rect origin. + CATransform3D translation = + CATransform3DMakeTranslation(-transformedBounds.origin.x, -transformedBounds.origin.y, 0); + transform = CATransform3DConcat(transform, translation); + _platformViewContainer.layer.sublayerTransform = transform; + + // By default NSView clips children to frame. If masterClip is tighter than mutator view frame, + // the frame is set to masterClip and child offset adjusted to compensate for the difference. + if (!CGRectEqualToRect(clipRect, transformedBounds)) { + NSMutableArray* subviews = [NSMutableArray arrayWithArray:self.subviews]; + [subviews removeObject:_trackingAreaContainer]; + FML_DCHECK(subviews.count == 1); + auto subview = subviews.firstObject; + FML_DCHECK(subview.frame.origin.x == 0 && subview.frame.origin.y == 0); + subview.frame = CGRectMake(transformedBounds.origin.x - clipRect.origin.x, + transformedBounds.origin.y - clipRect.origin.y, + subview.frame.size.width, subview.frame.size.height); + self.frame = clipRect; + } +} + +/// Whenever possible view will be clipped using layer bounds. +/// If clipping to path is needed, CAShapeLayer(s) will be used as mask. +/// Clipping to round rect only clips to path if round corners are intersected. +- (void)applyFlutterLayer:(const flutter::PlatformViewLayer*)layer { + // Compute the untransformed bounding rect for the platform view in logical pixels. + // FlutterLayer.size is in physical pixels but Cocoa uses logical points. + CGFloat scale = [self contentsScale]; + MutationVector mutations = MutationsForPlatformView(layer->mutations(), scale); + + CATransform3D finalTransform = CATransformFromMutations(mutations); + + // Compute the untransformed bounding rect for the platform view in logical pixels. + // FlutterLayer.size is in physical pixels but Cocoa uses logical points. + CGRect untransformedBoundingRect = + CGRectMake(0, 0, layer->size().width / scale, layer->size().height / scale); + CGRect finalBoundingRect = CGRectApplyAffineTransform( + untransformedBoundingRect, CATransform3DGetAffineTransform(finalTransform)); + self.frame = finalBoundingRect; + + // Compute the layer opacity. + self.layer.opacity = OpacityFromMutations(mutations); + + // Compute the master clip in global logical coordinates. + CGRect masterClip = MasterClipFromMutations(finalBoundingRect, mutations); + if (CGRectIsNull(masterClip)) { + self.hidden = YES; + return; + } + self.hidden = NO; + + /// Paths in global logical coordinates that need to be clipped to. + NSMutableArray* paths = ClipPathFromMutations(masterClip, mutations); + [self updatePathClipViewsWithPaths:paths]; + + /// Update PlatformViewContainer, PlatformView, and apply transforms and axis-aligned clip rect. + [self updatePlatformViewWithBounds:untransformedBoundingRect + transformedBounds:finalBoundingRect + transform:finalTransform + clipRect:masterClip]; + + [self addSubview:_trackingAreaContainer positioned:(NSWindowAbove)relativeTo:nil]; + _trackingAreaContainer.frame = self.bounds; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMutatorViewTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMutatorViewTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..d352eefe3ba65607b8559d78875649e7dfa37004 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMutatorViewTest.mm @@ -0,0 +1,733 @@ +// 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. + +#import +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMutatorView.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterView.h" + +#include "third_party/googletest/googletest/include/gtest/gtest.h" + +#import "flutter/shell/platform/darwin/macos/framework/Source/NSView+ClipsToBounds.h" + +@interface FlutterMutatorView (Private) + +@property(readonly, nonatomic, nonnull) NSMutableArray* pathClipViews; +@property(readonly, nonatomic, nullable) NSView* platformViewContainer; + +@end + +static constexpr float kMaxErr = 1e-10; + +namespace { +void ApplyFlutterLayer(FlutterMutatorView* view, + FlutterSize size, + const std::vector& mutations) { + flutter::PlatformViewLayer layer(0, // identifier + mutations, + // Offset is ignored by mutator view, the bounding rect is + // determined by width and transform. + FlutterPoint{0, 0}, // offset + size); + + [view applyFlutterLayer:&layer]; +} + +// Expect that each element within two CATransform3Ds is within an error bound. +// +// In order to avoid architecture-specific floating point differences we don't check for exact +// equality using, for example, CATransform3DEqualToTransform. +void ExpectTransform3DEqual(const CATransform3D& t, const CATransform3D& u) { + EXPECT_NEAR(t.m11, u.m11, kMaxErr); + EXPECT_NEAR(t.m12, u.m12, kMaxErr); + EXPECT_NEAR(t.m13, u.m13, kMaxErr); + EXPECT_NEAR(t.m14, u.m14, kMaxErr); + + EXPECT_NEAR(t.m21, u.m21, kMaxErr); + EXPECT_NEAR(t.m22, u.m22, kMaxErr); + EXPECT_NEAR(t.m23, u.m23, kMaxErr); + EXPECT_NEAR(t.m24, u.m24, kMaxErr); + + EXPECT_NEAR(t.m31, u.m31, kMaxErr); + EXPECT_NEAR(t.m32, u.m32, kMaxErr); + EXPECT_NEAR(t.m33, u.m33, kMaxErr); + EXPECT_NEAR(t.m34, u.m34, kMaxErr); + + EXPECT_NEAR(t.m41, u.m41, kMaxErr); + EXPECT_NEAR(t.m42, u.m42, kMaxErr); + EXPECT_NEAR(t.m43, u.m43, kMaxErr); + EXPECT_NEAR(t.m44, u.m44, kMaxErr); +} +} // namespace + +TEST(FlutterMutatorViewTest, BasicFrameIsCorrect) { + NSView* platformView = [[NSView alloc] init]; + FlutterMutatorView* mutatorView = [[FlutterMutatorView alloc] initWithPlatformView:platformView]; + + EXPECT_EQ(mutatorView.platformView, platformView); + + std::vector mutations{ + { + .type = kFlutterPlatformViewMutationTypeTransformation, + .transformation = + FlutterTransformation{ + .scaleX = 1, + .transX = 100, + .scaleY = 1, + .transY = 50, + }, + }, + }; + + ApplyFlutterLayer(mutatorView, FlutterSize{30, 20}, mutations); + + EXPECT_TRUE(CGRectEqualToRect(mutatorView.frame, CGRectMake(100, 50, 30, 20))); + EXPECT_TRUE(CGRectEqualToRect(platformView.frame, CGRectMake(0, 0, 30, 20))); + EXPECT_EQ(mutatorView.pathClipViews.count, 0ull); + EXPECT_NE(mutatorView.platformViewContainer, nil); +} + +TEST(FlutterMutatorViewTest, ClipsToBounds) { + NSView* platformView = [[NSView alloc] init]; + FlutterMutatorView* mutatorView = [[FlutterMutatorView alloc] initWithPlatformView:platformView]; + EXPECT_TRUE(mutatorView.clipsToBounds); +} + +TEST(FlutterMutatorViewTest, TransformedFrameIsCorrect) { + NSView* platformView = [[NSView alloc] init]; + FlutterMutatorView* mutatorView = [[FlutterMutatorView alloc] initWithPlatformView:platformView]; + NSView* mutatorViewParent = [[NSView alloc] init]; + mutatorViewParent.wantsLayer = YES; + mutatorViewParent.layer.contentsScale = 2.0; + [mutatorViewParent addSubview:mutatorView]; + + std::vector mutations{ + { + .type = kFlutterPlatformViewMutationTypeTransformation, + .transformation = + FlutterTransformation{ + .scaleX = 2, + .scaleY = 2, + }, + }, + { + .type = kFlutterPlatformViewMutationTypeTransformation, + .transformation = + FlutterTransformation{ + .scaleX = 1, + .transX = 100, + .scaleY = 1, + .transY = 50, + }, + }, + { + .type = kFlutterPlatformViewMutationTypeTransformation, + .transformation = + FlutterTransformation{ + .scaleX = 1.5, + .transX = -7.5, + .scaleY = 1.5, + .transY = -5, + }, + }, + }; + + // PlatformView size form engine comes in physical pixels + ApplyFlutterLayer(mutatorView, FlutterSize{30 * 2, 20 * 2}, mutations); + EXPECT_TRUE(CGRectEqualToRect(mutatorView.frame, CGRectMake(92.5, 45, 45, 30))); + EXPECT_TRUE(CGRectEqualToRect(platformView.frame, CGRectMake(0, 0, 30, 20))); + + ExpectTransform3DEqual(mutatorView.platformViewContainer.layer.sublayerTransform, + CATransform3DMakeScale(1.5, 1.5, 1)); +} + +TEST(FlutterMutatorViewTest, FrameWithLooseClipIsCorrect) { + NSView* platformView = [[NSView alloc] init]; + FlutterMutatorView* mutatorView = [[FlutterMutatorView alloc] initWithPlatformView:platformView]; + + EXPECT_EQ(mutatorView.platformView, platformView); + + std::vector mutations{ + { + .type = kFlutterPlatformViewMutationTypeClipRect, + .clip_rect = FlutterRect{80, 40, 200, 100}, + }, + { + .type = kFlutterPlatformViewMutationTypeTransformation, + .transformation = + FlutterTransformation{ + .scaleX = 1, + .transX = 100, + .scaleY = 1, + .transY = 50, + }, + }, + }; + + ApplyFlutterLayer(mutatorView, FlutterSize{30, 20}, mutations); + + EXPECT_TRUE(CGRectEqualToRect(mutatorView.frame, CGRectMake(100, 50, 30, 20))); + EXPECT_TRUE(CGRectEqualToRect(platformView.frame, CGRectMake(0, 0, 30, 20))); +} + +TEST(FlutterMutatorViewTest, FrameWithTightClipIsCorrect) { + NSView* platformView = [[NSView alloc] init]; + FlutterMutatorView* mutatorView = [[FlutterMutatorView alloc] initWithPlatformView:platformView]; + + EXPECT_EQ(mutatorView.platformView, platformView); + + std::vector mutations{ + { + .type = kFlutterPlatformViewMutationTypeClipRect, + .clip_rect = FlutterRect{80, 40, 200, 100}, + }, + { + .type = kFlutterPlatformViewMutationTypeClipRect, + .clip_rect = FlutterRect{110, 55, 120, 65}, + }, + { + .type = kFlutterPlatformViewMutationTypeTransformation, + .transformation = + FlutterTransformation{ + .scaleX = 1, + .transX = 100, + .scaleY = 1, + .transY = 50, + }, + }, + }; + + ApplyFlutterLayer(mutatorView, FlutterSize{30, 20}, mutations); + + EXPECT_TRUE(CGRectEqualToRect(mutatorView.frame, CGRectMake(110, 55, 10, 10))); + EXPECT_TRUE( + CGRectEqualToRect(mutatorView.subviews.firstObject.frame, CGRectMake(-10, -5, 30, 20))); + EXPECT_TRUE(CGRectEqualToRect(platformView.frame, CGRectMake(0, 0, 30, 20))); +} + +TEST(FlutterMutatorViewTest, FrameWithTightClipAndTransformIsCorrect) { + NSView* platformView = [[NSView alloc] init]; + FlutterMutatorView* mutatorView = [[FlutterMutatorView alloc] initWithPlatformView:platformView]; + NSView* mutatorViewParent = [[NSView alloc] init]; + mutatorViewParent.wantsLayer = YES; + mutatorViewParent.layer.contentsScale = 2.0; + [mutatorViewParent addSubview:mutatorView]; + + std::vector mutations{ + { + .type = kFlutterPlatformViewMutationTypeTransformation, + .transformation = + FlutterTransformation{ + .scaleX = 2, + .scaleY = 2, + }, + }, + { + .type = kFlutterPlatformViewMutationTypeClipRect, + .clip_rect = FlutterRect{80, 40, 200, 100}, + }, + { + .type = kFlutterPlatformViewMutationTypeClipRect, + .clip_rect = FlutterRect{110, 55, 120, 65}, + }, + { + .type = kFlutterPlatformViewMutationTypeTransformation, + .transformation = + FlutterTransformation{ + .scaleX = 1, + .transX = 100, + .scaleY = 1, + .transY = 50, + }, + }, + { + .type = kFlutterPlatformViewMutationTypeTransformation, + .transformation = + FlutterTransformation{ + .scaleX = 1.5, + .transX = -7.5, + .scaleY = 1.5, + .transY = -5, + }, + }, + }; + + ApplyFlutterLayer(mutatorView, FlutterSize{30 * 2, 20 * 2}, mutations); + + EXPECT_TRUE(CGRectEqualToRect(mutatorView.frame, CGRectMake(110, 55, 10, 10))); + EXPECT_TRUE( + CGRectEqualToRect(mutatorView.subviews.firstObject.frame, CGRectMake(-17.5, -10, 45, 30))); + EXPECT_TRUE(CGRectEqualToRect(platformView.frame, CGRectMake(0, 0, 30, 20))); +} + +// Rounded rectangle without hitting the corner +TEST(FlutterMutatorViewTest, RoundRectClipsToSimpleRectangle) { + NSView* platformView = [[NSView alloc] init]; + FlutterMutatorView* mutatorView = [[FlutterMutatorView alloc] initWithPlatformView:platformView]; + + std::vector mutations{ + { + .type = kFlutterPlatformViewMutationTypeClipRoundedRect, + .clip_rounded_rect = + FlutterRoundedRect{ + .rect = FlutterRect{110, 30, 120, 90}, + .upper_left_corner_radius = FlutterSize{10, 10}, + .upper_right_corner_radius = FlutterSize{10, 10}, + .lower_right_corner_radius = FlutterSize{10, 10}, + .lower_left_corner_radius = FlutterSize{10, 10}, + }, + }, + { + .type = kFlutterPlatformViewMutationTypeTransformation, + .transformation = + FlutterTransformation{ + .scaleX = 1, + .transX = 100, + .scaleY = 1, + .transY = 50, + }, + }, + }; + + ApplyFlutterLayer(mutatorView, FlutterSize{30, 20}, mutations); + + EXPECT_TRUE(CGRectEqualToRect(mutatorView.frame, CGRectMake(110, 50, 10, 20))); + EXPECT_TRUE( + CGRectEqualToRect(mutatorView.subviews.firstObject.frame, CGRectMake(-10, 0, 30, 20))); + EXPECT_TRUE(CGRectEqualToRect(platformView.frame, CGRectMake(0, 0, 30, 20))); + EXPECT_EQ(mutatorView.pathClipViews.count, 0ul); +} + +// Ensure that the mutator view, clip views, and container all use a flipped y axis. The transforms +// sent from the framework assume this, and so aside from the consistency with every other embedder, +// we can avoid a lot of extra math. +TEST(FlutterMutatorViewTest, ViewsSetIsFlipped) { + NSView* platformView = [[NSView alloc] init]; + FlutterMutatorView* mutatorView = [[FlutterMutatorView alloc] initWithPlatformView:platformView]; + + std::vector mutations{ + { + .type = kFlutterPlatformViewMutationTypeClipRoundedRect, + .clip_rounded_rect = + FlutterRoundedRect{ + .rect = FlutterRect{110, 60, 150, 150}, + .upper_left_corner_radius = FlutterSize{10, 10}, + .upper_right_corner_radius = FlutterSize{10, 10}, + .lower_right_corner_radius = FlutterSize{10, 10}, + .lower_left_corner_radius = FlutterSize{10, 10}, + }, + }, + { + .type = kFlutterPlatformViewMutationTypeTransformation, + .transformation = + FlutterTransformation{ + .scaleX = 1, + .transX = 100, + .scaleY = 1, + .transY = 50, + }, + }, + }; + + ApplyFlutterLayer(mutatorView, FlutterSize{30, 20}, mutations); + + EXPECT_TRUE(mutatorView.isFlipped); + ASSERT_EQ(mutatorView.pathClipViews.count, 1ul); + EXPECT_TRUE(mutatorView.pathClipViews.firstObject.isFlipped); + EXPECT_TRUE(mutatorView.platformViewContainer.isFlipped); +} + +TEST(FlutterMutatorViewTest, RectsClipsToPathWhenRotated) { + NSView* platformView = [[NSView alloc] init]; + FlutterMutatorView* mutatorView = [[FlutterMutatorView alloc] initWithPlatformView:platformView]; + std::vector mutations{ + { + .type = kFlutterPlatformViewMutationTypeTransformation, + // Roation M_PI / 8 + .transformation = + FlutterTransformation{ + .scaleX = 0.9238795325112867, + .skewX = -0.3826834323650898, + .skewY = 0.3826834323650898, + .scaleY = 0.9238795325112867, + }, + }, + { + .type = kFlutterPlatformViewMutationTypeClipRect, + .clip_rect = FlutterRect{110, 60, 150, 150}, + }, + { + .type = kFlutterPlatformViewMutationTypeTransformation, + .transformation = + FlutterTransformation{ + .scaleX = 1, + .transX = 100, + .scaleY = 1, + .transY = 50, + }, + }, + }; + ApplyFlutterLayer(mutatorView, FlutterSize{30, 20}, mutations); + EXPECT_EQ(mutatorView.pathClipViews.count, 1ul); + EXPECT_NEAR(mutatorView.platformViewContainer.frame.size.width, 35.370054622640396, kMaxErr); + EXPECT_NEAR(mutatorView.platformViewContainer.frame.size.height, 29.958093621178421, kMaxErr); +} + +TEST(FlutterMutatorViewTest, RoundRectClipsToPath) { + NSView* platformView = [[NSView alloc] init]; + FlutterMutatorView* mutatorView = [[FlutterMutatorView alloc] initWithPlatformView:platformView]; + + std::vector mutations{ + { + .type = kFlutterPlatformViewMutationTypeClipRoundedRect, + .clip_rounded_rect = + FlutterRoundedRect{ + .rect = FlutterRect{110, 60, 150, 150}, + .upper_left_corner_radius = FlutterSize{10, 10}, + .upper_right_corner_radius = FlutterSize{10, 10}, + .lower_right_corner_radius = FlutterSize{10, 10}, + .lower_left_corner_radius = FlutterSize{10, 10}, + }, + }, + { + .type = kFlutterPlatformViewMutationTypeTransformation, + .transformation = + FlutterTransformation{ + .scaleX = 1, + .transX = 100, + .scaleY = 1, + .transY = 50, + }, + }, + }; + + ApplyFlutterLayer(mutatorView, FlutterSize{30, 20}, mutations); + + EXPECT_TRUE(CGRectEqualToRect(mutatorView.frame, CGRectMake(110, 60, 20, 10))); + EXPECT_TRUE( + CGRectEqualToRect(mutatorView.subviews.firstObject.frame, CGRectMake(-10, -10, 30, 20))); + EXPECT_TRUE(CGRectEqualToRect(platformView.frame, CGRectMake(0, 0, 30, 20))); + EXPECT_EQ(mutatorView.pathClipViews.count, 1ul); + ExpectTransform3DEqual(mutatorView.pathClipViews.firstObject.layer.mask.transform, + CATransform3DMakeTranslation(-100, -50, 0)); +} + +TEST(FlutterMutatorViewTest, PathClipViewsAreAddedAndRemoved) { + NSView* platformView = [[NSView alloc] init]; + FlutterMutatorView* mutatorView = [[FlutterMutatorView alloc] initWithPlatformView:platformView]; + + std::vector mutations{ + { + .type = kFlutterPlatformViewMutationTypeTransformation, + .transformation = + FlutterTransformation{ + .scaleX = 1, + .transX = 100, + .scaleY = 1, + .transY = 50, + }, + }, + }; + + ApplyFlutterLayer(mutatorView, FlutterSize{30, 20}, mutations); + + EXPECT_TRUE(CGRectEqualToRect(mutatorView.frame, CGRectMake(100, 50, 30, 20))); + EXPECT_EQ(mutatorView.pathClipViews.count, 0ull); + + std::vector mutations2{ + { + .type = kFlutterPlatformViewMutationTypeClipRoundedRect, + .clip_rounded_rect = + FlutterRoundedRect{ + .rect = FlutterRect{110, 60, 150, 150}, + .upper_left_corner_radius = FlutterSize{10, 10}, + .upper_right_corner_radius = FlutterSize{10, 10}, + .lower_right_corner_radius = FlutterSize{10, 10}, + .lower_left_corner_radius = FlutterSize{10, 10}, + }, + }, + { + .type = kFlutterPlatformViewMutationTypeTransformation, + .transformation = + FlutterTransformation{ + .scaleX = 1, + .transX = 100, + .scaleY = 1, + .transY = 50, + }, + }, + }; + + ApplyFlutterLayer(mutatorView, FlutterSize{30, 20}, mutations2); + + EXPECT_TRUE(CGRectEqualToRect(mutatorView.frame, CGRectMake(110, 60, 20, 10))); + EXPECT_TRUE( + CGRectEqualToRect(mutatorView.subviews.firstObject.frame, CGRectMake(-10, -10, 30, 20))); + EXPECT_TRUE(CGRectEqualToRect(platformView.frame, CGRectMake(0, 0, 30, 20))); + EXPECT_EQ(mutatorView.pathClipViews.count, 1ul); + + EXPECT_EQ(platformView.superview, mutatorView.platformViewContainer); + EXPECT_EQ(mutatorView.platformViewContainer.superview, mutatorView.pathClipViews[0]); + EXPECT_EQ(mutatorView.pathClipViews[0].superview, mutatorView); + + std::vector mutations3{ + { + .type = kFlutterPlatformViewMutationTypeClipRoundedRect, + .clip_rounded_rect = + FlutterRoundedRect{ + .rect = FlutterRect{110, 55, 150, 150}, + .upper_left_corner_radius = FlutterSize{10, 10}, + .upper_right_corner_radius = FlutterSize{10, 10}, + .lower_right_corner_radius = FlutterSize{10, 10}, + .lower_left_corner_radius = FlutterSize{10, 10}, + }, + }, + { + .type = kFlutterPlatformViewMutationTypeClipRoundedRect, + .clip_rounded_rect = + FlutterRoundedRect{ + .rect = FlutterRect{30, 30, 120, 65}, + .upper_left_corner_radius = FlutterSize{10, 10}, + .upper_right_corner_radius = FlutterSize{10, 10}, + .lower_right_corner_radius = FlutterSize{10, 10}, + .lower_left_corner_radius = FlutterSize{10, 10}, + }, + }, + { + .type = kFlutterPlatformViewMutationTypeTransformation, + .transformation = + FlutterTransformation{ + .scaleX = 1, + .transX = 100, + .scaleY = 1, + .transY = 50, + }, + }, + }; + + ApplyFlutterLayer(mutatorView, FlutterSize{30, 20}, mutations3); + + EXPECT_TRUE(CGRectEqualToRect(mutatorView.frame, CGRectMake(110, 55, 10, 10))); + EXPECT_TRUE( + CGRectEqualToRect(mutatorView.subviews.firstObject.frame, CGRectMake(-10, -5, 30, 20))); + EXPECT_EQ(mutatorView.pathClipViews.count, 2ul); + + EXPECT_EQ(platformView.superview, mutatorView.platformViewContainer); + EXPECT_EQ(mutatorView.platformViewContainer.superview, mutatorView.pathClipViews[1]); + EXPECT_EQ(mutatorView.pathClipViews[1].superview, mutatorView.pathClipViews[0]); + EXPECT_EQ(mutatorView.pathClipViews[0].superview, mutatorView); + + ApplyFlutterLayer(mutatorView, FlutterSize{30, 20}, mutations2); + + EXPECT_TRUE(CGRectEqualToRect(mutatorView.frame, CGRectMake(110, 60, 20, 10))); + EXPECT_TRUE( + CGRectEqualToRect(mutatorView.subviews.firstObject.frame, CGRectMake(-10, -10, 30, 20))); + EXPECT_TRUE(CGRectEqualToRect(platformView.frame, CGRectMake(0, 0, 30, 20))); + EXPECT_EQ(mutatorView.pathClipViews.count, 1ul); + + EXPECT_EQ(platformView.superview, mutatorView.platformViewContainer); + EXPECT_EQ(mutatorView.platformViewContainer.superview, mutatorView.pathClipViews[0]); + EXPECT_EQ(mutatorView.pathClipViews[0].superview, mutatorView); + + ApplyFlutterLayer(mutatorView, FlutterSize{30, 20}, mutations); + + EXPECT_TRUE(CGRectEqualToRect(mutatorView.frame, CGRectMake(100, 50, 30, 20))); + EXPECT_EQ(mutatorView.pathClipViews.count, 0ull); +} + +TEST(FlutterMutatorViewTest, HitTestIgnoreRegion) { + NSView* platformView = [[NSView alloc] init]; + FlutterMutatorView* mutatorView = [[FlutterMutatorView alloc] initWithPlatformView:platformView]; + ApplyFlutterLayer(mutatorView, FlutterSize{100, 100}, {}); + EXPECT_EQ([mutatorView hitTest:NSMakePoint(10, 10)], platformView); + EXPECT_EQ([mutatorView hitTest:NSMakePoint(50, 10)], platformView); + + [mutatorView resetHitTestRegion]; + [mutatorView addHitTestIgnoreRegion:CGRectMake(0, 0, 50, 50)]; + [mutatorView addHitTestIgnoreRegion:CGRectMake(50, 50, 50, 50)]; + + EXPECT_EQ([mutatorView hitTest:NSMakePoint(10, 10)], nil); + EXPECT_EQ([mutatorView hitTest:NSMakePoint(49, 10)], nil); + EXPECT_EQ([mutatorView hitTest:NSMakePoint(10, 49)], nil); + EXPECT_EQ([mutatorView hitTest:NSMakePoint(50, 50)], nil); + EXPECT_EQ([mutatorView hitTest:NSMakePoint(50, 10)], platformView); + EXPECT_EQ([mutatorView hitTest:NSMakePoint(10, 50)], platformView); + + [mutatorView resetHitTestRegion]; + EXPECT_EQ([mutatorView hitTest:NSMakePoint(10, 10)], platformView); + EXPECT_EQ([mutatorView hitTest:NSMakePoint(49, 10)], platformView); + EXPECT_EQ([mutatorView hitTest:NSMakePoint(10, 49)], platformView); + EXPECT_EQ([mutatorView hitTest:NSMakePoint(50, 50)], platformView); + EXPECT_EQ([mutatorView hitTest:NSMakePoint(50, 10)], platformView); + EXPECT_EQ([mutatorView hitTest:NSMakePoint(10, 50)], platformView); +} + +TEST(FlutterMutatorViewTest, ReparentingPlatformView) { + NSView* platformView = [[NSView alloc] init]; + FlutterMutatorView* mutatorView = [[FlutterMutatorView alloc] initWithPlatformView:platformView]; + ApplyFlutterLayer(mutatorView, FlutterSize{100, 100}, {}); + EXPECT_TRUE(platformView.superview == mutatorView.platformViewContainer); + EXPECT_TRUE(CGRectEqualToRect(platformView.frame, CGRectMake(0, 0, 100, 100))); + + // Reparent platform view and replace it with placeholder (mimicking WKWebKit going full screen) + NSView* newParent = [[NSView alloc] init]; + [newParent addSubview:platformView]; + platformView.frame = CGRectMake(10, 10, 200, 200); + + NSView* placeholderView = [[NSView alloc] init]; + [mutatorView.platformViewContainer addSubview:placeholderView]; + ApplyFlutterLayer(mutatorView, FlutterSize{100, 100}, {}); + + // Platform view should not be touched but the replacement view should be properly positioned. + EXPECT_TRUE(platformView.superview == newParent); + EXPECT_TRUE(CGRectEqualToRect(platformView.frame, CGRectMake(10, 10, 200, 200))); + EXPECT_TRUE(CGRectEqualToRect(placeholderView.frame, CGRectMake(0, 0, 100, 100))); +} + +@interface FlutterCursorCoordinatorTest : NSObject + +@end + +@implementation FlutterCursorCoordinatorTest +- (void)testCoordinatorEventWithinFlutterContent { + id flutterView = OCMClassMock([FlutterView class]); + FlutterCursorCoordinator* coordinator = + [[FlutterCursorCoordinator alloc] initWithFlutterView:flutterView]; + { + id platformView = OCMClassMock([NSView class]); + OCMStub([flutterView cursorUpdate:[OCMArg any]]); + id mutatorView = OCMStrictClassMock([FlutterMutatorView class]); + OCMStub([mutatorView platformView]).andReturn(platformView); + CGPoint location = NSMakePoint(50, 50); + OCMStub([mutatorView convertPoint:location fromView:[OCMArg any]]).andReturn(location); + NSEvent* event = [NSEvent mouseEventWithType:NSEventTypeMouseMoved + location:location + modifierFlags:0 + timestamp:0 + windowNumber:0 + context:nil + eventNumber:0 + clickCount:0 + pressure:0]; + [coordinator processMouseMoveEvent:event + forMutatorView:mutatorView + overlayRegion:{CGRectMake(0, 0, 100, 100)}]; + OCMVerify([flutterView cursorUpdate:event]); + } + { + id platformView = OCMClassMock([NSView class]); + // Make sure once event is handled the coordinator will not send cursorUpdate again. + OCMReject([flutterView cursorUpdate:[OCMArg any]]); + id mutatorView = OCMStrictClassMock([FlutterMutatorView class]); + OCMStub([mutatorView platformView]).andReturn(platformView); + CGPoint location = NSMakePoint(50, 50); + OCMStub([mutatorView convertPoint:location fromView:[OCMArg any]]).andReturn(location); + NSEvent* event = [NSEvent mouseEventWithType:NSEventTypeMouseMoved + location:location + modifierFlags:0 + timestamp:0 + windowNumber:0 + context:nil + eventNumber:0 + clickCount:0 + pressure:0]; + [coordinator processMouseMoveEvent:event + forMutatorView:mutatorView + overlayRegion:{CGRectMake(0, 0, 100, 100)}]; + } + EXPECT_TRUE(coordinator.cleanupScheduled); + [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; + EXPECT_FALSE(coordinator.cleanupScheduled); +} + +- (void)testCoordinatorEventOutsideFlutterContent { + id flutterView = OCMClassMock([FlutterView class]); + OCMReject([flutterView cursorUpdate:[OCMArg any]]); + FlutterCursorCoordinator* coordinator = + [[FlutterCursorCoordinator alloc] initWithFlutterView:flutterView]; + id platformViewWindow = OCMClassMock([NSWindow class]); + { + id platformView = OCMClassMock([NSView class]); + OCMStub([platformViewWindow invalidateCursorRectsForView:platformView]); + OCMStub([platformView window]).andReturn(platformViewWindow); + OCMStub([flutterView cursorUpdate:[OCMArg any]]); + id mutatorView = OCMStrictClassMock([FlutterMutatorView class]); + OCMStub([mutatorView platformView]).andReturn(platformView); + CGPoint location = NSMakePoint(150, 150); + OCMStub([mutatorView convertPoint:location fromView:[OCMArg any]]).andReturn(location); + NSEvent* event = [NSEvent mouseEventWithType:NSEventTypeMouseMoved + location:location + modifierFlags:0 + timestamp:0 + windowNumber:0 + context:nil + eventNumber:0 + clickCount:0 + pressure:0]; + [coordinator processMouseMoveEvent:event + forMutatorView:mutatorView + overlayRegion:{CGRectMake(0, 0, 100, 100)}]; + OCMVerify([platformViewWindow invalidateCursorRectsForView:platformView]); + } + { + // Make sure this is not called again for subsequent invocation during same run loop turn. + OCMReject([platformViewWindow invalidateCursorRectsForView:[OCMArg any]]); + + id platformView = OCMClassMock([NSView class]); + OCMStub([platformViewWindow invalidateCursorRectsForView:platformView]); + OCMStub([platformView window]).andReturn(platformViewWindow); + OCMStub([flutterView cursorUpdate:[OCMArg any]]); + id mutatorView = OCMStrictClassMock([FlutterMutatorView class]); + OCMStub([mutatorView platformView]).andReturn(platformView); + CGPoint location = NSMakePoint(150, 150); + OCMStub([mutatorView convertPoint:location fromView:[OCMArg any]]).andReturn(location); + NSEvent* event = [NSEvent mouseEventWithType:NSEventTypeMouseMoved + location:location + modifierFlags:0 + timestamp:0 + windowNumber:0 + context:nil + eventNumber:0 + clickCount:0 + pressure:0]; + [coordinator processMouseMoveEvent:event + forMutatorView:mutatorView + overlayRegion:{CGRectMake(0, 0, 100, 100)}]; + } + EXPECT_TRUE(coordinator.cleanupScheduled); + [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; + EXPECT_FALSE(coordinator.cleanupScheduled); + + // Check that invalidateCursorRectsForView is called again + platformViewWindow = OCMClassMock([NSWindow class]); + { + id platformView = OCMClassMock([NSView class]); + OCMStub([platformViewWindow invalidateCursorRectsForView:platformView]); + OCMStub([platformView window]).andReturn(platformViewWindow); + OCMStub([flutterView cursorUpdate:[OCMArg any]]); + id mutatorView = OCMStrictClassMock([FlutterMutatorView class]); + OCMStub([mutatorView platformView]).andReturn(platformView); + CGPoint location = NSMakePoint(150, 150); + OCMStub([mutatorView convertPoint:location fromView:[OCMArg any]]).andReturn(location); + NSEvent* event = [NSEvent mouseEventWithType:NSEventTypeMouseMoved + location:location + modifierFlags:0 + timestamp:0 + windowNumber:0 + context:nil + eventNumber:0 + clickCount:0 + pressure:0]; + [coordinator processMouseMoveEvent:event + forMutatorView:mutatorView + overlayRegion:{CGRectMake(0, 0, 100, 100)}]; + OCMVerify([platformViewWindow invalidateCursorRectsForView:platformView]); + } + [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; +} +@end + +TEST(FlutterMutatorViewTest, CursorCoordinator) { + [[[FlutterCursorCoordinatorTest alloc] init] testCoordinatorEventWithinFlutterContent]; + [[[FlutterCursorCoordinatorTest alloc] init] testCoordinatorEventOutsideFlutterContent]; +} \ No newline at end of file diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.h new file mode 100644 index 0000000000000000000000000000000000000000..62014f670ddf1cfca5fe65cc5a36683628d2b0dc --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.h @@ -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. + +#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMNODEDELEGATEMAC_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMNODEDELEGATEMAC_H_ + +#import + +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h" + +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/common/accessibility_bridge.h" +#include "flutter/shell/platform/common/flutter_platform_node_delegate.h" +#include "flutter/shell/platform/embedder/embedder.h" + +namespace flutter { + +//------------------------------------------------------------------------------ +/// The macOS implementation of FlutterPlatformNodeDelegate. This class uses +/// AXPlatformNodeMac to manage the macOS-specific accessibility objects. +class FlutterPlatformNodeDelegateMac : public FlutterPlatformNodeDelegate { + public: + FlutterPlatformNodeDelegateMac(std::weak_ptr bridge, + __weak FlutterViewController* view_controller); + virtual ~FlutterPlatformNodeDelegateMac(); + + void Init(std::weak_ptr bridge, ui::AXNode* node) override; + + void NodeDataChanged(const ui::AXNodeData& old_node_data, + const ui::AXNodeData& new_node_data) override; + + //--------------------------------------------------------------------------- + /// @brief Gets the live region text of this node in UTF-8 format. This + /// is useful to determine the changes in between semantics + /// updates when generating accessibility events. + std::string GetLiveRegionText() const; + + // |ui::AXPlatformNodeDelegate| + gfx::NativeViewAccessible GetNativeViewAccessible() override; + + // |ui::AXPlatformNodeDelegate| + gfx::NativeViewAccessible GetNSWindow() override; + + // |FlutterPlatformNodeDelegate| + gfx::NativeViewAccessible GetParent() override; + + // |FlutterPlatformNodeDelegate| + gfx::Rect GetBoundsRect( + const ui::AXCoordinateSystem coordinate_system, + const ui::AXClippingBehavior clipping_behavior, + ui::AXOffscreenResult* offscreen_result) const override; + + private: + ui::AXPlatformNode* ax_platform_node_; + std::weak_ptr bridge_; + __weak FlutterViewController* view_controller_; + + gfx::RectF ConvertBoundsFromLocalToScreen( + const gfx::RectF& local_bounds) const; + gfx::RectF ConvertBoundsFromScreenToGlobal( + const gfx::RectF& window_bounds) const; + + FML_DISALLOW_COPY_AND_ASSIGN(FlutterPlatformNodeDelegateMac); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMNODEDELEGATEMAC_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.mm new file mode 100644 index 0000000000000000000000000000000000000000..5a6c0235d0931667619cc1f31b343d6bb20a0fee --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.mm @@ -0,0 +1,138 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.h" + +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppDelegate.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" + +#include "flutter/shell/platform/common/accessibility_bridge.h" +#include "flutter/third_party/accessibility/ax/ax_action_data.h" +#include "flutter/third_party/accessibility/ax/ax_node_position.h" +#include "flutter/third_party/accessibility/ax/platform/ax_platform_node.h" +#include "flutter/third_party/accessibility/ax/platform/ax_platform_node_base.h" +#include "flutter/third_party/accessibility/base/string_utils.h" +#include "flutter/third_party/accessibility/gfx/geometry/rect_conversions.h" +#include "flutter/third_party/accessibility/gfx/mac/coordinate_conversion.h" + +namespace flutter { // namespace + +FlutterPlatformNodeDelegateMac::FlutterPlatformNodeDelegateMac( + std::weak_ptr bridge, + __weak FlutterViewController* view_controller) + : bridge_(std::move(bridge)), view_controller_(view_controller) {} + +void FlutterPlatformNodeDelegateMac::Init(std::weak_ptr bridge, ui::AXNode* node) { + FlutterPlatformNodeDelegate::Init(bridge, node); + if (GetData().IsTextField()) { + ax_platform_node_ = new FlutterTextPlatformNode(this, view_controller_); + } else { + ax_platform_node_ = ui::AXPlatformNode::Create(this); + } + NSCAssert(ax_platform_node_, @"Failed to create platform node."); +} + +void FlutterPlatformNodeDelegateMac::NodeDataChanged(const ui::AXNodeData& old_node_data, + const ui::AXNodeData& new_node_data) { + if (old_node_data.IsTextField() && !new_node_data.IsTextField()) { + ax_platform_node_->Destroy(); + ax_platform_node_ = ui::AXPlatformNode::Create(this); + } else if (!old_node_data.IsTextField() && new_node_data.IsTextField()) { + ax_platform_node_->Destroy(); + ax_platform_node_ = new FlutterTextPlatformNode(this, view_controller_); + } +} + +FlutterPlatformNodeDelegateMac::~FlutterPlatformNodeDelegateMac() { + // Destroy() also calls delete on itself. + ax_platform_node_->Destroy(); +} + +gfx::NativeViewAccessible FlutterPlatformNodeDelegateMac::GetNativeViewAccessible() { + NSCAssert(ax_platform_node_, @"Platform node does not exist."); + return ax_platform_node_->GetNativeViewAccessible(); +} + +gfx::NativeViewAccessible FlutterPlatformNodeDelegateMac::GetParent() { + gfx::NativeViewAccessible parent = FlutterPlatformNodeDelegate::GetParent(); + if (!parent) { + NSCAssert(view_controller_.viewLoaded, @"Flutter view must be loaded"); + return view_controller_.flutterView; + } + return parent; +} + +gfx::Rect FlutterPlatformNodeDelegateMac::GetBoundsRect( + const ui::AXCoordinateSystem coordinate_system, + const ui::AXClippingBehavior clipping_behavior, + ui::AXOffscreenResult* offscreen_result) const { + gfx::Rect local_bounds = FlutterPlatformNodeDelegate::GetBoundsRect( + coordinate_system, clipping_behavior, offscreen_result); + gfx::RectF local_bounds_f(local_bounds); + gfx::RectF screen_bounds = ConvertBoundsFromLocalToScreen(local_bounds_f); + return gfx::ToEnclosingRect(ConvertBoundsFromScreenToGlobal(screen_bounds)); +} + +gfx::NativeViewAccessible FlutterPlatformNodeDelegateMac::GetNSWindow() { + FlutterAppDelegate* appDelegate = (FlutterAppDelegate*)[NSApp delegate]; + return appDelegate.mainFlutterWindow; +} + +std::string FlutterPlatformNodeDelegateMac::GetLiveRegionText() const { + if (GetAXNode()->IsIgnored()) { + return ""; + } + + std::string text = GetData().GetStringAttribute(ax::mojom::StringAttribute::kName); + if (!text.empty()) { + return text; + }; + auto bridge_ptr = bridge_.lock(); + NSCAssert(bridge_ptr, @"Accessibility bridge in flutter engine must not be null."); + for (int32_t child : GetData().child_ids) { + auto delegate_child = bridge_ptr->GetFlutterPlatformNodeDelegateFromID(child).lock(); + if (!delegate_child) { + continue; + } + text += std::static_pointer_cast(delegate_child) + ->GetLiveRegionText(); + } + return text; +} + +gfx::RectF FlutterPlatformNodeDelegateMac::ConvertBoundsFromLocalToScreen( + const gfx::RectF& local_bounds) const { + // Converts to NSRect to use NSView rect conversion. + NSRect ns_local_bounds = + NSMakeRect(local_bounds.x(), local_bounds.y(), local_bounds.width(), local_bounds.height()); + // The macOS XY coordinates start at bottom-left and increase toward top-right, + // which is different from the Flutter's XY coordinates that start at top-left + // increasing to bottom-right. Therefore, this method needs to flip the y coordinate when + // it converts the bounds from flutter coordinates to macOS coordinates. + ns_local_bounds.origin.y = -ns_local_bounds.origin.y - ns_local_bounds.size.height; + + NSCAssert(view_controller_.viewLoaded, @"Flutter view must be loaded."); + NSRect ns_view_bounds = [view_controller_.flutterView convertRectFromBacking:ns_local_bounds]; + NSRect ns_window_bounds = [view_controller_.flutterView convertRect:ns_view_bounds toView:nil]; + NSRect ns_screen_bounds = + [[view_controller_.flutterView window] convertRectToScreen:ns_window_bounds]; + gfx::RectF screen_bounds(ns_screen_bounds.origin.x, ns_screen_bounds.origin.y, + ns_screen_bounds.size.width, ns_screen_bounds.size.height); + return screen_bounds; +} + +gfx::RectF FlutterPlatformNodeDelegateMac::ConvertBoundsFromScreenToGlobal( + const gfx::RectF& screen_bounds) const { + // The VoiceOver seems to only accept bounds that are relative to primary screen. + // Thus, this method uses [[NSScreen screens] firstObject] instead of [NSScreen mainScreen]. + NSScreen* screen = [[NSScreen screens] firstObject]; + NSRect primary_screen_bounds = [screen frame]; + // The screen is flipped against y axis. + float flipped_y = primary_screen_bounds.size.height - screen_bounds.y() - screen_bounds.height(); + return {screen_bounds.x(), flipped_y, screen_bounds.width(), screen_bounds.height()}; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMacTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMacTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..405e24347ee28bfb1a1f4c9d72090e306f5003e2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMacTest.mm @@ -0,0 +1,376 @@ +// 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/testing/testing.h" + +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMac.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" + +#include "flutter/shell/platform/common/accessibility_bridge.h" +#include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h" +#include "flutter/third_party/accessibility/ax/ax_action_data.h" + +namespace flutter::testing { + +namespace { +// Returns a view controller configured for the text fixture resource configuration. +FlutterViewController* CreateTestViewController() { + NSString* fixtures = @(testing::GetFixturesPath()); + FlutterDartProject* project = [[FlutterDartProject alloc] + initWithAssetsPath:fixtures + ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; + return [[FlutterViewController alloc] initWithProject:project]; +} +} // namespace + +TEST(FlutterPlatformNodeDelegateMac, Basics) { + FlutterViewController* viewController = CreateTestViewController(); + FlutterEngine* engine = viewController.engine; + engine.semanticsEnabled = YES; + auto bridge = viewController.accessibilityBridge.lock(); + // Initialize ax node data. + FlutterSemanticsNode2 root; + root.id = 0; + root.flags = static_cast(0); + ; + root.actions = static_cast(0); + root.text_selection_base = -1; + root.text_selection_extent = -1; + root.label = "accessibility"; + root.hint = ""; + root.value = ""; + root.increased_value = ""; + root.decreased_value = ""; + root.tooltip = ""; + root.child_count = 0; + root.custom_accessibility_actions_count = 0; + bridge->AddFlutterSemanticsNodeUpdate(root); + + bridge->CommitUpdates(); + + auto root_platform_node_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); + // Verify the accessibility attribute matches. + NSAccessibilityElement* native_accessibility = + root_platform_node_delegate->GetNativeViewAccessible(); + std::string value = [native_accessibility.accessibilityValue UTF8String]; + EXPECT_TRUE(value == "accessibility"); + EXPECT_EQ(native_accessibility.accessibilityRole, NSAccessibilityStaticTextRole); + EXPECT_EQ([native_accessibility.accessibilityChildren count], 0u); + [engine shutDownEngine]; +} + +TEST(FlutterPlatformNodeDelegateMac, SelectableTextHasCorrectSemantics) { + FlutterViewController* viewController = CreateTestViewController(); + FlutterEngine* engine = viewController.engine; + engine.semanticsEnabled = YES; + auto bridge = viewController.accessibilityBridge.lock(); + // Initialize ax node data. + FlutterSemanticsNode2 root; + root.id = 0; + root.flags = + static_cast(FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField | + FlutterSemanticsFlag::kFlutterSemanticsFlagIsReadOnly); + root.actions = static_cast(0); + root.text_selection_base = 1; + root.text_selection_extent = 3; + root.label = ""; + root.hint = ""; + // Selectable text store its text in value + root.value = "selectable text"; + root.increased_value = ""; + root.decreased_value = ""; + root.tooltip = ""; + root.child_count = 0; + root.custom_accessibility_actions_count = 0; + bridge->AddFlutterSemanticsNodeUpdate(root); + + bridge->CommitUpdates(); + + auto root_platform_node_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); + // Verify the accessibility attribute matches. + NSAccessibilityElement* native_accessibility = + root_platform_node_delegate->GetNativeViewAccessible(); + std::string value = [native_accessibility.accessibilityValue UTF8String]; + EXPECT_EQ(value, "selectable text"); + EXPECT_EQ(native_accessibility.accessibilityRole, NSAccessibilityStaticTextRole); + EXPECT_EQ([native_accessibility.accessibilityChildren count], 0u); + NSRange selection = native_accessibility.accessibilitySelectedTextRange; + EXPECT_EQ(selection.location, 1u); + EXPECT_EQ(selection.length, 2u); + std::string selected_text = [native_accessibility.accessibilitySelectedText UTF8String]; + EXPECT_EQ(selected_text, "el"); +} + +TEST(FlutterPlatformNodeDelegateMac, SelectableTextWithoutSelectionReturnZeroRange) { + FlutterViewController* viewController = CreateTestViewController(); + FlutterEngine* engine = viewController.engine; + engine.semanticsEnabled = YES; + auto bridge = viewController.accessibilityBridge.lock(); + // Initialize ax node data. + FlutterSemanticsNode2 root; + root.id = 0; + root.flags = + static_cast(FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField | + FlutterSemanticsFlag::kFlutterSemanticsFlagIsReadOnly); + root.actions = static_cast(0); + root.text_selection_base = -1; + root.text_selection_extent = -1; + root.label = ""; + root.hint = ""; + // Selectable text store its text in value + root.value = "selectable text"; + root.increased_value = ""; + root.decreased_value = ""; + root.tooltip = ""; + root.child_count = 0; + root.custom_accessibility_actions_count = 0; + bridge->AddFlutterSemanticsNodeUpdate(root); + + bridge->CommitUpdates(); + + auto root_platform_node_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); + // Verify the accessibility attribute matches. + NSAccessibilityElement* native_accessibility = + root_platform_node_delegate->GetNativeViewAccessible(); + NSRange selection = native_accessibility.accessibilitySelectedTextRange; + EXPECT_TRUE(selection.location == NSNotFound); + EXPECT_EQ(selection.length, 0u); +} + +// MOCK_ENGINE_PROC is leaky by design +// NOLINTBEGIN(clang-analyzer-core.StackAddressEscape) + +TEST(FlutterPlatformNodeDelegateMac, CanPerformAction) { + FlutterViewController* viewController = CreateTestViewController(); + FlutterEngine* engine = viewController.engine; + + // Attach the view to a NSWindow. + NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600) + styleMask:NSBorderlessWindowMask + backing:NSBackingStoreBuffered + defer:NO]; + window.contentView = viewController.view; + + engine.semanticsEnabled = YES; + auto bridge = viewController.accessibilityBridge.lock(); + // Initialize ax node data. + FlutterSemanticsNode2 root; + root.id = 0; + root.label = "root"; + root.hint = ""; + root.value = ""; + root.increased_value = ""; + root.decreased_value = ""; + root.tooltip = ""; + root.child_count = 1; + int32_t children[] = {1}; + root.children_in_traversal_order = children; + root.custom_accessibility_actions_count = 0; + bridge->AddFlutterSemanticsNodeUpdate(root); + + FlutterSemanticsNode2 child1; + child1.id = 1; + child1.label = "child 1"; + child1.hint = ""; + child1.value = ""; + child1.increased_value = ""; + child1.decreased_value = ""; + child1.tooltip = ""; + child1.child_count = 0; + child1.custom_accessibility_actions_count = 0; + bridge->AddFlutterSemanticsNodeUpdate(child1); + + bridge->CommitUpdates(); + + auto root_platform_node_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock(); + + // Set up embedder API mock. + FlutterSemanticsAction called_action; + uint64_t called_id; + + engine.embedderAPI.DispatchSemanticsAction = MOCK_ENGINE_PROC( + DispatchSemanticsAction, + ([&called_id, &called_action](auto engine, uint64_t id, FlutterSemanticsAction action, + const uint8_t* data, size_t data_length) { + called_id = id; + called_action = action; + return kSuccess; + })); + + // Performs an AXAction. + ui::AXActionData action_data; + action_data.action = ax::mojom::Action::kDoDefault; + root_platform_node_delegate->AccessibilityPerformAction(action_data); + + EXPECT_EQ(called_action, FlutterSemanticsAction::kFlutterSemanticsActionTap); + EXPECT_EQ(called_id, 1u); + + [engine setViewController:nil]; + [engine shutDownEngine]; +} + +// NOLINTEND(clang-analyzer-core.StackAddressEscape) + +TEST(FlutterPlatformNodeDelegateMac, TextFieldUsesFlutterTextField) { + FlutterViewController* viewController = CreateTestViewController(); + FlutterEngine* engine = viewController.engine; + [viewController loadView]; + + // Unit test localization is unnecessary. + // NOLINTNEXTLINE(clang-analyzer-optin.osx.cocoa.localizability.NonLocalizedStringChecker) + engine.textInputPlugin.string = @"textfield"; + // Creates a NSWindow so that the native text field can become first responder. + NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600) + styleMask:NSBorderlessWindowMask + backing:NSBackingStoreBuffered + defer:NO]; + window.contentView = viewController.view; + engine.semanticsEnabled = YES; + + auto bridge = viewController.accessibilityBridge.lock(); + // Initialize ax node data. + FlutterSemanticsNode2 root; + root.id = 0; + root.flags = static_cast(0); + root.actions = static_cast(0); + root.label = "root"; + root.hint = ""; + root.value = ""; + root.increased_value = ""; + root.decreased_value = ""; + root.tooltip = ""; + root.child_count = 1; + int32_t children[] = {1}; + root.children_in_traversal_order = children; + root.custom_accessibility_actions_count = 0; + root.rect = {0, 0, 100, 100}; // LTRB + root.transform = {1, 0, 0, 0, 1, 0, 0, 0, 1}; + bridge->AddFlutterSemanticsNodeUpdate(root); + + double rectSize = 50; + double transformFactor = 0.5; + + FlutterSemanticsNode2 child1; + child1.id = 1; + child1.flags = FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField; + child1.actions = static_cast(0); + child1.label = ""; + child1.hint = ""; + child1.value = "textfield"; + child1.increased_value = ""; + child1.decreased_value = ""; + child1.tooltip = ""; + child1.text_selection_base = -1; + child1.text_selection_extent = -1; + child1.child_count = 0; + child1.custom_accessibility_actions_count = 0; + child1.rect = {0, 0, rectSize, rectSize}; // LTRB + child1.transform = {transformFactor, 0, 0, 0, transformFactor, 0, 0, 0, 1}; + bridge->AddFlutterSemanticsNodeUpdate(child1); + + bridge->CommitUpdates(); + + auto child_platform_node_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock(); + // Verify the accessibility attribute matches. + id native_accessibility = child_platform_node_delegate->GetNativeViewAccessible(); + EXPECT_EQ([native_accessibility isKindOfClass:[FlutterTextField class]], YES); + FlutterTextField* native_text_field = (FlutterTextField*)native_accessibility; + + NSView* view = viewController.flutterView; + CGRect scaledBounds = [view convertRectToBacking:view.bounds]; + CGSize scaledSize = scaledBounds.size; + double pixelRatio = view.bounds.size.width == 0 ? 1 : scaledSize.width / view.bounds.size.width; + + double expectedFrameSize = rectSize * transformFactor / pixelRatio; + EXPECT_EQ(NSEqualRects(native_text_field.frame, NSMakeRect(0, 600 - expectedFrameSize, + expectedFrameSize, expectedFrameSize)), + YES); + + [native_text_field startEditing]; + EXPECT_EQ([native_text_field.stringValue isEqualToString:@"textfield"], YES); +} + +TEST(FlutterPlatformNodeDelegateMac, ChangingFlagsUpdatesNativeViewAccessible) { + FlutterViewController* viewController = CreateTestViewController(); + FlutterEngine* engine = viewController.engine; + [viewController loadView]; + + // Creates a NSWindow so that the native text field can become first responder. + NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600) + styleMask:NSBorderlessWindowMask + backing:NSBackingStoreBuffered + defer:NO]; + window.contentView = viewController.view; + engine.semanticsEnabled = YES; + + auto bridge = viewController.accessibilityBridge.lock(); + // Initialize ax node data. + FlutterSemanticsNode2 root; + root.id = 0; + root.flags = static_cast(0); + root.actions = static_cast(0); + root.label = "root"; + root.hint = ""; + root.value = ""; + root.increased_value = ""; + root.decreased_value = ""; + root.tooltip = ""; + root.child_count = 1; + int32_t children[] = {1}; + root.children_in_traversal_order = children; + root.custom_accessibility_actions_count = 0; + root.rect = {0, 0, 100, 100}; // LTRB + root.transform = {1, 0, 0, 0, 1, 0, 0, 0, 1}; + bridge->AddFlutterSemanticsNodeUpdate(root); + + double rectSize = 50; + double transformFactor = 0.5; + + FlutterSemanticsNode2 child1; + child1.id = 1; + child1.flags = static_cast(0); + child1.actions = static_cast(0); + child1.label = ""; + child1.hint = ""; + child1.value = "textfield"; + child1.increased_value = ""; + child1.decreased_value = ""; + child1.tooltip = ""; + child1.text_selection_base = -1; + child1.text_selection_extent = -1; + child1.child_count = 0; + child1.custom_accessibility_actions_count = 0; + child1.rect = {0, 0, rectSize, rectSize}; // LTRB + child1.transform = {transformFactor, 0, 0, 0, transformFactor, 0, 0, 0, 1}; + bridge->AddFlutterSemanticsNodeUpdate(child1); + + bridge->CommitUpdates(); + + auto child_platform_node_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock(); + // Verify the accessibility attribute matches. + id native_accessibility = child_platform_node_delegate->GetNativeViewAccessible(); + EXPECT_TRUE([[native_accessibility className] isEqualToString:@"AXPlatformNodeCocoa"]); + + // Converting child to text field should produce `FlutterTextField` native view accessible. + child1.flags = FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField; + bridge->AddFlutterSemanticsNodeUpdate(child1); + bridge->CommitUpdates(); + + native_accessibility = child_platform_node_delegate->GetNativeViewAccessible(); + EXPECT_TRUE([native_accessibility isKindOfClass:[FlutterTextField class]]); + + child1.flags = static_cast(0); + bridge->AddFlutterSemanticsNodeUpdate(child1); + bridge->CommitUpdates(); + + native_accessibility = child_platform_node_delegate->GetNativeViewAccessible(); + EXPECT_TRUE([[native_accessibility className] isEqualToString:@"AXPlatformNodeCocoa"]); +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewController.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewController.h new file mode 100644 index 0000000000000000000000000000000000000000..a784a69b94d0ba3217a3b786ad54c5872972d76d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewController.h @@ -0,0 +1,68 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMVIEWCONTROLLER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMVIEWCONTROLLER_H_ + +#import + +#import "FlutterChannels.h" + +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterPlatformViews.h" + +#include +#include + +@interface FlutterPlatformViewController : NSViewController +@end + +@interface FlutterPlatformViewController () + +/** + * Creates a platform view of viewType with viewId and arguments passed from + * the framework's creationParams constructor parameter. + * FlutterResult is updated to contain nil for success or to contain + * a FlutterError if there is an error. + */ +- (void)onCreateWithViewIdentifier:(int64_t)viewId + viewType:(nonnull NSString*)viewType + arguments:(nullable id)args + result:(nonnull FlutterResult)result; + +/** + * Disposes the platform view with `viewId`. + * FlutterResult is updated to contain nil for success or a FlutterError if there is an error. + */ +- (void)onDisposeWithViewID:(int64_t)viewId result:(nonnull FlutterResult)result; + +/** + * Returns the platform view associated with the viewId. + */ +- (nullable NSView*)platformViewWithID:(int64_t)viewId; + +/** + * Register a view factory by adding an entry into the platformViewFactories map with key factoryId + * and value factory. + */ +- (void)registerViewFactory:(nonnull NSObject*)factory + withId:(nonnull NSString*)factoryId; + +/** + * Handles platform view related method calls, for example create, dispose, etc. + */ +- (void)handleMethodCall:(nonnull FlutterMethodCall*)call result:(nonnull FlutterResult)result; + +/** + * Removes platform views slated to be disposed via method handler calls. + */ +- (void)disposePlatformViews; + +/** + * Removes all platform views. + */ +- (void)reset; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMVIEWCONTROLLER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewController.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewController.mm new file mode 100644 index 0000000000000000000000000000000000000000..5e7230c7d1319e1f1ac03ed3b76f640b3b7d22a9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewController.mm @@ -0,0 +1,180 @@ +// 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/fml/logging.h" + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewController.h" + +@implementation FlutterPlatformViewController { + // NSDictionary maps platform view type identifiers to FlutterPlatformViewFactories. + NSMutableDictionary*>* _platformViewFactories; + + // Map from platform view id to the underlying NSView. + std::map _platformViews; + + // View ids that are going to be disposed on the next present call. + std::unordered_set _platformViewsToDispose; +} + +- (instancetype)init { + self = [super init]; + if (self) { + _platformViewFactories = [[NSMutableDictionary alloc] init]; + } + return self; +} + +- (void)onCreateWithViewIdentifier:(int64_t)viewId + viewType:(nonnull NSString*)viewType + arguments:(nullable id)args + result:(nonnull FlutterResult)result { + if (_platformViews.count(viewId) != 0) { + result([FlutterError errorWithCode:@"recreating_view" + message:@"trying to create an already created view" + details:[NSString stringWithFormat:@"view id: '%lld'", viewId]]); + return; + } + + NSObject* factory = _platformViewFactories[viewType]; + if (!factory) { + result([FlutterError + errorWithCode:@"unregistered_view_type" + message:[NSString stringWithFormat:@"A UIKitView widget is trying to create a " + @"PlatformView with an unregistered type: < %@ >", + viewType] + details:@"If you are the author of the PlatformView, make sure `registerViewFactory` " + @"is invoked.\n" + @"See: " + @"https://docs.flutter.dev/development/platform-integration/" + @"platform-views#on-the-platform-side-1 for more details.\n" + @"If you are not the author of the PlatformView, make sure to call " + @"`GeneratedPluginRegistrant.register`."]); + return; + } + + NSView* platform_view = [factory createWithViewIdentifier:viewId arguments:args]; + // Flutter compositing requires CALayer-backed platform views. + // Force the platform view to be backed by a CALayer. + [platform_view setWantsLayer:YES]; + _platformViews[viewId] = platform_view; + result(nil); +} + +- (void)onDisposeWithViewID:(int64_t)viewId result:(nonnull FlutterResult)result { + if (_platformViews.count(viewId) == 0) { + result([FlutterError errorWithCode:@"unknown_view" + message:@"trying to dispose an unknown" + details:[NSString stringWithFormat:@"view id: '%lld'", viewId]]); + return; + } + + // The following disposePlatformViews call will dispose the views. + _platformViewsToDispose.insert(viewId); + result(nil); +} + +- (void)registerViewFactory:(nonnull NSObject*)factory + withId:(nonnull NSString*)factoryId { + _platformViewFactories[factoryId] = factory; +} + +- (nullable NSView*)platformViewWithID:(int64_t)viewId { + if (_platformViews.count(viewId)) { + return _platformViews[viewId]; + } else { + return nil; + } +} + +- (void)handleMethodCall:(nonnull FlutterMethodCall*)call result:(nonnull FlutterResult)result { + if ([[call method] isEqualToString:@"create"]) { + NSMutableDictionary* args = [call arguments]; + if ([args objectForKey:@"id"]) { + int64_t viewId = [args[@"id"] longLongValue]; + NSString* viewType = [NSString stringWithUTF8String:([args[@"viewType"] UTF8String])]; + + id creationArgs = nil; + NSObject* factory = _platformViewFactories[viewType]; + if ([factory respondsToSelector:@selector(createArgsCodec)]) { + NSObject* codec = [factory createArgsCodec]; + if (codec != nil && args[@"params"] != nil) { + FlutterStandardTypedData* creationArgsData = args[@"params"]; + creationArgs = [codec decode:creationArgsData.data]; + } + } + [self onCreateWithViewIdentifier:viewId + viewType:viewType + arguments:creationArgs + result:result]; + } else { + result([FlutterError errorWithCode:@"unknown_view" + message:@"'id' argument must be passed to create a platform view." + details:[NSString stringWithFormat:@"'id' not specified."]]); + } + } else if ([[call method] isEqualToString:@"dispose"]) { + NSNumber* arg = [call arguments]; + int64_t viewId = [arg longLongValue]; + [self onDisposeWithViewID:viewId result:result]; + } else if ([[call method] isEqualToString:@"acceptGesture"]) { + [self handleAcceptGesture:call result:result]; + } else if ([[call method] isEqualToString:@"rejectGesture"]) { + [self handleRejectGesture:call result:result]; + } else { + result(FlutterMethodNotImplemented); + } +} + +- (void)handleAcceptGesture:(FlutterMethodCall*)call result:(FlutterResult)result { + NSDictionary* args = [call arguments]; + NSAssert(args && args[@"id"], @"id argument is required"); + int64_t viewId = [args[@"id"] longLongValue]; + if (_platformViews.count(viewId) == 0) { + result([FlutterError errorWithCode:@"unknown_view" + message:@"trying to set gesture state for an unknown view" + details:[NSString stringWithFormat:@"view id: '%lld'", viewId]]); + return; + } + + // TODO(cbracken): Implement. https://github.com/flutter/flutter/issues/124492 + result(nil); +} + +- (void)handleRejectGesture:(FlutterMethodCall*)call result:(FlutterResult)result { + NSDictionary* args = [call arguments]; + NSAssert(args && args[@"id"], @"id argument is required"); + int64_t viewId = [args[@"id"] longLongValue]; + if (_platformViews.count(viewId) == 0) { + result([FlutterError errorWithCode:@"unknown_view" + message:@"trying to set gesture state for an unknown view" + details:[NSString stringWithFormat:@"view id: '%lld'", viewId]]); + return; + } + + // TODO(cbracken): Implement. https://github.com/flutter/flutter/issues/124492 + result(nil); +} + +- (void)disposePlatformViews { + if (_platformViewsToDispose.empty()) { + return; + } + + FML_DCHECK([[NSThread currentThread] isMainThread]) + << "Must be on the main thread to handle disposing platform views"; + for (int64_t viewId : _platformViewsToDispose) { + NSView* view = _platformViews[viewId]; + [view removeFromSuperview]; + _platformViews.erase(viewId); + } + _platformViewsToDispose.clear(); +} + +- (void)reset { + for (const auto& pair : _platformViews) { + _platformViewsToDispose.insert(pair.first); + } + [self disposePlatformViews]; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewControllerTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewControllerTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..066eeff4dc938d414bd5993a44f3d1eb45454a74 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewControllerTest.mm @@ -0,0 +1,334 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewController.h" + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/TestFlutterPlatformView.h" + +#include "flutter/testing/testing.h" + +namespace flutter::testing { + +TEST(FlutterPlatformViewController, TestCreatePlatformViewNoMatchingViewType) { + // Use id so we can access handleMethodCall method. + id platformViewController = [[FlutterPlatformViewController alloc] init]; + + FlutterMethodCall* methodCall = + [FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"FlutterPlatformViewMock" + }]; + + __block bool errored = false; + FlutterResult result = ^(id result) { + if ([result isKindOfClass:[FlutterError class]]) { + errored = true; + } + }; + + [platformViewController handleMethodCall:methodCall result:result]; + + // We expect the call to error since no factories are registered. + EXPECT_TRUE(errored); +} + +TEST(FlutterPlatformViewController, TestRegisterPlatformViewFactoryAndCreate) { + // Use id so we can access handleMethodCall method. + id platformViewController = [[FlutterPlatformViewController alloc] init]; + + TestFlutterPlatformViewFactory* factory = [TestFlutterPlatformViewFactory alloc]; + + [platformViewController registerViewFactory:factory withId:@"MockPlatformView"]; + + NSDictionary* creationArgs = @{ + @"album" : @"スコットとリバース", + @"releaseYear" : @2013, + @"artists" : @[ @"Scott Murphy", @"Rivers Cuomo" ], + @"playlist" : @[ @"おかしいやつ", @"ほどけていたんだ" ], + }; + NSObject* codec = [factory createArgsCodec]; + FlutterStandardTypedData* creationArgsData = + [FlutterStandardTypedData typedDataWithBytes:[codec encode:creationArgs]]; + + FlutterMethodCall* methodCall = + [FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockPlatformView", + @"params" : creationArgsData, + }]; + + __block bool success = false; + FlutterResult result = ^(id result) { + // If a platform view is successfully created, the result is nil. + if (result == nil) { + success = true; + } + }; + [platformViewController handleMethodCall:methodCall result:result]; + EXPECT_TRUE(success); + + // Verify PlatformView parameters are decoded correctly. + TestFlutterPlatformView* view = + (TestFlutterPlatformView*)[platformViewController platformViewWithID:2]; + ASSERT_TRUE(view != nil); + ASSERT_TRUE(view.args != nil); + + // Verify string type. + NSString* album = [view.args objectForKey:@"album"]; + EXPECT_TRUE([album isEqualToString:@"スコットとリバース"]); + + // Verify int type. + NSNumber* releaseYear = [view.args objectForKey:@"releaseYear"]; + EXPECT_EQ(releaseYear.intValue, 2013); + + // Verify list/array types. + NSArray* artists = [view.args objectForKey:@"artists"]; + ASSERT_TRUE(artists != nil); + ASSERT_EQ(artists.count, 2ul); + EXPECT_TRUE([artists[0] isEqualToString:@"Scott Murphy"]); + EXPECT_TRUE([artists[1] isEqualToString:@"Rivers Cuomo"]); + + NSArray* playlist = [view.args objectForKey:@"playlist"]; + ASSERT_EQ(playlist.count, 2ul); + EXPECT_TRUE([playlist[0] isEqualToString:@"おかしいやつ"]); + EXPECT_TRUE([playlist[1] isEqualToString:@"ほどけていたんだ"]); +} + +TEST(FlutterPlatformViewController, TestCreateAndDispose) { + // Use id so we can access handleMethodCall method. + id platformViewController = [[FlutterPlatformViewController alloc] init]; + + TestFlutterPlatformViewFactory* factory = [TestFlutterPlatformViewFactory alloc]; + + [platformViewController registerViewFactory:factory withId:@"MockPlatformView"]; + + FlutterMethodCall* methodCallOnCreate = + [FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @2, + @"viewType" : @"MockPlatformView" + }]; + + __block bool created = false; + FlutterResult resultOnCreate = ^(id result) { + // If a platform view is successfully created, the result is nil. + if (result == nil) { + created = true; + } + }; + + [platformViewController handleMethodCall:methodCallOnCreate result:resultOnCreate]; + + FlutterMethodCall* methodCallOnDispose = + [FlutterMethodCall methodCallWithMethodName:@"dispose" + arguments:[NSNumber numberWithLongLong:2]]; + + __block bool disposed = false; + FlutterResult resultOnDispose = ^(id result) { + // If a platform view is successfully created, the result is nil. + if (result == nil) { + disposed = true; + } + }; + + [platformViewController handleMethodCall:methodCallOnDispose result:resultOnDispose]; + + EXPECT_TRUE(created); + EXPECT_TRUE(disposed); +} + +TEST(FlutterPlatformViewController, TestReset) { + // Use id so we can access handleMethodCall method. + id platformViewController = [[FlutterPlatformViewController alloc] init]; + TestFlutterPlatformViewFactory* factory = [TestFlutterPlatformViewFactory alloc]; + + [platformViewController registerViewFactory:factory withId:@"MockPlatformView"]; + + __block bool created = false; + FlutterResult resultOnCreate = ^(id result) { + // If a platform view is successfully created, the result is nil. + if (result == nil) { + created = true; + } else { + created = false; + } + }; + + // Create 2 views. + FlutterMethodCall* methodCallOnCreate0 = + [FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @0, + @"viewType" : @"MockPlatformView" + }]; + + [platformViewController handleMethodCall:methodCallOnCreate0 result:resultOnCreate]; + EXPECT_TRUE(created); + + FlutterMethodCall* methodCallOnCreate1 = + [FlutterMethodCall methodCallWithMethodName:@"create" + arguments:@{ + @"id" : @1, + @"viewType" : @"MockPlatformView" + }]; + [platformViewController handleMethodCall:methodCallOnCreate1 result:resultOnCreate]; + EXPECT_TRUE(created); + + TestFlutterPlatformView* view = nil; + + // Before the reset, the views exist. + view = (TestFlutterPlatformView*)[platformViewController platformViewWithID:0]; + EXPECT_TRUE(view != nil); + view = (TestFlutterPlatformView*)[platformViewController platformViewWithID:1]; + EXPECT_TRUE(view != nil); + + // After a reset, the views should no longer exist. + [platformViewController reset]; + + view = (TestFlutterPlatformView*)[platformViewController platformViewWithID:0]; + EXPECT_TRUE(view == nil); + view = (TestFlutterPlatformView*)[platformViewController platformViewWithID:1]; + EXPECT_TRUE(view == nil); +} + +TEST(FlutterPlatformViewController, TestDisposeOnMissingViewId) { + // Use id so we can access handleMethodCall method. + id platformViewController = [[FlutterPlatformViewController alloc] init]; + + FlutterMethodCall* methodCall = + [FlutterMethodCall methodCallWithMethodName:@"dispose" + arguments:[NSNumber numberWithLongLong:20]]; + + __block bool errored = false; + FlutterResult result = ^(id result) { + if ([result isKindOfClass:[FlutterError class]]) { + errored = true; + } + }; + + [platformViewController handleMethodCall:methodCall result:result]; + + EXPECT_TRUE(errored); +} + +TEST(FlutterPlatformViewController, TestAcceptGesture) { + FlutterPlatformViewController* platformViewController = + [[FlutterPlatformViewController alloc] init]; + [platformViewController registerViewFactory:[TestFlutterPlatformViewFactory alloc] + withId:@"MockPlatformView"]; + + // Create the PlatformView. + const NSNumber* viewId = [NSNumber numberWithLongLong:2]; + FlutterMethodCall* methodCallOnCreate = [FlutterMethodCall + methodCallWithMethodName:@"create" + arguments:@{@"id" : viewId, @"viewType" : @"MockPlatformView"}]; + __block bool created = false; + FlutterResult resultOnCreate = ^(id result) { + // If a platform view is successfully created, the result is nil. + if (result == nil) { + created = true; + } + }; + [platformViewController handleMethodCall:methodCallOnCreate result:resultOnCreate]; + + // Call acceptGesture. + FlutterMethodCall* methodCallAcceptGesture = + [FlutterMethodCall methodCallWithMethodName:@"acceptGesture" arguments:@{@"id" : viewId}]; + __block bool acceptGestureCalled = false; + FlutterResult resultAcceptGesture = ^(id result) { + // If a acceptGesture is successful, the result is nil. + if (result == nil) { + acceptGestureCalled = true; + } + }; + [platformViewController handleMethodCall:methodCallAcceptGesture result:resultAcceptGesture]; + + EXPECT_TRUE(created); + EXPECT_TRUE(acceptGestureCalled); +} + +TEST(FlutterPlatformViewController, TestAcceptGestureOnMissingViewId) { + FlutterPlatformViewController* platformViewController = + [[FlutterPlatformViewController alloc] init]; + [platformViewController registerViewFactory:[TestFlutterPlatformViewFactory alloc] + withId:@"MockPlatformView"]; + + // Call rejectGesture. + FlutterMethodCall* methodCallAcceptGesture = + [FlutterMethodCall methodCallWithMethodName:@"acceptGesture" arguments:@{ + @"id" : @20 + }]; + __block bool errored = false; + FlutterResult result = ^(id result) { + if ([result isKindOfClass:[FlutterError class]]) { + errored = true; + } + }; + [platformViewController handleMethodCall:methodCallAcceptGesture result:result]; + + EXPECT_TRUE(errored); +} + +TEST(FlutterPlatformViewController, TestRejectGesture) { + FlutterPlatformViewController* platformViewController = + [[FlutterPlatformViewController alloc] init]; + [platformViewController registerViewFactory:[TestFlutterPlatformViewFactory alloc] + withId:@"MockPlatformView"]; + + // Create the PlatformView. + const NSNumber* viewId = [NSNumber numberWithLongLong:2]; + FlutterMethodCall* methodCallOnCreate = [FlutterMethodCall + methodCallWithMethodName:@"create" + arguments:@{@"id" : viewId, @"viewType" : @"MockPlatformView"}]; + __block bool created = false; + FlutterResult resultOnCreate = ^(id result) { + // If a platform view is successfully created, the result is nil. + if (result == nil) { + created = true; + } + }; + [platformViewController handleMethodCall:methodCallOnCreate result:resultOnCreate]; + + // Call rejectGesture. + FlutterMethodCall* methodCallRejectGesture = + [FlutterMethodCall methodCallWithMethodName:@"rejectGesture" arguments:@{@"id" : viewId}]; + __block bool rejectGestureCalled = false; + FlutterResult resultRejectGesture = ^(id result) { + // If a rejectGesture is successful, the result is nil. + if (result == nil) { + rejectGestureCalled = true; + } + }; + [platformViewController handleMethodCall:methodCallRejectGesture result:resultRejectGesture]; + + EXPECT_TRUE(created); + EXPECT_TRUE(rejectGestureCalled); +} + +TEST(FlutterPlatformViewController, TestRejectGestureOnMissingViewId) { + FlutterPlatformViewController* platformViewController = + [[FlutterPlatformViewController alloc] init]; + [platformViewController registerViewFactory:[TestFlutterPlatformViewFactory alloc] + withId:@"MockPlatformView"]; + + // Call rejectGesture. + FlutterMethodCall* methodCallRejectGesture = + [FlutterMethodCall methodCallWithMethodName:@"rejectGesture" arguments:@{ + @"id" : @20 + }]; + __block bool errored = false; + FlutterResult result = ^(id result) { + if ([result isKindOfClass:[FlutterError class]]) { + errored = true; + } + }; + [platformViewController handleMethodCall:methodCallRejectGesture result:result]; + + EXPECT_TRUE(errored); +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderer.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderer.h new file mode 100644 index 0000000000000000000000000000000000000000..b2f82e3d927a49678a14a0cda6d23487a0ac71bb --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderer.h @@ -0,0 +1,49 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERRENDERER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERRENDERER_H_ + +#import + +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextureRegistrar.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterView.h" +#import "flutter/shell/platform/embedder/embedder.h" + +/** + * Rendering backend agnostic FlutterRendererConfig provider to be used by the embedder API. + */ +@interface FlutterRenderer + : FlutterTextureRegistrar + +/** + * Interface to the system GPU. Used to issue all the rendering commands. + */ +@property(nonatomic, readonly, nonnull) id device; + +/** + * Used to get the command buffers for the MTLDevice to render to. + */ +@property(nonatomic, readonly, nonnull) id commandQueue; + +/** + * Intializes the renderer with the given FlutterEngine. + */ +- (nullable instancetype)initWithFlutterEngine:(nonnull FlutterEngine*)flutterEngine; + +/** + * Creates a FlutterRendererConfig that renders using the appropriate backend. + */ +- (FlutterRendererConfig)createRendererConfig; + +/** + * Populates the texture registry with the provided metalTexture. + */ +- (BOOL)populateTextureWithIdentifier:(int64_t)textureID + metalTexture:(nonnull FlutterMetalExternalTexture*)metalTexture; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERRENDERER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderer.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderer.mm new file mode 100644 index 0000000000000000000000000000000000000000..e517134384edf630f2b5d6e97b6fb634c70611e3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderer.mm @@ -0,0 +1,112 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderer.h" + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterExternalTexture.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewEngineProvider.h" +#include "flutter/shell/platform/embedder/embedder.h" + +#pragma mark - Static callbacks that require the engine. + +static FlutterMetalTexture OnGetNextDrawable(void* user_data, const FlutterFrameInfo* frameInfo) { + NSCAssert(NO, @"The renderer config should not be used to get the next drawable."); + return FlutterMetalTexture{}; +} + +static bool OnPresentDrawable(void* user_data, const FlutterMetalTexture* texture) { + NSCAssert(NO, @"The renderer config should not be used to present drawable."); + return false; +} + +static bool OnAcquireExternalTexture(void* user_data, + int64_t textureIdentifier, + size_t width, + size_t height, + FlutterMetalExternalTexture* metalTexture) { + FlutterEngine* engine = (__bridge FlutterEngine*)user_data; + return [engine.renderer populateTextureWithIdentifier:textureIdentifier + metalTexture:metalTexture]; +} + +#pragma mark - FlutterRenderer implementation + +@implementation FlutterRenderer { + FlutterDarwinContextMetalSkia* _darwinMetalContext; +} + +namespace { + +// Attempts to find the integrated GPU backed metal device. +// +// See also: https://developer.apple.com/documentation/metal/multi-gpu-systems?language=objc +id SelectMetalDevice() { + NSArray>* devices = MTLCopyAllDevices(); + for (id device in devices) { + if (@available(macOS 10.15, *)) { + if (device.hasUnifiedMemory) { + return device; + } + } + } + return MTLCreateSystemDefaultDevice(); +} +} // namespace + +- (instancetype)initWithFlutterEngine:(nonnull FlutterEngine*)flutterEngine { + self = [super initWithDelegate:self engine:flutterEngine]; + if (self) { + _device = SelectMetalDevice(); + if (!_device) { + NSLog(@"Could not acquire Metal device."); + return nil; + } + + _commandQueue = [_device newCommandQueue]; + if (!_commandQueue) { + NSLog(@"Could not create Metal command queue."); + return nil; + } + + _darwinMetalContext = [[FlutterDarwinContextMetalSkia alloc] initWithMTLDevice:_device + commandQueue:_commandQueue]; + } + return self; +} + +- (FlutterRendererConfig)createRendererConfig { + FlutterRendererConfig config = { + .type = FlutterRendererType::kMetal, + .metal = { + .struct_size = sizeof(FlutterMetalRendererConfig), + .device = (__bridge FlutterMetalDeviceHandle)_device, + .present_command_queue = (__bridge FlutterMetalCommandQueueHandle)_commandQueue, + .get_next_drawable_callback = + reinterpret_cast(OnGetNextDrawable), + .present_drawable_callback = + reinterpret_cast(OnPresentDrawable), + .external_texture_frame_callback = + reinterpret_cast(OnAcquireExternalTexture), + }}; + return config; +} + +#pragma mark - Embedder callback implementations. + +- (BOOL)populateTextureWithIdentifier:(int64_t)textureID + metalTexture:(FlutterMetalExternalTexture*)textureOut { + FlutterExternalTexture* texture = [self getTextureWithID:textureID]; + return [texture populateTexture:textureOut]; +} + +#pragma mark - FlutterTextureRegistrar methods. + +- (FlutterExternalTexture*)onRegisterTexture:(id)texture { + return [[FlutterExternalTexture alloc] initWithFlutterTexture:texture + darwinMetalContext:_darwinMetalContext]; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterResizeSynchronizer.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterResizeSynchronizer.h new file mode 100644 index 0000000000000000000000000000000000000000..3b15aca2fdec45abcbf3991e4d690d6aa7adf318 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterResizeSynchronizer.h @@ -0,0 +1,43 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERRESIZESYNCHRONIZER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERRESIZESYNCHRONIZER_H_ + +#import + +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterRunLoop.h" + +/** + * Class responsible for coordinating window resize with content update. + */ +@interface FlutterResizeSynchronizer : NSObject + +/** + * Begins a resize operation for the given size. Block the thread until + * performCommitForSize: with the same size is called. + * While the thread is blocked Flutter messages are being pumped. + * See [FlutterRunLoop pollFlutterMessagesOnce]. + */ +- (void)beginResizeForSize:(CGSize)size notify:(nonnull dispatch_block_t)notify; + +/** + * Called from raster thread. Schedules the given block on platform thread + * at given delay and unblocks the platform thread if waiting for the surface + * during resize. + */ +- (void)performCommitForSize:(CGSize)size + notify:(nonnull dispatch_block_t)notify + delay:(NSTimeInterval)delay; + +/** + * Called when the view is shut down. Unblocks platform thread if blocked + * during resize. + */ +- (void)shutDown; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERRESIZESYNCHRONIZER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterResizeSynchronizer.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterResizeSynchronizer.mm new file mode 100644 index 0000000000000000000000000000000000000000..1effdab11a853f15ff4bdb1177e26b32ef5d3406 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterResizeSynchronizer.mm @@ -0,0 +1,61 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterResizeSynchronizer.h" +#import "flutter/fml/logging.h" + +#include + +@implementation FlutterResizeSynchronizer { + std::atomic_bool _inResize; + BOOL _shuttingDown; + BOOL _didReceiveFrame; + CGSize _contentSize; +} + +- (void)beginResizeForSize:(CGSize)size notify:(nonnull dispatch_block_t)notify { + if (!_didReceiveFrame || _shuttingDown) { + notify(); + return; + } + + _inResize = true; + _contentSize = CGSizeMake(-1, -1); + notify(); + CFAbsoluteTime start = CFAbsoluteTimeGetCurrent(); + while (true) { + if (CGSizeEqualToSize(_contentSize, size) || _shuttingDown) { + break; + } + if (CFAbsoluteTimeGetCurrent() - start > 1.0) { + FML_LOG(ERROR) << "Resize timed out."; + break; + } + [FlutterRunLoop.mainRunLoop pollFlutterMessagesOnce]; + } + _inResize = false; +} + +- (void)performCommitForSize:(CGSize)size + notify:(nonnull dispatch_block_t)notify + delay:(NSTimeInterval)delay { + if (_inResize) { + delay = 0; + } + [FlutterRunLoop.mainRunLoop + performBlock:^{ + _didReceiveFrame = YES; + _contentSize = size; + notify(); + } + afterDelay:delay]; +} + +- (void)shutDown { + [FlutterRunLoop.mainRunLoop performBlock:^{ + _shuttingDown = YES; + }]; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterResizeSynchronizerTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterResizeSynchronizerTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..9d50046ab57c849dd8c1831beacaa6914548703d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterResizeSynchronizerTest.mm @@ -0,0 +1,121 @@ +// 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/fml/synchronization/waitable_event.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterResizeSynchronizer.h" +#import "flutter/testing/testing.h" + +TEST(FlutterThreadSynchronizerTest, NotBlocked) { + [FlutterRunLoop ensureMainLoopInitialized]; + + FlutterResizeSynchronizer* synchronizer = [[FlutterResizeSynchronizer alloc] init]; + __block BOOL performed = NO; + + [NSThread detachNewThreadWithBlock:^{ + [synchronizer performCommitForSize:CGSizeMake(100, 100) + notify:^{ + performed = YES; + } + delay:0]; + }]; + + CFTimeInterval start = CFAbsoluteTimeGetCurrent(); + + while (!performed && CFAbsoluteTimeGetCurrent() - start < 1.0) { + [FlutterRunLoop.mainRunLoop pollFlutterMessagesOnce]; + } + EXPECT_EQ(performed, YES); +} + +TEST(FlutterThreadSynchronizerTest, WaitForResize) { + [FlutterRunLoop ensureMainLoopInitialized]; + + FlutterResizeSynchronizer* synchronizer = [[FlutterResizeSynchronizer alloc] init]; + + __block BOOL commit1 = NO; + __block BOOL commit2 = NO; + + // Capturing c++ objects in blocks requires copy constructor, that also applies + // to __block variables where the copy is made on heap. + fml::AutoResetWaitableEvent latch_; + fml::AutoResetWaitableEvent& latch = latch_; + + // Resize synchronizer must have at received one frame in order to block. + __block BOOL didReceiveFrame = NO; + [synchronizer performCommitForSize:CGSizeMake(10, 10) + notify:^{ + didReceiveFrame = YES; + } + delay:0]; + + CFTimeInterval start = CFAbsoluteTimeGetCurrent(); + while (!didReceiveFrame && CFAbsoluteTimeGetCurrent() - start < 1.0) { + [FlutterRunLoop.mainRunLoop pollFlutterMessagesOnce]; + } + + // Now resize should block until it has received expected size. + + [NSThread detachNewThreadWithBlock:^{ + latch.Wait(); + + [synchronizer performCommitForSize:CGSizeMake(50, 100) + notify:^{ + commit1 = YES; + } + delay:0]; + + [synchronizer performCommitForSize:CGSizeMake(100, 100) + notify:^{ + commit2 = YES; + } + delay:0]; + }]; + + [synchronizer beginResizeForSize:CGSizeMake(100, 100) + notify:^{ + latch.Signal(); + }]; + + EXPECT_EQ(commit1, YES); + EXPECT_EQ(commit2, YES); +} + +TEST(FlutterThreadSynchronizerTest, UnblocksOnShutDown) { + [FlutterRunLoop ensureMainLoopInitialized]; + + FlutterResizeSynchronizer* synchronizer = [[FlutterResizeSynchronizer alloc] init]; + + // Resize synchronizer must have at received one frame in order to block. + __block BOOL didReceiveFrame = NO; + [synchronizer performCommitForSize:CGSizeMake(10, 10) + notify:^{ + didReceiveFrame = YES; + } + delay:0]; + + CFTimeInterval start = CFAbsoluteTimeGetCurrent(); + while (!didReceiveFrame && CFAbsoluteTimeGetCurrent() - start < 1.0) { + [FlutterRunLoop.mainRunLoop pollFlutterMessagesOnce]; + } + + fml::AutoResetWaitableEvent latch_; + fml::AutoResetWaitableEvent& latch = latch_; + + [NSThread detachNewThreadWithBlock:^{ + latch.Wait(); + + [synchronizer shutDown]; + }]; + + [synchronizer beginResizeForSize:CGSizeMake(100, 100) + notify:^{ + // Unblock resize + latch.Signal(); + }]; + + // Subsequent calls should not block. + [synchronizer beginResizeForSize:CGSizeMake(100, 100) + notify:^{ + }]; +} diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterRunLoop.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterRunLoop.h new file mode 100644 index 0000000000000000000000000000000000000000..86535c7f98c7d1f32718f52363adbb5b43b38ab1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterRunLoop.h @@ -0,0 +1,46 @@ +#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERRUNLOOP_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERRUNLOOP_H_ + +#import + +/** + * Interface for scheduling tasks on the run loop. + * + * Main difference between using `FlutterRunLoop` to schedule tasks compared to + * `dispatch_async` or `[NSRunLoop performBlock:]` is that `FlutterRunLoop` + * schedules the task in both common run loop mode and a private run loop mode, + * which allows it to run in mode where it only processes Flutter messages + * (`[FlutterRunLoop pollFlutterMessagesOnce]`). + */ +@interface FlutterRunLoop : NSObject + +/** + * Ensures that the `FlutterRunLoop` for main thread is initialized. Only + * needs to be called once and must be called on the main thread. + */ ++ (void)ensureMainLoopInitialized; + +/** + * Returns the `FlutterRunLoop` for the main thread. + */ ++ (FlutterRunLoop*)mainRunLoop; + +/** + * Schedules a block to be executed on the main thread. + */ +- (void)performBlock:(void (^)(void))block; + +/** + * Schedules a block to be executed on the main thread after a delay. + */ +- (void)performBlock:(void (^)(void))block afterDelay:(NSTimeInterval)delay; + +/** + * Executes single iteration of the run loop in the mode where only Flutter + * messages are processed. + */ +- (void)pollFlutterMessagesOnce; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERRUNLOOP_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterRunLoop.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterRunLoop.mm new file mode 100644 index 0000000000000000000000000000000000000000..ddd38897ef59d79c58b74e9f21940e4c60874335 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterRunLoop.mm @@ -0,0 +1,127 @@ +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterRunLoop.h" +#include +#include "fml/logging.h" + +namespace { +struct Task { + void (^block)(void); + CFAbsoluteTime target_time; + + Task(void (^block)(void), CFAbsoluteTime target_time) : block(block), target_time(target_time) {} +}; + +const CFStringRef kFlutterRunLoopMode = CFSTR("FlutterRunLoopMode"); + +FlutterRunLoop* mainLoop; + +} // namespace + +@implementation FlutterRunLoop { + CFRunLoopRef _runLoop; + CFRunLoopSourceRef _source; + CFRunLoopTimerRef _timer; + std::vector _tasks; +} + +static void Perform(void* info) { + FlutterRunLoop* runner = (__bridge FlutterRunLoop*)info; + [runner performExpiredTasks]; +} + +static void PerformTimer(CFRunLoopTimerRef timer, void* info) { + FlutterRunLoop* runner = (__bridge FlutterRunLoop*)info; + [runner performExpiredTasks]; +} + +- (instancetype)init { + if (self = [super init]) { + _runLoop = CFRunLoopGetCurrent(); + CFRunLoopSourceContext sourceContext = { + .info = (__bridge void*)self, + .perform = Perform, + }; + _source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &sourceContext); + CFRunLoopAddSource(_runLoop, _source, kCFRunLoopCommonModes); + CFRunLoopAddSource(_runLoop, _source, kFlutterRunLoopMode); + + CFRunLoopTimerContext timerContext = { + .info = (__bridge void*)self, + }; + _timer = CFRunLoopTimerCreate(kCFAllocatorDefault, HUGE_VALF, HUGE_VALF, 0, 0, PerformTimer, + &timerContext); + CFRunLoopAddTimer(_runLoop, _timer, kCFRunLoopCommonModes); + CFRunLoopAddTimer(_runLoop, _timer, kFlutterRunLoopMode); + } + return self; +} + +- (void)dealloc { + CFRunLoopTimerInvalidate(_timer); + CFRunLoopRemoveTimer(_runLoop, _timer, kCFRunLoopCommonModes); + CFRunLoopRemoveTimer(_runLoop, _timer, kFlutterRunLoopMode); + CFRunLoopSourceInvalidate(_source); + CFRunLoopRemoveSource(_runLoop, _source, kCFRunLoopCommonModes); + CFRunLoopRemoveSource(_runLoop, _source, kFlutterRunLoopMode); +} + +- (void)rearmTimer { + CFAbsoluteTime nextFireTime = HUGE_VALF; + for (const auto& task : _tasks) { + nextFireTime = std::min(nextFireTime, task.target_time); + } + CFRunLoopTimerSetNextFireDate(_timer, nextFireTime); +} + +- (void)performExpiredTasks { + std::vector expiredTasks; + @synchronized(self) { + CFAbsoluteTime now = CFAbsoluteTimeGetCurrent(); + std::vector::iterator it = _tasks.begin(); + while (it != _tasks.end()) { + if (it->target_time <= now) { + expiredTasks.push_back(std::move(*it)); + it = _tasks.erase(it); + } else { + ++it; + } + } + [self rearmTimer]; + } + for (const auto& task : expiredTasks) { + task.block(); + } +} + +- (void)performBlock:(void (^)(void))block afterDelay:(NSTimeInterval)delay { + @synchronized(self) { + _tasks.emplace_back(block, CFAbsoluteTimeGetCurrent() + delay); + if (delay > 0) { + [self rearmTimer]; + } else { + CFRunLoopSourceSignal(_source); + CFRunLoopWakeUp(_runLoop); + } + } +} + +- (void)performBlock:(void (^)(void))block { + [self performBlock:block afterDelay:0]; +} + ++ (void)ensureMainLoopInitialized { + FML_DCHECK(NSRunLoop.currentRunLoop == NSRunLoop.mainRunLoop); + if (mainLoop == nil) { + mainLoop = [[FlutterRunLoop alloc] init]; + } +} + ++ (FlutterRunLoop*)mainRunLoop { + FML_DCHECK(mainLoop != nil); + return mainLoop; +} + +- (void)pollFlutterMessagesOnce { + CFRunLoopRunInMode(kFlutterRunLoopMode, 0.1, YES); +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterSurface.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterSurface.h new file mode 100644 index 0000000000000000000000000000000000000000..50f6a2ab324466b74c3652405cd606ae8164f175 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterSurface.h @@ -0,0 +1,44 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERSURFACE_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERSURFACE_H_ + +#import + +#import "flutter/shell/platform/embedder/embedder.h" + +/** + * Opaque surface type. + * Can be represented as FlutterMetalTexture to cross the embedder API boundary. + */ +@interface FlutterSurface : NSObject + +- (FlutterMetalTexture)asFlutterMetalTexture; + ++ (nullable FlutterSurface*)fromFlutterMetalTexture:(nonnull const FlutterMetalTexture*)texture; + +@end + +/** + * Internal FlutterSurface interface used by FlutterSurfaceManager. + * Wraps an IOSurface framebuffer and metadata related to the surface. + */ +@interface FlutterSurface (Private) + +- (nonnull instancetype)initWithSize:(CGSize)size device:(nonnull id)device; + +@property(readonly, nonatomic, nonnull) IOSurfaceRef ioSurface; +@property(readonly, nonatomic) CGSize size; +@property(readonly, nonatomic) int64_t textureId; +// Whether the surface is currently in use by the compositor. +@property(readonly, nonatomic) BOOL isInUse; + +@end + +@interface FlutterSurface (Testing) +@property(readwrite, nonatomic) BOOL isInUseOverride; +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERSURFACE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterSurface.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterSurface.mm new file mode 100644 index 0000000000000000000000000000000000000000..83c4ea2f8ebb6380c31849522140914ec6067703 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterSurface.mm @@ -0,0 +1,111 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterSurface.h" + +#import +#import + +#import "flutter/fml/platform/darwin/cf_utils.h" + +@interface FlutterSurface () { + CGSize _size; + fml::CFRef _ioSurface; + id _texture; + // Used for testing. + BOOL _isInUseOverride; +} +@end + +@implementation FlutterSurface + +- (IOSurfaceRef)ioSurface { + return _ioSurface; +} + +- (CGSize)size { + return _size; +} + +- (int64_t)textureId { + return reinterpret_cast(_texture); +} + +- (BOOL)isInUse { + return _isInUseOverride || IOSurfaceIsInUse(_ioSurface); +} + +- (BOOL)isInUseOverride { + return _isInUseOverride; +} + +- (void)setIsInUseOverride:(BOOL)isInUseOverride { + _isInUseOverride = isInUseOverride; +} + +- (instancetype)initWithSize:(CGSize)size device:(id)device { + if (self = [super init]) { + self->_size = size; + self->_ioSurface.Reset([FlutterSurface createIOSurfaceWithSize:size]); + self->_texture = [FlutterSurface createTextureForIOSurface:_ioSurface size:size device:device]; + } + return self; +} + +- (FlutterMetalTexture)asFlutterMetalTexture { + return FlutterMetalTexture{ + .struct_size = sizeof(FlutterMetalTexture), + .texture_id = self.textureId, + .texture = (__bridge void*)_texture, + // Retain for use in [FlutterSurface fromFlutterMetalTexture]. Released in + // destruction_callback. + .user_data = (__bridge_retained void*)self, + .destruction_callback = + [](void* user_data) { + // Balancing release for the retain when setting user_data above. + FlutterSurface* surface = (__bridge_transfer FlutterSurface*)user_data; + surface = nil; + }, + }; +} + ++ (FlutterSurface*)fromFlutterMetalTexture:(const FlutterMetalTexture*)texture { + return (__bridge FlutterSurface*)texture->user_data; +} + ++ (IOSurfaceRef)createIOSurfaceWithSize:(CGSize)size { + unsigned pixelFormat = kCVPixelFormatType_32BGRA; + unsigned bytesPerElement = 4; + + size_t bytesPerRow = IOSurfaceAlignProperty(kIOSurfaceBytesPerRow, size.width * bytesPerElement); + size_t totalBytes = IOSurfaceAlignProperty(kIOSurfaceAllocSize, size.height * bytesPerRow); + NSDictionary* options = @{ + (id)kIOSurfaceWidth : @(size.width), + (id)kIOSurfaceHeight : @(size.height), + (id)kIOSurfacePixelFormat : @(pixelFormat), + (id)kIOSurfaceBytesPerElement : @(bytesPerElement), + (id)kIOSurfaceBytesPerRow : @(bytesPerRow), + (id)kIOSurfaceAllocSize : @(totalBytes), + }; + + IOSurfaceRef res = IOSurfaceCreate((CFDictionaryRef)options); + IOSurfaceSetValue(res, kIOSurfaceColorSpace, kCGColorSpaceSRGB); + return res; +} + ++ (id)createTextureForIOSurface:(IOSurfaceRef)surface + size:(CGSize)size + device:(id)device { + MTLTextureDescriptor* textureDescriptor = + [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm + width:size.width + height:size.height + mipmapped:NO]; + textureDescriptor.usage = + MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget | MTLTextureUsageShaderWrite; + // plane = 0 for BGRA. + return [device newTextureWithDescriptor:textureDescriptor iosurface:surface plane:0]; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManager.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManager.h new file mode 100644 index 0000000000000000000000000000000000000000..888b41e181a1b1811c67c82060f07055a11e921a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManager.h @@ -0,0 +1,113 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERSURFACEMANAGER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERSURFACEMANAGER_H_ + +#import +#import + +#include + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterSurface.h" + +/** + * Surface with additional properties needed for presenting. + */ +@interface FlutterSurfacePresentInfo : NSObject + +@property(readwrite, strong, nonatomic, nonnull) FlutterSurface* surface; +@property(readwrite, nonatomic) CGPoint offset; +@property(readwrite, nonatomic) size_t zIndex; +@property(readwrite, nonatomic) std::vector paintRegion; + +@end + +@protocol FlutterSurfaceManagerDelegate + +/* + * Schedules the block on the platform thread. + * Provided `frameSize` is used to unblock the platform thread if it waits for + * a certain frame size during resizing. + */ +- (void)onPresent:(CGSize)frameSize + withBlock:(nonnull dispatch_block_t)block + delay:(NSTimeInterval)delay; + +@end + +/** + * FlutterSurfaceManager is responsible for providing and presenting Core Animation render + * surfaces and managing sublayers. + * + * Owned by `FlutterView`. + */ +@interface FlutterSurfaceManager : NSObject + +/** + * Initializes and returns a surface manager that renders to a child layer (referred to as the + * content layer) of the containing layer. + */ +- (nullable instancetype)initWithDevice:(nonnull id)device + commandQueue:(nonnull id)commandQueue + layer:(nonnull CALayer*)containingLayer + delegate:(nonnull id)delegate; + +/** + * Returns a back buffer surface of the given size to which Flutter can render content. + * A cached surface will be returned if available; otherwise a new one will be created. + * + * Must be called on raster thread. + */ +- (nonnull FlutterSurface*)surfaceForSize:(CGSize)size; + +/** + * Sets the provided surfaces as contents of FlutterView. Will create, update and + * remove sublayers as needed. + * + * Must be called on raster thread. This will schedule a commit on the platform thread and block the + * raster thread until the commit is done. The `notify` block will be invoked on the platform thread + * and can be used to perform additional work, such as mutating platform views. It is guaranteed be + * called in the same CATransaction. + */ +- (void)presentSurfaces:(nonnull NSArray*)surfaces + atTime:(CFTimeInterval)presentationTime + notify:(nullable dispatch_block_t)notify; + +@end + +/** + * Cache of back buffers to prevent unnecessary IOSurface allocations. + */ +@interface FlutterBackBufferCache : NSObject + +/** + * Removes surface with given size from cache (if available) and returns it. + */ +- (nullable FlutterSurface*)removeSurfaceForSize:(CGSize)size; + +/** + * Removes all cached surfaces replacing them with new ones. + */ +- (void)returnSurfaces:(nonnull NSArray*)surfaces; + +/** + * Returns number of surfaces currently in cache. Used for tests. + */ +- (NSUInteger)count; + +@end + +/** + * Interface to internal properties used for testing. + */ +@interface FlutterSurfaceManager (Private) + +@property(readonly, nonatomic, nonnull) FlutterBackBufferCache* backBufferCache; +@property(readonly, nonatomic, nonnull) NSArray* frontSurfaces; +@property(readonly, nonatomic, nonnull) NSArray* layers; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERSURFACEMANAGER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManager.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManager.mm new file mode 100644 index 0000000000000000000000000000000000000000..a021a8b625b5b6431a18b55d1fcfcb2af0a44d64 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManager.mm @@ -0,0 +1,367 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManager.h" + +#import + +#include + +#include "flutter/fml/logging.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterSurface.h" + +@implementation FlutterSurfacePresentInfo +@end + +@interface FlutterSurfaceManager () { + id _device; + id _commandQueue; + CALayer* _containingLayer; + __weak id _delegate; + + // Available (cached) back buffer surfaces. These will be cleared during + // present and replaced by current frong surfaces. + FlutterBackBufferCache* _backBufferCache; + + // Surfaces currently used to back visible layers. + NSMutableArray* _frontSurfaces; + + // Currently visible layers. + NSMutableArray* _layers; + + // Whether to highlight borders of overlay surfaces. Determined by + // FLTEnableSurfaceDebugInfo value in main bundle Info.plist. + NSNumber* _enableSurfaceDebugInfo; + CATextLayer* _infoLayer; + + CFTimeInterval _lastPresentationTime; +} + +/** + * Updates underlying CALayers with the contents of the surfaces to present. + */ +- (void)commit:(NSArray*)surfaces; + +@end + +static NSColor* GetBorderColorForLayer(int layer) { + NSArray* colors = @[ + [NSColor yellowColor], + [NSColor cyanColor], + [NSColor magentaColor], + [NSColor greenColor], + [NSColor purpleColor], + [NSColor orangeColor], + [NSColor blueColor], + ]; + return colors[layer % colors.count]; +} + +/// Creates sublayers for given layer, each one displaying a portion of the +/// of the surface determined by a rectangle in the provided paint region. +static void UpdateContentSubLayers(CALayer* layer, + IOSurfaceRef surface, + CGFloat scale, + CGSize surfaceSize, + NSColor* borderColor, + const std::vector& paintRegion) { + // Adjust sublayer count to paintRegion count. + while (layer.sublayers.count > paintRegion.size()) { + [layer.sublayers.lastObject removeFromSuperlayer]; + } + + while (layer.sublayers.count < paintRegion.size()) { + CALayer* newLayer = [CALayer layer]; + [layer addSublayer:newLayer]; + } + + for (size_t i = 0; i < paintRegion.size(); i++) { + CALayer* subLayer = [layer.sublayers objectAtIndex:i]; + const auto& rect = paintRegion[i]; + subLayer.frame = CGRectMake(rect.left / scale, rect.top / scale, + (rect.right - rect.left) / scale, (rect.bottom - rect.top) / scale); + + double width = surfaceSize.width; + double height = surfaceSize.height; + + subLayer.contentsRect = + CGRectMake(rect.left / width, rect.top / height, (rect.right - rect.left) / width, + (rect.bottom - rect.top) / height); + + if (borderColor != nil) { + // Visualize sublayer + subLayer.borderColor = borderColor.CGColor; + subLayer.borderWidth = 1.0; + } + + subLayer.contents = (__bridge id)surface; + } +} + +@implementation FlutterSurfaceManager + +- (instancetype)initWithDevice:(id)device + commandQueue:(id)commandQueue + layer:(CALayer*)containingLayer + delegate:(__weak id)delegate { + if (self = [super init]) { + _device = device; + _commandQueue = commandQueue; + _containingLayer = containingLayer; + _delegate = delegate; + + _backBufferCache = [[FlutterBackBufferCache alloc] init]; + _frontSurfaces = [NSMutableArray array]; + _layers = [NSMutableArray array]; + } + return self; +} + +- (FlutterBackBufferCache*)backBufferCache { + return _backBufferCache; +} + +- (NSArray*)frontSurfaces { + return _frontSurfaces; +} + +- (NSArray*)layers { + return _layers; +} + +- (FlutterSurface*)surfaceForSize:(CGSize)size { + FlutterSurface* surface = [_backBufferCache removeSurfaceForSize:size]; + if (surface == nil) { + surface = [[FlutterSurface alloc] initWithSize:size device:_device]; + } + return surface; +} + +- (BOOL)enableSurfaceDebugInfo { + if (_enableSurfaceDebugInfo == nil) { + _enableSurfaceDebugInfo = + [[NSBundle mainBundle] objectForInfoDictionaryKey:@"FLTEnableSurfaceDebugInfo"]; + if (_enableSurfaceDebugInfo == nil) { + _enableSurfaceDebugInfo = @NO; + } + } + return [_enableSurfaceDebugInfo boolValue]; +} + +- (void)commit:(NSArray*)surfaces { + FML_DCHECK([NSThread isMainThread]); + + // Release all unused back buffer surfaces and replace them with front surfaces. + [_backBufferCache returnSurfaces:_frontSurfaces]; + + // Front surfaces will be replaced by currently presented surfaces. + [_frontSurfaces removeAllObjects]; + for (FlutterSurfacePresentInfo* info in surfaces) { + [_frontSurfaces addObject:info.surface]; + } + + // Add or remove layers to match the count of surfaces to present. + while (_layers.count > _frontSurfaces.count) { + [_layers.lastObject removeFromSuperlayer]; + [_layers removeLastObject]; + } + while (_layers.count < _frontSurfaces.count) { + CALayer* layer = [CALayer layer]; + [_containingLayer addSublayer:layer]; + [_layers addObject:layer]; + } + + bool enableSurfaceDebugInfo = self.enableSurfaceDebugInfo; + + // Update contents of surfaces. + for (size_t i = 0; i < surfaces.count; ++i) { + FlutterSurfacePresentInfo* info = surfaces[i]; + CALayer* layer = _layers[i]; + CGFloat scale = _containingLayer.contentsScale; + if (i == 0) { + layer.frame = CGRectMake(info.offset.x / scale, info.offset.y / scale, + info.surface.size.width / scale, info.surface.size.height / scale); + layer.contents = (__bridge id)info.surface.ioSurface; + } else { + layer.frame = CGRectZero; + NSColor* borderColor = enableSurfaceDebugInfo ? GetBorderColorForLayer(i - 1) : nil; + UpdateContentSubLayers(layer, info.surface.ioSurface, scale, info.surface.size, borderColor, + info.paintRegion); + } + layer.zPosition = info.zIndex; + } + + if (enableSurfaceDebugInfo) { + if (_infoLayer == nil) { + _infoLayer = [[CATextLayer alloc] init]; + [_containingLayer addSublayer:_infoLayer]; + _infoLayer.fontSize = 15; + _infoLayer.foregroundColor = [NSColor yellowColor].CGColor; + _infoLayer.frame = CGRectMake(15, 15, 300, 100); + _infoLayer.contentsScale = _containingLayer.contentsScale; + _infoLayer.zPosition = 100000; + } + _infoLayer.string = [NSString stringWithFormat:@"Surface count: %li", _layers.count]; + } +} + +static CGSize GetRequiredFrameSize(NSArray* surfaces) { + CGSize size = CGSizeZero; + for (FlutterSurfacePresentInfo* info in surfaces) { + size = CGSizeMake(std::max(size.width, info.offset.x + info.surface.size.width), + std::max(size.height, info.offset.y + info.surface.size.height)); + } + return size; +} + +- (void)presentSurfaces:(NSArray*)surfaces + atTime:(CFTimeInterval)presentationTime + notify:(dispatch_block_t)notify { + id commandBuffer = [_commandQueue commandBuffer]; + [commandBuffer commit]; + [commandBuffer waitUntilScheduled]; + + CGSize size = GetRequiredFrameSize(surfaces); + + CFTimeInterval delay = 0; + + if (presentationTime > 0) { + // Enforce frame pacing. It seems that the target timestamp of CVDisplayLink does not + // exactly correspond to core animation deadline. Especially with 120hz, setting the frame + // contents too close after previous target timestamp will result in uneven frame pacing. + // Empirically setting the content in the second half of frame interval seems to work + // well for both 60hz and 120hz. + // + // This schedules a timer on current (raster) thread runloop. Raster thread at + // this point should be idle (the next frame vsync has not been signalled yet). + // + // Alternative could be simply blocking the raster thread, but that would show + // as a average_frame_rasterizer_time_millis regresson. + CFTimeInterval minPresentationTime = (presentationTime + _lastPresentationTime) / 2.0; + CFTimeInterval now = CACurrentMediaTime(); + delay = std::max(minPresentationTime - now, 0.0); + } + [_delegate onPresent:size + withBlock:^{ + _lastPresentationTime = presentationTime; + [CATransaction begin]; + [CATransaction setDisableActions:YES]; + [self commit:surfaces]; + if (notify != nil) { + notify(); + } + [CATransaction commit]; + } + delay:delay]; +} + +@end + +// Cached back buffers will be released after kIdleDelay if there is no activity. +static const double kIdleDelay = 1.0; +// Once surfaces reach kEvictionAge, they will be evicted from the cache. +// The age of 30 has been chosen to reduce potential surface allocation churn. +// For unused surface 30 frames means only half a second at 60fps, and there is +// idle timeout of 1 second where all surfaces are evicted. +static const int kSurfaceEvictionAge = 30; + +@interface FlutterBackBufferCache () { + NSMutableArray* _surfaces; + NSMapTable* _surfaceAge; +} + +@end + +@implementation FlutterBackBufferCache + +- (instancetype)init { + if (self = [super init]) { + self->_surfaces = [[NSMutableArray alloc] init]; + self->_surfaceAge = [NSMapTable weakToStrongObjectsMapTable]; + } + return self; +} + +- (int)ageForSurface:(FlutterSurface*)surface { + NSNumber* age = [_surfaceAge objectForKey:surface]; + return age != nil ? age.intValue : 0; +} + +- (void)setAge:(int)age forSurface:(FlutterSurface*)surface { + [_surfaceAge setObject:@(age) forKey:surface]; +} + +- (nullable FlutterSurface*)removeSurfaceForSize:(CGSize)size { + @synchronized(self) { + // Purge all cached surfaces if the size has changed. + if (_surfaces.firstObject != nil && !CGSizeEqualToSize(_surfaces.firstObject.size, size)) { + [_surfaces removeAllObjects]; + } + + FlutterSurface* res; + + // Returns youngest surface that is not in use. Returning youngest surface ensures + // that the cache doesn't keep more surfaces than it needs to, as the unused surfaces + // kept in cache will have their age kept increasing until purged (inside [returnSurfaces:]). + for (FlutterSurface* surface in _surfaces) { + if (!surface.isInUse && + (res == nil || [self ageForSurface:res] > [self ageForSurface:surface])) { + res = surface; + } + } + if (res != nil) { + [_surfaces removeObject:res]; + } + return res; + } +} + +- (void)returnSurfaces:(nonnull NSArray*)returnedSurfaces { + @synchronized(self) { + for (FlutterSurface* surface in returnedSurfaces) { + [self setAge:0 forSurface:surface]; + } + for (FlutterSurface* surface in _surfaces) { + [self setAge:[self ageForSurface:surface] + 1 forSurface:surface]; + } + + [_surfaces addObjectsFromArray:returnedSurfaces]; + + // Purge all surface with age = kSurfaceEvictionAge. Reaching this age can mean two things: + // - Surface is still in use and we can't return it. This can happen in some edge + // cases where the compositor holds on to the surface for much longer than expected. + // - Surface is not in use but it hasn't been requested from the cache for a while. + // This means there are too many surfaces in the cache. + [_surfaces filterUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(FlutterSurface* surface, + NSDictionary* bindings) { + return [self ageForSurface:surface] < kSurfaceEvictionAge; + }]]; + } + + // performSelector:withObject:afterDelay needs to be performed on RunLoop thread + [self performSelectorOnMainThread:@selector(reschedule) withObject:nil waitUntilDone:NO]; +} + +- (NSUInteger)count { + @synchronized(self) { + return _surfaces.count; + } +} + +- (void)onIdle { + @synchronized(self) { + [_surfaces removeAllObjects]; + } +} + +- (void)reschedule { + [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(onIdle) object:nil]; + [self performSelector:@selector(onIdle) withObject:nil afterDelay:kIdleDelay]; +} + +- (void)dealloc { + [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(onIdle) object:nil]; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManagerTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManagerTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..30a2248b935d8d30fd0fb7b3bf44c65673d10664 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManagerTest.mm @@ -0,0 +1,301 @@ +// 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. + +#import +#import + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterSurface.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManager.h" + +#include "flutter/testing/testing.h" +#include "gtest/gtest.h" + +@interface TestView : NSView + +@property(readwrite, nonatomic) CGSize presentedFrameSize; +- (nonnull instancetype)init; + +@end + +@implementation TestView + +- (instancetype)init { + self = [super initWithFrame:NSZeroRect]; + if (self) { + [self setWantsLayer:YES]; + self.layer.contentsScale = 2.0; + } + return self; +} + +- (void)onPresent:(CGSize)frameSize + withBlock:(nonnull dispatch_block_t)block + delay:(NSTimeInterval)delay { + self.presentedFrameSize = frameSize; + block(); +} + +@end + +namespace flutter::testing { + +static FlutterSurfaceManager* CreateSurfaceManager(TestView* testView) { + id device = MTLCreateSystemDefaultDevice(); + id commandQueue = [device newCommandQueue]; + CALayer* layer = reinterpret_cast(testView.layer); + return [[FlutterSurfaceManager alloc] initWithDevice:device + commandQueue:commandQueue + layer:layer + delegate:testView]; +} + +static FlutterSurfacePresentInfo* CreatePresentInfo( + FlutterSurface* surface, + CGPoint offset = CGPointZero, + size_t index = 0, + const std::vector& paintRegion = {}) { + FlutterSurfacePresentInfo* res = [[FlutterSurfacePresentInfo alloc] init]; + res.surface = surface; + res.offset = offset; + res.zIndex = index; + res.paintRegion = paintRegion; + return res; +} + +TEST(FlutterSurfaceManager, MetalTextureSizeMatchesSurfaceSize) { + TestView* testView = [[TestView alloc] init]; + FlutterSurfaceManager* surfaceManager = CreateSurfaceManager(testView); + + // Get back buffer, lookup should work for borrowed surfaces util present. + auto surface = [surfaceManager surfaceForSize:CGSizeMake(100, 50)]; + auto texture = surface.asFlutterMetalTexture; + id metalTexture = (__bridge id)texture.texture; + EXPECT_EQ(metalTexture.width, 100ul); + EXPECT_EQ(metalTexture.height, 50ul); + texture.destruction_callback(texture.user_data); +} + +TEST(FlutterSurfaceManager, TestSurfaceLookupFromTexture) { + TestView* testView = [[TestView alloc] init]; + FlutterSurfaceManager* surfaceManager = CreateSurfaceManager(testView); + + // Get back buffer, lookup should work for borrowed surfaces util present. + auto surface = [surfaceManager surfaceForSize:CGSizeMake(100, 50)]; + + // SurfaceManager should keep texture alive while borrowed. + auto texture = surface.asFlutterMetalTexture; + texture.destruction_callback(texture.user_data); + + FlutterMetalTexture dummyTexture{.texture_id = 1, .texture = nullptr, .user_data = nullptr}; + auto surface1 = [FlutterSurface fromFlutterMetalTexture:&dummyTexture]; + EXPECT_EQ(surface1, nil); + + auto surface2 = [FlutterSurface fromFlutterMetalTexture:&texture]; + EXPECT_EQ(surface2, surface); +} + +TEST(FlutterSurfaceManager, BackBufferCacheDoesNotLeak) { + TestView* testView = [[TestView alloc] init]; + FlutterSurfaceManager* surfaceManager = CreateSurfaceManager(testView); + EXPECT_EQ(surfaceManager.backBufferCache.count, 0ul); + + auto surface1 = [surfaceManager surfaceForSize:CGSizeMake(100, 100)]; + [surfaceManager presentSurfaces:@[ CreatePresentInfo(surface1) ] atTime:0 notify:nil]; + + EXPECT_EQ(surfaceManager.backBufferCache.count, 0ul); + + auto surface2 = [surfaceManager surfaceForSize:CGSizeMake(110, 110)]; + [surfaceManager presentSurfaces:@[ CreatePresentInfo(surface2) ] atTime:0 notify:nil]; + + EXPECT_EQ(surfaceManager.backBufferCache.count, 1ul); + + auto surface3 = [surfaceManager surfaceForSize:CGSizeMake(120, 120)]; + [surfaceManager presentSurfaces:@[ CreatePresentInfo(surface3) ] atTime:0 notify:nil]; + + // Cache should be cleaned during present and only contain the last visible + // surface(s). + EXPECT_EQ(surfaceManager.backBufferCache.count, 1ul); + auto surfaceFromCache = [surfaceManager surfaceForSize:CGSizeMake(110, 110)]; + EXPECT_EQ(surfaceFromCache, surface2); + + // Submit empty surfaces until the one in cache gets to age >= kSurfaceEvictionAge, in which case + // it should be removed. + + for (int i = 0; i < 30 /* kSurfaceEvictionAge */; ++i) { + [surfaceManager presentSurfaces:@[] atTime:0 notify:nil]; + EXPECT_EQ(surfaceManager.backBufferCache.count, 1ul); + } + + [surfaceManager presentSurfaces:@[] atTime:0 notify:nil]; + EXPECT_EQ(surfaceManager.backBufferCache.count, 0ul); +} + +TEST(FlutterSurfaceManager, SurfacesAreRecycled) { + TestView* testView = [[TestView alloc] init]; + FlutterSurfaceManager* surfaceManager = CreateSurfaceManager(testView); + + EXPECT_EQ(surfaceManager.frontSurfaces.count, 0ul); + + // Get first surface and present it. + + auto surface1 = [surfaceManager surfaceForSize:CGSizeMake(100, 100)]; + EXPECT_TRUE(CGSizeEqualToSize(surface1.size, CGSizeMake(100, 100))); + + EXPECT_EQ(surfaceManager.backBufferCache.count, 0ul); + EXPECT_EQ(surfaceManager.frontSurfaces.count, 0ul); + + [surfaceManager presentSurfaces:@[ CreatePresentInfo(surface1) ] atTime:0 notify:nil]; + + EXPECT_EQ(surfaceManager.backBufferCache.count, 0ul); + EXPECT_EQ(surfaceManager.frontSurfaces.count, 1ul); + EXPECT_EQ(testView.layer.sublayers.count, 1ul); + + // Get second surface and present it. + + auto surface2 = [surfaceManager surfaceForSize:CGSizeMake(100, 100)]; + EXPECT_TRUE(CGSizeEqualToSize(surface2.size, CGSizeMake(100, 100))); + + EXPECT_EQ(surfaceManager.backBufferCache.count, 0ul); + + [surfaceManager presentSurfaces:@[ CreatePresentInfo(surface2) ] atTime:0 notify:nil]; + + // Check that current front surface returns to cache. + EXPECT_EQ(surfaceManager.backBufferCache.count, 1ul); + EXPECT_EQ(surfaceManager.frontSurfaces.count, 1ul); + EXPECT_EQ(testView.layer.sublayers.count, 1ull); + + // Check that surface is properly reused. + auto surface3 = [surfaceManager surfaceForSize:CGSizeMake(100, 100)]; + EXPECT_EQ(surface3, surface1); +} + +TEST(FlutterSurfaceManager, BackingStoreCacheSurfaceStuckInUse) { + TestView* testView = [[TestView alloc] init]; + FlutterSurfaceManager* surfaceManager = CreateSurfaceManager(testView); + + auto surface1 = [surfaceManager surfaceForSize:CGSizeMake(100, 100)]; + + [surfaceManager presentSurfaces:@[ CreatePresentInfo(surface1) ] atTime:0 notify:nil]; + // Pretend that compositor is holding on to the surface. The surface will be kept + // in cache until the age of kSurfaceEvictionAge is reached, and then evicted. + surface1.isInUseOverride = YES; + + auto surface2 = [surfaceManager surfaceForSize:CGSizeMake(100, 100)]; + [surfaceManager presentSurfaces:@[ CreatePresentInfo(surface2) ] atTime:0 notify:nil]; + EXPECT_EQ(surfaceManager.backBufferCache.count, 1ul); + + for (int i = 0; i < 30 /* kSurfaceEvictionAge */ - 1; ++i) { + auto surface3 = [surfaceManager surfaceForSize:CGSizeMake(100, 100)]; + [surfaceManager presentSurfaces:@[ CreatePresentInfo(surface3) ] atTime:0 notify:nil]; + EXPECT_EQ(surfaceManager.backBufferCache.count, 2ul); + } + + auto surface4 = [surfaceManager surfaceForSize:CGSizeMake(100, 100)]; + [surfaceManager presentSurfaces:@[ CreatePresentInfo(surface4) ] atTime:0 notify:nil]; + // Surface in use should bet old enough at this point to be evicted. + EXPECT_EQ(surfaceManager.backBufferCache.count, 1ul); +} + +inline bool operator==(const CGRect& lhs, const CGRect& rhs) { + return CGRectEqualToRect(lhs, rhs); +} + +TEST(FlutterSurfaceManager, LayerManagement) { + TestView* testView = [[TestView alloc] init]; + FlutterSurfaceManager* surfaceManager = CreateSurfaceManager(testView); + + EXPECT_EQ(testView.layer.sublayers.count, 0ul); + + auto surface1_1 = [surfaceManager surfaceForSize:CGSizeMake(50, 30)]; + [surfaceManager presentSurfaces:@[ CreatePresentInfo(surface1_1, CGPointMake(20, 10)) ] + atTime:0 + notify:nil]; + + EXPECT_EQ(testView.layer.sublayers.count, 1ul); + EXPECT_TRUE(CGSizeEqualToSize(testView.presentedFrameSize, CGSizeMake(70, 40))); + + auto surface2_1 = [surfaceManager surfaceForSize:CGSizeMake(50, 30)]; + auto surface2_2 = [surfaceManager surfaceForSize:CGSizeMake(20, 20)]; + [surfaceManager presentSurfaces:@[ + CreatePresentInfo(surface2_1, CGPointMake(20, 10), 1), + CreatePresentInfo(surface2_2, CGPointMake(40, 50), 2, + { + FlutterRect{0, 0, 20, 20}, + FlutterRect{40, 0, 60, 20}, + }) + ] + atTime:0 + notify:nil]; + + EXPECT_EQ(testView.layer.sublayers.count, 2ul); + EXPECT_EQ(testView.layer.sublayers[0].zPosition, 1.0); + EXPECT_EQ(testView.layer.sublayers[1].zPosition, 2.0); + CALayer* firstOverlaySublayer; + { + NSArray* sublayers = testView.layer.sublayers[1].sublayers; + EXPECT_EQ(sublayers.count, 2ul); + EXPECT_TRUE(CGRectEqualToRect(sublayers[0].frame, CGRectMake(0, 0, 10, 10))); + EXPECT_TRUE(CGRectEqualToRect(sublayers[1].frame, CGRectMake(20, 0, 10, 10))); + EXPECT_TRUE(CGRectEqualToRect(sublayers[0].contentsRect, CGRectMake(0, 0, 1, 1))); + EXPECT_TRUE(CGRectEqualToRect(sublayers[1].contentsRect, CGRectMake(2, 0, 1, 1))); + EXPECT_EQ(sublayers[0].contents, sublayers[1].contents); + firstOverlaySublayer = sublayers[0]; + } + EXPECT_TRUE(CGSizeEqualToSize(testView.presentedFrameSize, CGSizeMake(70, 70))); + + // Check second overlay sublayer is removed while first is reused and updated + [surfaceManager presentSurfaces:@[ + CreatePresentInfo(surface2_1, CGPointMake(20, 10), 1), + CreatePresentInfo(surface2_2, CGPointMake(40, 50), 2, + { + FlutterRect{0, 10, 20, 20}, + }) + ] + atTime:0 + notify:nil]; + EXPECT_EQ(testView.layer.sublayers.count, 2ul); + { + NSArray* sublayers = testView.layer.sublayers[1].sublayers; + EXPECT_EQ(sublayers.count, 1ul); + EXPECT_EQ(sublayers[0], firstOverlaySublayer); + EXPECT_TRUE(CGRectEqualToRect(sublayers[0].frame, CGRectMake(0, 5, 10, 5))); + } + + // Check that second overlay sublayer is added back while first is reused and updated + [surfaceManager presentSurfaces:@[ + CreatePresentInfo(surface2_1, CGPointMake(20, 10), 1), + CreatePresentInfo(surface2_2, CGPointMake(40, 50), 2, + { + FlutterRect{0, 0, 20, 20}, + FlutterRect{40, 0, 60, 20}, + }) + ] + atTime:0 + notify:nil]; + + EXPECT_EQ(testView.layer.sublayers.count, 2ul); + { + NSArray* sublayers = testView.layer.sublayers[1].sublayers; + EXPECT_EQ(sublayers.count, 2ul); + EXPECT_EQ(sublayers[0], firstOverlaySublayer); + EXPECT_TRUE(CGRectEqualToRect(sublayers[0].frame, CGRectMake(0, 0, 10, 10))); + EXPECT_TRUE(CGRectEqualToRect(sublayers[1].frame, CGRectMake(20, 0, 10, 10))); + EXPECT_EQ(sublayers[0].contents, sublayers[1].contents); + } + + auto surface3_1 = [surfaceManager surfaceForSize:CGSizeMake(50, 30)]; + [surfaceManager presentSurfaces:@[ CreatePresentInfo(surface3_1, CGPointMake(20, 10)) ] + atTime:0 + notify:nil]; + + EXPECT_EQ(testView.layer.sublayers.count, 1ul); + EXPECT_TRUE(CGSizeEqualToSize(testView.presentedFrameSize, CGSizeMake(70, 40))); + + // Check removal of all surfaces. + [surfaceManager presentSurfaces:@[] atTime:0 notify:nil]; + EXPECT_EQ(testView.layer.sublayers.count, 0ul); + EXPECT_TRUE(CGSizeEqualToSize(testView.presentedFrameSize, CGSizeMake(0, 0))); +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.h new file mode 100644 index 0000000000000000000000000000000000000000..bcf5e7aaa0bec744554d77685d3777ec9d9ed311 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.h @@ -0,0 +1,94 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERTEXTINPUTPLUGIN_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERTEXTINPUTPLUGIN_H_ + +#import + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h" +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h" + +@class FlutterTextField; + +/** + * Delegate for FlutterTextInputPlugin. Implemented by FlutterEngine. + */ +@protocol FlutterTextInputPluginDelegate + +/** + * Returns the FlutterViewController for the given view identifier. + */ +- (FlutterViewController*)viewControllerForIdentifier:(FlutterViewIdentifier)viewIdentifier; + +@property(nonatomic, readonly) id binaryMessenger; + +@end + +/** + * A plugin to handle text input. + * + * Responsible for bridging the native macOS text input system with the Flutter framework text + * editing classes, via system channels. + * + * This is not an FlutterPlugin since it needs access to FlutterViewController internals, so needs + * to be managed differently. + * + * When accessibility is on, accessibility bridge creates a NSTextField, i.e. FlutterTextField, + * for every text field in the Flutter. This plugin acts as a field editor for those NSTextField[s]. + */ +@interface FlutterTextInputPlugin : NSTextView + +/** + * The NSTextField that currently has this plugin as its field editor. + * + * Must be nil if accessibility is off. + */ +@property(nonatomic, weak) FlutterTextField* client; + +/** + * Returns the view controller text input plugin is currently attached to, + * nil if not attached to any view controller. + */ +@property(nonatomic, readonly, weak) FlutterViewController* currentViewController; + +/** + * Initializes a text input plugin that coordinates key event handling with |viewController|. + */ +- (instancetype)initWithDelegate:(id)delegate; + +/** + * Whether this plugin is the first responder of this NSWindow. + * + * When accessibility is on, this plugin is set as the first responder to act as the field + * editor for FlutterTextFields. + * + * Returns false if accessibility is off. + */ +- (BOOL)isFirstResponder; + +/** + * Handles key down events received from the view controller, responding YES if + * the event was handled. + * + * Note, the Apple docs suggest that clients should override essentially all the + * mouse and keyboard event-handling methods of NSResponder. However, experimentation + * indicates that only key events are processed by the native layer; Flutter processes + * mouse events. Additionally, processing both keyUp and keyDown results in duplicate + * processing of the same keys. + */ +- (BOOL)handleKeyEvent:(NSEvent*)event; + +@end + +// Private methods made visible for testing +@interface FlutterTextInputPlugin (TestMethods) +- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result; +- (NSRect)firstRectForCharacterRange:(NSRange)range actualRange:(NSRangePointer)actualRange; +- (NSDictionary*)editingState; +@property(nonatomic) NSTextInputContext* textInputContext; +@property(readwrite, nonatomic) NSString* customRunLoopMode; +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERTEXTINPUTPLUGIN_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.mm new file mode 100644 index 0000000000000000000000000000000000000000..22ade65600750e8016fa72797f82862147d2c025 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.mm @@ -0,0 +1,998 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.h" + +#import +#import + +#include +#include + +#include "flutter/fml/platform/darwin/string_range_sanitization.h" +#include "flutter/shell/platform/common/text_editing_delta.h" +#include "flutter/shell/platform/common/text_input_model.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/NSView+ClipsToBounds.h" + +static NSString* const kTextInputChannel = @"flutter/textinput"; + +#pragma mark - TextInput channel method names +// See https://api.flutter.dev/flutter/services/SystemChannels/textInput-constant.html +static NSString* const kSetClientMethod = @"TextInput.setClient"; +static NSString* const kShowMethod = @"TextInput.show"; +static NSString* const kHideMethod = @"TextInput.hide"; +static NSString* const kClearClientMethod = @"TextInput.clearClient"; +static NSString* const kSetEditingStateMethod = @"TextInput.setEditingState"; +static NSString* const kSetEditableSizeAndTransform = @"TextInput.setEditableSizeAndTransform"; +static NSString* const kSetCaretRect = @"TextInput.setCaretRect"; +static NSString* const kUpdateEditStateResponseMethod = @"TextInputClient.updateEditingState"; +static NSString* const kUpdateEditStateWithDeltasResponseMethod = + @"TextInputClient.updateEditingStateWithDeltas"; +static NSString* const kPerformAction = @"TextInputClient.performAction"; +static NSString* const kPerformSelectors = @"TextInputClient.performSelectors"; +static NSString* const kMultilineInputType = @"TextInputType.multiline"; + +#pragma mark - TextInputConfiguration field names +static NSString* const kViewId = @"viewId"; +static NSString* const kSecureTextEntry = @"obscureText"; +static NSString* const kTextInputAction = @"inputAction"; +static NSString* const kEnableDeltaModel = @"enableDeltaModel"; +static NSString* const kTextInputType = @"inputType"; +static NSString* const kTextInputTypeName = @"name"; +static NSString* const kSelectionBaseKey = @"selectionBase"; +static NSString* const kSelectionExtentKey = @"selectionExtent"; +static NSString* const kSelectionAffinityKey = @"selectionAffinity"; +static NSString* const kSelectionIsDirectionalKey = @"selectionIsDirectional"; +static NSString* const kComposingBaseKey = @"composingBase"; +static NSString* const kComposingExtentKey = @"composingExtent"; +static NSString* const kTextKey = @"text"; +static NSString* const kTransformKey = @"transform"; +static NSString* const kAssociatedAutofillFields = @"fields"; + +// TextInputConfiguration.autofill and sub-field names +static NSString* const kAutofillProperties = @"autofill"; +static NSString* const kAutofillId = @"uniqueIdentifier"; +static NSString* const kAutofillEditingValue = @"editingValue"; +static NSString* const kAutofillHints = @"hints"; + +// TextAffinity types +static NSString* const kTextAffinityDownstream = @"TextAffinity.downstream"; +static NSString* const kTextAffinityUpstream = @"TextAffinity.upstream"; + +// TextInputAction types +static NSString* const kInputActionNewline = @"TextInputAction.newline"; + +#pragma mark - Enums +/** + * The affinity of the current cursor position. If the cursor is at a position + * representing a soft line break, the cursor may be drawn either at the end of + * the current line (upstream) or at the beginning of the next (downstream). + */ +typedef NS_ENUM(NSUInteger, FlutterTextAffinity) { + kFlutterTextAffinityUpstream, + kFlutterTextAffinityDownstream +}; + +#pragma mark - Static functions + +/* + * Updates a range given base and extent fields. + */ +static flutter::TextRange RangeFromBaseExtent(NSNumber* base, + NSNumber* extent, + const flutter::TextRange& range) { + if (base == nil || extent == nil) { + return range; + } + if (base.intValue == -1 && extent.intValue == -1) { + return flutter::TextRange(0, 0); + } + return flutter::TextRange([base unsignedLongValue], [extent unsignedLongValue]); +} + +// Returns the autofill hint content type, if specified; otherwise nil. +static NSString* GetAutofillHint(NSDictionary* autofill) { + NSArray* hints = autofill[kAutofillHints]; + return hints.count > 0 ? hints[0] : nil; +} + +// Returns the text content type for the specified TextInputConfiguration. +// NSTextContentType is only available for macOS 11.0 and later. +static NSTextContentType GetTextContentType(NSDictionary* configuration) + API_AVAILABLE(macos(11.0)) { + // Check autofill hints. + NSDictionary* autofill = configuration[kAutofillProperties]; + if (autofill) { + NSString* hint = GetAutofillHint(autofill); + if ([hint isEqualToString:@"username"]) { + return NSTextContentTypeUsername; + } + if ([hint isEqualToString:@"password"]) { + return NSTextContentTypePassword; + } + if ([hint isEqualToString:@"oneTimeCode"]) { + return NSTextContentTypeOneTimeCode; + } + } + // If no autofill hints, guess based on other attributes. + if ([configuration[kSecureTextEntry] boolValue]) { + return NSTextContentTypePassword; + } + return nil; +} + +// Returns YES if configuration describes a field for which autocomplete should be enabled for +// the specified TextInputConfiguration. Autocomplete is enabled by default, but will be disabled +// if the field is password-related, or if the configuration contains no autofill settings. +static BOOL EnableAutocompleteForTextInputConfiguration(NSDictionary* configuration) { + // Disable if obscureText is set. + if ([configuration[kSecureTextEntry] boolValue]) { + return NO; + } + + // Disable if autofill properties are not set. + NSDictionary* autofill = configuration[kAutofillProperties]; + if (autofill == nil) { + return NO; + } + + // Disable if autofill properties indicate a username/password. + // See: https://github.com/flutter/flutter/issues/119824 + NSString* hint = GetAutofillHint(autofill); + if ([hint isEqualToString:@"password"] || [hint isEqualToString:@"username"]) { + return NO; + } + return YES; +} + +// Returns YES if configuration describes a field for which autocomplete should be enabled. +// Autocomplete is enabled by default, but will be disabled if the field is password-related, or if +// the configuration contains no autofill settings. +// +// In the case where the current field is part of an AutofillGroup, the configuration will have +// a fields attribute with a list of TextInputConfigurations, one for each field. In the case where +// any field in the group disables autocomplete, we disable it for all. +static BOOL EnableAutocomplete(NSDictionary* configuration) { + for (NSDictionary* field in configuration[kAssociatedAutofillFields]) { + if (!EnableAutocompleteForTextInputConfiguration(field)) { + return NO; + } + } + + // Check the top-level TextInputConfiguration. + return EnableAutocompleteForTextInputConfiguration(configuration); +} + +#pragma mark - NSEvent (KeyEquivalentMarker) protocol + +@interface NSEvent (KeyEquivalentMarker) + +// Internally marks that the event was received through performKeyEquivalent:. +// When text editing is active, keyboard events that have modifier keys pressed +// are received through performKeyEquivalent: instead of keyDown:. If such event +// is passed to TextInputContext but doesn't result in a text editing action it +// needs to be forwarded by FlutterKeyboardManager to the next responder. +- (void)markAsKeyEquivalent; + +// Returns YES if the event is marked as a key equivalent. +- (BOOL)isKeyEquivalent; + +@end + +@implementation NSEvent (KeyEquivalentMarker) + +// This field doesn't need a value because only its address is used as a unique identifier. +static char markerKey; + +- (void)markAsKeyEquivalent { + objc_setAssociatedObject(self, &markerKey, @true, OBJC_ASSOCIATION_RETAIN); +} + +- (BOOL)isKeyEquivalent { + return [objc_getAssociatedObject(self, &markerKey) boolValue] == YES; +} + +@end + +#pragma mark - FlutterTextInputPlugin private interface + +/** + * Private properties of FlutterTextInputPlugin. + */ +@interface FlutterTextInputPlugin () { + /** + * A text input context, representing a connection to the Cocoa text input system. + */ + NSTextInputContext* _textInputContext; + + /** + * The channel used to communicate with Flutter. + */ + FlutterMethodChannel* _channel; + + /** + * The FlutterViewController to manage input for. + */ + __weak FlutterViewController* _currentViewController; + + /** + * Used to obtain view controller on client creation + */ + __weak id _delegate; + + /** + * Whether the text input is shown in the view. + * + * Defaults to TRUE on startup. + */ + BOOL _shown; + + /** + * The current state of the keyboard and pressed keys. + */ + uint64_t _previouslyPressedFlags; + + /** + * The affinity for the current cursor position. + */ + FlutterTextAffinity _textAffinity; + + /** + * ID of the text input client. + */ + NSNumber* _clientID; + + /** + * Keyboard type of the client. See available options: + * https://api.flutter.dev/flutter/services/TextInputType-class.html + */ + NSString* _inputType; + + /** + * An action requested by the user on the input client. See available options: + * https://api.flutter.dev/flutter/services/TextInputAction-class.html + */ + NSString* _inputAction; + + /** + * Set to true if the last event fed to the input context produced a text editing command + * or text output. It is reset to false at the beginning of every key event, and is only + * used while processing this event. + */ + BOOL _eventProducedOutput; + + /** + * Whether to enable the sending of text input updates from the engine to the + * framework as TextEditingDeltas rather than as one TextEditingValue. + * For more information on the delta model, see: + * https://master-api.flutter.dev/flutter/services/TextInputConfiguration/enableDeltaModel.html + */ + BOOL _enableDeltaModel; + + /** + * Used to gather multiple selectors performed in one run loop turn. These + * will be all sent in one platform channel call so that the framework can process + * them in single microtask. + */ + NSMutableArray* _pendingSelectors; + + /** + * The currently active text input model. + */ + std::unique_ptr _activeModel; + + /** + * Transform for current the editable. Used to determine position of accent selection menu. + */ + CATransform3D _editableTransform; + + /** + * Current position of caret in local (editable) coordinates. + */ + CGRect _caretRect; +} + +/** + * Handles a Flutter system message on the text input channel. + */ +- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result; + +/** + * Updates the text input model with state received from the framework via the + * TextInput.setEditingState message. + */ +- (void)setEditingState:(NSDictionary*)state; + +/** + * Informs the Flutter framework of changes to the text input model's state by + * sending the entire new state. + */ +- (void)updateEditState; + +/** + * Informs the Flutter framework of changes to the text input model's state by + * sending only the difference. + */ +- (void)updateEditStateWithDelta:(const flutter::TextEditingDelta)delta; + +/** + * Updates the stringValue and selectedRange that stored in the NSTextView interface + * that this plugin inherits from. + * + * If there is a FlutterTextField uses this plugin as its field editor, this method + * will update the stringValue and selectedRange through the API of the FlutterTextField. + */ +- (void)updateTextAndSelection; + +/** + * Return the string representation of the current textAffinity as it should be + * sent over the FlutterMethodChannel. + */ +- (NSString*)textAffinityString; + +/** + * Allow overriding run loop mode for test. + */ +@property(readwrite, nonatomic) NSString* customRunLoopMode; +@property(nonatomic) NSTextInputContext* textInputContext; + +@end + +#pragma mark - FlutterTextInputPlugin + +@implementation FlutterTextInputPlugin + +- (instancetype)initWithDelegate:(id)delegate { + // The view needs an empty frame otherwise it is visible on dark background. + // https://github.com/flutter/flutter/issues/118504 + self = [super initWithFrame:NSZeroRect]; + self.clipsToBounds = YES; + if (self != nil) { + _delegate = delegate; + _channel = [FlutterMethodChannel methodChannelWithName:kTextInputChannel + binaryMessenger:_delegate.binaryMessenger + codec:[FlutterJSONMethodCodec sharedInstance]]; + _shown = FALSE; + // NSTextView does not support _weak reference, so this class has to + // use __unsafe_unretained and manage the reference by itself. + // + // Since the dealloc removes the handler, the pointer should + // be valid if the handler is ever called. + __unsafe_unretained FlutterTextInputPlugin* unsafeSelf = self; + [_channel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { + [unsafeSelf handleMethodCall:call result:result]; + }]; + _textInputContext = [[NSTextInputContext alloc] initWithClient:unsafeSelf]; + _previouslyPressedFlags = 0; + + // Initialize with the zero matrix which is not + // an affine transform. + _editableTransform = CATransform3D(); + _caretRect = CGRectNull; + } + return self; +} + +- (BOOL)isFirstResponder { + if (!_currentViewController.viewLoaded) { + return false; + } + return [_currentViewController.view.window firstResponder] == self; +} + +- (void)dealloc { + [_channel setMethodCallHandler:nil]; +} + +#pragma mark - Private + +- (void)resignAndRemoveFromSuperview { + if (self.superview != nil) { + [self.window makeFirstResponder:_currentViewController.flutterView]; + [self removeFromSuperview]; + } +} + +- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { + BOOL handled = YES; + NSString* method = call.method; + if ([method isEqualToString:kSetClientMethod]) { + FML_DCHECK(_currentViewController == nil); + if (!call.arguments[0] || !call.arguments[1]) { + result([FlutterError + errorWithCode:@"error" + message:@"Missing arguments" + details:@"Missing arguments while trying to set a text input client"]); + return; + } + NSNumber* clientID = call.arguments[0]; + if (clientID != nil) { + NSDictionary* config = call.arguments[1]; + + _clientID = clientID; + _inputAction = config[kTextInputAction]; + _enableDeltaModel = [config[kEnableDeltaModel] boolValue]; + NSDictionary* inputTypeInfo = config[kTextInputType]; + _inputType = inputTypeInfo[kTextInputTypeName]; + _textAffinity = kFlutterTextAffinityUpstream; + self.automaticTextCompletionEnabled = EnableAutocomplete(config); + if (@available(macOS 11.0, *)) { + self.contentType = GetTextContentType(config); + } + + _activeModel = std::make_unique(); + NSNumber* viewId = config[kViewId]; + _currentViewController = [_delegate viewControllerForIdentifier:viewId.longLongValue]; + FML_DCHECK(_currentViewController != nil); + } + } else if ([method isEqualToString:kShowMethod]) { + FML_DCHECK(_currentViewController != nil); + // Ensure the plugin is in hierarchy. Only do this with accessibility disabled. + // When accessibility is enabled cocoa will reparent the plugin inside + // FlutterTextField in [FlutterTextField startEditing]. + if (_client == nil) { + [_currentViewController.view addSubview:self]; + } + [self.window makeFirstResponder:self]; + _shown = TRUE; + } else if ([method isEqualToString:kHideMethod]) { + [self resignAndRemoveFromSuperview]; + _shown = FALSE; + } else if ([method isEqualToString:kClearClientMethod]) { + FML_DCHECK(_currentViewController != nil); + [self resignAndRemoveFromSuperview]; + // If there's an active mark region, commit it, end composing, and clear the IME's mark text. + if (_activeModel && _activeModel->composing()) { + _activeModel->CommitComposing(); + _activeModel->EndComposing(); + } + [_textInputContext discardMarkedText]; + + _clientID = nil; + _inputAction = nil; + _enableDeltaModel = NO; + _inputType = nil; + _activeModel = nullptr; + _currentViewController = nil; + } else if ([method isEqualToString:kSetEditingStateMethod]) { + FML_DCHECK(_currentViewController != nil); + NSDictionary* state = call.arguments; + [self setEditingState:state]; + } else if ([method isEqualToString:kSetEditableSizeAndTransform]) { + FML_DCHECK(_currentViewController != nil); + NSDictionary* state = call.arguments; + [self setEditableTransform:state[kTransformKey]]; + } else if ([method isEqualToString:kSetCaretRect]) { + FML_DCHECK(_currentViewController != nil); + NSDictionary* rect = call.arguments; + [self updateCaretRect:rect]; + } else { + handled = NO; + } + result(handled ? nil : FlutterMethodNotImplemented); +} + +- (void)setEditableTransform:(NSArray*)matrix { + CATransform3D* transform = &_editableTransform; + + transform->m11 = [matrix[0] doubleValue]; + transform->m12 = [matrix[1] doubleValue]; + transform->m13 = [matrix[2] doubleValue]; + transform->m14 = [matrix[3] doubleValue]; + + transform->m21 = [matrix[4] doubleValue]; + transform->m22 = [matrix[5] doubleValue]; + transform->m23 = [matrix[6] doubleValue]; + transform->m24 = [matrix[7] doubleValue]; + + transform->m31 = [matrix[8] doubleValue]; + transform->m32 = [matrix[9] doubleValue]; + transform->m33 = [matrix[10] doubleValue]; + transform->m34 = [matrix[11] doubleValue]; + + transform->m41 = [matrix[12] doubleValue]; + transform->m42 = [matrix[13] doubleValue]; + transform->m43 = [matrix[14] doubleValue]; + transform->m44 = [matrix[15] doubleValue]; +} + +- (void)updateCaretRect:(NSDictionary*)dictionary { + NSAssert(dictionary[@"x"] != nil && dictionary[@"y"] != nil && dictionary[@"width"] != nil && + dictionary[@"height"] != nil, + @"Expected a dictionary representing a CGRect, got %@", dictionary); + _caretRect = CGRectMake([dictionary[@"x"] doubleValue], [dictionary[@"y"] doubleValue], + [dictionary[@"width"] doubleValue], [dictionary[@"height"] doubleValue]); +} + +- (void)setEditingState:(NSDictionary*)state { + NSString* selectionAffinity = state[kSelectionAffinityKey]; + if (selectionAffinity != nil) { + _textAffinity = [selectionAffinity isEqualToString:kTextAffinityUpstream] + ? kFlutterTextAffinityUpstream + : kFlutterTextAffinityDownstream; + } + + NSString* text = state[kTextKey]; + + flutter::TextRange selected_range = RangeFromBaseExtent( + state[kSelectionBaseKey], state[kSelectionExtentKey], _activeModel->selection()); + _activeModel->SetSelection(selected_range); + + flutter::TextRange composing_range = RangeFromBaseExtent( + state[kComposingBaseKey], state[kComposingExtentKey], _activeModel->composing_range()); + + const bool wasComposing = _activeModel->composing(); + _activeModel->SetText([text UTF8String], selected_range, composing_range); + if (composing_range.collapsed() && wasComposing) { + [_textInputContext discardMarkedText]; + } + [_client startEditing]; + + [self updateTextAndSelection]; +} + +- (NSDictionary*)editingState { + if (_activeModel == nullptr) { + return nil; + } + + NSString* const textAffinity = [self textAffinityString]; + + int composingBase = _activeModel->composing() ? _activeModel->composing_range().base() : -1; + int composingExtent = _activeModel->composing() ? _activeModel->composing_range().extent() : -1; + + return @{ + kSelectionBaseKey : @(_activeModel->selection().base()), + kSelectionExtentKey : @(_activeModel->selection().extent()), + kSelectionAffinityKey : textAffinity, + kSelectionIsDirectionalKey : @NO, + kComposingBaseKey : @(composingBase), + kComposingExtentKey : @(composingExtent), + kTextKey : [NSString stringWithUTF8String:_activeModel->GetText().c_str()] ?: [NSNull null], + }; +} + +- (void)updateEditState { + if (_activeModel == nullptr) { + return; + } + + NSDictionary* state = [self editingState]; + [_channel invokeMethod:kUpdateEditStateResponseMethod arguments:@[ _clientID, state ]]; + [self updateTextAndSelection]; +} + +- (void)updateEditStateWithDelta:(const flutter::TextEditingDelta)delta { + NSUInteger selectionBase = _activeModel->selection().base(); + NSUInteger selectionExtent = _activeModel->selection().extent(); + int composingBase = _activeModel->composing() ? _activeModel->composing_range().base() : -1; + int composingExtent = _activeModel->composing() ? _activeModel->composing_range().extent() : -1; + + NSString* const textAffinity = [self textAffinityString]; + + NSDictionary* deltaToFramework = @{ + @"oldText" : @(delta.old_text().c_str()), + @"deltaText" : @(delta.delta_text().c_str()), + @"deltaStart" : @(delta.delta_start()), + @"deltaEnd" : @(delta.delta_end()), + @"selectionBase" : @(selectionBase), + @"selectionExtent" : @(selectionExtent), + @"selectionAffinity" : textAffinity, + @"selectionIsDirectional" : @(false), + @"composingBase" : @(composingBase), + @"composingExtent" : @(composingExtent), + }; + + NSDictionary* deltas = @{ + @"deltas" : @[ deltaToFramework ], + }; + + [_channel invokeMethod:kUpdateEditStateWithDeltasResponseMethod arguments:@[ _clientID, deltas ]]; + [self updateTextAndSelection]; +} + +- (void)updateTextAndSelection { + NSAssert(_activeModel != nullptr, @"Flutter text model must not be null."); + NSString* text = @(_activeModel->GetText().data()); + int start = _activeModel->selection().base(); + int extend = _activeModel->selection().extent(); + NSRange selection = NSMakeRange(MIN(start, extend), ABS(start - extend)); + // There may be a native text field client if VoiceOver is on. + // In this case, this plugin has to update text and selection through + // the client in order for VoiceOver to announce the text editing + // properly. + if (_client) { + [_client updateString:text withSelection:selection]; + } else { + self.string = text; + [self setSelectedRange:selection]; + } +} + +- (NSString*)textAffinityString { + return (_textAffinity == kFlutterTextAffinityUpstream) ? kTextAffinityUpstream + : kTextAffinityDownstream; +} + +- (BOOL)handleKeyEvent:(NSEvent*)event { + if (event.type == NSEventTypeKeyUp || + (event.type == NSEventTypeFlagsChanged && event.modifierFlags < _previouslyPressedFlags)) { + return NO; + } + _previouslyPressedFlags = event.modifierFlags; + if (!_shown) { + return NO; + } + + _eventProducedOutput = NO; + BOOL res = [_textInputContext handleEvent:event]; + // NSTextInputContext#handleEvent returns YES if the context handles the event. One of the reasons + // the event is handled is because it's a key equivalent. But a key equivalent might produce a + // text command (indicated by calling doCommandBySelector) or might not (for example, Cmd+Q). In + // the latter case, this command somehow has not been executed yet and Flutter must dispatch it to + // the next responder. See https://github.com/flutter/flutter/issues/106354 . + // The event is also not redispatched if there is IME composition active, because it might be + // handled by the IME. See https://github.com/flutter/flutter/issues/134699 + + // both NSEventModifierFlagNumericPad and NSEventModifierFlagFunction are set for arrow keys. + bool is_navigation = event.modifierFlags & NSEventModifierFlagFunction && + event.modifierFlags & NSEventModifierFlagNumericPad; + bool is_navigation_in_ime = is_navigation && self.hasMarkedText; + + if (event.isKeyEquivalent && !is_navigation_in_ime && !_eventProducedOutput) { + return NO; + } + return res; +} + +#pragma mark - +#pragma mark NSResponder + +- (void)keyDown:(NSEvent*)event { + [_currentViewController keyDown:event]; +} + +- (void)keyUp:(NSEvent*)event { + [_currentViewController keyUp:event]; +} + +- (BOOL)performKeyEquivalent:(NSEvent*)event { + if ([_currentViewController isDispatchingKeyEvent:event]) { + // When NSWindow is nextResponder, keyboard manager will send to it + // unhandled events (through [NSWindow keyDown:]). If event has both + // control and cmd modifiers set (i.e. cmd+control+space - emoji picker) + // NSWindow will then send this event as performKeyEquivalent: to first + // responder, which is FlutterTextInputPlugin. If that's the case, the + // plugin must not handle the event, otherwise the emoji picker would not + // work (due to first responder returning YES from performKeyEquivalent:) + // and there would be endless loop, because FlutterViewController will + // send the event back to [keyboardManager handleEvent:]. + return NO; + } + [event markAsKeyEquivalent]; + [_currentViewController keyDown:event]; + return YES; +} + +- (void)flagsChanged:(NSEvent*)event { + [_currentViewController flagsChanged:event]; +} + +- (void)mouseDown:(NSEvent*)event { + [_currentViewController mouseDown:event]; +} + +- (void)mouseUp:(NSEvent*)event { + [_currentViewController mouseUp:event]; +} + +- (void)mouseDragged:(NSEvent*)event { + [_currentViewController mouseDragged:event]; +} + +- (void)rightMouseDown:(NSEvent*)event { + [_currentViewController rightMouseDown:event]; +} + +- (void)rightMouseUp:(NSEvent*)event { + [_currentViewController rightMouseUp:event]; +} + +- (void)rightMouseDragged:(NSEvent*)event { + [_currentViewController rightMouseDragged:event]; +} + +- (void)otherMouseDown:(NSEvent*)event { + [_currentViewController otherMouseDown:event]; +} + +- (void)otherMouseUp:(NSEvent*)event { + [_currentViewController otherMouseUp:event]; +} + +- (void)otherMouseDragged:(NSEvent*)event { + [_currentViewController otherMouseDragged:event]; +} + +- (void)mouseMoved:(NSEvent*)event { + [_currentViewController mouseMoved:event]; +} + +- (void)scrollWheel:(NSEvent*)event { + [_currentViewController scrollWheel:event]; +} + +- (NSTextInputContext*)inputContext { + return _textInputContext; +} + +#pragma mark - +#pragma mark NSTextInputClient + +- (void)insertTab:(id)sender { + // Implementing insertTab: makes AppKit send tab as command, instead of + // insertText with '\t'. +} + +- (void)insertText:(id)string replacementRange:(NSRange)range { + if (_activeModel == nullptr) { + return; + } + + _eventProducedOutput |= true; + + if (range.location != NSNotFound) { + // The selected range can actually have negative numbers, since it can start + // at the end of the range if the user selected the text going backwards. + // Cast to a signed type to determine whether or not the selection is reversed. + long signedLength = static_cast(range.length); + long location = range.location; + long textLength = _activeModel->text_range().end(); + + size_t base = std::clamp(location, 0L, textLength); + size_t extent = std::clamp(location + signedLength, 0L, textLength); + + _activeModel->SetSelection(flutter::TextRange(base, extent)); + } + + flutter::TextRange oldSelection = _activeModel->selection(); + flutter::TextRange composingBeforeChange = _activeModel->composing_range(); + flutter::TextRange replacedRange(-1, -1); + + std::string textBeforeChange = _activeModel->GetText().c_str(); + std::string utf8String = [string UTF8String]; + _activeModel->AddText(utf8String); + if (_activeModel->composing()) { + replacedRange = composingBeforeChange; + _activeModel->CommitComposing(); + _activeModel->EndComposing(); + } else { + replacedRange = range.location == NSNotFound + ? flutter::TextRange(oldSelection.base(), oldSelection.extent()) + : flutter::TextRange(range.location, range.location + range.length); + } + if (_enableDeltaModel) { + [self updateEditStateWithDelta:flutter::TextEditingDelta(textBeforeChange, replacedRange, + utf8String)]; + } else { + [self updateEditState]; + } +} + +- (void)doCommandBySelector:(SEL)selector { + _eventProducedOutput |= selector != NSSelectorFromString(@"noop:"); + if ([self respondsToSelector:selector]) { + // Note: The more obvious [self performSelector...] doesn't give ARC enough information to + // handle retain semantics properly. See https://stackoverflow.com/questions/7017281/ for more + // information. + IMP imp = [self methodForSelector:selector]; + void (*func)(id, SEL, id) = reinterpret_cast(imp); + func(self, selector, nil); + } + if (_clientID == nil) { + // The macOS may still call selector even if it is no longer a first responder. + return; + } + + if (selector == @selector(insertNewline:)) { + // Already handled through text insertion (multiline) or action. + return; + } + + // Group multiple selectors received within a single run loop turn so that + // the framework can process them in single microtask. + NSString* name = NSStringFromSelector(selector); + if (_pendingSelectors == nil) { + _pendingSelectors = [NSMutableArray array]; + } + [_pendingSelectors addObject:name]; + + if (_pendingSelectors.count == 1) { + __weak NSMutableArray* selectors = _pendingSelectors; + __weak FlutterMethodChannel* channel = _channel; + __weak NSNumber* clientID = _clientID; + + CFStringRef runLoopMode = self.customRunLoopMode != nil + ? (__bridge CFStringRef)self.customRunLoopMode + : kCFRunLoopCommonModes; + + CFRunLoopPerformBlock(CFRunLoopGetMain(), runLoopMode, ^{ + if (selectors.count > 0) { + [channel invokeMethod:kPerformSelectors arguments:@[ clientID, selectors ]]; + [selectors removeAllObjects]; + } + }); + } +} + +- (void)insertNewline:(id)sender { + if (_activeModel == nullptr) { + return; + } + if (_activeModel->composing()) { + _activeModel->CommitComposing(); + _activeModel->EndComposing(); + } + if ([_inputType isEqualToString:kMultilineInputType] && + [_inputAction isEqualToString:kInputActionNewline]) { + [self insertText:@"\n" replacementRange:self.selectedRange]; + } + [_channel invokeMethod:kPerformAction arguments:@[ _clientID, _inputAction ]]; +} + +- (void)setMarkedText:(id)string + selectedRange:(NSRange)selectedRange + replacementRange:(NSRange)replacementRange { + if (_activeModel == nullptr) { + return; + } + std::string textBeforeChange = _activeModel->GetText().c_str(); + if (!_activeModel->composing()) { + _activeModel->BeginComposing(); + } + + if (replacementRange.location != NSNotFound) { + // According to the NSTextInputClient documentation replacementRange is + // computed from the beginning of the marked text. That doesn't seem to be + // the case, because in situations where the replacementRange is actually + // specified (i.e. when switching between characters equivalent after long + // key press) the replacementRange is provided while there is no composition. + _activeModel->SetComposingRange( + flutter::TextRange(replacementRange.location, + replacementRange.location + replacementRange.length), + 0); + } + + flutter::TextRange composingBeforeChange = _activeModel->composing_range(); + flutter::TextRange selectionBeforeChange = _activeModel->selection(); + + // Input string may be NSString or NSAttributedString. + BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]]; + const NSString* rawString = isAttributedString ? [string string] : string; + _activeModel->UpdateComposingText( + (const char16_t*)[rawString cStringUsingEncoding:NSUTF16StringEncoding], + flutter::TextRange(selectedRange.location, selectedRange.location + selectedRange.length)); + + if (_enableDeltaModel) { + std::string marked_text = [rawString UTF8String]; + [self updateEditStateWithDelta:flutter::TextEditingDelta(textBeforeChange, + selectionBeforeChange.collapsed() + ? composingBeforeChange + : selectionBeforeChange, + marked_text)]; + } else { + [self updateEditState]; + } +} + +- (void)unmarkText { + if (_activeModel == nullptr) { + return; + } + _activeModel->CommitComposing(); + _activeModel->EndComposing(); + if (_enableDeltaModel) { + [self updateEditStateWithDelta:flutter::TextEditingDelta(_activeModel->GetText().c_str())]; + } else { + [self updateEditState]; + } +} + +- (NSRange)markedRange { + if (_activeModel == nullptr) { + return NSMakeRange(NSNotFound, 0); + } + return NSMakeRange( + _activeModel->composing_range().base(), + _activeModel->composing_range().extent() - _activeModel->composing_range().base()); +} + +- (BOOL)hasMarkedText { + return _activeModel != nullptr && _activeModel->composing_range().length() > 0; +} + +- (NSAttributedString*)attributedSubstringForProposedRange:(NSRange)range + actualRange:(NSRangePointer)actualRange { + if (_activeModel == nullptr) { + return nil; + } + NSString* text = [NSString stringWithUTF8String:_activeModel->GetText().c_str()]; + if (range.location >= text.length) { + return nil; + } + range.length = std::min(range.length, text.length - range.location); + if (actualRange != nil) { + *actualRange = range; + } + NSString* substring = [text substringWithRange:range]; + return [[NSAttributedString alloc] initWithString:substring attributes:nil]; +} + +- (NSArray*)validAttributesForMarkedText { + return @[]; +} + +// Returns the bounding CGRect of the transformed incomingRect, in screen +// coordinates. +- (CGRect)screenRectFromFrameworkTransform:(CGRect)incomingRect { + CGPoint points[] = { + incomingRect.origin, + CGPointMake(incomingRect.origin.x, incomingRect.origin.y + incomingRect.size.height), + CGPointMake(incomingRect.origin.x + incomingRect.size.width, incomingRect.origin.y), + CGPointMake(incomingRect.origin.x + incomingRect.size.width, + incomingRect.origin.y + incomingRect.size.height)}; + + CGPoint origin = CGPointMake(CGFLOAT_MAX, CGFLOAT_MAX); + CGPoint farthest = CGPointMake(-CGFLOAT_MAX, -CGFLOAT_MAX); + + for (int i = 0; i < 4; i++) { + const CGPoint point = points[i]; + + CGFloat x = _editableTransform.m11 * point.x + _editableTransform.m21 * point.y + + _editableTransform.m41; + CGFloat y = _editableTransform.m12 * point.x + _editableTransform.m22 * point.y + + _editableTransform.m42; + + const CGFloat w = _editableTransform.m14 * point.x + _editableTransform.m24 * point.y + + _editableTransform.m44; + + if (w == 0.0) { + return CGRectZero; + } else if (w != 1.0) { + x /= w; + y /= w; + } + + origin.x = MIN(origin.x, x); + origin.y = MIN(origin.y, y); + farthest.x = MAX(farthest.x, x); + farthest.y = MAX(farthest.y, y); + } + + const NSView* fromView = _currentViewController.flutterView; + const CGRect rectInWindow = [fromView + convertRect:CGRectMake(origin.x, origin.y, farthest.x - origin.x, farthest.y - origin.y) + toView:nil]; + NSWindow* window = fromView.window; + return window ? [window convertRectToScreen:rectInWindow] : rectInWindow; +} + +- (NSRect)firstRectForCharacterRange:(NSRange)range actualRange:(NSRangePointer)actualRange { + // This only determines position of caret instead of any arbitrary range, but it's enough + // to properly position accent selection popup + return !_currentViewController.viewLoaded || CGRectEqualToRect(_caretRect, CGRectNull) + ? CGRectZero + : [self screenRectFromFrameworkTransform:_caretRect]; +} + +- (NSUInteger)characterIndexForPoint:(NSPoint)point { + // TODO(cbracken): Implement. + // Note: This function can't easily be implemented under the system-message architecture. + return 0; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPluginTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPluginTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..d88f0535464e71e4e2b952fee4abe79bdcb680cb --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPluginTest.mm @@ -0,0 +1,2397 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/NSView+ClipsToBounds.h" + +#import +#import "flutter/testing/testing.h" + +#include +#include "flutter/common/constants.h" + +@interface FlutterTextField (Testing) +- (void)setPlatformNode:(flutter::FlutterTextPlatformNode*)node; +@end + +@interface FlutterTextFieldMock : FlutterTextField + +@property(nonatomic, nullable, copy) NSString* lastUpdatedString; +@property(nonatomic) NSRange lastUpdatedSelection; + +@end + +@implementation FlutterTextFieldMock + +- (void)updateString:(NSString*)string withSelection:(NSRange)selection { + _lastUpdatedString = string; + _lastUpdatedSelection = selection; +} + +@end + +@interface NSTextInputContext (Private) +// This is a private method. +- (BOOL)isActive; +@end + +@interface TextInputTestViewController : FlutterViewController +@end + +@implementation TextInputTestViewController +- (nonnull FlutterView*)createFlutterViewWithMTLDevice:(id)device + commandQueue:(id)commandQueue { + return OCMClassMock([NSView class]); +} +@end + +@interface FlutterInputPluginTestObjc : NSObject +- (bool)testEmptyCompositionRange; +- (bool)testClearClientDuringComposing; +@end + +@interface FlutterTextInputPluginTestDelegate : NSObject { + id _binaryMessenger; + FlutterViewController* _viewController; +} + +@end + +@implementation FlutterTextInputPluginTestDelegate + +static const FlutterViewIdentifier kViewId = 1; + +@synthesize binaryMessenger = _binaryMessenger; + +- (instancetype)initWithBinaryMessenger:(id)messenger + viewController:(FlutterViewController*)viewController { + self = [super init]; + if (self) { + _binaryMessenger = messenger; + _viewController = viewController; + } + return self; +} + +- (nullable FlutterViewController*)viewControllerForIdentifier: + (FlutterViewIdentifier)viewIdentifier { + if (viewIdentifier == kViewId) { + return _viewController; + } else { + return nil; + } +} + +@end + +@implementation FlutterInputPluginTestObjc + +- (bool)testEmptyCompositionRange { + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + @"inputAction" : @"action", + @"inputType" : @{@"name" : @"inputName"}, + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + FlutterMethodCall* call = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditingState" + arguments:@{ + @"text" : @"Text", + @"selectionBase" : @(0), + @"selectionExtent" : @(0), + @"composingBase" : @(-1), + @"composingExtent" : @(-1), + }]; + + [plugin handleMethodCall:call + result:^(id){ + }]; + + // Verify editing state was set. + NSDictionary* editingState = [plugin editingState]; + EXPECT_STREQ([editingState[@"text"] UTF8String], "Text"); + EXPECT_STREQ([editingState[@"selectionAffinity"] UTF8String], "TextAffinity.upstream"); + EXPECT_FALSE([editingState[@"selectionIsDirectional"] boolValue]); + EXPECT_EQ([editingState[@"selectionBase"] intValue], 0); + EXPECT_EQ([editingState[@"selectionExtent"] intValue], 0); + EXPECT_EQ([editingState[@"composingBase"] intValue], -1); + EXPECT_EQ([editingState[@"composingExtent"] intValue], -1); + return true; +} + +- (bool)testSetMarkedTextWithSelectionChange { + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + @"inputAction" : @"action", + @"inputType" : @{@"name" : @"inputName"}, + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + FlutterMethodCall* call = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditingState" + arguments:@{ + @"text" : @"Text", + @"selectionBase" : @(4), + @"selectionExtent" : @(4), + @"composingBase" : @(-1), + @"composingExtent" : @(-1), + }]; + [plugin handleMethodCall:call + result:^(id){ + }]; + + [plugin setMarkedText:@"marked" + selectedRange:NSMakeRange(1, 0) + replacementRange:NSMakeRange(NSNotFound, 0)]; + + NSDictionary* expectedState = @{ + @"selectionBase" : @(5), + @"selectionExtent" : @(5), + @"selectionAffinity" : @"TextAffinity.upstream", + @"selectionIsDirectional" : @(NO), + @"composingBase" : @(4), + @"composingExtent" : @(10), + @"text" : @"Textmarked", + }; + + NSData* updateCall = [[FlutterJSONMethodCodec sharedInstance] + encodeMethodCall:[FlutterMethodCall + methodCallWithMethodName:@"TextInputClient.updateEditingState" + arguments:@[ @(1), expectedState ]]]; + + OCMExpect( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]); + + @try { + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]); + } @catch (...) { + return false; + } + return true; +} + +- (bool)testSetMarkedTextWithReplacementRange { + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + @"inputAction" : @"action", + @"inputType" : @{@"name" : @"inputName"}, + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + FlutterMethodCall* call = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditingState" + arguments:@{ + @"text" : @"1234", + @"selectionBase" : @(3), + @"selectionExtent" : @(3), + @"composingBase" : @(-1), + @"composingExtent" : @(-1), + }]; + [plugin handleMethodCall:call + result:^(id){ + }]; + + [plugin setMarkedText:@"marked" + selectedRange:NSMakeRange(1, 0) + replacementRange:NSMakeRange(1, 2)]; + + NSDictionary* expectedState = @{ + @"selectionBase" : @(2), + @"selectionExtent" : @(2), + @"selectionAffinity" : @"TextAffinity.upstream", + @"selectionIsDirectional" : @(NO), + @"composingBase" : @(1), + @"composingExtent" : @(7), + @"text" : @"1marked4", + }; + + NSData* updateCall = [[FlutterJSONMethodCodec sharedInstance] + encodeMethodCall:[FlutterMethodCall + methodCallWithMethodName:@"TextInputClient.updateEditingState" + arguments:@[ @(1), expectedState ]]]; + + OCMExpect( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]); + + @try { + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]); + } @catch (...) { + return false; + } + return true; +} + +- (bool)testComposingRegionRemovedByFramework { + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + @"inputAction" : @"action", + @"inputType" : @{@"name" : @"inputName"}, + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + FlutterMethodCall* call = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditingState" + arguments:@{ + @"text" : @"Text", + @"selectionBase" : @(4), + @"selectionExtent" : @(4), + @"composingBase" : @(2), + @"composingExtent" : @(4), + }]; + [plugin handleMethodCall:call + result:^(id){ + }]; + + // Update with the composing region removed. + call = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditingState" + arguments:@{ + @"text" : @"Te", + @"selectionBase" : @(2), + @"selectionExtent" : @(2), + @"composingBase" : @(-1), + @"composingExtent" : @(-1), + }]; + [plugin handleMethodCall:call + result:^(id){ + }]; + + // Verify editing state was set. + NSDictionary* editingState = [plugin editingState]; + EXPECT_STREQ([editingState[@"text"] UTF8String], "Te"); + EXPECT_STREQ([editingState[@"selectionAffinity"] UTF8String], "TextAffinity.upstream"); + EXPECT_FALSE([editingState[@"selectionIsDirectional"] boolValue]); + EXPECT_EQ([editingState[@"selectionBase"] intValue], 2); + EXPECT_EQ([editingState[@"selectionExtent"] intValue], 2); + EXPECT_EQ([editingState[@"composingBase"] intValue], -1); + EXPECT_EQ([editingState[@"composingExtent"] intValue], -1); + return true; +} + +- (bool)testClearClientDuringComposing { + // Set up FlutterTextInputPlugin. + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + // Set input client 1. + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + @"inputAction" : @"action", + @"inputType" : @{@"name" : @"inputName"}, + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + // Set editing state with an active composing range. + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditingState" + arguments:@{ + @"text" : @"Text", + @"selectionBase" : @(0), + @"selectionExtent" : @(0), + @"composingBase" : @(0), + @"composingExtent" : @(1), + }] + result:^(id){ + }]; + + // Verify composing range is (0, 1). + NSDictionary* editingState = [plugin editingState]; + EXPECT_EQ([editingState[@"composingBase"] intValue], 0); + EXPECT_EQ([editingState[@"composingExtent"] intValue], 1); + + // Clear input client. + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.clearClient" + arguments:@[]] + result:^(id){ + }]; + + // Verify composing range is collapsed. + editingState = [plugin editingState]; + EXPECT_EQ([editingState[@"composingBase"] intValue], [editingState[@"composingExtent"] intValue]); + return true; +} + +- (bool)testAutocompleteDisabledWhenAutofillNotSet { + // Set up FlutterTextInputPlugin. + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + // Set input client 1. + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + @"inputAction" : @"action", + @"inputType" : @{@"name" : @"inputName"}, + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + // Verify autocomplete is disabled. + EXPECT_FALSE([plugin isAutomaticTextCompletionEnabled]); + return true; +} + +- (bool)testAutocompleteEnabledWhenAutofillSet { + // Set up FlutterTextInputPlugin. + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + // Set input client 1. + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + @"inputAction" : @"action", + @"inputType" : @{@"name" : @"inputName"}, + @"autofill" : @{ + @"uniqueIdentifier" : @"field1", + @"hints" : @[ @"name" ], + @"editingValue" : @{@"text" : @""}, + } + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + // Verify autocomplete is enabled. + EXPECT_TRUE([plugin isAutomaticTextCompletionEnabled]); + + // Verify content type is nil for unsupported content types. + if (@available(macOS 11.0, *)) { + EXPECT_EQ([plugin contentType], nil); + } + return true; +} + +- (bool)testAutocompleteEnabledWhenAutofillSetNoHint { + // Set up FlutterTextInputPlugin. + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + // Set input client 1. + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + @"inputAction" : @"action", + @"inputType" : @{@"name" : @"inputName"}, + @"autofill" : @{ + @"uniqueIdentifier" : @"field1", + @"hints" : @[], + @"editingValue" : @{@"text" : @""}, + } + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + // Verify autocomplete is enabled. + EXPECT_TRUE([plugin isAutomaticTextCompletionEnabled]); + return true; +} + +- (bool)testAutocompleteDisabledWhenObscureTextSet { + // Set up FlutterTextInputPlugin. + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + // Set input client 1. + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + @"inputAction" : @"action", + @"inputType" : @{@"name" : @"inputName"}, + @"obscureText" : @YES, + @"autofill" : @{ + @"uniqueIdentifier" : @"field1", + @"editingValue" : @{@"text" : @""}, + } + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + // Verify autocomplete is disabled. + EXPECT_FALSE([plugin isAutomaticTextCompletionEnabled]); + return true; +} + +- (bool)testAutocompleteDisabledWhenPasswordAutofillSet { + // Set up FlutterTextInputPlugin. + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + // Set input client 1. + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + @"inputAction" : @"action", + @"inputType" : @{@"name" : @"inputName"}, + @"autofill" : @{ + @"uniqueIdentifier" : @"field1", + @"hints" : @[ @"password" ], + @"editingValue" : @{@"text" : @""}, + } + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + // Verify autocomplete is disabled. + EXPECT_FALSE([plugin isAutomaticTextCompletionEnabled]); + + // Verify content type is password. + if (@available(macOS 11.0, *)) { + EXPECT_EQ([plugin contentType], NSTextContentTypePassword); + } + return true; +} + +- (bool)testAutocompleteDisabledWhenAutofillGroupIncludesPassword { + // Set up FlutterTextInputPlugin. + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + // Set input client 1. + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + @"inputAction" : @"action", + @"inputType" : @{@"name" : @"inputName"}, + @"fields" : @[ + @{ + @"inputAction" : @"action", + @"inputType" : @{@"name" : @"inputName"}, + @"autofill" : @{ + @"uniqueIdentifier" : @"field1", + @"hints" : @[ @"password" ], + @"editingValue" : @{@"text" : @""}, + } + }, + @{ + @"inputAction" : @"action", + @"inputType" : @{@"name" : @"inputName"}, + @"autofill" : @{ + @"uniqueIdentifier" : @"field2", + @"hints" : @[ @"name" ], + @"editingValue" : @{@"text" : @""}, + } + } + ] + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + // Verify autocomplete is disabled. + EXPECT_FALSE([plugin isAutomaticTextCompletionEnabled]); + return true; +} + +- (bool)testContentTypeWhenAutofillTypeIsUsername { + // Set up FlutterTextInputPlugin. + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + // Set input client 1. + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + @"inputAction" : @"action", + @"inputType" : @{@"name" : @"inputName"}, + @"autofill" : @{ + @"uniqueIdentifier" : @"field1", + @"hints" : @[ @"name" ], + @"editingValue" : @{@"text" : @""}, + } + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + // Verify autocomplete is disabled. + EXPECT_FALSE([plugin isAutomaticTextCompletionEnabled]); + + // Verify content type is username. + if (@available(macOS 11.0, *)) { + EXPECT_EQ([plugin contentType], NSTextContentTypeUsername); + } + return true; +} + +- (bool)testContentTypeWhenAutofillTypeIsOneTimeCode { + // Set up FlutterTextInputPlugin. + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + // Set input client 1. + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + @"inputAction" : @"action", + @"inputType" : @{@"name" : @"inputName"}, + @"autofill" : @{ + @"uniqueIdentifier" : @"field1", + @"hints" : @[ @"oneTimeCode" ], + @"editingValue" : @{@"text" : @""}, + } + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + // Verify autocomplete is disabled. + EXPECT_FALSE([plugin isAutomaticTextCompletionEnabled]); + + // Verify content type is username. + if (@available(macOS 11.0, *)) { + EXPECT_EQ([plugin contentType], NSTextContentTypeOneTimeCode); + } + return true; +} + +- (bool)testFirstRectForCharacterRange { + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + FlutterViewController* controllerMock = + [[TextInputTestViewController alloc] initWithEngine:engineMock nibName:nil bundle:nil]; + [controllerMock loadView]; + id viewMock = controllerMock.flutterView; + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [viewMock bounds]) + .andReturn(NSMakeRect(0, 0, 200, 200)); + + id windowMock = OCMClassMock([NSWindow class]); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [viewMock window]) + .andReturn(windowMock); + + OCMExpect( // NOLINT(google-objc-avoid-throwing-exception) + [viewMock convertRect:NSMakeRect(28, 10, 2, 19) toView:nil]) + .andReturn(NSMakeRect(28, 10, 2, 19)); + + OCMExpect( // NOLINT(google-objc-avoid-throwing-exception) + [windowMock convertRectToScreen:NSMakeRect(28, 10, 2, 19)]) + .andReturn(NSMakeRect(38, 20, 2, 19)); + + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:controllerMock]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + FlutterMethodCall* call = [FlutterMethodCall + methodCallWithMethodName:@"TextInput.setEditableSizeAndTransform" + arguments:@{ + @"height" : @(20.0), + @"transform" : @[ + @(1.0), @(0.0), @(0.0), @(0.0), @(0.0), @(1.0), @(0.0), @(0.0), @(0.0), + @(0.0), @(1.0), @(0.0), @(20.0), @(10.0), @(0.0), @(1.0) + ], + @"width" : @(400.0), + }]; + + [plugin handleMethodCall:call + result:^(id){ + }]; + + call = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setCaretRect" + arguments:@{ + @"height" : @(19.0), + @"width" : @(2.0), + @"x" : @(8.0), + @"y" : @(0.0), + }]; + + [plugin handleMethodCall:call + result:^(id){ + }]; + + NSRect rect = [plugin firstRectForCharacterRange:NSMakeRange(0, 0) actualRange:nullptr]; + @try { + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + [windowMock convertRectToScreen:NSMakeRect(28, 10, 2, 19)]); + } @catch (...) { + return false; + } + + return NSEqualRects(rect, NSMakeRect(38, 20, 2, 19)); +} + +- (bool)testFirstRectForCharacterRangeAtInfinity { + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + FlutterViewController* controllerMock = + [[TextInputTestViewController alloc] initWithEngine:engineMock nibName:nil bundle:nil]; + [controllerMock loadView]; + id viewMock = controllerMock.flutterView; + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [viewMock bounds]) + .andReturn(NSMakeRect(0, 0, 200, 200)); + + id windowMock = OCMClassMock([NSWindow class]); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [viewMock window]) + .andReturn(windowMock); + + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:controllerMock]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + FlutterMethodCall* call = [FlutterMethodCall + methodCallWithMethodName:@"TextInput.setEditableSizeAndTransform" + arguments:@{ + @"height" : @(20.0), + // Projects all points to infinity. + @"transform" : @[ + @(1.0), @(0.0), @(0.0), @(0.0), @(0.0), @(1.0), @(0.0), @(0.0), @(0.0), + @(0.0), @(1.0), @(0.0), @(20.0), @(10.0), @(0.0), @(0.0) + ], + @"width" : @(400.0), + }]; + + [plugin handleMethodCall:call + result:^(id){ + }]; + + call = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setCaretRect" + arguments:@{ + @"height" : @(19.0), + @"width" : @(2.0), + @"x" : @(8.0), + @"y" : @(0.0), + }]; + + [plugin handleMethodCall:call + result:^(id){ + }]; + + NSRect rect = [plugin firstRectForCharacterRange:NSMakeRange(0, 0) actualRange:nullptr]; + return NSEqualRects(rect, CGRectZero); +} + +- (bool)testFirstRectForCharacterRangeWithEsotericAffineTransform { + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + FlutterViewController* controllerMock = + [[TextInputTestViewController alloc] initWithEngine:engineMock nibName:nil bundle:nil]; + [controllerMock loadView]; + id viewMock = controllerMock.flutterView; + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [viewMock bounds]) + .andReturn(NSMakeRect(0, 0, 200, 200)); + + id windowMock = OCMClassMock([NSWindow class]); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [viewMock window]) + .andReturn(windowMock); + + OCMExpect( // NOLINT(google-objc-avoid-throwing-exception) + [viewMock convertRect:NSMakeRect(-18, 6, 3, 3) toView:nil]) + .andReturn(NSMakeRect(-18, 6, 3, 3)); + + OCMExpect( // NOLINT(google-objc-avoid-throwing-exception) + [windowMock convertRectToScreen:NSMakeRect(-18, 6, 3, 3)]) + .andReturn(NSMakeRect(-18, 6, 3, 3)); + + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:controllerMock]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + FlutterMethodCall* call = [FlutterMethodCall + methodCallWithMethodName:@"TextInput.setEditableSizeAndTransform" + arguments:@{ + @"height" : @(20.0), + // This matrix can be generated by running this dart code snippet: + // Matrix4.identity()..scale(3.0)..rotateZ(math.pi/2)..translate(1.0, 2.0, + // 3.0); + @"transform" : @[ + @(0.0), @(3.0), @(0.0), @(0.0), @(-3.0), @(0.0), @(0.0), @(0.0), @(0.0), + @(0.0), @(3.0), @(0.0), @(-6.0), @(3.0), @(9.0), @(1.0) + ], + @"width" : @(400.0), + }]; + + [plugin handleMethodCall:call + result:^(id){ + }]; + + call = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setCaretRect" + arguments:@{ + @"height" : @(1.0), + @"width" : @(1.0), + @"x" : @(1.0), + @"y" : @(3.0), + }]; + + [plugin handleMethodCall:call + result:^(id){ + }]; + + NSRect rect = [plugin firstRectForCharacterRange:NSMakeRange(0, 0) actualRange:nullptr]; + + @try { + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + [windowMock convertRectToScreen:NSMakeRect(-18, 6, 3, 3)]); + } @catch (...) { + return false; + } + + return NSEqualRects(rect, NSMakeRect(-18, 6, 3, 3)); +} + +- (bool)testSetEditingStateWithTextEditingDelta { + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + @"inputAction" : @"action", + @"enableDeltaModel" : @"true", + @"inputType" : @{@"name" : @"inputName"}, + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + FlutterMethodCall* call = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditingState" + arguments:@{ + @"text" : @"Text", + @"selectionBase" : @(0), + @"selectionExtent" : @(0), + @"composingBase" : @(-1), + @"composingExtent" : @(-1), + }]; + + [plugin handleMethodCall:call + result:^(id){ + }]; + + // Verify editing state was set. + NSDictionary* editingState = [plugin editingState]; + EXPECT_STREQ([editingState[@"text"] UTF8String], "Text"); + EXPECT_STREQ([editingState[@"selectionAffinity"] UTF8String], "TextAffinity.upstream"); + EXPECT_FALSE([editingState[@"selectionIsDirectional"] boolValue]); + EXPECT_EQ([editingState[@"selectionBase"] intValue], 0); + EXPECT_EQ([editingState[@"selectionExtent"] intValue], 0); + EXPECT_EQ([editingState[@"composingBase"] intValue], -1); + EXPECT_EQ([editingState[@"composingExtent"] intValue], -1); + return true; +} + +- (bool)testOperationsThatTriggerDelta { + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + @"inputAction" : @"action", + @"enableDeltaModel" : @"true", + @"inputType" : @{@"name" : @"inputName"}, + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + [plugin insertText:@"text to insert"]; + + NSDictionary* deltaToFramework = @{ + @"oldText" : @"", + @"deltaText" : @"text to insert", + @"deltaStart" : @(0), + @"deltaEnd" : @(0), + @"selectionBase" : @(14), + @"selectionExtent" : @(14), + @"selectionAffinity" : @"TextAffinity.upstream", + @"selectionIsDirectional" : @(false), + @"composingBase" : @(-1), + @"composingExtent" : @(-1), + }; + NSDictionary* expectedState = @{ + @"deltas" : @[ deltaToFramework ], + }; + + NSData* updateCall = [[FlutterJSONMethodCodec sharedInstance] + encodeMethodCall:[FlutterMethodCall + methodCallWithMethodName:@"TextInputClient.updateEditingStateWithDeltas" + arguments:@[ @(1), expectedState ]]]; + + @try { + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]); + } @catch (...) { + return false; + } + + [plugin setMarkedText:@"marked text" selectedRange:NSMakeRange(0, 1)]; + + deltaToFramework = @{ + @"oldText" : @"text to insert", + @"deltaText" : @"marked text", + @"deltaStart" : @(14), + @"deltaEnd" : @(14), + @"selectionBase" : @(14), + @"selectionExtent" : @(15), + @"selectionAffinity" : @"TextAffinity.upstream", + @"selectionIsDirectional" : @(false), + @"composingBase" : @(14), + @"composingExtent" : @(25), + }; + expectedState = @{ + @"deltas" : @[ deltaToFramework ], + }; + + updateCall = [[FlutterJSONMethodCodec sharedInstance] + encodeMethodCall:[FlutterMethodCall + methodCallWithMethodName:@"TextInputClient.updateEditingStateWithDeltas" + arguments:@[ @(1), expectedState ]]]; + + @try { + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]); + } @catch (...) { + return false; + } + + [plugin unmarkText]; + + deltaToFramework = @{ + @"oldText" : @"text to insertmarked text", + @"deltaText" : @"", + @"deltaStart" : @(-1), + @"deltaEnd" : @(-1), + @"selectionBase" : @(25), + @"selectionExtent" : @(25), + @"selectionAffinity" : @"TextAffinity.upstream", + @"selectionIsDirectional" : @(false), + @"composingBase" : @(-1), + @"composingExtent" : @(-1), + }; + expectedState = @{ + @"deltas" : @[ deltaToFramework ], + }; + + updateCall = [[FlutterJSONMethodCodec sharedInstance] + encodeMethodCall:[FlutterMethodCall + methodCallWithMethodName:@"TextInputClient.updateEditingStateWithDeltas" + arguments:@[ @(1), expectedState ]]]; + + @try { + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]); + } @catch (...) { + return false; + } + return true; +} + +- (bool)testComposingWithDelta { + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + @"inputAction" : @"action", + @"enableDeltaModel" : @"true", + @"inputType" : @{@"name" : @"inputName"}, + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + [plugin setMarkedText:@"m" selectedRange:NSMakeRange(0, 1)]; + + NSDictionary* deltaToFramework = @{ + @"oldText" : @"", + @"deltaText" : @"m", + @"deltaStart" : @(0), + @"deltaEnd" : @(0), + @"selectionBase" : @(0), + @"selectionExtent" : @(1), + @"selectionAffinity" : @"TextAffinity.upstream", + @"selectionIsDirectional" : @(false), + @"composingBase" : @(0), + @"composingExtent" : @(1), + }; + NSDictionary* expectedState = @{ + @"deltas" : @[ deltaToFramework ], + }; + + NSData* updateCall = [[FlutterJSONMethodCodec sharedInstance] + encodeMethodCall:[FlutterMethodCall + methodCallWithMethodName:@"TextInputClient.updateEditingStateWithDeltas" + arguments:@[ @(1), expectedState ]]]; + + @try { + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]); + } @catch (...) { + return false; + } + + [plugin setMarkedText:@"ma" selectedRange:NSMakeRange(0, 1)]; + + deltaToFramework = @{ + @"oldText" : @"m", + @"deltaText" : @"ma", + @"deltaStart" : @(0), + @"deltaEnd" : @(1), + @"selectionBase" : @(0), + @"selectionExtent" : @(1), + @"selectionAffinity" : @"TextAffinity.upstream", + @"selectionIsDirectional" : @(false), + @"composingBase" : @(0), + @"composingExtent" : @(2), + }; + expectedState = @{ + @"deltas" : @[ deltaToFramework ], + }; + + updateCall = [[FlutterJSONMethodCodec sharedInstance] + encodeMethodCall:[FlutterMethodCall + methodCallWithMethodName:@"TextInputClient.updateEditingStateWithDeltas" + arguments:@[ @(1), expectedState ]]]; + + @try { + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]); + } @catch (...) { + return false; + } + + [plugin setMarkedText:@"mar" selectedRange:NSMakeRange(0, 1)]; + + deltaToFramework = @{ + @"oldText" : @"ma", + @"deltaText" : @"mar", + @"deltaStart" : @(0), + @"deltaEnd" : @(2), + @"selectionBase" : @(0), + @"selectionExtent" : @(1), + @"selectionAffinity" : @"TextAffinity.upstream", + @"selectionIsDirectional" : @(false), + @"composingBase" : @(0), + @"composingExtent" : @(3), + }; + expectedState = @{ + @"deltas" : @[ deltaToFramework ], + }; + + updateCall = [[FlutterJSONMethodCodec sharedInstance] + encodeMethodCall:[FlutterMethodCall + methodCallWithMethodName:@"TextInputClient.updateEditingStateWithDeltas" + arguments:@[ @(1), expectedState ]]]; + + @try { + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]); + } @catch (...) { + return false; + } + + [plugin setMarkedText:@"mark" selectedRange:NSMakeRange(0, 1)]; + + deltaToFramework = @{ + @"oldText" : @"mar", + @"deltaText" : @"mark", + @"deltaStart" : @(0), + @"deltaEnd" : @(3), + @"selectionBase" : @(0), + @"selectionExtent" : @(1), + @"selectionAffinity" : @"TextAffinity.upstream", + @"selectionIsDirectional" : @(false), + @"composingBase" : @(0), + @"composingExtent" : @(4), + }; + expectedState = @{ + @"deltas" : @[ deltaToFramework ], + }; + + updateCall = [[FlutterJSONMethodCodec sharedInstance] + encodeMethodCall:[FlutterMethodCall + methodCallWithMethodName:@"TextInputClient.updateEditingStateWithDeltas" + arguments:@[ @(1), expectedState ]]]; + + @try { + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]); + } @catch (...) { + return false; + } + + [plugin setMarkedText:@"marke" selectedRange:NSMakeRange(0, 1)]; + + deltaToFramework = @{ + @"oldText" : @"mark", + @"deltaText" : @"marke", + @"deltaStart" : @(0), + @"deltaEnd" : @(4), + @"selectionBase" : @(0), + @"selectionExtent" : @(1), + @"selectionAffinity" : @"TextAffinity.upstream", + @"selectionIsDirectional" : @(false), + @"composingBase" : @(0), + @"composingExtent" : @(5), + }; + expectedState = @{ + @"deltas" : @[ deltaToFramework ], + }; + + updateCall = [[FlutterJSONMethodCodec sharedInstance] + encodeMethodCall:[FlutterMethodCall + methodCallWithMethodName:@"TextInputClient.updateEditingStateWithDeltas" + arguments:@[ @(1), expectedState ]]]; + + @try { + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]); + } @catch (...) { + return false; + } + + [plugin setMarkedText:@"marked" selectedRange:NSMakeRange(0, 1)]; + + deltaToFramework = @{ + @"oldText" : @"marke", + @"deltaText" : @"marked", + @"deltaStart" : @(0), + @"deltaEnd" : @(5), + @"selectionBase" : @(0), + @"selectionExtent" : @(1), + @"selectionAffinity" : @"TextAffinity.upstream", + @"selectionIsDirectional" : @(false), + @"composingBase" : @(0), + @"composingExtent" : @(6), + }; + expectedState = @{ + @"deltas" : @[ deltaToFramework ], + }; + + updateCall = [[FlutterJSONMethodCodec sharedInstance] + encodeMethodCall:[FlutterMethodCall + methodCallWithMethodName:@"TextInputClient.updateEditingStateWithDeltas" + arguments:@[ @(1), expectedState ]]]; + + @try { + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]); + } @catch (...) { + return false; + } + + [plugin unmarkText]; + + deltaToFramework = @{ + @"oldText" : @"marked", + @"deltaText" : @"", + @"deltaStart" : @(-1), + @"deltaEnd" : @(-1), + @"selectionBase" : @(6), + @"selectionExtent" : @(6), + @"selectionAffinity" : @"TextAffinity.upstream", + @"selectionIsDirectional" : @(false), + @"composingBase" : @(-1), + @"composingExtent" : @(-1), + }; + expectedState = @{ + @"deltas" : @[ deltaToFramework ], + }; + + updateCall = [[FlutterJSONMethodCodec sharedInstance] + encodeMethodCall:[FlutterMethodCall + methodCallWithMethodName:@"TextInputClient.updateEditingStateWithDeltas" + arguments:@[ @(1), expectedState ]]]; + + @try { + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]); + } @catch (...) { + return false; + } + return true; +} + +- (bool)testComposingWithDeltasWhenSelectionIsActive { + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + @"inputAction" : @"action", + @"enableDeltaModel" : @"true", + @"inputType" : @{@"name" : @"inputName"}, + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + FlutterMethodCall* call = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditingState" + arguments:@{ + @"text" : @"Text", + @"selectionBase" : @(0), + @"selectionExtent" : @(4), + @"composingBase" : @(-1), + @"composingExtent" : @(-1), + }]; + [plugin handleMethodCall:call + result:^(id){ + }]; + + [plugin setMarkedText:@"~" + selectedRange:NSMakeRange(1, 0) + replacementRange:NSMakeRange(NSNotFound, 0)]; + + NSDictionary* deltaToFramework = @{ + @"oldText" : @"Text", + @"deltaText" : @"~", + @"deltaStart" : @(0), + @"deltaEnd" : @(4), + @"selectionBase" : @(1), + @"selectionExtent" : @(1), + @"selectionAffinity" : @"TextAffinity.upstream", + @"selectionIsDirectional" : @(false), + @"composingBase" : @(0), + @"composingExtent" : @(1), + }; + NSDictionary* expectedState = @{ + @"deltas" : @[ deltaToFramework ], + }; + + NSData* updateCall = [[FlutterJSONMethodCodec sharedInstance] + encodeMethodCall:[FlutterMethodCall + methodCallWithMethodName:@"TextInputClient.updateEditingStateWithDeltas" + arguments:@[ @(1), expectedState ]]]; + + @try { + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]); + } @catch (...) { + return false; + } + return true; +} + +- (bool)testPerformKeyEquivalent { + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + __block NSEvent* eventBeingDispatchedByKeyboardManager = nil; + FlutterViewController* viewControllerMock = OCMClassMock([FlutterViewController class]); + OCMStub([viewControllerMock isDispatchingKeyEvent:[OCMArg any]]) + .andDo(^(NSInvocation* invocation) { + NSEvent* event; + [invocation getArgument:(void*)&event atIndex:2]; + BOOL result = event == eventBeingDispatchedByKeyboardManager; + [invocation setReturnValue:&result]; + }); + + NSEvent* event = [NSEvent keyEventWithType:NSEventTypeKeyDown + location:NSZeroPoint + modifierFlags:0x100 + timestamp:0 + windowNumber:0 + context:nil + characters:@"" + charactersIgnoringModifiers:@"" + isARepeat:NO + keyCode:0x50]; + + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewControllerMock]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + OCMExpect([viewControllerMock keyDown:event]); + + // Require that event is handled (returns YES) + if (![plugin performKeyEquivalent:event]) { + return false; + }; + + @try { + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + [viewControllerMock keyDown:event]); + } @catch (...) { + return false; + } + + // performKeyEquivalent must not forward event if it is being + // dispatched by keyboard manager + eventBeingDispatchedByKeyboardManager = event; + + OCMReject([viewControllerMock keyDown:event]); + @try { + // Require that event is not handled (returns NO) and not + // forwarded to controller + if ([plugin performKeyEquivalent:event]) { + return false; + }; + } @catch (...) { + return false; + } + + return true; +} + +- (bool)handleArrowKeyWhenImePopoverIsActive { + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:FlutterKeyEvent {} + callback:nil + userData:nil]); + + NSTextInputContext* textInputContext = OCMClassMock([NSTextInputContext class]); + OCMStub([textInputContext handleEvent:[OCMArg any]]).andReturn(YES); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + plugin.textInputContext = textInputContext; + + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + @"inputAction" : @"action", + @"enableDeltaModel" : @"true", + @"inputType" : @{@"name" : @"inputName"}, + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.show" + arguments:@[]] + result:^(id){ + }]; + + // Set marked text, simulate active IME popover. + [plugin setMarkedText:@"m" + selectedRange:NSMakeRange(0, 1) + replacementRange:NSMakeRange(NSNotFound, 0)]; + + // Right arrow key. This, unlike the key below should be handled by the plugin. + NSEvent* event = [NSEvent keyEventWithType:NSEventTypeKeyDown + location:NSZeroPoint + modifierFlags:0xa00100 + timestamp:0 + windowNumber:0 + context:nil + characters:@"\uF702" + charactersIgnoringModifiers:@"\uF702" + isARepeat:NO + keyCode:0x4]; + + // Plugin should mark the event as key equivalent. + [plugin performKeyEquivalent:event]; + + if ([plugin handleKeyEvent:event] != true) { + return false; + } + + // CTRL+H (delete backwards) + event = [NSEvent keyEventWithType:NSEventTypeKeyDown + location:NSZeroPoint + modifierFlags:0x40101 + timestamp:0 + windowNumber:0 + context:nil + characters:@"\uF702" + charactersIgnoringModifiers:@"\uF702" + isARepeat:NO + keyCode:0x4]; + + // Plugin should mark the event as key equivalent. + [plugin performKeyEquivalent:event]; + + if ([plugin handleKeyEvent:event] != false) { + return false; + } + + return true; +} + +- (bool)unhandledKeyEquivalent { + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + @"inputAction" : @"action", + @"enableDeltaModel" : @"true", + @"inputType" : @{@"name" : @"inputName"}, + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.show" + arguments:@[]] + result:^(id){ + }]; + + // CTRL+H (delete backwards) + NSEvent* event = [NSEvent keyEventWithType:NSEventTypeKeyDown + location:NSZeroPoint + modifierFlags:0x40101 + timestamp:0 + windowNumber:0 + context:nil + characters:@"" + charactersIgnoringModifiers:@"h" + isARepeat:NO + keyCode:0x4]; + + // Plugin should mark the event as key equivalent. + [plugin performKeyEquivalent:event]; + + // Simulate KeyboardManager sending unhandled event to plugin. This must return + // true because it is a known editing command. + if ([plugin handleKeyEvent:event] != true) { + return false; + } + + // CMD+W + event = [NSEvent keyEventWithType:NSEventTypeKeyDown + location:NSZeroPoint + modifierFlags:0x100108 + timestamp:0 + windowNumber:0 + context:nil + characters:@"w" + charactersIgnoringModifiers:@"w" + isARepeat:NO + keyCode:0x13]; + + // Plugin should mark the event as key equivalent. + [plugin performKeyEquivalent:event]; + + // This is not a valid editing command, plugin must return false so that + // KeyboardManager sends the event to next responder. + if ([plugin handleKeyEvent:event] != false) { + return false; + } + + return true; +} + +- (bool)testInsertNewLine { + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:FlutterKeyEvent {} + callback:nil + userData:nil]); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + @"inputType" : @{@"name" : @"TextInputType.multiline"}, + @"inputAction" : @"TextInputAction.newline", + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + FlutterMethodCall* call = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditingState" + arguments:@{ + @"text" : @"Text", + @"selectionBase" : @(4), + @"selectionExtent" : @(4), + @"composingBase" : @(-1), + @"composingExtent" : @(-1), + }]; + + [plugin handleMethodCall:call + result:^(id){ + }]; + + // Verify editing state was set. + NSDictionary* editingState = [plugin editingState]; + EXPECT_STREQ([editingState[@"text"] UTF8String], "Text"); + EXPECT_STREQ([editingState[@"selectionAffinity"] UTF8String], "TextAffinity.upstream"); + EXPECT_FALSE([editingState[@"selectionIsDirectional"] boolValue]); + EXPECT_EQ([editingState[@"selectionBase"] intValue], 4); + EXPECT_EQ([editingState[@"selectionExtent"] intValue], 4); + EXPECT_EQ([editingState[@"composingBase"] intValue], -1); + EXPECT_EQ([editingState[@"composingExtent"] intValue], -1); + + [plugin doCommandBySelector:@selector(insertNewline:)]; + + // Verify editing state was set. + editingState = [plugin editingState]; + EXPECT_STREQ([editingState[@"text"] UTF8String], "Text\n"); + EXPECT_STREQ([editingState[@"selectionAffinity"] UTF8String], "TextAffinity.upstream"); + EXPECT_FALSE([editingState[@"selectionIsDirectional"] boolValue]); + EXPECT_EQ([editingState[@"selectionBase"] intValue], 5); + EXPECT_EQ([editingState[@"selectionExtent"] intValue], 5); + EXPECT_EQ([editingState[@"composingBase"] intValue], -1); + EXPECT_EQ([editingState[@"composingExtent"] intValue], -1); + + return true; +} + +- (bool)testSendActionDoNotInsertNewLine { + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:FlutterKeyEvent {} + callback:nil + userData:nil]); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + @"inputType" : @{@"name" : @"TextInputType.multiline"}, + @"inputAction" : @"TextInputAction.send", + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + FlutterMethodCall* call = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditingState" + arguments:@{ + @"text" : @"Text", + @"selectionBase" : @(4), + @"selectionExtent" : @(4), + @"composingBase" : @(-1), + @"composingExtent" : @(-1), + }]; + + NSDictionary* expectedState = @{ + @"selectionBase" : @(4), + @"selectionExtent" : @(4), + @"selectionAffinity" : @"TextAffinity.upstream", + @"selectionIsDirectional" : @(NO), + @"composingBase" : @(-1), + @"composingExtent" : @(-1), + @"text" : @"Text", + }; + + NSData* updateCall = [[FlutterJSONMethodCodec sharedInstance] + encodeMethodCall:[FlutterMethodCall + methodCallWithMethodName:@"TextInputClient.updateEditingState" + arguments:@[ @(1), expectedState ]]]; + + OCMExpect( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]); + + [plugin handleMethodCall:call + result:^(id){ + }]; + + [plugin doCommandBySelector:@selector(insertNewline:)]; + + NSData* performActionCall = [[FlutterJSONMethodCodec sharedInstance] + encodeMethodCall:[FlutterMethodCall + methodCallWithMethodName:@"TextInputClient.performAction" + arguments:@[ @(1), @"TextInputAction.send" ]]]; + + // Input action should be notified. + @try { + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/textinput" message:performActionCall]); + } @catch (...) { + return false; + } + + NSDictionary* updatedState = @{ + @"selectionBase" : @(5), + @"selectionExtent" : @(5), + @"selectionAffinity" : @"TextAffinity.upstream", + @"selectionIsDirectional" : @(NO), + @"composingBase" : @(-1), + @"composingExtent" : @(-1), + @"text" : @"Text\n", + }; + + updateCall = [[FlutterJSONMethodCodec sharedInstance] + encodeMethodCall:[FlutterMethodCall + methodCallWithMethodName:@"TextInputClient.updateEditingState" + arguments:@[ @(1), updatedState ]]]; + + // Verify that editing state was not be updated. + @try { + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]); + return false; + } @catch (...) { + // Expected. + } + + return true; +} + +- (bool)testLocalTextAndSelectionUpdateAfterDelta { + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + @"inputAction" : @"action", + @"enableDeltaModel" : @"true", + @"inputType" : @{@"name" : @"inputName"}, + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + [plugin insertText:@"text to insert"]; + + NSDictionary* deltaToFramework = @{ + @"oldText" : @"", + @"deltaText" : @"text to insert", + @"deltaStart" : @(0), + @"deltaEnd" : @(0), + @"selectionBase" : @(14), + @"selectionExtent" : @(14), + @"selectionAffinity" : @"TextAffinity.upstream", + @"selectionIsDirectional" : @(false), + @"composingBase" : @(-1), + @"composingExtent" : @(-1), + }; + NSDictionary* expectedState = @{ + @"deltas" : @[ deltaToFramework ], + }; + + NSData* updateCall = [[FlutterJSONMethodCodec sharedInstance] + encodeMethodCall:[FlutterMethodCall + methodCallWithMethodName:@"TextInputClient.updateEditingStateWithDeltas" + arguments:@[ @(1), expectedState ]]]; + + @try { + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/textinput" message:updateCall]); + } @catch (...) { + return false; + } + + bool localTextAndSelectionUpdated = [plugin.string isEqualToString:@"text to insert"] && + NSEqualRanges(plugin.selectedRange, NSMakeRange(14, 0)); + + return localTextAndSelectionUpdated; +} + +- (bool)testSelectorsAreForwardedToFramework { + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + @"inputAction" : @"action", + @"enableDeltaModel" : @"true", + @"inputType" : @{@"name" : @"inputName"}, + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + // Can't run CFRunLoop in default mode because it causes crashes from scheduled + // sources from other tests. + NSString* runLoopMode = @"FlutterTestRunLoopMode"; + plugin.customRunLoopMode = runLoopMode; + + // Ensure both selectors are grouped in one platform channel call. + [plugin doCommandBySelector:@selector(moveUp:)]; + [plugin doCommandBySelector:@selector(moveRightAndModifySelection:)]; + + __block bool done = false; + CFRunLoopPerformBlock(CFRunLoopGetMain(), (__bridge CFStringRef)runLoopMode, ^{ + done = true; + }); + + while (!done) { + // Each invocation will handle one source. + CFRunLoopRunInMode((__bridge CFStringRef)runLoopMode, 0, true); + } + + NSData* performSelectorCall = [[FlutterJSONMethodCodec sharedInstance] + encodeMethodCall:[FlutterMethodCall + methodCallWithMethodName:@"TextInputClient.performSelectors" + arguments:@[ + @(1), @[ @"moveUp:", @"moveRightAndModifySelection:" ] + ]]]; + + @try { + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/textinput" message:performSelectorCall]); + } @catch (...) { + return false; + } + + return true; +} + +- (bool)testSelectorsNotForwardedToFrameworkIfNoClient { + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + // Make sure the selectors are not forwarded to the framework. + OCMReject([binaryMessengerMock sendOnChannel:@"flutter/textinput" message:[OCMArg any]]); + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + // Can't run CFRunLoop in default mode because it causes crashes from scheduled + // sources from other tests. + NSString* runLoopMode = @"FlutterTestRunLoopMode"; + plugin.customRunLoopMode = runLoopMode; + + // Call selectors without setting a client. + [plugin doCommandBySelector:@selector(moveUp:)]; + [plugin doCommandBySelector:@selector(moveRightAndModifySelection:)]; + + __block bool done = false; + CFRunLoopPerformBlock(CFRunLoopGetMain(), (__bridge CFStringRef)runLoopMode, ^{ + done = true; + }); + + while (!done) { + CFRunLoopRunInMode((__bridge CFStringRef)runLoopMode, 0, true); + } + // At this point the selectors should be dropped; otherwise, OCMReject will throw. + return true; +} + +@end + +namespace flutter::testing { + +namespace { +// Allocates and returns an engine configured for the text fixture resource configuration. +FlutterEngine* CreateTestEngine() { + NSString* fixtures = @(testing::GetFixturesPath()); + FlutterDartProject* project = [[FlutterDartProject alloc] + initWithAssetsPath:fixtures + ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; + return [[FlutterEngine alloc] initWithName:@"test" project:project allowHeadlessExecution:true]; +} +} // namespace + +TEST(FlutterTextInputPluginTest, TestEmptyCompositionRange) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testEmptyCompositionRange]); +} + +TEST(FlutterTextInputPluginTest, TestSetMarkedTextWithSelectionChange) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testSetMarkedTextWithSelectionChange]); +} + +TEST(FlutterTextInputPluginTest, TestSetMarkedTextWithReplacementRange) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testSetMarkedTextWithReplacementRange]); +} + +TEST(FlutterTextInputPluginTest, TestComposingRegionRemovedByFramework) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testComposingRegionRemovedByFramework]); +} + +TEST(FlutterTextInputPluginTest, TestClearClientDuringComposing) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testClearClientDuringComposing]); +} + +TEST(FlutterTextInputPluginTest, TestAutocompleteDisabledWhenAutofillNotSet) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testAutocompleteDisabledWhenAutofillNotSet]); +} + +TEST(FlutterTextInputPluginTest, TestAutocompleteEnabledWhenAutofillSet) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testAutocompleteEnabledWhenAutofillSet]); +} + +TEST(FlutterTextInputPluginTest, TestAutocompleteEnabledWhenAutofillSetNoHint) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testAutocompleteEnabledWhenAutofillSetNoHint]); +} + +TEST(FlutterTextInputPluginTest, TestAutocompleteDisabledWhenObscureTextSet) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testAutocompleteDisabledWhenObscureTextSet]); +} + +TEST(FlutterTextInputPluginTest, TestAutocompleteDisabledWhenPasswordAutofillSet) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testAutocompleteDisabledWhenPasswordAutofillSet]); +} + +TEST(FlutterTextInputPluginTest, TestAutocompleteDisabledWhenAutofillGroupIncludesPassword) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] + testAutocompleteDisabledWhenAutofillGroupIncludesPassword]); +} + +TEST(FlutterTextInputPluginTest, TestFirstRectForCharacterRange) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testFirstRectForCharacterRange]); +} + +TEST(FlutterTextInputPluginTest, TestFirstRectForCharacterRangeAtInfinity) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testFirstRectForCharacterRangeAtInfinity]); +} + +TEST(FlutterTextInputPluginTest, TestFirstRectForCharacterRangeWithEsotericAffineTransform) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] + testFirstRectForCharacterRangeWithEsotericAffineTransform]); +} + +TEST(FlutterTextInputPluginTest, TestSetEditingStateWithTextEditingDelta) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testSetEditingStateWithTextEditingDelta]); +} + +TEST(FlutterTextInputPluginTest, TestOperationsThatTriggerDelta) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testOperationsThatTriggerDelta]); +} + +TEST(FlutterTextInputPluginTest, TestComposingWithDelta) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testComposingWithDelta]); +} + +TEST(FlutterTextInputPluginTest, TestComposingWithDeltasWhenSelectionIsActive) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testComposingWithDeltasWhenSelectionIsActive]); +} + +TEST(FlutterTextInputPluginTest, TestLocalTextAndSelectionUpdateAfterDelta) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testLocalTextAndSelectionUpdateAfterDelta]); +} + +TEST(FlutterTextInputPluginTest, TestPerformKeyEquivalent) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testPerformKeyEquivalent]); +} + +TEST(FlutterTextInputPluginTest, HandleArrowKeyWhenImePopoverIsActive) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] handleArrowKeyWhenImePopoverIsActive]); +} + +TEST(FlutterTextInputPluginTest, UnhandledKeyEquivalent) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] unhandledKeyEquivalent]); +} + +TEST(FlutterTextInputPluginTest, TestSelectorsAreForwardedToFramework) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testSelectorsAreForwardedToFramework]); +} + +TEST(FlutterTextInputPluginTest, TestSelectorsNotForwardedToFrameworkIfNoClient) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testSelectorsNotForwardedToFrameworkIfNoClient]); +} + +TEST(FlutterTextInputPluginTest, TestInsertNewLine) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testInsertNewLine]); +} + +TEST(FlutterTextInputPluginTest, TestSendActionDoNotInsertNewLine) { + ASSERT_TRUE([[FlutterInputPluginTestObjc alloc] testSendActionDoNotInsertNewLine]); +} + +TEST(FlutterTextInputPluginTest, TestAttributedSubstringOutOfRange) { + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + NSDictionary* setClientConfig = @{ + @"viewId" : @(kViewId), + @"inputAction" : @"action", + @"enableDeltaModel" : @"true", + @"inputType" : @{@"name" : @"inputName"}, + }; + [plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + FlutterMethodCall* call = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditingState" + arguments:@{ + @"text" : @"Text", + @"selectionBase" : @(0), + @"selectionExtent" : @(0), + @"composingBase" : @(-1), + @"composingExtent" : @(-1), + }]; + + [plugin handleMethodCall:call + result:^(id){ + }]; + + NSRange out; + NSAttributedString* text = [plugin attributedSubstringForProposedRange:NSMakeRange(1, 10) + actualRange:&out]; + EXPECT_TRUE([text.string isEqualToString:@"ext"]); + EXPECT_EQ(out.location, 1u); + EXPECT_EQ(out.length, 3u); + + text = [plugin attributedSubstringForProposedRange:NSMakeRange(4, 10) actualRange:&out]; + EXPECT_EQ(text, nil); +} + +TEST(FlutterTextInputPluginTest, CanWorkWithFlutterTextField) { + FlutterEngine* engine = CreateTestEngine(); + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + [viewController loadView]; + // Create a NSWindow so that the native text field can become first responder. + NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600) + styleMask:NSBorderlessWindowMask + backing:NSBackingStoreBuffered + defer:NO]; + window.contentView = viewController.view; + + engine.semanticsEnabled = YES; + + auto bridge = viewController.accessibilityBridge.lock(); + FlutterPlatformNodeDelegateMac delegate(bridge, viewController); + ui::AXTree tree; + ui::AXNode ax_node(&tree, nullptr, 0, 0); + ui::AXNodeData node_data; + node_data.SetValue("initial text"); + ax_node.SetData(node_data); + delegate.Init(viewController.accessibilityBridge, &ax_node); + { + FlutterTextPlatformNode text_platform_node(&delegate, viewController); + + FlutterTextFieldMock* mockTextField = + [[FlutterTextFieldMock alloc] initWithPlatformNode:&text_platform_node + fieldEditor:engine.textInputPlugin]; + [viewController.view addSubview:mockTextField]; + [mockTextField startEditing]; + + NSDictionary* setClientConfig = @{ + @"viewId" : @(flutter::kFlutterImplicitViewId), + @"inputAction" : @"action", + @"inputType" : @{@"name" : @"inputName"}, + }; + FlutterMethodCall* methodCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]]; + FlutterResult result = ^(id result) { + }; + [engine.textInputPlugin handleMethodCall:methodCall result:result]; + + NSDictionary* arguments = @{ + @"text" : @"new text", + @"selectionBase" : @(1), + @"selectionExtent" : @(2), + @"composingBase" : @(-1), + @"composingExtent" : @(-1), + }; + methodCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditingState" + arguments:arguments]; + [engine.textInputPlugin handleMethodCall:methodCall result:result]; + EXPECT_EQ([mockTextField.lastUpdatedString isEqualToString:@"new text"], YES); + EXPECT_EQ(NSEqualRanges(mockTextField.lastUpdatedSelection, NSMakeRange(1, 1)), YES); + + // This blocks the FlutterTextFieldMock, which is held onto by the main event + // loop, from crashing. + [mockTextField setPlatformNode:nil]; + } + + // This verifies that clearing the platform node works. + [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; +} + +TEST(FlutterTextInputPluginTest, CanNotBecomeResponderIfNoViewController) { + FlutterEngine* engine = CreateTestEngine(); + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + [viewController loadView]; + // Creates a NSWindow so that the native text field can become first responder. + NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600) + styleMask:NSBorderlessWindowMask + backing:NSBackingStoreBuffered + defer:NO]; + window.contentView = viewController.view; + + engine.semanticsEnabled = YES; + + auto bridge = viewController.accessibilityBridge.lock(); + FlutterPlatformNodeDelegateMac delegate(bridge, viewController); + ui::AXTree tree; + ui::AXNode ax_node(&tree, nullptr, 0, 0); + ui::AXNodeData node_data; + node_data.SetValue("initial text"); + ax_node.SetData(node_data); + delegate.Init(viewController.accessibilityBridge, &ax_node); + FlutterTextPlatformNode text_platform_node(&delegate, viewController); + + FlutterTextField* textField = text_platform_node.GetNativeViewAccessible(); + EXPECT_EQ([textField becomeFirstResponder], YES); + // Removes view controller. + [engine setViewController:nil]; + FlutterTextPlatformNode text_platform_node_no_controller(&delegate, nil); + textField = text_platform_node_no_controller.GetNativeViewAccessible(); + EXPECT_EQ([textField becomeFirstResponder], NO); +} + +TEST(FlutterTextInputPluginTest, IsAddedAndRemovedFromViewHierarchy) { + FlutterEngine* engine = CreateTestEngine(); + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + [viewController loadView]; + + NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600) + styleMask:NSBorderlessWindowMask + backing:NSBackingStoreBuffered + defer:NO]; + window.contentView = viewController.view; + + ASSERT_EQ(engine.textInputPlugin.superview, nil); + ASSERT_FALSE(window.firstResponder == engine.textInputPlugin); + + NSDictionary* setClientConfig = @{ + @"viewId" : @(flutter::kFlutterImplicitViewId), + }; + [engine.textInputPlugin + handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + [engine.textInputPlugin + handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.show" arguments:@[]] + result:^(id){ + }]; + + ASSERT_EQ(engine.textInputPlugin.superview, viewController.view); + ASSERT_TRUE(window.firstResponder == engine.textInputPlugin); + + [engine.textInputPlugin + handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.hide" arguments:@[]] + result:^(id){ + }]; + + ASSERT_EQ(engine.textInputPlugin.superview, nil); + ASSERT_FALSE(window.firstResponder == engine.textInputPlugin); +} + +TEST(FlutterTextInputPluginTest, FirstResponderIsCorrect) { + FlutterEngine* engine = CreateTestEngine(); + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + [viewController loadView]; + + NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600) + styleMask:NSBorderlessWindowMask + backing:NSBackingStoreBuffered + defer:NO]; + window.contentView = viewController.view; + + ASSERT_TRUE(viewController.flutterView.acceptsFirstResponder); + + [window makeFirstResponder:viewController.flutterView]; + + NSDictionary* setClientConfig = @{ + @"viewId" : @(flutter::kFlutterImplicitViewId), + }; + [engine.textInputPlugin + handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]] + result:^(id){ + }]; + + [engine.textInputPlugin + handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.show" arguments:@[]] + result:^(id){ + }]; + + ASSERT_TRUE(window.firstResponder == engine.textInputPlugin); + + ASSERT_FALSE(viewController.flutterView.acceptsFirstResponder); + + [engine.textInputPlugin + handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.hide" arguments:@[]] + result:^(id){ + }]; + + ASSERT_TRUE(viewController.flutterView.acceptsFirstResponder); + ASSERT_TRUE(window.firstResponder == viewController.flutterView); +} + +TEST(FlutterTextInputPluginTest, HasZeroSizeAndClipsToBounds) { + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + + FlutterTextInputPluginTestDelegate* delegate = + [[FlutterTextInputPluginTestDelegate alloc] initWithBinaryMessenger:binaryMessengerMock + viewController:viewController]; + + FlutterTextInputPlugin* plugin = [[FlutterTextInputPlugin alloc] initWithDelegate:delegate]; + + ASSERT_TRUE(NSIsEmptyRect(plugin.frame)); + ASSERT_TRUE(plugin.clipsToBounds); +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.h new file mode 100644 index 0000000000000000000000000000000000000000..82e0e1ad816b1cdc6e7cc07ae5f432a6fd1993ff --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.h @@ -0,0 +1,106 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERTEXTINPUTSEMANTICSOBJECT_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERTEXTINPUTSEMANTICSOBJECT_H_ + +#import + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.h" + +#include "flutter/fml/macros.h" +#include "flutter/third_party/accessibility/ax/platform/ax_platform_node_base.h" + +@class FlutterTextField; +@class FlutterTextInputPlugin; + +namespace flutter { + +//------------------------------------------------------------------------------ +/// The ax platform node for a text field. +class FlutterTextPlatformNode : public ui::AXPlatformNodeBase { + public: + //--------------------------------------------------------------------------- + /// @brief Creates a FlutterTextPlatformNode that uses a + /// FlutterTextField as its NativeViewAccessible. + /// @param[in] delegate The delegate that provides accessibility + /// data. + /// @param[in] view_controller The view_controller that is used for querying + /// the information about FlutterView and + /// FlutterTextInputPlugin. + explicit FlutterTextPlatformNode(FlutterPlatformNodeDelegate* delegate, + __weak FlutterViewController* view_controller); + ~FlutterTextPlatformNode() override; + + //------------------------------------------------------------------------------ + /// @brief Gets the frame of this platform node relative to the view of + /// FlutterViewController. This is used by the FlutterTextField to get its + /// frame rect because the FlutterTextField is a subview of the + /// FlutterViewController.view. + NSRect GetFrame(); + + // |ui::AXPlatformNodeBase| + gfx::NativeViewAccessible GetNativeViewAccessible() override; + + private: + FlutterTextField* appkit_text_field_; + __weak FlutterViewController* view_controller_; + + //------------------------------------------------------------------------------ + /// @brief Ensures the FlutterTextField is attached to the FlutterView. This + /// method returns true if the text field is succesfully attached. If + /// this method returns false, that means the FlutterTextField could not + /// be attached to the FlutterView. This can happen when the FlutterEngine + /// does not have a FlutterViewController or the FlutterView is not loaded + /// yet. + bool EnsureAttachedToView(); + + //------------------------------------------------------------------------------ + /// @brief Detaches the FlutterTextField from the FlutterView if it is not + /// already detached. + void EnsureDetachedFromView(); + + FML_DISALLOW_COPY_AND_ASSIGN(FlutterTextPlatformNode); +}; + +} // namespace flutter + +/** + * An NSTextField implementation that represents the NativeViewAccessible for the + * FlutterTextPlatformNode + * + * The NSAccessibility protocol does not provide full support for text editing. This + * appkit text field is used to get around this problem. The FlutterTextPlatformNode + * creates a hidden FlutterTextField, since VoiceOver only provides text editing + * announcements for NSTextField subclasses. + * + * All of the text editing events in this native text field are redirected to the + * FlutterTextInputPlugin. + */ +@interface FlutterTextField : NSTextField + +/** + * Initializes a FlutterTextField that uses the FlutterTextInputPlugin as its field editor. + * The text field redirects all of the text editing events to the FlutterTextInputPlugin. + */ +- (instancetype)initWithPlatformNode:(flutter::FlutterTextPlatformNode*)node + fieldEditor:(FlutterTextInputPlugin*)plugin; + +/** + * Updates the string value and the selection of this text field. + * + * Calling this method is necessary for macOS to get notified about string and selection + * changes. + */ +- (void)updateString:(NSString*)string withSelection:(NSRange)selection; + +/** + * Makes the field editor (plugin) current editor for this TextField, meaning + * that the text field will start getting editing events. + */ +- (void)startEditing; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERTEXTINPUTSEMANTICSOBJECT_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.mm new file mode 100644 index 0000000000000000000000000000000000000000..7a5653b0955a3eb9488fabbe7a030af51d7fe544 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.mm @@ -0,0 +1,226 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.h" + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" + +#include "flutter/third_party/accessibility/ax/ax_action_data.h" +#include "flutter/third_party/accessibility/gfx/geometry/rect_conversions.h" +#include "flutter/third_party/accessibility/gfx/mac/coordinate_conversion.h" + +#pragma mark - FlutterTextFieldCell +/** + * A convenient class that can be used to set a custom field editor for an + * NSTextField. + * + * The FlutterTextField uses this class set the FlutterTextInputPlugin as + * its field editor. + */ +@interface FlutterTextFieldCell : NSTextFieldCell + +/** + * Initializes the NSCell for the input NSTextField. + */ +- (instancetype)initWithTextField:(NSTextField*)textField fieldEditor:(NSTextView*)editor; + +@end + +@implementation FlutterTextFieldCell { + NSTextView* _editor; +} + +#pragma mark - Private + +- (instancetype)initWithTextField:(NSTextField*)textField fieldEditor:(NSTextView*)editor { + self = [super initTextCell:textField.stringValue]; + if (self) { + _editor = editor; + [self setControlView:textField]; + // Read-only text fields are sent to the mac embedding as static + // text. This text field must be editable and selectable at this + // point. + self.editable = YES; + self.selectable = YES; + } + return self; +} + +#pragma mark - NSCell + +- (NSTextView*)fieldEditorForView:(NSView*)controlView { + return _editor; +} + +@end + +#pragma mark - FlutterTextField + +@implementation FlutterTextField { + flutter::FlutterTextPlatformNode* _node; + FlutterTextInputPlugin* _plugin; +} + +#pragma mark - Public + +- (instancetype)initWithPlatformNode:(flutter::FlutterTextPlatformNode*)node + fieldEditor:(FlutterTextInputPlugin*)plugin { + self = [super initWithFrame:NSZeroRect]; + if (self) { + _node = node; + _plugin = plugin; + [self setCell:[[FlutterTextFieldCell alloc] initWithTextField:self fieldEditor:plugin]]; + } + return self; +} + +- (void)updateString:(NSString*)string withSelection:(NSRange)selection { + NSAssert(_plugin.client == self, + @"Can't update FlutterTextField when it is not the first responder"); + if (![[self stringValue] isEqualToString:string]) { + [self setStringValue:string]; + } + if (!NSEqualRanges(_plugin.selectedRange, selection)) { + [_plugin setSelectedRange:selection]; + } +} + +#pragma mark - NSView + +- (NSRect)frame { + if (!_node) { + return NSZeroRect; + } + return _node->GetFrame(); +} + +#pragma mark - NSAccessibilityProtocol + +- (void)setAccessibilityFocused:(BOOL)isFocused { + if (!_node) { + return; + } + [super setAccessibilityFocused:isFocused]; + ui::AXActionData data; + data.action = isFocused ? ax::mojom::Action::kFocus : ax::mojom::Action::kBlur; + _node->GetDelegate()->AccessibilityPerformAction(data); +} + +- (void)startEditing { + if (!_plugin) { + return; + } + if (self.currentEditor == _plugin) { + return; + } + if (!_node) { + return; + } + // Selecting text seems to be the only way to make the field editor + // current editor. + [self selectText:self]; + NSAssert(self.currentEditor == _plugin, @"Failed to set current editor"); + + _plugin.client = self; + + // Restore previous selection. + NSString* textValue = @(_node->GetStringAttribute(ax::mojom::StringAttribute::kValue).data()); + int start = _node->GetIntAttribute(ax::mojom::IntAttribute::kTextSelStart); + int end = _node->GetIntAttribute(ax::mojom::IntAttribute::kTextSelEnd); + NSAssert((start >= 0 && end >= 0) || (start == -1 && end == -1), @"selection is invalid"); + NSRange selection; + if (start >= 0 && end >= 0) { + selection = NSMakeRange(MIN(start, end), ABS(end - start)); + } else { + // The native behavior is to place the cursor at the end of the string if + // there is no selection. + selection = NSMakeRange([self stringValue].length, 0); + } + [self updateString:textValue withSelection:selection]; +} + +- (void)setPlatformNode:(flutter::FlutterTextPlatformNode*)node { + _node = node; +} + +#pragma mark - NSObject + +- (void)dealloc { + if (_plugin.client == self) { + _plugin.client = nil; + } +} + +@end + +namespace flutter { + +FlutterTextPlatformNode::FlutterTextPlatformNode(FlutterPlatformNodeDelegate* delegate, + __weak FlutterViewController* view_controller) { + Init(delegate); + view_controller_ = view_controller; + appkit_text_field_ = + [[FlutterTextField alloc] initWithPlatformNode:this + fieldEditor:view_controller.engine.textInputPlugin]; + appkit_text_field_.bezeled = NO; + appkit_text_field_.drawsBackground = NO; + appkit_text_field_.bordered = NO; + appkit_text_field_.focusRingType = NSFocusRingTypeNone; +} + +FlutterTextPlatformNode::~FlutterTextPlatformNode() { + [appkit_text_field_ setPlatformNode:nil]; + EnsureDetachedFromView(); +} + +gfx::NativeViewAccessible FlutterTextPlatformNode::GetNativeViewAccessible() { + if (EnsureAttachedToView()) { + return appkit_text_field_; + } + return nil; +} + +NSRect FlutterTextPlatformNode::GetFrame() { + if (!view_controller_.viewLoaded) { + return NSZeroRect; + } + FlutterPlatformNodeDelegate* delegate = static_cast(GetDelegate()); + bool offscreen; + auto bridge_ptr = delegate->GetOwnerBridge().lock(); + if (!bridge_ptr) { + return NSZeroRect; + } + gfx::RectF bounds = bridge_ptr->RelativeToGlobalBounds(delegate->GetAXNode(), offscreen, true); + + // Converts to NSRect to use NSView rect conversion. + NSRect ns_local_bounds = NSMakeRect(bounds.x(), bounds.y(), bounds.width(), bounds.height()); + // The macOS XY coordinates start at bottom-left and increase toward top-right, + // which is different from the Flutter's XY coordinates that start at top-left + // increasing to bottom-right. Flip the y coordinate to convert from Flutter + // coordinates to macOS coordinates. + ns_local_bounds.origin.y = -ns_local_bounds.origin.y - ns_local_bounds.size.height; + NSRect ns_view_bounds = [view_controller_.flutterView convertRectFromBacking:ns_local_bounds]; + return [view_controller_.flutterView convertRect:ns_view_bounds toView:nil]; +} + +bool FlutterTextPlatformNode::EnsureAttachedToView() { + if (!view_controller_.viewLoaded) { + return false; + } + if ([appkit_text_field_ isDescendantOf:view_controller_.view]) { + return true; + } + [view_controller_.view addSubview:appkit_text_field_ + positioned:NSWindowBelow + relativeTo:view_controller_.flutterView]; + return true; +} + +void FlutterTextPlatformNode::EnsureDetachedFromView() { + [appkit_text_field_ removeFromSuperview]; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObjectTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObjectTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..fcba538dc11dd16a3b6e10d206f980ed36be9814 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObjectTest.mm @@ -0,0 +1,70 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" + +#import "flutter/testing/testing.h" + +namespace flutter::testing { + +namespace { +// Returns an engine configured for the text fixture resource configuration. +FlutterEngine* CreateTestEngine() { + NSString* fixtures = @(testing::GetFixturesPath()); + FlutterDartProject* project = [[FlutterDartProject alloc] + initWithAssetsPath:fixtures + ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; + return [[FlutterEngine alloc] initWithName:@"test" project:project allowHeadlessExecution:true]; +} +} // namespace + +TEST(FlutterTextInputSemanticsObjectTest, DoesInitialize) { + FlutterEngine* engine = CreateTestEngine(); + { + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + [viewController loadView]; + // Create a NSWindow so that the native text field can become first responder. + NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600) + styleMask:NSBorderlessWindowMask + backing:NSBackingStoreBuffered + defer:NO]; + window.contentView = viewController.view; + + engine.semanticsEnabled = YES; + + auto bridge = viewController.accessibilityBridge.lock(); + FlutterPlatformNodeDelegateMac delegate(bridge, viewController); + ui::AXTree tree; + ui::AXNode ax_node(&tree, nullptr, 0, 0); + ui::AXNodeData node_data; + node_data.SetValue("initial text"); + ax_node.SetData(node_data); + delegate.Init(viewController.accessibilityBridge, &ax_node); + // Verify that a FlutterTextField is attached to the view. + FlutterTextPlatformNode text_platform_node(&delegate, viewController); + id native_accessibility = text_platform_node.GetNativeViewAccessible(); + EXPECT_TRUE([native_accessibility isKindOfClass:[FlutterTextField class]]); + auto subviews = [viewController.view subviews]; + EXPECT_EQ([subviews count], 2u); + EXPECT_TRUE([subviews[0] isKindOfClass:[FlutterTextField class]]); + FlutterTextField* nativeTextField = subviews[0]; + EXPECT_EQ(text_platform_node.GetNativeViewAccessible(), nativeTextField); + } + + [engine shutDownEngine]; + engine = nil; + // Pump the event loop to make sure no stray nodes cause crashes after the + // engine has been destroyed. + // From issue: https://github.com/flutter/flutter/issues/115599 + [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextureRegistrar.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextureRegistrar.h new file mode 100644 index 0000000000000000000000000000000000000000..d95aab90e1a1dad14af2b86926465de22b6fd4e5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextureRegistrar.h @@ -0,0 +1,53 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERTEXTUREREGISTRAR_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERTEXTUREREGISTRAR_H_ + +#import + +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterExternalTexture.h" + +/* + * Delegate methods for FlutterTextureRegistrar. + */ +@protocol FlutterTextureRegistrarDelegate + +/* + * Called by the FlutterTextureRegistrar when a texture is registered. + */ +- (nonnull FlutterExternalTexture*)onRegisterTexture:(nonnull id)texture; + +@end + +/* + * Holds the external textures and implements the FlutterTextureRegistry. + */ +@interface FlutterTextureRegistrar : NSObject + +/* + * Use `initWithDelegate:engine:` instead. + */ +- (nullable instancetype)init NS_UNAVAILABLE; + +/* + * Use `initWithDelegate:engine:` instead. + */ ++ (nullable instancetype)new NS_UNAVAILABLE; + +/* + * Initialzes the texture registrar. + */ +- (nullable instancetype)initWithDelegate:(nonnull id)delegate + engine:(nonnull FlutterEngine*)engine NS_DESIGNATED_INITIALIZER; + +/* + * Returns the registered texture with the provided `textureID`. + */ +- (nullable FlutterExternalTexture*)getTextureWithID:(int64_t)textureID; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERTEXTUREREGISTRAR_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextureRegistrar.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextureRegistrar.mm new file mode 100644 index 0000000000000000000000000000000000000000..c4f97a49bf23eabbfc1c3f66fda244bae5153efa --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextureRegistrar.mm @@ -0,0 +1,61 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextureRegistrar.h" + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" + +@implementation FlutterTextureRegistrar { + __weak id _delegate; + + __weak FlutterEngine* _flutterEngine; + + // A mapping of textureID to internal FlutterExternalTexture wrapper. + NSMutableDictionary* _textures; +} + +- (instancetype)initWithDelegate:(id)delegate + engine:(FlutterEngine*)engine { + if (self = [super init]) { + _delegate = delegate; + _flutterEngine = engine; + _textures = [[NSMutableDictionary alloc] init]; + } + return self; +} + +- (int64_t)registerTexture:(id)texture { + FlutterExternalTexture* externalTexture = [_delegate onRegisterTexture:texture]; + int64_t textureID = [externalTexture textureID]; + BOOL success = [_flutterEngine registerTextureWithID:textureID]; + if (success) { + _textures[@(textureID)] = externalTexture; + return textureID; + } else { + NSLog(@"Unable to register the texture with id: %lld.", textureID); + return 0; + } +} + +- (void)textureFrameAvailable:(int64_t)textureID { + BOOL success = [_flutterEngine markTextureFrameAvailable:textureID]; + if (!success) { + NSLog(@"Unable to mark texture with id %lld as available.", textureID); + } +} + +- (void)unregisterTexture:(int64_t)textureID { + bool success = [_flutterEngine unregisterTextureWithID:textureID]; + if (success) { + [_textures removeObjectForKey:@(textureID)]; + } else { + NSLog(@"Unable to unregister texture with id: %lld.", textureID); + } +} + +- (FlutterExternalTexture*)getTextureWithID:(int64_t)textureID { + return _textures[@(textureID)]; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTimeConverter.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTimeConverter.h new file mode 100644 index 0000000000000000000000000000000000000000..c7e94b109920a4f5a7f0c5e7b6c2d88da8ccaa94 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTimeConverter.h @@ -0,0 +1,22 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERTIMECONVERTER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERTIMECONVERTER_H_ + +#import + +@class FlutterEngine; + +/// Converts between the time representation used by Flutter Engine and CAMediaTime. +@interface FlutterTimeConverter : NSObject + +- (instancetype)initWithEngine:(FlutterEngine*)engine; + +- (uint64_t)CAMediaTimeToEngineTime:(CFTimeInterval)time; +- (CFTimeInterval)engineTimeToCAMediaTime:(uint64_t)time; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERTIMECONVERTER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTimeConverter.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTimeConverter.mm new file mode 100644 index 0000000000000000000000000000000000000000..e8f7ef042b8fd6303c409ee0f0ffc5940169ccd3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTimeConverter.mm @@ -0,0 +1,46 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTER_TIME_CONVERTER_MM_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTER_TIME_CONVERTER_MM_ + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTimeConverter.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" + +@interface FlutterTimeConverter () { + __weak FlutterEngine* _engine; +} +@end + +@implementation FlutterTimeConverter + +- (instancetype)initWithEngine:(FlutterEngine*)engine { + self = [super init]; + if (self) { + _engine = engine; + } + return self; +} + +- (uint64_t)CAMediaTimeToEngineTime:(CFTimeInterval)time { + FlutterEngine* engine = _engine; + if (!engine) { + return 0; + } + return (time - CACurrentMediaTime()) * NSEC_PER_SEC + engine.embedderAPI.GetCurrentTime(); +} + +- (CFTimeInterval)engineTimeToCAMediaTime:(uint64_t)time { + FlutterEngine* engine = _engine; + if (!engine) { + return 0; + } + return (static_cast(time) - static_cast(engine.embedderAPI.GetCurrentTime())) / + static_cast(NSEC_PER_SEC) + + CACurrentMediaTime(); +} + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTER_TIME_CONVERTER_MM_- diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterUmbrellaImportTests.m b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterUmbrellaImportTests.m new file mode 100644 index 0000000000000000000000000000000000000000..b81280d464c19c522886820644353dac6561c8a2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterUmbrellaImportTests.m @@ -0,0 +1,11 @@ +// 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. + +// FLUTTER_NOLINT: https://github.com/flutter/flutter/issues/93360 + +// The only point of this file is to ensure that the Flutter framework umbrella header can be +// cleanly imported from an Objective-C translation unit. The target that uses this file copies the +// headers to a path that simulates how users would actually import the framework outside of the +// engine source root. +#import diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterVSyncWaiter.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterVSyncWaiter.h new file mode 100644 index 0000000000000000000000000000000000000000..712a7bcfefc3f877f350e8df048892fdd39a196b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterVSyncWaiter.h @@ -0,0 +1,25 @@ +#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVSYNCWAITER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVSYNCWAITER_H_ + +#import + +@class FlutterDisplayLink; + +@interface FlutterVSyncWaiter : NSObject + +/// Creates new waiter instance tied to provided NSView. +/// This function must be called on the main thread. +/// +/// Provided |block| will be invoked on main thread. +- (instancetype)initWithDisplayLink:(FlutterDisplayLink*)displayLink + block:(void (^)(CFTimeInterval timestamp, + CFTimeInterval targetTimestamp, + uintptr_t baton))block; + +/// Schedules |baton| to be signaled on next display refresh. +/// This function must be called on the main thread. +- (void)waitForVSync:(uintptr_t)baton; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVSYNCWAITER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterVSyncWaiter.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterVSyncWaiter.mm new file mode 100644 index 0000000000000000000000000000000000000000..884ae112167a928cd280fdff3cdf335d309f5f3e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterVSyncWaiter.mm @@ -0,0 +1,166 @@ +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterVSyncWaiter.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDisplayLink.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterRunLoop.h" + +#include "flutter/fml/logging.h" + +#include +#include + +#if (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_PROFILE) +#define VSYNC_TRACING_ENABLED 1 +#endif + +#if VSYNC_TRACING_ENABLED +#include + +// Trace vsync events using os_signpost so that they can be seen in Instruments "Points of +// Interest". +#define TRACE_VSYNC(event_type, baton) \ + do { \ + os_log_t log = os_log_create("FlutterVSync", "PointsOfInterest"); \ + os_signpost_event_emit(log, OS_SIGNPOST_ID_EXCLUSIVE, event_type, "baton %lx", baton); \ + } while (0) +#else +#define TRACE_VSYNC(event_type, baton) \ + do { \ + } while (0) +#endif + +@interface FlutterVSyncWaiter () +@end + +// It's preferable to fire the timers slightly early than too late due to scheduling latency. +// 1ms before vsync should be late enough for all events to be processed. +static const CFTimeInterval kTimerLatencyCompensation = 0.001; + +@implementation FlutterVSyncWaiter { + std::optional _pendingBaton; + FlutterDisplayLink* _displayLink; + void (^_block)(CFTimeInterval, CFTimeInterval, uintptr_t); + CFTimeInterval _lastTargetTimestamp; + BOOL _warmUpFrame; +} + +- (instancetype)initWithDisplayLink:(FlutterDisplayLink*)displayLink + block:(void (^)(CFTimeInterval timestamp, + CFTimeInterval targetTimestamp, + uintptr_t baton))block { + FML_DCHECK([NSThread isMainThread]); + if (self = [super init]) { + _block = block; + + _displayLink = displayLink; + _displayLink.delegate = self; + // Get at least one callback to initialize _lastTargetTimestamp. + _displayLink.paused = NO; + _warmUpFrame = YES; + } + return self; +} + +// Called from display link thread. +- (void)onDisplayLink:(CFTimeInterval)timestamp targetTimestamp:(CFTimeInterval)targetTimestamp { + if (_lastTargetTimestamp == 0) { + // Initial vsync - timestamp will be used to determine vsync phase. + _lastTargetTimestamp = targetTimestamp; + _displayLink.paused = YES; + } else { + _lastTargetTimestamp = targetTimestamp; + + // CVDisplayLink callback is called one and a half frame before the target + // timestamp. That can cause frame-pacing issues if the frame is rendered too early, + // it may also trigger frame start before events are processed. + CFTimeInterval minStart = targetTimestamp - _displayLink.nominalOutputRefreshPeriod; + CFTimeInterval current = CACurrentMediaTime(); + CFTimeInterval remaining = std::max(minStart - current - kTimerLatencyCompensation, 0.0); + + TRACE_VSYNC("DisplayLinkCallback-Original", _pendingBaton.value_or(0)); + + [FlutterRunLoop.mainRunLoop + performBlock:^{ + if (!_pendingBaton.has_value()) { + TRACE_VSYNC("DisplayLinkPaused", size_t(0)); + _displayLink.paused = YES; + return; + } + TRACE_VSYNC("DisplayLinkCallback-Delayed", _pendingBaton.value_or(0)); + _block(minStart, targetTimestamp, *_pendingBaton); + _pendingBaton = std::nullopt; + } + afterDelay:remaining]; + } +} + +// Called from UI thread. +- (void)waitForVSync:(uintptr_t)baton { + FML_DCHECK([NSThread isMainThread]); + // CVDisplayLink start -> callback latency is two frames, there is + // no need to delay the warm-up frame. + if (_warmUpFrame) { + _warmUpFrame = NO; + TRACE_VSYNC("WarmUpFrame", baton); + CFTimeInterval now = CACurrentMediaTime(); + _block(now, now, baton); + return; + } + + if (_pendingBaton.has_value()) { + FML_LOG(WARNING) << "Engine requested vsync while another was pending"; + _block(0, 0, *_pendingBaton); + _pendingBaton = std::nullopt; + } + + TRACE_VSYNC("VSyncRequest", _pendingBaton.value_or(0)); + + CFTimeInterval tick_interval = _displayLink.nominalOutputRefreshPeriod; + if (_displayLink.paused || tick_interval == 0) { + // When starting display link the first notification will come in the middle + // of next frame, which would incur a whole frame period of latency. + // To avoid that, first vsync notification will be fired using a timer + // scheduled to fire where the next frame is expected to start. + // Also use a timer if display link does not belong to any display + // (nominalOutputRefreshPeriod being 0) + + // Start of the vsync interval. + CFTimeInterval start = CACurrentMediaTime(); + + // Timer delay is calculated as the time to the next frame start. + CFTimeInterval delay = 0; + + if (tick_interval != 0 && _lastTargetTimestamp != 0) { + CFTimeInterval phase = fmod(_lastTargetTimestamp, tick_interval); + CFTimeInterval now = start; + start = now - (fmod(now, tick_interval)) + phase; + if (start < now) { + start += tick_interval; + } + delay = std::max(start - now - kTimerLatencyCompensation, 0.0); + } + + [FlutterRunLoop.mainRunLoop + performBlock:^{ + CFTimeInterval targetTimestamp = start + tick_interval; + TRACE_VSYNC("SynthesizedInitialVSync", baton); + _block(start, targetTimestamp, baton); + } + afterDelay:delay]; + _displayLink.paused = NO; + } else { + _pendingBaton = baton; + } +} + +- (void)dealloc { + if (_pendingBaton.has_value()) { + FML_LOG(WARNING) << "Deallocating FlutterVSyncWaiter with a pending vsync"; + } + // It is possible that block running on UI thread held the last reference to + // the waiter, in which case reschedule to main thread. + FlutterDisplayLink* link = _displayLink; + dispatch_async(dispatch_get_main_queue(), ^{ + [link invalidate]; + }); +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterVSyncWaiterTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterVSyncWaiterTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..6e3882243f3ebce127eb957dcf5895ed95aa2b89 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterVSyncWaiterTest.mm @@ -0,0 +1,207 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDisplayLink.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterRunLoop.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterVSyncWaiter.h" + +#import "flutter/testing/testing.h" + +@interface TestDisplayLink : FlutterDisplayLink + +@property(nonatomic) CFTimeInterval nominalOutputRefreshPeriod; + +@end + +@implementation TestDisplayLink + +// Synthesize properties declared readonly in FlutterDisplayLink. +@synthesize nominalOutputRefreshPeriod = _nominalOutputRefreshPeriod; + +- (instancetype)init { + if (self = [super init]) { + self.paused = YES; + } + return self; +} + +- (void)tickWithTimestamp:(CFTimeInterval)timestamp + targetTimestamp:(CFTimeInterval)targetTimestamp { + [self.delegate onDisplayLink:timestamp targetTimestamp:targetTimestamp]; +} + +- (void)invalidate { +} + +@end + +class FlutterVSyncWaiterTest : public testing::Test { + public: + void SetUp() override { [FlutterRunLoop ensureMainLoopInitialized]; } +}; + +TEST_F(FlutterVSyncWaiterTest, RequestsInitialVSync) { + TestDisplayLink* displayLink = [[TestDisplayLink alloc] init]; + EXPECT_TRUE(displayLink.paused); + // When created waiter requests a reference vsync to determine vsync phase. + FlutterVSyncWaiter* waiter = [[FlutterVSyncWaiter alloc] + initWithDisplayLink:displayLink + block:^(CFTimeInterval timestamp, CFTimeInterval targetTimestamp, + uintptr_t baton){ + }]; + (void)waiter; + EXPECT_FALSE(displayLink.paused); + [displayLink tickWithTimestamp:CACurrentMediaTime() + targetTimestamp:CACurrentMediaTime() + 1.0 / 60.0]; + EXPECT_TRUE(displayLink.paused); +} + +static void BusyWait(CFTimeInterval duration) { + CFTimeInterval start = CACurrentMediaTime(); + while (CACurrentMediaTime() < start + duration) { + } +} + +// See FlutterVSyncWaiter.mm for the original definition. +static const CFTimeInterval kTimerLatencyCompensation = 0.001; + +TEST_F(FlutterVSyncWaiterTest, FirstVSyncIsSynthesized) { + TestDisplayLink* displayLink = [[TestDisplayLink alloc] init]; + displayLink.nominalOutputRefreshPeriod = 1.0 / 60.0; + + auto test = [&](CFTimeInterval waitDuration, CFTimeInterval expectedDelay) { + __block CFTimeInterval timestamp = 0; + __block CFTimeInterval targetTimestamp = 0; + __block size_t baton = 0; + const uintptr_t kWarmUpBaton = 0xFFFFFFFF; + FlutterVSyncWaiter* waiter = [[FlutterVSyncWaiter alloc] + initWithDisplayLink:displayLink + block:^(CFTimeInterval _timestamp, CFTimeInterval _targetTimestamp, + uintptr_t _baton) { + if (_baton == kWarmUpBaton) { + return; + } + timestamp = _timestamp; + targetTimestamp = _targetTimestamp; + baton = _baton; + EXPECT_TRUE(CACurrentMediaTime() >= _timestamp - kTimerLatencyCompensation); + CFRunLoopStop(CFRunLoopGetCurrent()); + }]; + + [waiter waitForVSync:kWarmUpBaton]; + + // Reference vsync to setup phase. + CFTimeInterval now = CACurrentMediaTime(); + // CVDisplayLink callback is called one and a half frame before the target. + [displayLink tickWithTimestamp:now + 0.5 * displayLink.nominalOutputRefreshPeriod + targetTimestamp:now + 2 * displayLink.nominalOutputRefreshPeriod]; + EXPECT_EQ(displayLink.paused, YES); + // Vsync was not requested yet, block should not have been called. + EXPECT_EQ(timestamp, 0); + + BusyWait(waitDuration); + + // Synthesized vsync should come in 1/60th of a second after the first. + CFTimeInterval expectedTimestamp = now + expectedDelay; + [waiter waitForVSync:1]; + + CFRunLoopRun(); + + EXPECT_DOUBLE_EQ(timestamp, expectedTimestamp); + EXPECT_DOUBLE_EQ(targetTimestamp, expectedTimestamp + displayLink.nominalOutputRefreshPeriod); + EXPECT_EQ(baton, size_t(1)); + }; + + // First argument if the wait duration after reference vsync. + // Second argument is the expected delay between reference vsync and synthesized vsync. + test(0.005, displayLink.nominalOutputRefreshPeriod); + test(0.025, 2 * displayLink.nominalOutputRefreshPeriod); + test(0.040, 3 * displayLink.nominalOutputRefreshPeriod); +} + +TEST_F(FlutterVSyncWaiterTest, VSyncWorks) { + TestDisplayLink* displayLink = [[TestDisplayLink alloc] init]; + displayLink.nominalOutputRefreshPeriod = 1.0 / 60.0; + const uintptr_t kWarmUpBaton = 0xFFFFFFFF; + + struct Entry { + CFTimeInterval timestamp; + CFTimeInterval targetTimestamp; + size_t baton; + }; + __block std::vector entries; + + FlutterVSyncWaiter* waiter = [[FlutterVSyncWaiter alloc] + initWithDisplayLink:displayLink + block:^(CFTimeInterval timestamp, CFTimeInterval targetTimestamp, + uintptr_t baton) { + entries.push_back({timestamp, targetTimestamp, baton}); + if (baton == kWarmUpBaton) { + return; + } + EXPECT_TRUE(CACurrentMediaTime() >= timestamp - kTimerLatencyCompensation); + CFRunLoopStop(CFRunLoopGetCurrent()); + }]; + + __block CFTimeInterval expectedStartUntil; + // Warm up tick is scheduled immediately in a scheduled block. Schedule another + // block here to determine the maximum time when the warm up tick should be + // scheduled. + [waiter waitForVSync:kWarmUpBaton]; + [[NSRunLoop currentRunLoop] performBlock:^{ + expectedStartUntil = CACurrentMediaTime(); + }]; + + // Reference vsync to setup phase. + CFTimeInterval now = CACurrentMediaTime(); + // CVDisplayLink callback is called one and a half frame before the target. + [displayLink tickWithTimestamp:now + 0.5 * displayLink.nominalOutputRefreshPeriod + targetTimestamp:now + 2 * displayLink.nominalOutputRefreshPeriod]; + EXPECT_EQ(displayLink.paused, YES); + + [waiter waitForVSync:1]; + CFRunLoopRun(); + + [waiter waitForVSync:2]; + [displayLink tickWithTimestamp:now + 1.5 * displayLink.nominalOutputRefreshPeriod + targetTimestamp:now + 3 * displayLink.nominalOutputRefreshPeriod]; + CFRunLoopRun(); + + [waiter waitForVSync:3]; + [displayLink tickWithTimestamp:now + 2.5 * displayLink.nominalOutputRefreshPeriod + targetTimestamp:now + 4 * displayLink.nominalOutputRefreshPeriod]; + CFRunLoopRun(); + + EXPECT_FALSE(displayLink.paused); + // Vsync without baton should pause the display link. + [displayLink tickWithTimestamp:now + 3.5 * displayLink.nominalOutputRefreshPeriod + targetTimestamp:now + 5 * displayLink.nominalOutputRefreshPeriod]; + + CFTimeInterval start = CACurrentMediaTime(); + while (!displayLink.paused) { + // Make sure to run the timer scheduled in display link callback. + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.02, NO); + if (CACurrentMediaTime() - start > 1.0) { + break; + } + } + ASSERT_TRUE(displayLink.paused); + + EXPECT_EQ(entries.size(), size_t(4)); + + // Warm up frame should be presented as soon as possible. + EXPECT_TRUE(entries[0].timestamp <= expectedStartUntil); + EXPECT_TRUE(entries[0].targetTimestamp <= expectedStartUntil); + EXPECT_EQ(entries[0].baton, kWarmUpBaton); + + EXPECT_DOUBLE_EQ(entries[1].timestamp, now + displayLink.nominalOutputRefreshPeriod); + EXPECT_DOUBLE_EQ(entries[1].targetTimestamp, now + 2 * displayLink.nominalOutputRefreshPeriod); + EXPECT_EQ(entries[1].baton, size_t(1)); + EXPECT_DOUBLE_EQ(entries[2].timestamp, now + 2 * displayLink.nominalOutputRefreshPeriod); + EXPECT_DOUBLE_EQ(entries[2].targetTimestamp, now + 3 * displayLink.nominalOutputRefreshPeriod); + EXPECT_EQ(entries[2].baton, size_t(2)); + EXPECT_DOUBLE_EQ(entries[3].timestamp, now + 3 * displayLink.nominalOutputRefreshPeriod); + EXPECT_DOUBLE_EQ(entries[3].targetTimestamp, now + 4 * displayLink.nominalOutputRefreshPeriod); + EXPECT_EQ(entries[3].baton, size_t(3)); +} diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterView.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterView.h new file mode 100644 index 0000000000000000000000000000000000000000..35b3430d9d0900752d390889e842421f45dc007a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterView.h @@ -0,0 +1,81 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVIEW_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVIEW_H_ + +#import + +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManager.h" + +#include + +/** + * Delegate for FlutterView. + */ +@protocol FlutterViewDelegate +/** + * Called when the view's backing store changes size. + */ +- (void)viewDidReshape:(nonnull NSView*)view; + +/** + * Called to determine whether the view should accept first responder status. + */ +- (BOOL)viewShouldAcceptFirstResponder:(nonnull NSView*)view; + +@end + +/** + * View capable of acting as a rendering target and input source for the Flutter + * engine. + */ +@interface FlutterView : NSView + +/** + * Initialize a FlutterView that will be rendered to using Metal rendering apis. + */ +- (nullable instancetype)initWithMTLDevice:(nonnull id)device + commandQueue:(nonnull id)commandQueue + delegate:(nonnull id)delegate + viewIdentifier:(FlutterViewIdentifier)viewIdentifier + NS_DESIGNATED_INITIALIZER; + +- (nullable instancetype)initWithFrame:(NSRect)frameRect + pixelFormat:(nullable NSOpenGLPixelFormat*)format NS_UNAVAILABLE; +- (nonnull instancetype)initWithFrame:(NSRect)frameRect NS_UNAVAILABLE; +- (nullable instancetype)initWithCoder:(nonnull NSCoder*)coder NS_UNAVAILABLE; +- (nonnull instancetype)init NS_UNAVAILABLE; + +/** + * Returns SurfaceManager for this view. SurfaceManager is responsible for + * providing and presenting render surfaces. + */ +@property(readonly, nonatomic, nonnull) FlutterSurfaceManager* surfaceManager; + +/** + * By default, the `FlutterSurfaceManager` creates two layers to manage Flutter + * content, the content layer and containing layer. To set the native background + * color, onto which the Flutter content is drawn, call this method with the + * NSColor which you would like to override the default, black background color + * with. + */ +- (void)setBackgroundColor:(nonnull NSColor*)color; + +/** + * Called from the engine to notify the view that mouse cursor was updated while + * the mouse is over the view. The view is responsible from restoring the cursor + * when the mouse enters the view from another subview. + */ +- (void)didUpdateMouseCursor:(nonnull NSCursor*)cursor; + +/** + * Called from the controller to unblock resize synchronizer when shutting down. + */ +- (void)shutDown; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVIEW_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterView.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterView.mm new file mode 100644 index 0000000000000000000000000000000000000000..756e9e9d719feb85c8890a9c706bf2999e147363 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterView.mm @@ -0,0 +1,157 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterView.h" + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterResizeSynchronizer.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManager.h" + +#import + +@interface FlutterView () { + FlutterViewIdentifier _viewIdentifier; + __weak id _viewDelegate; + FlutterResizeSynchronizer* _resizeSynchronizer; + FlutterSurfaceManager* _surfaceManager; + NSCursor* _lastCursor; +} + +@end + +@implementation FlutterView + +- (instancetype)initWithMTLDevice:(id)device + commandQueue:(id)commandQueue + delegate:(id)delegate + viewIdentifier:(FlutterViewIdentifier)viewIdentifier { + self = [super initWithFrame:NSZeroRect]; + if (self) { + [self setWantsLayer:YES]; + [self setBackgroundColor:[NSColor blackColor]]; + [self setLayerContentsRedrawPolicy:NSViewLayerContentsRedrawDuringViewResize]; + _viewIdentifier = viewIdentifier; + _viewDelegate = delegate; + _surfaceManager = [[FlutterSurfaceManager alloc] initWithDevice:device + commandQueue:commandQueue + layer:self.layer + delegate:self]; + _resizeSynchronizer = [[FlutterResizeSynchronizer alloc] init]; + } + return self; +} + +- (void)onPresent:(CGSize)frameSize withBlock:(dispatch_block_t)block delay:(NSTimeInterval)delay { + [_resizeSynchronizer performCommitForSize:frameSize notify:block delay:delay]; +} + +- (FlutterSurfaceManager*)surfaceManager { + return _surfaceManager; +} + +- (void)shutDown { + [_resizeSynchronizer shutDown]; +} + +- (void)setBackgroundColor:(NSColor*)color { + self.layer.backgroundColor = color.CGColor; +} + +#pragma mark - NSView overrides + +- (void)setFrameSize:(NSSize)newSize { + [super setFrameSize:newSize]; + CGSize scaledSize = [self convertSizeToBacking:self.bounds.size]; + [_resizeSynchronizer beginResizeForSize:scaledSize + notify:^{ + [_viewDelegate viewDidReshape:self]; + }]; +} + +/** + * Declares that the view uses a flipped coordinate system, consistent with Flutter conventions. + */ +- (BOOL)isFlipped { + return YES; +} + +- (BOOL)isOpaque { + return YES; +} + +/** + * Declares that the initial mouse-down when the view is not in focus will send an event to the + * view. + */ +- (BOOL)acceptsFirstMouse:(NSEvent*)event { + return YES; +} + +- (BOOL)acceptsFirstResponder { + // This is to ensure that FlutterView does not take first responder status from TextInputPlugin + // on mouse clicks. + return [_viewDelegate viewShouldAcceptFirstResponder:self]; +} + +- (void)didUpdateMouseCursor:(NSCursor*)cursor { + _lastCursor = cursor; +} + +// Restores mouse cursor. There are few cases when this is needed and framework will not handle +// this automatically: +// - When mouse cursor leaves subview of FlutterView (technically still within bound of +// FlutterView tracking area so the framework won't be notified) +// - When context menu above FlutterView is closed. Context menu will change current cursor to +// arrow and will not restore it back. +- (void)cursorUpdate:(NSEvent*)event { + // Make sure to not override cursor when over a platform view. + NSPoint mouseLocation = [[self superview] convertPoint:event.locationInWindow fromView:nil]; + NSView* hitTestView = [self hitTest:mouseLocation]; + if (hitTestView != self) { + return; + } + [_lastCursor set]; + // It is possible that there is a platform view with NSTrackingArea below flutter content. + // This could override the mouse cursor as a result of mouse move event. There is no good way + // to prevent that short of swizzling [NSCursor set], so as a workaround force flutter cursor + // in next runloop turn. This is not ideal, as it may cause the cursor flicker a bit. + [[NSRunLoop currentRunLoop] performBlock:^{ + [_lastCursor set]; + }]; +} + +- (void)viewDidChangeBackingProperties { + [super viewDidChangeBackingProperties]; + // Force redraw + [_viewDelegate viewDidReshape:self]; +} + +- (BOOL)layer:(CALayer*)layer + shouldInheritContentsScale:(CGFloat)newScale + fromWindow:(NSWindow*)window { + return YES; +} + +#pragma mark - NSAccessibility overrides + +- (BOOL)isAccessibilityElement { + return YES; +} + +- (NSAccessibilityRole)accessibilityRole { + return NSAccessibilityGroupRole; +} + +- (NSString*)accessibilityLabel { + // TODO(chunhtai): Provides a way to let developer customize the accessibility + // label. + // https://github.com/flutter/flutter/issues/75446 + NSString* applicationName = + [NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleDisplayName"]; + if (!applicationName) { + applicationName = [NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleName"]; + } + return applicationName; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController.mm new file mode 100644 index 0000000000000000000000000000000000000000..5346c452dae708008c87201754f0e11e9d458071 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController.mm @@ -0,0 +1,965 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" + +#include +#import + +#include "flutter/common/constants.h" +#include "flutter/fml/platform/darwin/cf_utils.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h" +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyPrimaryResponder.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderer.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterView.h" +#include "flutter/shell/platform/embedder/embedder.h" + +#pragma mark - Static types and data. + +namespace { + +// Use different device ID for mouse and pan/zoom events, since we can't differentiate the actual +// device (mouse v.s. trackpad). +static constexpr int32_t kMousePointerDeviceId = 0; +static constexpr int32_t kPointerPanZoomDeviceId = 1; + +// A trackpad touch following inertial scrolling should cause an inertia cancel +// event to be issued. Use a window of 50 milliseconds after the scroll to account +// for delays in event propagation observed in macOS Ventura. +static constexpr double kTrackpadTouchInertiaCancelWindowMs = 0.050; + +/** + * State tracking for mouse events, to adapt between the events coming from the system and the + * events that the embedding API expects. + */ +struct MouseState { + /** + * The currently pressed buttons, as represented in FlutterPointerEvent. + */ + int64_t buttons = 0; + + /** + * The accumulated gesture pan. + */ + CGFloat delta_x = 0; + CGFloat delta_y = 0; + + /** + * The accumulated gesture zoom scale. + */ + CGFloat scale = 0; + + /** + * The accumulated gesture rotation. + */ + CGFloat rotation = 0; + + /** + * Whether or not a kAdd event has been sent (or sent again since the last kRemove if tracking is + * enabled). Used to determine whether to send a kAdd event before sending an incoming mouse + * event, since Flutter expects pointers to be added before events are sent for them. + */ + bool flutter_state_is_added = false; + + /** + * Whether or not a kDown has been sent since the last kAdd/kUp. + */ + bool flutter_state_is_down = false; + + /** + * Whether or not mouseExited: was received while a button was down. Cocoa's behavior when + * dragging out of a tracked area is to send an exit, then keep sending drag events until the last + * button is released. Flutter doesn't expect to receive events after a kRemove, so the kRemove + * for the exit needs to be delayed until after the last mouse button is released. If cursor + * returns back to the window while still dragging, the flag is cleared in mouseEntered:. + */ + bool has_pending_exit = false; + + /* + * Whether or not a kPanZoomStart has been sent since the last kAdd/kPanZoomEnd. + */ + bool flutter_state_is_pan_zoom_started = false; + + /** + * State of pan gesture. + */ + NSEventPhase pan_gesture_phase = NSEventPhaseNone; + + /** + * State of scale gesture. + */ + NSEventPhase scale_gesture_phase = NSEventPhaseNone; + + /** + * State of rotate gesture. + */ + NSEventPhase rotate_gesture_phase = NSEventPhaseNone; + + /** + * Time of last scroll momentum event. + */ + NSTimeInterval last_scroll_momentum_changed_time = 0; + + /** + * Resets all gesture state to default values. + */ + void GestureReset() { + delta_x = 0; + delta_y = 0; + scale = 0; + rotation = 0; + flutter_state_is_pan_zoom_started = false; + pan_gesture_phase = NSEventPhaseNone; + scale_gesture_phase = NSEventPhaseNone; + rotate_gesture_phase = NSEventPhaseNone; + } + + /** + * Resets all state to default values. + */ + void Reset() { + flutter_state_is_added = false; + flutter_state_is_down = false; + has_pending_exit = false; + buttons = 0; + } +}; + +} // namespace + +#pragma mark - Private interface declaration. + +/** + * FlutterViewWrapper is a convenience class that wraps a FlutterView and provides + * a mechanism to attach AppKit views such as FlutterTextField without affecting + * the accessibility subtree of the wrapped FlutterView itself. + * + * The FlutterViewController uses this class to create its content view. When + * any of the accessibility services (e.g. VoiceOver) is turned on, the accessibility + * bridge creates FlutterTextFields that interact with the service. The bridge has to + * attach the FlutterTextField somewhere in the view hierarchy in order for the + * FlutterTextField to interact correctly with VoiceOver. Those FlutterTextFields + * will be attached to this view so that they won't affect the accessibility subtree + * of FlutterView. + */ +@interface FlutterViewWrapper : NSView + +- (void)setBackgroundColor:(NSColor*)color; + +@end + +/** + * Private interface declaration for FlutterViewController. + */ +@interface FlutterViewController () + +/** + * The tracking area used to generate hover events, if enabled. + */ +@property(nonatomic) NSTrackingArea* trackingArea; + +/** + * The current state of the mouse and the sent mouse events. + */ +@property(nonatomic) MouseState mouseState; + +/** + * Event monitor for keyUp events. + */ +@property(nonatomic) id keyUpMonitor; + +/** + * Starts running |engine|, including any initial setup. + */ +- (BOOL)launchEngine; + +/** + * Updates |trackingArea| for the current tracking settings, creating it with + * the correct mode if tracking is enabled, or removing it if not. + */ +- (void)configureTrackingArea; + +/** + * Calls dispatchMouseEvent:phase: with a phase determined by self.mouseState. + * + * mouseState.buttons should be updated before calling this method. + */ +- (void)dispatchMouseEvent:(nonnull NSEvent*)event; + +/** + * Calls dispatchMouseEvent:phase: with a phase determined by event.phase. + */ +- (void)dispatchGestureEvent:(nonnull NSEvent*)event; + +/** + * Converts |event| to a FlutterPointerEvent with the given phase, and sends it to the engine. + */ +- (void)dispatchMouseEvent:(nonnull NSEvent*)event phase:(FlutterPointerPhase)phase; + +@end + +#pragma mark - FlutterViewWrapper implementation. + +@implementation FlutterViewWrapper { + FlutterView* _flutterView; + __weak FlutterViewController* _controller; +} + +- (instancetype)initWithFlutterView:(FlutterView*)view + controller:(FlutterViewController*)controller { + self = [super initWithFrame:NSZeroRect]; + if (self) { + _flutterView = view; + _controller = controller; + view.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable; + [self addSubview:view]; + } + return self; +} + +- (void)setBackgroundColor:(NSColor*)color { + [_flutterView setBackgroundColor:color]; +} + +- (BOOL)performKeyEquivalent:(NSEvent*)event { + // Do not intercept the event if flutterView is not first responder, otherwise this would + // interfere with TextInputPlugin, which also handles key equivalents. + // + // Also do not intercept the event if key equivalent is a product of an event being + // redispatched by the TextInputPlugin, in which case it needs to bubble up so that menus + // can handle key equivalents. + if (self.window.firstResponder != _flutterView || [_controller isDispatchingKeyEvent:event]) { + return [super performKeyEquivalent:event]; + } + [_flutterView keyDown:event]; + return YES; +} + +- (NSArray*)accessibilityChildren { + return @[ _flutterView ]; +} + +// TODO(cbracken): https://github.com/flutter/flutter/issues/154063 +// Remove this whole method override when we drop support for macOS 12 (Monterey). +- (void)mouseDown:(NSEvent*)event { + if (@available(macOS 13.3.1, *)) { + [super mouseDown:event]; + } else { + // Work around an AppKit bug where mouseDown/mouseUp are not called on the view controller if + // the view is the content view of an NSPopover AND macOS's Reduced Transparency accessibility + // setting is enabled. + // + // This simply calls mouseDown on the next responder in the responder chain as the default + // implementation on NSResponder is documented to do. + // + // See: https://github.com/flutter/flutter/issues/115015 + // See: http://www.openradar.me/FB12050037 + // See: https://developer.apple.com/documentation/appkit/nsresponder/1524634-mousedown + [self.nextResponder mouseDown:event]; + } +} + +// TODO(cbracken): https://github.com/flutter/flutter/issues/154063 +// Remove this workaround when we drop support for macOS 12 (Monterey). +- (void)mouseUp:(NSEvent*)event { + if (@available(macOS 13.3.1, *)) { + [super mouseUp:event]; + } else { + // Work around an AppKit bug where mouseDown/mouseUp are not called on the view controller if + // the view is the content view of an NSPopover AND macOS's Reduced Transparency accessibility + // setting is enabled. + // + // This simply calls mouseUp on the next responder in the responder chain as the default + // implementation on NSResponder is documented to do. + // + // See: https://github.com/flutter/flutter/issues/115015 + // See: http://www.openradar.me/FB12050037 + // See: https://developer.apple.com/documentation/appkit/nsresponder/1535349-mouseup + [self.nextResponder mouseUp:event]; + } +} + +@end + +#pragma mark - FlutterViewController implementation. + +@implementation FlutterViewController { + // The project to run in this controller's engine. + FlutterDartProject* _project; + + std::shared_ptr _bridge; +} + +// Synthesize properties declared readonly. +@synthesize viewIdentifier = _viewIdentifier; + +@dynamic accessibilityBridge; + +// Returns the text input plugin associated with this view controller. +// This method only returns non nil instance if the text input plugin has active +// client with viewId matching this controller's view identifier. +- (FlutterTextInputPlugin*)activeTextInputPlugin { + if (_engine.textInputPlugin.currentViewController == self) { + return _engine.textInputPlugin; + } else { + return nil; + } +} + +/** + * Performs initialization that's common between the different init paths. + */ +static void CommonInit(FlutterViewController* controller, FlutterEngine* engine) { + if (!engine) { + engine = [[FlutterEngine alloc] initWithName:@"io.flutter" + project:controller->_project + allowHeadlessExecution:NO]; + } + NSCAssert(controller.engine == nil, + @"The FlutterViewController is unexpectedly attached to " + @"engine %@ before initialization.", + controller.engine); + [engine addViewController:controller]; + NSCAssert(controller.engine != nil, + @"The FlutterViewController unexpectedly stays unattached after initialization. " + @"In unit tests, this is likely because either the FlutterViewController or " + @"the FlutterEngine is mocked. Please subclass these classes instead.", + controller.engine, controller.viewIdentifier); + controller->_mouseTrackingMode = kFlutterMouseTrackingModeInKeyWindow; + [controller notifySemanticsEnabledChanged]; +} + +- (instancetype)initWithCoder:(NSCoder*)coder { + self = [super initWithCoder:coder]; + NSAssert(self, @"Super init cannot be nil"); + + CommonInit(self, nil); + return self; +} + +- (instancetype)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil { + self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; + NSAssert(self, @"Super init cannot be nil"); + + CommonInit(self, nil); + return self; +} + +- (instancetype)initWithProject:(nullable FlutterDartProject*)project { + self = [super initWithNibName:nil bundle:nil]; + NSAssert(self, @"Super init cannot be nil"); + + _project = project; + CommonInit(self, nil); + return self; +} + +- (instancetype)initWithEngine:(nonnull FlutterEngine*)engine + nibName:(nullable NSString*)nibName + bundle:(nullable NSBundle*)nibBundle { + NSAssert(engine != nil, @"Engine is required"); + + self = [super initWithNibName:nibName bundle:nibBundle]; + if (self) { + CommonInit(self, engine); + } + + return self; +} + +- (BOOL)isDispatchingKeyEvent:(NSEvent*)event { + return [_engine.keyboardManager isDispatchingKeyEvent:event]; +} + +- (void)loadView { + FlutterView* flutterView; + id device = _engine.renderer.device; + id commandQueue = _engine.renderer.commandQueue; + if (!device || !commandQueue) { + NSLog(@"Unable to create FlutterView; no MTLDevice or MTLCommandQueue available."); + return; + } + flutterView = [self createFlutterViewWithMTLDevice:device commandQueue:commandQueue]; + if (_backgroundColor != nil) { + [flutterView setBackgroundColor:_backgroundColor]; + } + FlutterViewWrapper* wrapperView = [[FlutterViewWrapper alloc] initWithFlutterView:flutterView + controller:self]; + self.view = wrapperView; + _flutterView = flutterView; +} + +- (void)viewDidLoad { + [self configureTrackingArea]; + [self.view setAllowedTouchTypes:NSTouchTypeMaskIndirect]; + [self.view setWantsRestingTouches:YES]; + [_engine viewControllerViewDidLoad:self]; +} + +- (void)viewWillAppear { + [super viewWillAppear]; + if (!_engine.running) { + [self launchEngine]; + } + [self listenForMetaModifiedKeyUpEvents]; +} + +- (void)viewWillDisappear { + // Per Apple's documentation, it is discouraged to call removeMonitor: in dealloc, and it's + // recommended to be called earlier in the lifecycle. + [NSEvent removeMonitor:_keyUpMonitor]; + _keyUpMonitor = nil; +} + +- (void)dealloc { + if ([self attached]) { + [_engine removeViewController:self]; + } + [self.flutterView shutDown]; +} + +#pragma mark - Public methods + +- (void)setMouseTrackingMode:(FlutterMouseTrackingMode)mode { + if (_mouseTrackingMode == mode) { + return; + } + _mouseTrackingMode = mode; + [self configureTrackingArea]; +} + +- (void)setBackgroundColor:(NSColor*)color { + _backgroundColor = color; + [_flutterView setBackgroundColor:_backgroundColor]; +} + +- (FlutterViewIdentifier)viewIdentifier { + NSAssert([self attached], @"This view controller is not attached."); + return _viewIdentifier; +} + +- (void)onPreEngineRestart { +} + +- (void)notifySemanticsEnabledChanged { + BOOL mySemanticsEnabled = !!_bridge; + BOOL newSemanticsEnabled = _engine.semanticsEnabled; + if (newSemanticsEnabled == mySemanticsEnabled) { + return; + } + if (newSemanticsEnabled) { + _bridge = [self createAccessibilityBridgeWithEngine:_engine]; + } else { + // Remove the accessibility children from flutter view before resetting the bridge. + _flutterView.accessibilityChildren = nil; + _bridge.reset(); + } + NSAssert(newSemanticsEnabled == !!_bridge, @"Failed to update semantics for the view."); +} + +- (std::weak_ptr)accessibilityBridge { + return _bridge; +} + +- (void)setUpWithEngine:(FlutterEngine*)engine + viewIdentifier:(FlutterViewIdentifier)viewIdentifier { + NSAssert(_engine == nil, @"Already attached to an engine %@.", _engine); + _engine = engine; + _viewIdentifier = viewIdentifier; +} + +- (void)detachFromEngine { + NSAssert(_engine != nil, @"Not attached to any engine."); + _engine = nil; +} + +- (BOOL)attached { + return _engine != nil; +} + +- (void)updateSemantics:(const FlutterSemanticsUpdate2*)update { + // Semantics will be disabled when unfocusing application but the updateSemantics: + // callback is received in next run loop turn. + if (!_engine.semanticsEnabled) { + return; + } + for (size_t i = 0; i < update->node_count; i++) { + const FlutterSemanticsNode2* node = update->nodes[i]; + _bridge->AddFlutterSemanticsNodeUpdate(*node); + } + + for (size_t i = 0; i < update->custom_action_count; i++) { + const FlutterSemanticsCustomAction2* action = update->custom_actions[i]; + _bridge->AddFlutterSemanticsCustomActionUpdate(*action); + } + + _bridge->CommitUpdates(); + + // Accessibility tree can only be used when the view is loaded. + if (!self.viewLoaded) { + return; + } + // Attaches the accessibility root to the flutter view. + auto root = _bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); + if (root) { + if ([self.flutterView.accessibilityChildren count] == 0) { + NSAccessibilityElement* native_root = root->GetNativeViewAccessible(); + self.flutterView.accessibilityChildren = @[ native_root ]; + } + } else { + self.flutterView.accessibilityChildren = nil; + } +} + +#pragma mark - Private methods + +- (BOOL)launchEngine { + if (![_engine runWithEntrypoint:nil]) { + return NO; + } + return YES; +} + +// macOS does not call keyUp: on a key while the command key is pressed. This results in a loss +// of a key event once the modified key is released. This method registers the +// ViewController as a listener for a keyUp event before it's handled by NSApplication, and should +// NOT modify the event to avoid any unexpected behavior. +- (void)listenForMetaModifiedKeyUpEvents { + if (_keyUpMonitor != nil) { + // It is possible for [NSViewController viewWillAppear] to be invoked multiple times + // in a row. https://github.com/flutter/flutter/issues/105963 + return; + } + FlutterViewController* __weak weakSelf = self; + _keyUpMonitor = [NSEvent + addLocalMonitorForEventsMatchingMask:NSEventMaskKeyUp + handler:^NSEvent*(NSEvent* event) { + // Intercept keyUp only for events triggered on the current + // view or textInputPlugin. + NSResponder* firstResponder = [[event window] firstResponder]; + if (weakSelf.viewLoaded && weakSelf.flutterView && + (firstResponder == weakSelf.flutterView || + firstResponder == weakSelf.activeTextInputPlugin) && + ([event modifierFlags] & NSEventModifierFlagCommand) && + ([event type] == NSEventTypeKeyUp)) { + [weakSelf keyUp:event]; + } + return event; + }]; +} + +- (void)configureTrackingArea { + if (!self.viewLoaded) { + // The viewDidLoad will call configureTrackingArea again when + // the view is actually loaded. + return; + } + if (_mouseTrackingMode != kFlutterMouseTrackingModeNone && self.flutterView) { + NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | + NSTrackingInVisibleRect | NSTrackingEnabledDuringMouseDrag; + switch (_mouseTrackingMode) { + case kFlutterMouseTrackingModeInKeyWindow: + options |= NSTrackingActiveInKeyWindow; + break; + case kFlutterMouseTrackingModeInActiveApp: + options |= NSTrackingActiveInActiveApp; + break; + case kFlutterMouseTrackingModeAlways: + options |= NSTrackingActiveAlways; + break; + default: + NSLog(@"Error: Unrecognized mouse tracking mode: %ld", _mouseTrackingMode); + return; + } + _trackingArea = [[NSTrackingArea alloc] initWithRect:NSZeroRect + options:options + owner:self + userInfo:nil]; + [self.flutterView addTrackingArea:_trackingArea]; + } else if (_trackingArea) { + [self.flutterView removeTrackingArea:_trackingArea]; + _trackingArea = nil; + } +} + +- (void)dispatchMouseEvent:(nonnull NSEvent*)event { + FlutterPointerPhase phase = _mouseState.buttons == 0 + ? (_mouseState.flutter_state_is_down ? kUp : kHover) + : (_mouseState.flutter_state_is_down ? kMove : kDown); + [self dispatchMouseEvent:event phase:phase]; +} + +- (void)dispatchGestureEvent:(nonnull NSEvent*)event { + if (event.phase == NSEventPhaseBegan || event.phase == NSEventPhaseMayBegin) { + [self dispatchMouseEvent:event phase:kPanZoomStart]; + } else if (event.phase == NSEventPhaseChanged) { + [self dispatchMouseEvent:event phase:kPanZoomUpdate]; + } else if (event.phase == NSEventPhaseEnded || event.phase == NSEventPhaseCancelled) { + [self dispatchMouseEvent:event phase:kPanZoomEnd]; + } else if (event.phase == NSEventPhaseNone && event.momentumPhase == NSEventPhaseNone) { + [self dispatchMouseEvent:event phase:kHover]; + } else { + // Waiting until the first momentum change event is a workaround for an issue where + // touchesBegan: is called unexpectedly while in low power mode within the interval between + // momentum start and the first momentum change. + if (event.momentumPhase == NSEventPhaseChanged) { + _mouseState.last_scroll_momentum_changed_time = event.timestamp; + } + // Skip momentum update events, the framework will generate scroll momentum. + NSAssert(event.momentumPhase != NSEventPhaseNone, + @"Received gesture event with unexpected phase"); + } +} + +- (void)dispatchMouseEvent:(NSEvent*)event phase:(FlutterPointerPhase)phase { + NSAssert(self.viewLoaded, @"View must be loaded before it handles the mouse event"); + // There are edge cases where the system will deliver enter out of order relative to other + // events (e.g., drag out and back in, release, then click; mouseDown: will be called before + // mouseEntered:). Discard those events, since the add will already have been synthesized. + if (_mouseState.flutter_state_is_added && phase == kAdd) { + return; + } + + // Multiple gesture recognizers could be active at once, we can't send multiple kPanZoomStart. + // For example: rotation and magnification. + if (phase == kPanZoomStart || phase == kPanZoomEnd) { + if (event.type == NSEventTypeScrollWheel) { + _mouseState.pan_gesture_phase = event.phase; + } else if (event.type == NSEventTypeMagnify) { + _mouseState.scale_gesture_phase = event.phase; + } else if (event.type == NSEventTypeRotate) { + _mouseState.rotate_gesture_phase = event.phase; + } + } + if (phase == kPanZoomStart) { + if (event.type == NSEventTypeScrollWheel) { + // Ensure scroll inertia cancel event is not sent afterwards. + _mouseState.last_scroll_momentum_changed_time = 0; + } + if (_mouseState.flutter_state_is_pan_zoom_started) { + // Already started on a previous gesture type + return; + } + _mouseState.flutter_state_is_pan_zoom_started = true; + } + if (phase == kPanZoomEnd) { + if (!_mouseState.flutter_state_is_pan_zoom_started) { + // NSEventPhaseCancelled is sometimes received at incorrect times in the state + // machine, just ignore it here if it doesn't make sense + // (we have no active gesture to cancel). + NSAssert(event.phase == NSEventPhaseCancelled, + @"Received gesture event with unexpected phase"); + return; + } + // NSEventPhase values are powers of two, we can use this to inspect merged phases. + NSEventPhase all_gestures_fields = _mouseState.pan_gesture_phase | + _mouseState.scale_gesture_phase | + _mouseState.rotate_gesture_phase; + NSEventPhase active_mask = NSEventPhaseBegan | NSEventPhaseChanged; + if ((all_gestures_fields & active_mask) != 0) { + // Even though this gesture type ended, a different type is still active. + return; + } + } + + // If a pointer added event hasn't been sent, synthesize one using this event for the basic + // information. + if (!_mouseState.flutter_state_is_added && phase != kAdd) { + // Only the values extracted for use in flutterEvent below matter, the rest are dummy values. + NSEvent* addEvent = [NSEvent enterExitEventWithType:NSEventTypeMouseEntered + location:event.locationInWindow + modifierFlags:0 + timestamp:event.timestamp + windowNumber:event.windowNumber + context:nil + eventNumber:0 + trackingNumber:0 + userData:NULL]; + [self dispatchMouseEvent:addEvent phase:kAdd]; + } + + NSPoint locationInView = [self.flutterView convertPoint:event.locationInWindow fromView:nil]; + NSPoint locationInBackingCoordinates = [self.flutterView convertPointToBacking:locationInView]; + int32_t device = kMousePointerDeviceId; + FlutterPointerDeviceKind deviceKind = kFlutterPointerDeviceKindMouse; + if (phase == kPanZoomStart || phase == kPanZoomUpdate || phase == kPanZoomEnd) { + device = kPointerPanZoomDeviceId; + deviceKind = kFlutterPointerDeviceKindTrackpad; + } + FlutterPointerEvent flutterEvent = { + .struct_size = sizeof(flutterEvent), + .phase = phase, + .timestamp = static_cast(event.timestamp * USEC_PER_SEC), + .x = locationInBackingCoordinates.x, + .y = -locationInBackingCoordinates.y, // convertPointToBacking makes this negative. + .device = device, + .device_kind = deviceKind, + // If a click triggered a synthesized kAdd, don't pass the buttons in that event. + .buttons = phase == kAdd ? 0 : _mouseState.buttons, + .view_id = static_cast(_viewIdentifier), + }; + + if (phase == kPanZoomUpdate) { + if (event.type == NSEventTypeScrollWheel) { + _mouseState.delta_x += event.scrollingDeltaX * self.flutterView.layer.contentsScale; + _mouseState.delta_y += event.scrollingDeltaY * self.flutterView.layer.contentsScale; + } else if (event.type == NSEventTypeMagnify) { + _mouseState.scale += event.magnification; + } else if (event.type == NSEventTypeRotate) { + _mouseState.rotation += event.rotation * (-M_PI / 180.0); + } + flutterEvent.pan_x = _mouseState.delta_x; + flutterEvent.pan_y = _mouseState.delta_y; + // Scale value needs to be normalized to range 0->infinity. + flutterEvent.scale = pow(2.0, _mouseState.scale); + flutterEvent.rotation = _mouseState.rotation; + } else if (phase == kPanZoomEnd) { + _mouseState.GestureReset(); + } else if (phase != kPanZoomStart && event.type == NSEventTypeScrollWheel) { + flutterEvent.signal_kind = kFlutterPointerSignalKindScroll; + + double pixelsPerLine = 1.0; + if (!event.hasPreciseScrollingDeltas) { + // The scrollingDelta needs to be multiplied by the line height. + // CGEventSourceGetPixelsPerLine() will return 10, which will result in + // scrolling that is noticeably slower than in other applications. + // Using 40.0 as the multiplier to match Chromium. + // See https://source.chromium.org/chromium/chromium/src/+/main:ui/events/cocoa/events_mac.mm + pixelsPerLine = 40.0; + } + double scaleFactor = self.flutterView.layer.contentsScale; + // When mouse input is received while shift is pressed (regardless of + // any other pressed keys), Mac automatically flips the axis. Other + // platforms do not do this, so we flip it back to normalize the input + // received by the framework. The keyboard+mouse-scroll mechanism is exposed + // in the ScrollBehavior of the framework so developers can customize the + // behavior. + // At time of change, Apple does not expose any other type of API or signal + // that the X/Y axes have been flipped. + double scaledDeltaX = -event.scrollingDeltaX * pixelsPerLine * scaleFactor; + double scaledDeltaY = -event.scrollingDeltaY * pixelsPerLine * scaleFactor; + if (event.modifierFlags & NSShiftKeyMask) { + flutterEvent.scroll_delta_x = scaledDeltaY; + flutterEvent.scroll_delta_y = scaledDeltaX; + } else { + flutterEvent.scroll_delta_x = scaledDeltaX; + flutterEvent.scroll_delta_y = scaledDeltaY; + } + } + + [_engine.keyboardManager syncModifiersIfNeeded:event.modifierFlags timestamp:event.timestamp]; + [_engine sendPointerEvent:flutterEvent]; + + // Update tracking of state as reported to Flutter. + if (phase == kDown) { + _mouseState.flutter_state_is_down = true; + } else if (phase == kUp) { + _mouseState.flutter_state_is_down = false; + if (_mouseState.has_pending_exit) { + [self dispatchMouseEvent:event phase:kRemove]; + _mouseState.has_pending_exit = false; + } + } else if (phase == kAdd) { + _mouseState.flutter_state_is_added = true; + } else if (phase == kRemove) { + _mouseState.Reset(); + } +} + +- (void)onAccessibilityStatusChanged:(BOOL)enabled { + if (!enabled && self.viewLoaded && [self.activeTextInputPlugin isFirstResponder]) { + // Normally TextInputPlugin, when editing, is child of FlutterViewWrapper. + // When accessibility is enabled the TextInputPlugin gets added as an indirect + // child to FlutterTextField. When disabling the plugin needs to be reparented + // back. + [self.view addSubview:self.activeTextInputPlugin]; + } +} + +- (std::shared_ptr)createAccessibilityBridgeWithEngine: + (nonnull FlutterEngine*)engine { + return std::make_shared(engine, self); +} + +- (nonnull FlutterView*)createFlutterViewWithMTLDevice:(id)device + commandQueue:(id)commandQueue { + return [[FlutterView alloc] initWithMTLDevice:device + commandQueue:commandQueue + delegate:self + viewIdentifier:_viewIdentifier]; +} + +- (NSString*)lookupKeyForAsset:(NSString*)asset { + return [FlutterDartProject lookupKeyForAsset:asset]; +} + +- (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package { + return [FlutterDartProject lookupKeyForAsset:asset fromPackage:package]; +} + +#pragma mark - FlutterViewDelegate + +/** + * Responds to view reshape by notifying the engine of the change in dimensions. + */ +- (void)viewDidReshape:(NSView*)view { + FML_DCHECK(view == _flutterView); + [_engine updateWindowMetricsForViewController:self]; +} + +- (BOOL)viewShouldAcceptFirstResponder:(NSView*)view { + FML_DCHECK(view == _flutterView); + // Only allow FlutterView to become first responder if TextInputPlugin is + // not active. Otherwise a mouse event inside FlutterView would cause the + // TextInputPlugin to lose first responder status. + return !self.activeTextInputPlugin.isFirstResponder; +} + +#pragma mark - FlutterPluginRegistry + +- (id)registrarForPlugin:(NSString*)pluginName { + return [_engine registrarForPlugin:pluginName]; +} + +- (NSObject*)valuePublishedByPlugin:(NSString*)pluginKey { + return [_engine valuePublishedByPlugin:pluginKey]; +} + +#pragma mark - FlutterKeyboardViewDelegate + +- (BOOL)onTextInputKeyEvent:(nonnull NSEvent*)event { + return [self.activeTextInputPlugin handleKeyEvent:event]; +} + +#pragma mark - NSResponder + +- (BOOL)acceptsFirstResponder { + return YES; +} + +- (void)keyDown:(NSEvent*)event { + [_engine.keyboardManager handleEvent:event withContext:self]; +} + +- (void)keyUp:(NSEvent*)event { + [_engine.keyboardManager handleEvent:event withContext:self]; +} + +- (void)flagsChanged:(NSEvent*)event { + [_engine.keyboardManager handleEvent:event withContext:self]; +} + +- (void)mouseEntered:(NSEvent*)event { + if (_mouseState.has_pending_exit) { + _mouseState.has_pending_exit = false; + } else { + [self dispatchMouseEvent:event phase:kAdd]; + } +} + +- (void)mouseExited:(NSEvent*)event { + if (_mouseState.buttons != 0) { + _mouseState.has_pending_exit = true; + return; + } + [self dispatchMouseEvent:event phase:kRemove]; +} + +- (void)mouseDown:(NSEvent*)event { + _mouseState.buttons |= kFlutterPointerButtonMousePrimary; + [self dispatchMouseEvent:event]; +} + +- (void)mouseUp:(NSEvent*)event { + _mouseState.buttons &= ~static_cast(kFlutterPointerButtonMousePrimary); + [self dispatchMouseEvent:event]; +} + +- (void)mouseDragged:(NSEvent*)event { + [self dispatchMouseEvent:event]; +} + +- (void)rightMouseDown:(NSEvent*)event { + _mouseState.buttons |= kFlutterPointerButtonMouseSecondary; + [self dispatchMouseEvent:event]; +} + +- (void)rightMouseUp:(NSEvent*)event { + _mouseState.buttons &= ~static_cast(kFlutterPointerButtonMouseSecondary); + [self dispatchMouseEvent:event]; +} + +- (void)rightMouseDragged:(NSEvent*)event { + [self dispatchMouseEvent:event]; +} + +- (void)otherMouseDown:(NSEvent*)event { + _mouseState.buttons |= (1 << event.buttonNumber); + [self dispatchMouseEvent:event]; +} + +- (void)otherMouseUp:(NSEvent*)event { + _mouseState.buttons &= ~static_cast(1 << event.buttonNumber); + [self dispatchMouseEvent:event]; +} + +- (void)otherMouseDragged:(NSEvent*)event { + [self dispatchMouseEvent:event]; +} + +- (void)mouseMoved:(NSEvent*)event { + [self dispatchMouseEvent:event]; +} + +- (void)scrollWheel:(NSEvent*)event { + [self dispatchGestureEvent:event]; +} + +- (void)magnifyWithEvent:(NSEvent*)event { + [self dispatchGestureEvent:event]; +} + +- (void)rotateWithEvent:(NSEvent*)event { + [self dispatchGestureEvent:event]; +} + +- (void)swipeWithEvent:(NSEvent*)event { + // Not needed, it's handled by scrollWheel. +} + +- (void)touchesBeganWithEvent:(NSEvent*)event { + NSTouch* touch = event.allTouches.anyObject; + if (touch != nil) { + if ((event.timestamp - _mouseState.last_scroll_momentum_changed_time) < + kTrackpadTouchInertiaCancelWindowMs) { + // The trackpad has been touched following a scroll momentum event. + // A scroll inertia cancel message should be sent to the framework. + NSPoint locationInView = [self.flutterView convertPoint:event.locationInWindow fromView:nil]; + NSPoint locationInBackingCoordinates = + [self.flutterView convertPointToBacking:locationInView]; + FlutterPointerEvent flutterEvent = { + .struct_size = sizeof(flutterEvent), + .timestamp = static_cast(event.timestamp * USEC_PER_SEC), + .x = locationInBackingCoordinates.x, + .y = -locationInBackingCoordinates.y, // convertPointToBacking makes this negative. + .device = kPointerPanZoomDeviceId, + .signal_kind = kFlutterPointerSignalKindScrollInertiaCancel, + .device_kind = kFlutterPointerDeviceKindTrackpad, + .view_id = static_cast(_viewIdentifier), + }; + + [_engine sendPointerEvent:flutterEvent]; + // Ensure no further scroll inertia cancel event will be sent. + _mouseState.last_scroll_momentum_changed_time = 0; + } + } +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..8f3aae4acdbceacdd7f540919b8c7584a022cff5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTest.mm @@ -0,0 +1,1313 @@ +// 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. + +#import "KeyCodeMap_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" + +#import + +#include "flutter/common/constants.h" +#include "flutter/fml/platform/darwin/cf_utils.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h" +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderer.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.h" +#include "flutter/shell/platform/embedder/test_utils/key_codes.g.h" +#include "flutter/testing/autoreleasepool_test.h" +#include "flutter/testing/testing.h" + +#pragma mark - Test Helper Classes + +static const FlutterPointerEvent kDefaultFlutterPointerEvent = {}; +static const FlutterKeyEvent kDefaultFlutterKeyEvent = {}; + +// A wrap to convert FlutterKeyEvent to a ObjC class. +@interface KeyEventWrapper : NSObject +@property(nonatomic) FlutterKeyEvent* data; +- (nonnull instancetype)initWithEvent:(const FlutterKeyEvent*)event; +@end + +@implementation KeyEventWrapper +- (instancetype)initWithEvent:(const FlutterKeyEvent*)event { + self = [super init]; + _data = new FlutterKeyEvent(*event); + return self; +} + +- (void)dealloc { + delete _data; +} +@end + +/// Responder wrapper that forwards key events to another responder. This is a necessary middle step +/// for mocking responder because when setting the responder to controller AppKit will access ivars +/// of the objects, which means it must extend NSResponder instead of just implementing the +/// selectors. +@interface FlutterResponderWrapper : NSResponder { + NSResponder* _responder; +} +@end + +@implementation FlutterResponderWrapper + +- (instancetype)initWithResponder:(NSResponder*)responder { + if (self = [super init]) { + _responder = responder; + } + return self; +} + +- (void)keyDown:(NSEvent*)event { + [_responder keyDown:event]; +} + +- (void)keyUp:(NSEvent*)event { + [_responder keyUp:event]; +} + +- (BOOL)performKeyEquivalent:(NSEvent*)event { + return [_responder performKeyEquivalent:event]; +} + +- (void)flagsChanged:(NSEvent*)event { + [_responder flagsChanged:event]; +} + +@end + +// A FlutterViewController subclass for testing that mouseDown/mouseUp get called when +// mouse events are sent to the associated view. +@interface MouseEventFlutterViewController : FlutterViewController +@property(nonatomic, assign) BOOL mouseDownCalled; +@property(nonatomic, assign) BOOL mouseUpCalled; +@end + +@implementation MouseEventFlutterViewController +- (void)mouseDown:(NSEvent*)event { + self.mouseDownCalled = YES; +} + +- (void)mouseUp:(NSEvent*)event { + self.mouseUpCalled = YES; +} +@end + +@interface FlutterViewControllerTestObjC : NSObject +- (bool)testKeyEventsAreSentToFramework:(id)mockEngine; +- (bool)testKeyEventsArePropagatedIfNotHandled:(id)mockEngine; +- (bool)testKeyEventsAreNotPropagatedIfHandled:(id)mockEngine; +- (bool)testCtrlTabKeyEventIsPropagated:(id)mockEngine; +- (bool)testKeyEquivalentIsPassedToTextInputPlugin:(id)mockEngine; +- (bool)testFlagsChangedEventsArePropagatedIfNotHandled:(id)mockEngine; +- (bool)testKeyboardIsRestartedOnEngineRestart:(id)mockEngine; +- (bool)testTrackpadGesturesAreSentToFramework:(id)mockEngine; +- (bool)mouseAndGestureEventsAreHandledSeparately:(id)engineMock; +- (bool)testMouseDownUpEventsSentToNextResponder:(id)mockEngine; +- (bool)testModifierKeysAreSynthesizedOnMouseMove:(id)mockEngine; +- (bool)testViewWillAppearCalledMultipleTimes:(id)mockEngine; +- (bool)testFlutterViewIsConfigured:(id)mockEngine; +- (bool)testLookupKeyAssets; +- (bool)testLookupKeyAssetsWithPackage; +- (bool)testViewControllerIsReleased; + ++ (void)respondFalseForSendEvent:(const FlutterKeyEvent&)event + callback:(nullable FlutterKeyEventCallback)callback + userData:(nullable void*)userData; +@end + +#pragma mark - Static helper functions + +using namespace ::flutter::testing::keycodes; + +namespace flutter::testing { + +namespace { + +id MockGestureEvent(NSEventType type, NSEventPhase phase, double magnification, double rotation) { + id event = [OCMockObject mockForClass:[NSEvent class]]; + NSPoint locationInWindow = NSMakePoint(0, 0); + CGFloat deltaX = 0; + CGFloat deltaY = 0; + NSTimeInterval timestamp = 1; + NSUInteger modifierFlags = 0; + [(NSEvent*)[[event stub] andReturnValue:OCMOCK_VALUE(type)] type]; + [(NSEvent*)[[event stub] andReturnValue:OCMOCK_VALUE(phase)] phase]; + [(NSEvent*)[[event stub] andReturnValue:OCMOCK_VALUE(locationInWindow)] locationInWindow]; + [(NSEvent*)[[event stub] andReturnValue:OCMOCK_VALUE(deltaX)] deltaX]; + [(NSEvent*)[[event stub] andReturnValue:OCMOCK_VALUE(deltaY)] deltaY]; + [(NSEvent*)[[event stub] andReturnValue:OCMOCK_VALUE(timestamp)] timestamp]; + [(NSEvent*)[[event stub] andReturnValue:OCMOCK_VALUE(modifierFlags)] modifierFlags]; + [(NSEvent*)[[event stub] andReturnValue:OCMOCK_VALUE(magnification)] magnification]; + [(NSEvent*)[[event stub] andReturnValue:OCMOCK_VALUE(rotation)] rotation]; + return event; +} + +// Allocates and returns an engine configured for the test fixture resource configuration. +FlutterEngine* CreateTestEngine() { + NSString* fixtures = @(testing::GetFixturesPath()); + FlutterDartProject* project = [[FlutterDartProject alloc] + initWithAssetsPath:fixtures + ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; + return [[FlutterEngine alloc] initWithName:@"test" project:project allowHeadlessExecution:true]; +} + +NSResponder* mockResponder() { + NSResponder* mock = OCMStrictClassMock([NSResponder class]); + OCMStub([mock keyDown:[OCMArg any]]).andDo(nil); + OCMStub([mock keyUp:[OCMArg any]]).andDo(nil); + OCMStub([mock flagsChanged:[OCMArg any]]).andDo(nil); + return mock; +} + +NSEvent* CreateMouseEvent(NSEventModifierFlags modifierFlags) { + return [NSEvent mouseEventWithType:NSEventTypeMouseMoved + location:NSZeroPoint + modifierFlags:modifierFlags + timestamp:0 + windowNumber:0 + context:nil + eventNumber:0 + clickCount:1 + pressure:1.0]; +} + +} // namespace + +#pragma mark - gtest tests + +// Test-specific names for AutoreleasePoolTest, MockFlutterEngineTest fixtures. +using FlutterViewControllerTest = AutoreleasePoolTest; +using FlutterViewControllerMockEngineTest = MockFlutterEngineTest; + +TEST_F(FlutterViewControllerTest, HasViewThatHidesOtherViewsInAccessibility) { + FlutterViewController* viewControllerMock = CreateMockViewController(); + + [viewControllerMock loadView]; + auto subViews = [viewControllerMock.view subviews]; + + EXPECT_EQ([subViews count], 1u); + EXPECT_EQ(subViews[0], viewControllerMock.flutterView); + + NSTextField* textField = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 1, 1)]; + [viewControllerMock.view addSubview:textField]; + + subViews = [viewControllerMock.view subviews]; + EXPECT_EQ([subViews count], 2u); + + auto accessibilityChildren = viewControllerMock.view.accessibilityChildren; + // The accessibilityChildren should only contains the FlutterView. + EXPECT_EQ([accessibilityChildren count], 1u); + EXPECT_EQ(accessibilityChildren[0], viewControllerMock.flutterView); +} + +TEST_F(FlutterViewControllerTest, FlutterViewAcceptsFirstMouse) { + FlutterViewController* viewControllerMock = CreateMockViewController(); + [viewControllerMock loadView]; + EXPECT_EQ([viewControllerMock.flutterView acceptsFirstMouse:nil], YES); +} + +TEST_F(FlutterViewControllerTest, ReparentsPluginWhenAccessibilityDisabled) { + FlutterEngine* engine = CreateTestEngine(); + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + [viewController loadView]; + // Creates a NSWindow so that sub view can be first responder. + NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600) + styleMask:NSBorderlessWindowMask + backing:NSBackingStoreBuffered + defer:NO]; + window.contentView = viewController.view; + NSView* dummyView = [[NSView alloc] initWithFrame:CGRectZero]; + [viewController.view addSubview:dummyView]; + + NSDictionary* setClientConfig = @{ + @"viewId" : @(flutter::kFlutterImplicitViewId), + }; + FlutterMethodCall* methodCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]]; + FlutterResult result = ^(id result) { + }; + [engine.textInputPlugin handleMethodCall:methodCall result:result]; + + // Attaches FlutterTextInputPlugin to the view; + [dummyView addSubview:engine.textInputPlugin]; + // Makes sure the textInputPlugin can be the first responder. + + EXPECT_TRUE([window makeFirstResponder:engine.textInputPlugin]); + EXPECT_EQ([window firstResponder], engine.textInputPlugin); + EXPECT_FALSE(engine.textInputPlugin.superview == viewController.view); + [viewController onAccessibilityStatusChanged:NO]; + // FlutterView becomes child of view controller + EXPECT_TRUE(viewController.engine.textInputPlugin.superview == viewController.view); +} + +TEST_F(FlutterViewControllerTest, CanSetMouseTrackingModeBeforeViewLoaded) { + NSString* fixtures = @(testing::GetFixturesPath()); + FlutterDartProject* project = [[FlutterDartProject alloc] + initWithAssetsPath:fixtures + ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithProject:project]; + viewController.mouseTrackingMode = kFlutterMouseTrackingModeInActiveApp; + ASSERT_EQ(viewController.mouseTrackingMode, kFlutterMouseTrackingModeInActiveApp); +} + +TEST_F(FlutterViewControllerMockEngineTest, TestKeyEventsAreSentToFramework) { + id mockEngine = GetMockEngine(); + ASSERT_TRUE([[FlutterViewControllerTestObjC alloc] testKeyEventsAreSentToFramework:mockEngine]); +} + +TEST_F(FlutterViewControllerMockEngineTest, TestKeyEventsArePropagatedIfNotHandled) { + id mockEngine = GetMockEngine(); + ASSERT_TRUE( + [[FlutterViewControllerTestObjC alloc] testKeyEventsArePropagatedIfNotHandled:mockEngine]); +} + +TEST_F(FlutterViewControllerMockEngineTest, TestKeyEventsAreNotPropagatedIfHandled) { + id mockEngine = GetMockEngine(); + ASSERT_TRUE( + [[FlutterViewControllerTestObjC alloc] testKeyEventsAreNotPropagatedIfHandled:mockEngine]); +} + +TEST_F(FlutterViewControllerMockEngineTest, TestCtrlTabKeyEventIsPropagated) { + id mockEngine = GetMockEngine(); + ASSERT_TRUE([[FlutterViewControllerTestObjC alloc] testCtrlTabKeyEventIsPropagated:mockEngine]); +} + +TEST_F(FlutterViewControllerMockEngineTest, TestKeyEquivalentIsPassedToTextInputPlugin) { + id mockEngine = GetMockEngine(); + ASSERT_TRUE([[FlutterViewControllerTestObjC alloc] + testKeyEquivalentIsPassedToTextInputPlugin:mockEngine]); +} + +TEST_F(FlutterViewControllerMockEngineTest, TestFlagsChangedEventsArePropagatedIfNotHandled) { + id mockEngine = GetMockEngine(); + ASSERT_TRUE([[FlutterViewControllerTestObjC alloc] + testFlagsChangedEventsArePropagatedIfNotHandled:mockEngine]); +} + +TEST_F(FlutterViewControllerMockEngineTest, TestKeyboardIsRestartedOnEngineRestart) { + id mockEngine = GetMockEngine(); + ASSERT_TRUE( + [[FlutterViewControllerTestObjC alloc] testKeyboardIsRestartedOnEngineRestart:mockEngine]); +} + +TEST_F(FlutterViewControllerMockEngineTest, TestTrackpadGesturesAreSentToFramework) { + id mockEngine = GetMockEngine(); + ASSERT_TRUE( + [[FlutterViewControllerTestObjC alloc] testTrackpadGesturesAreSentToFramework:mockEngine]); +} + +TEST_F(FlutterViewControllerMockEngineTest, TestmouseAndGestureEventsAreHandledSeparately) { + id mockEngine = GetMockEngine(); + ASSERT_TRUE( + [[FlutterViewControllerTestObjC alloc] mouseAndGestureEventsAreHandledSeparately:mockEngine]); +} + +TEST_F(FlutterViewControllerMockEngineTest, TestMouseDownUpEventsSentToNextResponder) { + id mockEngine = GetMockEngine(); + ASSERT_TRUE( + [[FlutterViewControllerTestObjC alloc] testMouseDownUpEventsSentToNextResponder:mockEngine]); +} + +TEST_F(FlutterViewControllerMockEngineTest, TestModifierKeysAreSynthesizedOnMouseMove) { + id mockEngine = GetMockEngine(); + ASSERT_TRUE( + [[FlutterViewControllerTestObjC alloc] testModifierKeysAreSynthesizedOnMouseMove:mockEngine]); +} + +TEST_F(FlutterViewControllerMockEngineTest, testViewWillAppearCalledMultipleTimes) { + id mockEngine = GetMockEngine(); + ASSERT_TRUE( + [[FlutterViewControllerTestObjC alloc] testViewWillAppearCalledMultipleTimes:mockEngine]); +} + +TEST_F(FlutterViewControllerMockEngineTest, testFlutterViewIsConfigured) { + id mockEngine = GetMockEngine(); + ASSERT_TRUE([[FlutterViewControllerTestObjC alloc] testFlutterViewIsConfigured:mockEngine]); +} + +TEST_F(FlutterViewControllerTest, testLookupKeyAssets) { + ASSERT_TRUE([[FlutterViewControllerTestObjC alloc] testLookupKeyAssets]); +} + +TEST_F(FlutterViewControllerTest, testLookupKeyAssetsWithPackage) { + ASSERT_TRUE([[FlutterViewControllerTestObjC alloc] testLookupKeyAssetsWithPackage]); +} + +TEST_F(FlutterViewControllerTest, testViewControllerIsReleased) { + ASSERT_TRUE([[FlutterViewControllerTestObjC alloc] testViewControllerIsReleased]); +} + +} // namespace flutter::testing + +#pragma mark - FlutterViewControllerTestObjC + +@implementation FlutterViewControllerTestObjC + +- (bool)testKeyEventsAreSentToFramework:(id)engineMock { + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + FlutterKeyboardManager* keyboardManager = + [[FlutterKeyboardManager alloc] initWithDelegate:engineMock]; + OCMStub([engineMock keyboardManager]).andReturn(keyboardManager); + + OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:kDefaultFlutterKeyEvent + callback:nil + userData:nil]) + .andCall([FlutterViewControllerTestObjC class], + @selector(respondFalseForSendEvent:callback:userData:)); + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + NSDictionary* expectedEvent = @{ + @"keymap" : @"macos", + @"type" : @"keydown", + @"keyCode" : @(65), + @"modifiers" : @(538968064), + @"characters" : @".", + @"charactersIgnoringModifiers" : @".", + }; + NSData* encodedKeyEvent = [[FlutterJSONMessageCodec sharedInstance] encode:expectedEvent]; + CGEventRef cgEvent = CGEventCreateKeyboardEvent(NULL, 65, TRUE); + NSEvent* event = [NSEvent eventWithCGEvent:cgEvent]; + [viewController viewWillAppear]; // Initializes the event channel. + [viewController keyDown:event]; + @try { + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/keyevent" + message:encodedKeyEvent + binaryReply:[OCMArg any]]); + } @catch (...) { + return false; + } + return true; +} + +// Regression test for https://github.com/flutter/flutter/issues/122084. +- (bool)testCtrlTabKeyEventIsPropagated:(id)engineMock { + __block bool called = false; + __block FlutterKeyEvent last_event; + OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:kDefaultFlutterKeyEvent + callback:nil + userData:nil]) + .andDo((^(NSInvocation* invocation) { + FlutterKeyEvent* event; + [invocation getArgument:&event atIndex:2]; + called = true; + last_event = *event; + })); + FlutterKeyboardManager* keyboardManager = + [[FlutterKeyboardManager alloc] initWithDelegate:engineMock]; + OCMStub([engineMock keyboardManager]).andReturn(keyboardManager); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + // Ctrl+tab + NSEvent* event = [NSEvent keyEventWithType:NSEventTypeKeyDown + location:NSZeroPoint + modifierFlags:0x40101 + timestamp:0 + windowNumber:0 + context:nil + characters:@"" + charactersIgnoringModifiers:@"" + isARepeat:NO + keyCode:48]; + const uint64_t kPhysicalKeyTab = 0x7002b; + + [viewController viewWillAppear]; // Initializes the event channel. + // Creates a NSWindow so that FlutterView view can be first responder. + NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600) + styleMask:NSBorderlessWindowMask + backing:NSBackingStoreBuffered + defer:NO]; + window.contentView = viewController.view; + [window makeFirstResponder:viewController.flutterView]; + [viewController.view performKeyEquivalent:event]; + + EXPECT_TRUE(called); + EXPECT_EQ(last_event.type, kFlutterKeyEventTypeDown); + EXPECT_EQ(last_event.physical, kPhysicalKeyTab); + return true; +} + +- (bool)testKeyEquivalentIsPassedToTextInputPlugin:(id)engineMock { + __block bool called = false; + __block FlutterKeyEvent last_event; + OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:kDefaultFlutterKeyEvent + callback:nil + userData:nil]) + .andDo((^(NSInvocation* invocation) { + FlutterKeyEvent* event; + [invocation getArgument:&event atIndex:2]; + called = true; + last_event = *event; + })); + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + // Ctrl+tab + NSEvent* event = [NSEvent keyEventWithType:NSEventTypeKeyDown + location:NSZeroPoint + modifierFlags:0x40101 + timestamp:0 + windowNumber:0 + context:nil + characters:@"" + charactersIgnoringModifiers:@"" + isARepeat:NO + keyCode:48]; + const uint64_t kPhysicalKeyTab = 0x7002b; + + [viewController viewWillAppear]; // Initializes the event channel. + + NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600) + styleMask:NSBorderlessWindowMask + backing:NSBackingStoreBuffered + defer:NO]; + window.contentView = viewController.view; + + NSDictionary* setClientConfig = @{ + @"viewId" : @(flutter::kFlutterImplicitViewId), + }; + FlutterMethodCall* methodCall = + [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient" + arguments:@[ @(1), setClientConfig ]]; + FlutterResult result = ^(id result) { + }; + [viewController.engine.textInputPlugin handleMethodCall:methodCall result:result]; + + [viewController.engine.textInputPlugin + handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"TextInput.show" arguments:@[]] + result:^(id){ + }]; + + // Make the textInputPlugin first responder. This should still result in + // view controller reporting the key event. + [window makeFirstResponder:viewController.engine.textInputPlugin]; + + [viewController.view performKeyEquivalent:event]; + + EXPECT_TRUE(called); + EXPECT_EQ(last_event.type, kFlutterKeyEventTypeDown); + EXPECT_EQ(last_event.physical, kPhysicalKeyTab); + return true; +} + +- (bool)testKeyEventsArePropagatedIfNotHandled:(id)engineMock { + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + FlutterKeyboardManager* keyboardManager = + [[FlutterKeyboardManager alloc] initWithDelegate:engineMock]; + OCMStub([engineMock keyboardManager]).andReturn(keyboardManager); + OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:kDefaultFlutterKeyEvent + callback:nil + userData:nil]) + .andCall([FlutterViewControllerTestObjC class], + @selector(respondFalseForSendEvent:callback:userData:)); + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + id responderMock = flutter::testing::mockResponder(); + id responderWrapper = [[FlutterResponderWrapper alloc] initWithResponder:responderMock]; + viewController.nextResponder = responderWrapper; + NSDictionary* expectedEvent = @{ + @"keymap" : @"macos", + @"type" : @"keydown", + @"keyCode" : @(65), + @"modifiers" : @(538968064), + @"characters" : @".", + @"charactersIgnoringModifiers" : @".", + }; + NSData* encodedKeyEvent = [[FlutterJSONMessageCodec sharedInstance] encode:expectedEvent]; + CGEventRef cgEvent = CGEventCreateKeyboardEvent(NULL, 65, TRUE); + NSEvent* event = [NSEvent eventWithCGEvent:cgEvent]; + OCMExpect( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/keyevent" + message:encodedKeyEvent + binaryReply:[OCMArg any]]) + .andDo((^(NSInvocation* invocation) { + FlutterBinaryReply handler; + [invocation getArgument:&handler atIndex:4]; + NSDictionary* reply = @{ + @"handled" : @(false), + }; + NSData* encodedReply = [[FlutterJSONMessageCodec sharedInstance] encode:reply]; + handler(encodedReply); + })); + [viewController viewWillAppear]; // Initializes the event channel. + [viewController keyDown:event]; + @try { + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + [responderMock keyDown:[OCMArg any]]); + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/keyevent" + message:encodedKeyEvent + binaryReply:[OCMArg any]]); + } @catch (...) { + return false; + } + return true; +} + +- (bool)testFlutterViewIsConfigured:(id)engineMock { + FlutterRenderer* renderer_ = [[FlutterRenderer alloc] initWithFlutterEngine:engineMock]; + OCMStub([engineMock renderer]).andReturn(renderer_); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + [viewController loadView]; + + @try { + // Make sure "renderer" was called during "loadView", which means "flutterView" is created + OCMVerify([engineMock renderer]); + } @catch (...) { + return false; + } + + return true; +} + +- (bool)testFlagsChangedEventsArePropagatedIfNotHandled:(id)engineMock { + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + FlutterKeyboardManager* keyboardManager = + [[FlutterKeyboardManager alloc] initWithDelegate:engineMock]; + OCMStub([engineMock keyboardManager]).andReturn(keyboardManager); + OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:kDefaultFlutterKeyEvent + callback:nil + userData:nil]) + .andCall([FlutterViewControllerTestObjC class], + @selector(respondFalseForSendEvent:callback:userData:)); + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + id responderMock = flutter::testing::mockResponder(); + id responderWrapper = [[FlutterResponderWrapper alloc] initWithResponder:responderMock]; + viewController.nextResponder = responderWrapper; + NSDictionary* expectedEvent = @{ + @"keymap" : @"macos", + @"type" : @"keydown", + @"keyCode" : @(56), // SHIFT key + @"modifiers" : @(537001986), + }; + NSData* encodedKeyEvent = [[FlutterJSONMessageCodec sharedInstance] encode:expectedEvent]; + CGEventRef cgEvent = CGEventCreateKeyboardEvent(NULL, 56, TRUE); // SHIFT key + CGEventSetType(cgEvent, kCGEventFlagsChanged); + NSEvent* event = [NSEvent eventWithCGEvent:cgEvent]; + OCMExpect( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/keyevent" + message:encodedKeyEvent + binaryReply:[OCMArg any]]) + .andDo((^(NSInvocation* invocation) { + FlutterBinaryReply handler; + [invocation getArgument:&handler atIndex:4]; + NSDictionary* reply = @{ + @"handled" : @(false), + }; + NSData* encodedReply = [[FlutterJSONMessageCodec sharedInstance] encode:reply]; + handler(encodedReply); + })); + [viewController viewWillAppear]; // Initializes the event channel. + [viewController flagsChanged:event]; + @try { + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/keyevent" + message:encodedKeyEvent + binaryReply:[OCMArg any]]); + } @catch (NSException* e) { + NSLog(@"%@", e.reason); + return false; + } + return true; +} + +- (bool)testKeyEventsAreNotPropagatedIfHandled:(id)engineMock { + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + FlutterKeyboardManager* keyboardManager = + [[FlutterKeyboardManager alloc] initWithDelegate:engineMock]; + OCMStub([engineMock keyboardManager]).andReturn(keyboardManager); + OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:kDefaultFlutterKeyEvent + callback:nil + userData:nil]) + .andCall([FlutterViewControllerTestObjC class], + @selector(respondFalseForSendEvent:callback:userData:)); + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + id responderMock = flutter::testing::mockResponder(); + id responderWrapper = [[FlutterResponderWrapper alloc] initWithResponder:responderMock]; + viewController.nextResponder = responderWrapper; + NSDictionary* expectedEvent = @{ + @"keymap" : @"macos", + @"type" : @"keydown", + @"keyCode" : @(65), + @"modifiers" : @(538968064), + @"characters" : @".", + @"charactersIgnoringModifiers" : @".", + }; + NSData* encodedKeyEvent = [[FlutterJSONMessageCodec sharedInstance] encode:expectedEvent]; + CGEventRef cgEvent = CGEventCreateKeyboardEvent(NULL, 65, TRUE); + NSEvent* event = [NSEvent eventWithCGEvent:cgEvent]; + OCMExpect( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/keyevent" + message:encodedKeyEvent + binaryReply:[OCMArg any]]) + .andDo((^(NSInvocation* invocation) { + FlutterBinaryReply handler; + [invocation getArgument:&handler atIndex:4]; + NSDictionary* reply = @{ + @"handled" : @(true), + }; + NSData* encodedReply = [[FlutterJSONMessageCodec sharedInstance] encode:reply]; + handler(encodedReply); + })); + [viewController viewWillAppear]; // Initializes the event channel. + [viewController keyDown:event]; + @try { + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + never(), [responderMock keyDown:[OCMArg any]]); + OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) + [binaryMessengerMock sendOnChannel:@"flutter/keyevent" + message:encodedKeyEvent + binaryReply:[OCMArg any]]); + } @catch (...) { + return false; + } + return true; +} + +- (bool)testKeyboardIsRestartedOnEngineRestart:(id)engineMock { + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + __block bool called = false; + __block FlutterKeyEvent last_event; + __block FlutterKeyboardManager* keyboardManager = + [[FlutterKeyboardManager alloc] initWithDelegate:engineMock]; + + OCMStub([engineMock keyboardManager]).andDo(^(NSInvocation* invocation) { + [invocation setReturnValue:&keyboardManager]; + }); + + OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:kDefaultFlutterKeyEvent + callback:nil + userData:nil]) + .andDo((^(NSInvocation* invocation) { + FlutterKeyEvent* event; + [invocation getArgument:&event atIndex:2]; + called = true; + last_event = *event; + })); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + [viewController viewWillAppear]; + NSEvent* keyADown = [NSEvent keyEventWithType:NSEventTypeKeyDown + location:NSZeroPoint + modifierFlags:0x100 + timestamp:0 + windowNumber:0 + context:nil + characters:@"a" + charactersIgnoringModifiers:@"a" + isARepeat:FALSE + keyCode:0]; + const uint64_t kPhysicalKeyA = 0x70004; + + // Send KeyA key down event twice. Without restarting the keyboard during + // onPreEngineRestart, the second event received will be an empty event with + // physical key 0x0 because duplicate key down events are ignored. + + called = false; + [viewController keyDown:keyADown]; + EXPECT_TRUE(called); + EXPECT_EQ(last_event.type, kFlutterKeyEventTypeDown); + EXPECT_EQ(last_event.physical, kPhysicalKeyA); + + keyboardManager = [[FlutterKeyboardManager alloc] initWithDelegate:engineMock]; + + called = false; + [viewController keyDown:keyADown]; + EXPECT_TRUE(called); + EXPECT_EQ(last_event.type, kFlutterKeyEventTypeDown); + EXPECT_EQ(last_event.physical, kPhysicalKeyA); + return true; +} + ++ (void)respondFalseForSendEvent:(const FlutterKeyEvent&)event + callback:(nullable FlutterKeyEventCallback)callback + userData:(nullable void*)userData { + if (callback != nullptr) { + callback(false, userData); + } +} + +- (bool)testTrackpadGesturesAreSentToFramework:(id)engineMock { + // Need to return a real renderer to allow view controller to load. + FlutterRenderer* renderer_ = [[FlutterRenderer alloc] initWithFlutterEngine:engineMock]; + OCMStub([engineMock renderer]).andReturn(renderer_); + __block bool called = false; + __block FlutterPointerEvent last_event; + OCMStub([[engineMock ignoringNonObjectArgs] sendPointerEvent:kDefaultFlutterPointerEvent]) + .andDo((^(NSInvocation* invocation) { + FlutterPointerEvent* event; + [invocation getArgument:&event atIndex:2]; + called = true; + last_event = *event; + })); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + [viewController loadView]; + + // Test for pan events. + // Start gesture. + CGEventRef cgEventStart = CGEventCreateScrollWheelEvent(NULL, kCGScrollEventUnitPixel, 1, 0); + CGEventSetType(cgEventStart, kCGEventScrollWheel); + CGEventSetIntegerValueField(cgEventStart, kCGScrollWheelEventScrollPhase, kCGScrollPhaseBegan); + CGEventSetIntegerValueField(cgEventStart, kCGScrollWheelEventIsContinuous, 1); + + called = false; + [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventStart]]; + EXPECT_TRUE(called); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + EXPECT_EQ(last_event.phase, kPanZoomStart); + EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + + // Update gesture. + CGEventRef cgEventUpdate = CGEventCreateCopy(cgEventStart); + CGEventSetIntegerValueField(cgEventUpdate, kCGScrollWheelEventScrollPhase, kCGScrollPhaseChanged); + CGEventSetIntegerValueField(cgEventUpdate, kCGScrollWheelEventDeltaAxis2, 1); // pan_x + CGEventSetIntegerValueField(cgEventUpdate, kCGScrollWheelEventDeltaAxis1, 2); // pan_y + + called = false; + [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventUpdate]]; + EXPECT_TRUE(called); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + EXPECT_EQ(last_event.phase, kPanZoomUpdate); + EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + EXPECT_EQ(last_event.pan_x, 8 * viewController.flutterView.layer.contentsScale); + EXPECT_EQ(last_event.pan_y, 16 * viewController.flutterView.layer.contentsScale); + + // Make sure the pan values accumulate. + called = false; + [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventUpdate]]; + EXPECT_TRUE(called); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + EXPECT_EQ(last_event.phase, kPanZoomUpdate); + EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + EXPECT_EQ(last_event.pan_x, 16 * viewController.flutterView.layer.contentsScale); + EXPECT_EQ(last_event.pan_y, 32 * viewController.flutterView.layer.contentsScale); + + // End gesture. + CGEventRef cgEventEnd = CGEventCreateCopy(cgEventStart); + CGEventSetIntegerValueField(cgEventEnd, kCGScrollWheelEventScrollPhase, kCGScrollPhaseEnded); + + called = false; + [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventEnd]]; + EXPECT_TRUE(called); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + EXPECT_EQ(last_event.phase, kPanZoomEnd); + EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + + // Start system momentum. + CGEventRef cgEventMomentumStart = CGEventCreateCopy(cgEventStart); + CGEventSetIntegerValueField(cgEventMomentumStart, kCGScrollWheelEventScrollPhase, 0); + CGEventSetIntegerValueField(cgEventMomentumStart, kCGScrollWheelEventMomentumPhase, + kCGMomentumScrollPhaseBegin); + + called = false; + [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventMomentumStart]]; + EXPECT_FALSE(called); + + // Advance system momentum. + CGEventRef cgEventMomentumUpdate = CGEventCreateCopy(cgEventStart); + CGEventSetIntegerValueField(cgEventMomentumUpdate, kCGScrollWheelEventScrollPhase, 0); + CGEventSetIntegerValueField(cgEventMomentumUpdate, kCGScrollWheelEventMomentumPhase, + kCGMomentumScrollPhaseContinue); + + called = false; + [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventMomentumUpdate]]; + EXPECT_FALSE(called); + + // Mock a touch on the trackpad. + id touchMock = OCMClassMock([NSTouch class]); + NSSet* touchSet = [NSSet setWithObject:touchMock]; + id touchEventMock1 = OCMClassMock([NSEvent class]); + OCMStub([touchEventMock1 allTouches]).andReturn(touchSet); + CGPoint touchLocation = {0, 0}; + OCMStub([touchEventMock1 locationInWindow]).andReturn(touchLocation); + OCMStub([(NSEvent*)touchEventMock1 timestamp]).andReturn(0.150); // 150 milliseconds. + + // Scroll inertia cancel event should not be issued (timestamp too far in the future). + called = false; + [viewController touchesBeganWithEvent:touchEventMock1]; + EXPECT_FALSE(called); + + // Mock another touch on the trackpad. + id touchEventMock2 = OCMClassMock([NSEvent class]); + OCMStub([touchEventMock2 allTouches]).andReturn(touchSet); + OCMStub([touchEventMock2 locationInWindow]).andReturn(touchLocation); + OCMStub([(NSEvent*)touchEventMock2 timestamp]).andReturn(0.005); // 5 milliseconds. + + // Scroll inertia cancel event should be issued. + called = false; + [viewController touchesBeganWithEvent:touchEventMock2]; + EXPECT_TRUE(called); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindScrollInertiaCancel); + EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); + + // End system momentum. + CGEventRef cgEventMomentumEnd = CGEventCreateCopy(cgEventStart); + CGEventSetIntegerValueField(cgEventMomentumEnd, kCGScrollWheelEventScrollPhase, 0); + CGEventSetIntegerValueField(cgEventMomentumEnd, kCGScrollWheelEventMomentumPhase, + kCGMomentumScrollPhaseEnd); + + called = false; + [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventMomentumEnd]]; + EXPECT_FALSE(called); + + // May-begin and cancel are used while macOS determines which type of gesture to choose. + CGEventRef cgEventMayBegin = CGEventCreateCopy(cgEventStart); + CGEventSetIntegerValueField(cgEventMayBegin, kCGScrollWheelEventScrollPhase, + kCGScrollPhaseMayBegin); + + called = false; + [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventMayBegin]]; + EXPECT_TRUE(called); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + EXPECT_EQ(last_event.phase, kPanZoomStart); + EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + + // Cancel gesture. + CGEventRef cgEventCancel = CGEventCreateCopy(cgEventStart); + CGEventSetIntegerValueField(cgEventCancel, kCGScrollWheelEventScrollPhase, + kCGScrollPhaseCancelled); + + called = false; + [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventCancel]]; + EXPECT_TRUE(called); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + EXPECT_EQ(last_event.phase, kPanZoomEnd); + EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + + // A discrete scroll event should use the PointerSignal system. + CGEventRef cgEventDiscrete = CGEventCreateScrollWheelEvent(NULL, kCGScrollEventUnitPixel, 1, 0); + CGEventSetType(cgEventDiscrete, kCGEventScrollWheel); + CGEventSetIntegerValueField(cgEventDiscrete, kCGScrollWheelEventIsContinuous, 0); + CGEventSetIntegerValueField(cgEventDiscrete, kCGScrollWheelEventDeltaAxis2, 1); // scroll_delta_x + CGEventSetIntegerValueField(cgEventDiscrete, kCGScrollWheelEventDeltaAxis1, 2); // scroll_delta_y + + called = false; + [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventDiscrete]]; + EXPECT_TRUE(called); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindScroll); + // pixelsPerLine is 40.0 and direction is reversed. + EXPECT_EQ(last_event.scroll_delta_x, -40 * viewController.flutterView.layer.contentsScale); + EXPECT_EQ(last_event.scroll_delta_y, -80 * viewController.flutterView.layer.contentsScale); + + // A discrete scroll event should use the PointerSignal system, and flip the + // direction when shift is pressed. + CGEventRef cgEventDiscreteShift = + CGEventCreateScrollWheelEvent(NULL, kCGScrollEventUnitPixel, 1, 0); + CGEventSetType(cgEventDiscreteShift, kCGEventScrollWheel); + CGEventSetFlags(cgEventDiscreteShift, kCGEventFlagMaskShift | flutter::kModifierFlagShiftLeft); + CGEventSetIntegerValueField(cgEventDiscreteShift, kCGScrollWheelEventIsContinuous, 0); + CGEventSetIntegerValueField(cgEventDiscreteShift, kCGScrollWheelEventDeltaAxis2, + 0); // scroll_delta_x + CGEventSetIntegerValueField(cgEventDiscreteShift, kCGScrollWheelEventDeltaAxis1, + 2); // scroll_delta_y + + called = false; + [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventDiscreteShift]]; + EXPECT_TRUE(called); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindScroll); + // pixelsPerLine is 40.0, direction is reversed and axes have been flipped back. + EXPECT_FLOAT_EQ(last_event.scroll_delta_x, 0.0 * viewController.flutterView.layer.contentsScale); + EXPECT_FLOAT_EQ(last_event.scroll_delta_y, + -80.0 * viewController.flutterView.layer.contentsScale); + + // Test for scale events. + // Start gesture. + called = false; + [viewController magnifyWithEvent:flutter::testing::MockGestureEvent(NSEventTypeMagnify, + NSEventPhaseBegan, 1, 0)]; + EXPECT_TRUE(called); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + EXPECT_EQ(last_event.phase, kPanZoomStart); + EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + + // Update gesture. + called = false; + [viewController magnifyWithEvent:flutter::testing::MockGestureEvent(NSEventTypeMagnify, + NSEventPhaseChanged, 1, 0)]; + EXPECT_TRUE(called); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + EXPECT_EQ(last_event.phase, kPanZoomUpdate); + EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + EXPECT_EQ(last_event.pan_x, 0); + EXPECT_EQ(last_event.pan_y, 0); + EXPECT_EQ(last_event.scale, 2); // macOS uses logarithmic scaling values, the linear value for + // flutter here should be 2^1 = 2. + EXPECT_EQ(last_event.rotation, 0); + + // Make sure the scale values accumulate. + called = false; + [viewController magnifyWithEvent:flutter::testing::MockGestureEvent(NSEventTypeMagnify, + NSEventPhaseChanged, 1, 0)]; + EXPECT_TRUE(called); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + EXPECT_EQ(last_event.phase, kPanZoomUpdate); + EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + EXPECT_EQ(last_event.pan_x, 0); + EXPECT_EQ(last_event.pan_y, 0); + EXPECT_EQ(last_event.scale, 4); // macOS uses logarithmic scaling values, the linear value for + // flutter here should be 2^(1+1) = 2. + EXPECT_EQ(last_event.rotation, 0); + + // End gesture. + called = false; + [viewController magnifyWithEvent:flutter::testing::MockGestureEvent(NSEventTypeMagnify, + NSEventPhaseEnded, 0, 0)]; + EXPECT_TRUE(called); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + EXPECT_EQ(last_event.phase, kPanZoomEnd); + EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + + // Test for rotation events. + // Start gesture. + called = false; + [viewController rotateWithEvent:flutter::testing::MockGestureEvent(NSEventTypeRotate, + NSEventPhaseBegan, 1, 0)]; + EXPECT_TRUE(called); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + EXPECT_EQ(last_event.phase, kPanZoomStart); + EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + + // Update gesture. + called = false; + [viewController rotateWithEvent:flutter::testing::MockGestureEvent( + NSEventTypeRotate, NSEventPhaseChanged, 0, -180)]; // degrees + EXPECT_TRUE(called); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + EXPECT_EQ(last_event.phase, kPanZoomUpdate); + EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + EXPECT_EQ(last_event.pan_x, 0); + EXPECT_EQ(last_event.pan_y, 0); + EXPECT_EQ(last_event.scale, 1); + EXPECT_EQ(last_event.rotation, M_PI); // radians + + // Make sure the rotation values accumulate. + called = false; + [viewController rotateWithEvent:flutter::testing::MockGestureEvent( + NSEventTypeRotate, NSEventPhaseChanged, 0, -360)]; // degrees + EXPECT_TRUE(called); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + EXPECT_EQ(last_event.phase, kPanZoomUpdate); + EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + EXPECT_EQ(last_event.pan_x, 0); + EXPECT_EQ(last_event.pan_y, 0); + EXPECT_EQ(last_event.scale, 1); + EXPECT_EQ(last_event.rotation, 3 * M_PI); // radians + + // End gesture. + called = false; + [viewController rotateWithEvent:flutter::testing::MockGestureEvent(NSEventTypeRotate, + NSEventPhaseEnded, 0, 0)]; + EXPECT_TRUE(called); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + EXPECT_EQ(last_event.phase, kPanZoomEnd); + EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); + EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); + + // Test that stray NSEventPhaseCancelled event does not crash + called = false; + [viewController rotateWithEvent:flutter::testing::MockGestureEvent(NSEventTypeRotate, + NSEventPhaseCancelled, 0, 0)]; + EXPECT_FALSE(called); + + return true; +} + +// Magic mouse can interleave mouse events with scroll events. This must not crash. +- (bool)mouseAndGestureEventsAreHandledSeparately:(id)engineMock { + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + [viewController loadView]; + + // Test for pan events. + // Start gesture. + fml::CFRef cgEventStart( + CGEventCreateScrollWheelEvent(NULL, kCGScrollEventUnitPixel, 1, 0)); + CGEventSetType(cgEventStart, kCGEventScrollWheel); + CGEventSetIntegerValueField(cgEventStart, kCGScrollWheelEventScrollPhase, kCGScrollPhaseBegan); + CGEventSetIntegerValueField(cgEventStart, kCGScrollWheelEventIsContinuous, 1); + [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventStart]]; + + fml::CFRef cgEventUpdate(CGEventCreateCopy(cgEventStart)); + CGEventSetIntegerValueField(cgEventUpdate, kCGScrollWheelEventScrollPhase, kCGScrollPhaseChanged); + CGEventSetIntegerValueField(cgEventUpdate, kCGScrollWheelEventDeltaAxis2, 1); // pan_x + CGEventSetIntegerValueField(cgEventUpdate, kCGScrollWheelEventDeltaAxis1, 2); // pan_y + [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventUpdate]]; + + NSEvent* mouseEvent = flutter::testing::CreateMouseEvent(0x00); + [viewController mouseEntered:mouseEvent]; + [viewController mouseExited:mouseEvent]; + + // End gesture. + fml::CFRef cgEventEnd(CGEventCreateCopy(cgEventStart)); + CGEventSetIntegerValueField(cgEventEnd, kCGScrollWheelEventScrollPhase, kCGScrollPhaseEnded); + [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventEnd]]; + + return true; +} + +- (bool)testViewWillAppearCalledMultipleTimes:(id)engineMock { + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + [viewController viewWillAppear]; + [viewController viewWillAppear]; + return true; +} + +- (bool)testLookupKeyAssets { + FlutterViewController* viewController = [[FlutterViewController alloc] initWithProject:nil]; + NSString* key = [viewController lookupKeyForAsset:@"test.png"]; + EXPECT_TRUE( + [key isEqualToString:@"Contents/Frameworks/App.framework/Resources/flutter_assets/test.png"]); + return true; +} + +- (bool)testLookupKeyAssetsWithPackage { + FlutterViewController* viewController = [[FlutterViewController alloc] initWithProject:nil]; + + NSString* packageKey = [viewController lookupKeyForAsset:@"test.png" fromPackage:@"test"]; + EXPECT_TRUE([packageKey + isEqualToString: + @"Contents/Frameworks/App.framework/Resources/flutter_assets/packages/test/test.png"]); + return true; +} + +static void SwizzledNoop(id self, SEL _cmd) {} + +// Verify workaround an AppKit bug where mouseDown/mouseUp are not called on the view controller if +// the view is the content view of an NSPopover AND macOS's Reduced Transparency accessibility +// setting is enabled. +// +// See: https://github.com/flutter/flutter/issues/115015 +// See: http://www.openradar.me/FB12050037 +// See: https://developer.apple.com/documentation/appkit/nsresponder/1524634-mousedown +// +// TODO(cbracken): https://github.com/flutter/flutter/issues/154063 +// Remove this test when we drop support for macOS 12 (Monterey). +- (bool)testMouseDownUpEventsSentToNextResponder:(id)engineMock { + if (@available(macOS 13.3.1, *)) { + // This workaround is disabled for macOS 13.3.1 onwards, since the underlying AppKit bug is + // fixed. + return true; + } + + // The root cause of the above bug is NSResponder mouseDown/mouseUp methods that don't correctly + // walk the responder chain calling the appropriate method on the next responder under certain + // conditions. Simulate this by swizzling out the default implementations and replacing them with + // no-ops. + Method mouseDown = class_getInstanceMethod([NSResponder class], @selector(mouseDown:)); + Method mouseUp = class_getInstanceMethod([NSResponder class], @selector(mouseUp:)); + IMP noopImp = (IMP)SwizzledNoop; + IMP origMouseDown = method_setImplementation(mouseDown, noopImp); + IMP origMouseUp = method_setImplementation(mouseUp, noopImp); + + // Verify that mouseDown/mouseUp trigger mouseDown/mouseUp calls on FlutterViewController. + MouseEventFlutterViewController* viewController = + [[MouseEventFlutterViewController alloc] initWithEngine:engineMock nibName:@"" bundle:nil]; + FlutterView* view = (FlutterView*)[viewController view]; + + EXPECT_FALSE(viewController.mouseDownCalled); + EXPECT_FALSE(viewController.mouseUpCalled); + + NSEvent* mouseEvent = flutter::testing::CreateMouseEvent(0x00); + [view mouseDown:mouseEvent]; + EXPECT_TRUE(viewController.mouseDownCalled); + EXPECT_FALSE(viewController.mouseUpCalled); + + viewController.mouseDownCalled = NO; + [view mouseUp:mouseEvent]; + EXPECT_FALSE(viewController.mouseDownCalled); + EXPECT_TRUE(viewController.mouseUpCalled); + + // Restore the original NSResponder mouseDown/mouseUp implementations. + method_setImplementation(mouseDown, origMouseDown); + method_setImplementation(mouseUp, origMouseUp); + + return true; +} + +- (bool)testModifierKeysAreSynthesizedOnMouseMove:(id)engineMock { + id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); + OCMStub( // NOLINT(google-objc-avoid-throwing-exception) + [engineMock binaryMessenger]) + .andReturn(binaryMessengerMock); + + // Need to return a real renderer to allow view controller to load. + FlutterRenderer* renderer_ = [[FlutterRenderer alloc] initWithFlutterEngine:engineMock]; + OCMStub([engineMock renderer]).andReturn(renderer_); + + FlutterKeyboardManager* keyboardManager = + [[FlutterKeyboardManager alloc] initWithDelegate:engineMock]; + OCMStub([engineMock keyboardManager]).andReturn(keyboardManager); + + // Capture calls to sendKeyEvent + __block NSMutableArray* events = [NSMutableArray array]; + OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:kDefaultFlutterKeyEvent + callback:nil + userData:nil]) + .andDo((^(NSInvocation* invocation) { + FlutterKeyEvent* event; + [invocation getArgument:&event atIndex:2]; + [events addObject:[[KeyEventWrapper alloc] initWithEvent:event]]; + })); + + __block NSMutableArray* channelEvents = [NSMutableArray array]; + OCMStub([binaryMessengerMock sendOnChannel:@"flutter/keyevent" + message:[OCMArg any] + binaryReply:[OCMArg any]]) + .andDo((^(NSInvocation* invocation) { + NSData* data; + [invocation getArgument:&data atIndex:3]; + id event = [[FlutterJSONMessageCodec sharedInstance] decode:data]; + [channelEvents addObject:event]; + })); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + [viewController loadView]; + [viewController viewWillAppear]; + + // Zeroed modifier flag should not synthesize events. + NSEvent* mouseEvent = flutter::testing::CreateMouseEvent(0x00); + [viewController mouseMoved:mouseEvent]; + EXPECT_EQ([events count], 0u); + + // For each modifier key, check that key events are synthesized. + for (NSNumber* keyCode in flutter::keyCodeToModifierFlag) { + FlutterKeyEvent* event; + NSDictionary* channelEvent; + NSNumber* logicalKey; + NSNumber* physicalKey; + NSEventModifierFlags flag = [flutter::keyCodeToModifierFlag[keyCode] unsignedLongValue]; + + // Cocoa event always contain combined flags. + if (flag & (flutter::kModifierFlagShiftLeft | flutter::kModifierFlagShiftRight)) { + flag |= NSEventModifierFlagShift; + } + if (flag & (flutter::kModifierFlagControlLeft | flutter::kModifierFlagControlRight)) { + flag |= NSEventModifierFlagControl; + } + if (flag & (flutter::kModifierFlagAltLeft | flutter::kModifierFlagAltRight)) { + flag |= NSEventModifierFlagOption; + } + if (flag & (flutter::kModifierFlagMetaLeft | flutter::kModifierFlagMetaRight)) { + flag |= NSEventModifierFlagCommand; + } + + // Should synthesize down event. + NSEvent* mouseEvent = flutter::testing::CreateMouseEvent(flag); + [viewController mouseMoved:mouseEvent]; + EXPECT_EQ([events count], 1u); + event = events[0].data; + logicalKey = [flutter::keyCodeToLogicalKey objectForKey:keyCode]; + physicalKey = [flutter::keyCodeToPhysicalKey objectForKey:keyCode]; + EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); + EXPECT_EQ(event->logical, logicalKey.unsignedLongLongValue); + EXPECT_EQ(event->physical, physicalKey.unsignedLongLongValue); + EXPECT_EQ(event->synthesized, true); + + channelEvent = channelEvents[0]; + EXPECT_TRUE([channelEvent[@"type"] isEqual:@"keydown"]); + EXPECT_TRUE([channelEvent[@"keyCode"] isEqual:keyCode]); + EXPECT_TRUE([channelEvent[@"modifiers"] isEqual:@(flag)]); + + // Should synthesize up event. + mouseEvent = flutter::testing::CreateMouseEvent(0x00); + [viewController mouseMoved:mouseEvent]; + EXPECT_EQ([events count], 2u); + event = events[1].data; + logicalKey = [flutter::keyCodeToLogicalKey objectForKey:keyCode]; + physicalKey = [flutter::keyCodeToPhysicalKey objectForKey:keyCode]; + EXPECT_EQ(event->type, kFlutterKeyEventTypeUp); + EXPECT_EQ(event->logical, logicalKey.unsignedLongLongValue); + EXPECT_EQ(event->physical, physicalKey.unsignedLongLongValue); + EXPECT_EQ(event->synthesized, true); + + channelEvent = channelEvents[1]; + EXPECT_TRUE([channelEvent[@"type"] isEqual:@"keyup"]); + EXPECT_TRUE([channelEvent[@"keyCode"] isEqual:keyCode]); + EXPECT_TRUE([channelEvent[@"modifiers"] isEqual:@(0)]); + + [events removeAllObjects]; + [channelEvents removeAllObjects]; + }; + + return true; +} + +- (bool)testViewControllerIsReleased { + __weak FlutterViewController* weakController; + @autoreleasepool { + id engineMock = flutter::testing::CreateMockFlutterEngine(@""); + + FlutterRenderer* renderer_ = [[FlutterRenderer alloc] initWithFlutterEngine:engineMock]; + OCMStub([engineMock renderer]).andReturn(renderer_); + + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock + nibName:@"" + bundle:nil]; + [viewController loadView]; + weakController = viewController; + + [engineMock shutDownEngine]; + } + + EXPECT_EQ(weakController, nil); + return true; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..6cfb45e0969c20fb246f33593a0b7aaa175b34a0 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.h @@ -0,0 +1,22 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVIEWCONTROLLERTESTUTILS_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVIEWCONTROLLERTESTUTILS_H_ + +#import +#import + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" +#import "flutter/testing/testing.h" + +namespace flutter::testing { + +// Returns a mock FlutterViewController. +id CreateMockViewController(); + +} // namespace flutter::testing + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVIEWCONTROLLERTESTUTILS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.mm new file mode 100644 index 0000000000000000000000000000000000000000..a1457984a97251a9413c0f34a0abe65df72ff87b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.mm @@ -0,0 +1,21 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.h" + +namespace flutter::testing { + +id CreateMockViewController() { + { + NSString* fixtures = @(testing::GetFixturesPath()); + FlutterDartProject* project = [[FlutterDartProject alloc] + initWithAssetsPath:fixtures + ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithProject:project]; + id viewControllerMock = OCMPartialMock(viewController); + return viewControllerMock; + } +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h new file mode 100644 index 0000000000000000000000000000000000000000..301d584fdf61e3272f7d27a934b99a6203eba9d9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h @@ -0,0 +1,75 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVIEWCONTROLLER_INTERNAL_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVIEWCONTROLLER_INTERNAL_H_ + +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h" + +#include + +#import "flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMac.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterView.h" + +@interface FlutterViewController () + +// The FlutterView for this view controller. +@property(nonatomic, readonly, nullable) FlutterView* flutterView; + +@property(nonatomic, readonly) std::weak_ptr accessibilityBridge; + +/** + * Returns YES if provided event is being currently redispatched by keyboard manager. + */ +- (BOOL)isDispatchingKeyEvent:(nonnull NSEvent*)event; + +/** + * Set up the controller with `engine` and `id`, and other engine-level classes. + * + * This method is called by FlutterEngine. A view controller must be set up + * before being used, and must be set up only once until detachFromEngine:. + */ +- (void)setUpWithEngine:(nonnull FlutterEngine*)engine + viewIdentifier:(FlutterViewIdentifier)viewIdentifier; + +/** + * Reset the `engine` and `id` of this controller. + * + * This method is called by FlutterEngine. + */ +- (void)detachFromEngine; + +/** + * Called by the associated FlutterEngine when FlutterEngine#semanticsEnabled + * has changed. + */ +- (void)notifySemanticsEnabledChanged; + +/** + * Notify from the framework that the semantics for this view needs to be + * updated. + */ +- (void)updateSemantics:(nonnull const FlutterSemanticsUpdate2*)update; + +@end + +// Private methods made visible for testing +@interface FlutterViewController (TestMethods) +- (void)onAccessibilityStatusChanged:(BOOL)enabled; + +/* Creates an accessibility bridge with the provided parameters. + * + * By default this method calls AccessibilityBridgeMac's initializer. Exposing + * this method allows unit tests to override. + */ +- (std::shared_ptr)createAccessibilityBridgeWithEngine: + (nonnull FlutterEngine*)engine; + +- (nonnull FlutterView*)createFlutterViewWithMTLDevice:(nonnull id)device + commandQueue:(nonnull id)commandQueue; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVIEWCONTROLLER_INTERNAL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewEngineProvider.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewEngineProvider.h new file mode 100644 index 0000000000000000000000000000000000000000..d8e0b19aab3f15fac0596efd0951ead79d16b5c9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewEngineProvider.h @@ -0,0 +1,27 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVIEWENGINEPROVIDER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVIEWENGINEPROVIDER_H_ + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewProvider.h" + +@class FlutterEngine; + +/** + * A facade over FlutterEngine that allows FlutterEngine's children components + * to query FlutterView. + * + * FlutterViewProvider only holds a weak reference to FlutterEngine. + */ +@interface FlutterViewEngineProvider : NSObject + +/** + * Create a FlutterViewProvider with the underlying engine. + */ +- (nonnull instancetype)initWithEngine:(nonnull __weak FlutterEngine*)engine; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVIEWENGINEPROVIDER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewEngineProvider.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewEngineProvider.mm new file mode 100644 index 0000000000000000000000000000000000000000..2e2cd551925128f81f76e0f110d90a8247a2bbbc --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewEngineProvider.mm @@ -0,0 +1,29 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewEngineProvider.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" + +@interface FlutterViewEngineProvider () { + __weak FlutterEngine* _engine; +} + +@end + +@implementation FlutterViewEngineProvider + +- (instancetype)initWithEngine:(FlutterEngine*)engine { + self = [super init]; + if (self != nil) { + _engine = engine; + } + return self; +} + +- (nullable FlutterView*)viewForIdentifier:(FlutterViewIdentifier)viewIdentifier { + return [_engine viewControllerForIdentifier:viewIdentifier].flutterView; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewEngineProviderTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewEngineProviderTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..f3d158d84ea474c4e94035d942d3613305713d5b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewEngineProviderTest.mm @@ -0,0 +1,46 @@ +// 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 +#import +#import + +#include "flutter/common/constants.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewEngineProvider.h" +#import "flutter/testing/testing.h" +#include "third_party/googletest/googletest/include/gtest/gtest.h" + +namespace flutter::testing { + +TEST(FlutterViewEngineProviderUnittests, GetViewReturnsTheCorrectView) { + FlutterViewEngineProvider* viewProvider; + id mockEngine = CreateMockFlutterEngine(@""); + __block id mockFlutterViewController; + OCMStub([mockEngine viewControllerForIdentifier:0]) + .ignoringNonObjectArgs() + .andDo(^(NSInvocation* invocation) { + FlutterViewIdentifier viewIdentifier; + [invocation getArgument:&viewIdentifier atIndex:2]; + if (viewIdentifier == kFlutterImplicitViewId) { + if (mockFlutterViewController != nil) { + [invocation setReturnValue:&mockFlutterViewController]; + } + } + }); + viewProvider = [[FlutterViewEngineProvider alloc] initWithEngine:mockEngine]; + + // When the view controller is not set, the returned view is nil. + EXPECT_EQ([viewProvider viewForIdentifier:0], nil); + + // When the view controller is set, the returned view is the controller's view. + mockFlutterViewController = OCMStrictClassMock([FlutterViewController class]); + id mockView = OCMStrictClassMock([FlutterView class]); + OCMStub([mockFlutterViewController flutterView]).andReturn(mockView); + EXPECT_EQ([viewProvider viewForIdentifier:0], mockView); +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewProvider.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewProvider.h new file mode 100644 index 0000000000000000000000000000000000000000..aa4a17d05f38ff0674f268a180235a4699622750 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewProvider.h @@ -0,0 +1,28 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVIEWPROVIDER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVIEWPROVIDER_H_ + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterView.h" + +/** + * An interface to query FlutterView. + * + * See also: + * + * * FlutterViewEngineProvider, a typical implementation. + */ +@protocol FlutterViewProvider + +/** + * Get the FlutterView with the given view ID. + * + * Returns nil if the ID is invalid. + */ +- (nullable FlutterView*)viewForIdentifier:(FlutterViewIdentifier)id; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVIEWPROVIDER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..d64c6d1603622b4e3b98da2fe11f806079f1b61e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewTest.mm @@ -0,0 +1,154 @@ +// 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. + +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterView.h" + +#import + +#import "flutter/testing/testing.h" + +constexpr int64_t kImplicitViewId = 0ll; + +@interface TestFlutterViewDelegate : NSObject + +@end + +@implementation TestFlutterViewDelegate + +- (void)viewDidReshape:(nonnull NSView*)view { +} + +- (BOOL)viewShouldAcceptFirstResponder:(NSView*)view { + return YES; +} + +@end + +TEST(FlutterView, ShouldInheritContentsScaleReturnsYes) { + id device = MTLCreateSystemDefaultDevice(); + id queue = [device newCommandQueue]; + TestFlutterViewDelegate* delegate = [[TestFlutterViewDelegate alloc] init]; + FlutterView* view = [[FlutterView alloc] initWithMTLDevice:device + commandQueue:queue + delegate:delegate + viewIdentifier:kImplicitViewId]; + EXPECT_EQ([view layer:view.layer shouldInheritContentsScale:3.0 fromWindow:view.window], YES); +} + +@interface TestFlutterView : FlutterView + +@property(readwrite, nonatomic) NSView* (^onHitTest)(NSPoint point); + +@end + +@implementation TestFlutterView + +@synthesize onHitTest; + +- (NSView*)hitTest:(NSPoint)point { + return self.onHitTest(point); +} + +- (void)reshaped { + // Disable resize synchronization for testing. +} + +@end + +@interface TestCursor : NSCursor +@property(readwrite, nonatomic) BOOL setCalled; +@end + +@implementation TestCursor + +- (void)set { + self.setCalled = YES; +} + +@end + +TEST(FlutterView, CursorUpdateDoesHitTest) { + id device = MTLCreateSystemDefaultDevice(); + id queue = [device newCommandQueue]; + TestFlutterViewDelegate* delegate = [[TestFlutterViewDelegate alloc] init]; + TestFlutterView* view = [[TestFlutterView alloc] initWithMTLDevice:device + commandQueue:queue + delegate:delegate + viewIdentifier:kImplicitViewId]; + NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600) + styleMask:NSBorderlessWindowMask + backing:NSBackingStoreBuffered + defer:NO]; + + TestCursor* cursor = [[TestCursor alloc] init]; + + window.contentView = view; + __weak NSView* weakView = view; + __block BOOL hitTestCalled = NO; + __block NSPoint hitTestCoordinate = NSZeroPoint; + view.onHitTest = ^NSView*(NSPoint point) { + hitTestCalled = YES; + hitTestCoordinate = point; + return weakView; + }; + NSEvent* mouseEvent = [NSEvent mouseEventWithType:NSEventTypeMouseMoved + location:NSMakePoint(100, 100) + modifierFlags:0 + timestamp:0 + windowNumber:0 + context:nil + eventNumber:0 + clickCount:0 + pressure:0]; + [view didUpdateMouseCursor:cursor]; + [view cursorUpdate:mouseEvent]; + + EXPECT_TRUE(hitTestCalled); + // The hit test coordinate should be in the window coordinate system. + EXPECT_TRUE(CGPointEqualToPoint(hitTestCoordinate, CGPointMake(100, 100))); + EXPECT_TRUE(cursor.setCalled); +} + +TEST(FlutterView, CursorUpdateDoesNotOverridePlatformView) { + id device = MTLCreateSystemDefaultDevice(); + id queue = [device newCommandQueue]; + TestFlutterViewDelegate* delegate = [[TestFlutterViewDelegate alloc] init]; + TestFlutterView* view = [[TestFlutterView alloc] initWithMTLDevice:device + commandQueue:queue + delegate:delegate + viewIdentifier:kImplicitViewId]; + NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600) + styleMask:NSBorderlessWindowMask + backing:NSBackingStoreBuffered + defer:NO]; + + TestCursor* cursor = [[TestCursor alloc] init]; + + NSView* platformView = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)]; + + window.contentView = view; + __block BOOL hitTestCalled = NO; + __block NSPoint hitTestCoordinate = NSZeroPoint; + view.onHitTest = ^NSView*(NSPoint point) { + hitTestCalled = YES; + hitTestCoordinate = point; + return platformView; + }; + NSEvent* mouseEvent = [NSEvent mouseEventWithType:NSEventTypeMouseMoved + location:NSMakePoint(100, 100) + modifierFlags:0 + timestamp:0 + windowNumber:0 + context:nil + eventNumber:0 + clickCount:0 + pressure:0]; + [view didUpdateMouseCursor:cursor]; + [view cursorUpdate:mouseEvent]; + + EXPECT_TRUE(hitTestCalled); + // The hit test coordinate should be in the window coordinate system. + EXPECT_TRUE(CGPointEqualToPoint(hitTestCoordinate, CGPointMake(100, 100))); + EXPECT_FALSE(cursor.setCalled); +} diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/KeyCodeMap.g.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/KeyCodeMap.g.mm new file mode 100644 index 0000000000000000000000000000000000000000..0704ad2406cdbeb3d50237b7e93f18543b99e3cc --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/KeyCodeMap.g.mm @@ -0,0 +1,300 @@ +// 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. + +#import +#import +#include "./KeyCodeMap_Internal.h" + +// DO NOT EDIT -- DO NOT EDIT -- DO NOT EDIT +// This file is generated by +// flutter/flutter:dev/tools/gen_keycodes/bin/gen_keycodes.dart and should not +// be edited directly. +// +// Edit the template +// flutter/flutter:dev/tools/gen_keycodes/data/keyboard_map_macos_cc.tmpl +// instead. +// +// See flutter/flutter:dev/tools/gen_keycodes/README.md for more information. + +namespace flutter { + +const uint64_t kValueMask = 0x000ffffffff; +const uint64_t kUnicodePlane = 0x00000000000; +const uint64_t kMacosPlane = 0x01400000000; + +const NSDictionary* keyCodeToPhysicalKey = @{ + @0x00000000 : @0x00070004, // keyA + @0x00000001 : @0x00070016, // keyS + @0x00000002 : @0x00070007, // keyD + @0x00000003 : @0x00070009, // keyF + @0x00000004 : @0x0007000b, // keyH + @0x00000005 : @0x0007000a, // keyG + @0x00000006 : @0x0007001d, // keyZ + @0x00000007 : @0x0007001b, // keyX + @0x00000008 : @0x00070006, // keyC + @0x00000009 : @0x00070019, // keyV + @0x0000000a : @0x00070064, // intlBackslash + @0x0000000b : @0x00070005, // keyB + @0x0000000c : @0x00070014, // keyQ + @0x0000000d : @0x0007001a, // keyW + @0x0000000e : @0x00070008, // keyE + @0x0000000f : @0x00070015, // keyR + @0x00000010 : @0x0007001c, // keyY + @0x00000011 : @0x00070017, // keyT + @0x00000012 : @0x0007001e, // digit1 + @0x00000013 : @0x0007001f, // digit2 + @0x00000014 : @0x00070020, // digit3 + @0x00000015 : @0x00070021, // digit4 + @0x00000016 : @0x00070023, // digit6 + @0x00000017 : @0x00070022, // digit5 + @0x00000018 : @0x0007002e, // equal + @0x00000019 : @0x00070026, // digit9 + @0x0000001a : @0x00070024, // digit7 + @0x0000001b : @0x0007002d, // minus + @0x0000001c : @0x00070025, // digit8 + @0x0000001d : @0x00070027, // digit0 + @0x0000001e : @0x00070030, // bracketRight + @0x0000001f : @0x00070012, // keyO + @0x00000020 : @0x00070018, // keyU + @0x00000021 : @0x0007002f, // bracketLeft + @0x00000022 : @0x0007000c, // keyI + @0x00000023 : @0x00070013, // keyP + @0x00000024 : @0x00070028, // enter + @0x00000025 : @0x0007000f, // keyL + @0x00000026 : @0x0007000d, // keyJ + @0x00000027 : @0x00070034, // quote + @0x00000028 : @0x0007000e, // keyK + @0x00000029 : @0x00070033, // semicolon + @0x0000002a : @0x00070031, // backslash + @0x0000002b : @0x00070036, // comma + @0x0000002c : @0x00070038, // slash + @0x0000002d : @0x00070011, // keyN + @0x0000002e : @0x00070010, // keyM + @0x0000002f : @0x00070037, // period + @0x00000030 : @0x0007002b, // tab + @0x00000031 : @0x0007002c, // space + @0x00000032 : @0x00070035, // backquote + @0x00000033 : @0x0007002a, // backspace + @0x00000035 : @0x00070029, // escape + @0x00000036 : @0x000700e7, // metaRight + @0x00000037 : @0x000700e3, // metaLeft + @0x00000038 : @0x000700e1, // shiftLeft + @0x00000039 : @0x00070039, // capsLock + @0x0000003a : @0x000700e2, // altLeft + @0x0000003b : @0x000700e0, // controlLeft + @0x0000003c : @0x000700e5, // shiftRight + @0x0000003d : @0x000700e6, // altRight + @0x0000003e : @0x000700e4, // controlRight + @0x0000003f : @0x00000012, // fn + @0x00000040 : @0x0007006c, // f17 + @0x00000041 : @0x00070063, // numpadDecimal + @0x00000043 : @0x00070055, // numpadMultiply + @0x00000045 : @0x00070057, // numpadAdd + @0x00000047 : @0x00070053, // numLock + @0x00000048 : @0x00070080, // audioVolumeUp + @0x00000049 : @0x00070081, // audioVolumeDown + @0x0000004a : @0x0007007f, // audioVolumeMute + @0x0000004b : @0x00070054, // numpadDivide + @0x0000004c : @0x00070058, // numpadEnter + @0x0000004e : @0x00070056, // numpadSubtract + @0x0000004f : @0x0007006d, // f18 + @0x00000050 : @0x0007006e, // f19 + @0x00000051 : @0x00070067, // numpadEqual + @0x00000052 : @0x00070062, // numpad0 + @0x00000053 : @0x00070059, // numpad1 + @0x00000054 : @0x0007005a, // numpad2 + @0x00000055 : @0x0007005b, // numpad3 + @0x00000056 : @0x0007005c, // numpad4 + @0x00000057 : @0x0007005d, // numpad5 + @0x00000058 : @0x0007005e, // numpad6 + @0x00000059 : @0x0007005f, // numpad7 + @0x0000005a : @0x0007006f, // f20 + @0x0000005b : @0x00070060, // numpad8 + @0x0000005c : @0x00070061, // numpad9 + @0x0000005d : @0x00070089, // intlYen + @0x0000005e : @0x00070087, // intlRo + @0x0000005f : @0x00070085, // numpadComma + @0x00000060 : @0x0007003e, // f5 + @0x00000061 : @0x0007003f, // f6 + @0x00000062 : @0x00070040, // f7 + @0x00000063 : @0x0007003c, // f3 + @0x00000064 : @0x00070041, // f8 + @0x00000065 : @0x00070042, // f9 + @0x00000066 : @0x00070091, // lang2 + @0x00000067 : @0x00070044, // f11 + @0x00000068 : @0x00070090, // lang1 + @0x00000069 : @0x00070068, // f13 + @0x0000006a : @0x0007006b, // f16 + @0x0000006b : @0x00070069, // f14 + @0x0000006d : @0x00070043, // f10 + @0x0000006e : @0x00070065, // contextMenu + @0x0000006f : @0x00070045, // f12 + @0x00000071 : @0x0007006a, // f15 + @0x00000072 : @0x00070049, // insert + @0x00000073 : @0x0007004a, // home + @0x00000074 : @0x0007004b, // pageUp + @0x00000075 : @0x0007004c, // delete + @0x00000076 : @0x0007003d, // f4 + @0x00000077 : @0x0007004d, // end + @0x00000078 : @0x0007003b, // f2 + @0x00000079 : @0x0007004e, // pageDown + @0x0000007a : @0x0007003a, // f1 + @0x0000007b : @0x00070050, // arrowLeft + @0x0000007c : @0x0007004f, // arrowRight + @0x0000007d : @0x00070051, // arrowDown + @0x0000007e : @0x00070052, // arrowUp +}; + +const NSDictionary* keyCodeToLogicalKey = @{ + @0x00000024 : @0x0010000000d, // Enter -> enter + @0x00000030 : @0x00100000009, // Tab -> tab + @0x00000033 : @0x00100000008, // Backspace -> backspace + @0x00000035 : @0x0010000001b, // Escape -> escape + @0x00000036 : @0x00200000107, // MetaRight -> metaRight + @0x00000037 : @0x00200000106, // MetaLeft -> metaLeft + @0x00000038 : @0x00200000102, // ShiftLeft -> shiftLeft + @0x00000039 : @0x00100000104, // CapsLock -> capsLock + @0x0000003a : @0x00200000104, // AltLeft -> altLeft + @0x0000003b : @0x00200000100, // ControlLeft -> controlLeft + @0x0000003c : @0x00200000103, // ShiftRight -> shiftRight + @0x0000003d : @0x00200000105, // AltRight -> altRight + @0x0000003e : @0x00200000101, // ControlRight -> controlRight + @0x0000003f : @0x00100000106, // Fn -> fn + @0x00000040 : @0x00100000811, // F17 -> f17 + @0x00000041 : @0x0020000022e, // NumpadDecimal -> numpadDecimal + @0x00000043 : @0x0020000022a, // NumpadMultiply -> numpadMultiply + @0x00000045 : @0x0020000022b, // NumpadAdd -> numpadAdd + @0x00000047 : @0x0010000010a, // NumLock -> numLock + @0x00000048 : @0x00100000a10, // AudioVolumeUp -> audioVolumeUp + @0x00000049 : @0x00100000a0f, // AudioVolumeDown -> audioVolumeDown + @0x0000004a : @0x00100000a11, // AudioVolumeMute -> audioVolumeMute + @0x0000004b : @0x0020000022f, // NumpadDivide -> numpadDivide + @0x0000004c : @0x0020000020d, // NumpadEnter -> numpadEnter + @0x0000004e : @0x0020000022d, // NumpadSubtract -> numpadSubtract + @0x0000004f : @0x00100000812, // F18 -> f18 + @0x00000050 : @0x00100000813, // F19 -> f19 + @0x00000051 : @0x0020000023d, // NumpadEqual -> numpadEqual + @0x00000052 : @0x00200000230, // Numpad0 -> numpad0 + @0x00000053 : @0x00200000231, // Numpad1 -> numpad1 + @0x00000054 : @0x00200000232, // Numpad2 -> numpad2 + @0x00000055 : @0x00200000233, // Numpad3 -> numpad3 + @0x00000056 : @0x00200000234, // Numpad4 -> numpad4 + @0x00000057 : @0x00200000235, // Numpad5 -> numpad5 + @0x00000058 : @0x00200000236, // Numpad6 -> numpad6 + @0x00000059 : @0x00200000237, // Numpad7 -> numpad7 + @0x0000005a : @0x00100000814, // F20 -> f20 + @0x0000005b : @0x00200000238, // Numpad8 -> numpad8 + @0x0000005c : @0x00200000239, // Numpad9 -> numpad9 + @0x0000005d : @0x00200000022, // IntlYen -> intlYen + @0x0000005e : @0x00200000021, // IntlRo -> intlRo + @0x0000005f : @0x0020000022c, // NumpadComma -> numpadComma + @0x00000060 : @0x00100000805, // F5 -> f5 + @0x00000061 : @0x00100000806, // F6 -> f6 + @0x00000062 : @0x00100000807, // F7 -> f7 + @0x00000063 : @0x00100000803, // F3 -> f3 + @0x00000064 : @0x00100000808, // F8 -> f8 + @0x00000065 : @0x00100000809, // F9 -> f9 + @0x00000066 : @0x00200000011, // Lang2 -> lang2 + @0x00000067 : @0x0010000080b, // F11 -> f11 + @0x00000068 : @0x00200000010, // Lang1 -> lang1 + @0x00000069 : @0x0010000080d, // F13 -> f13 + @0x0000006a : @0x00100000810, // F16 -> f16 + @0x0000006b : @0x0010000080e, // F14 -> f14 + @0x0000006d : @0x0010000080a, // F10 -> f10 + @0x0000006e : @0x00100000505, // ContextMenu -> contextMenu + @0x0000006f : @0x0010000080c, // F12 -> f12 + @0x00000071 : @0x0010000080f, // F15 -> f15 + @0x00000072 : @0x00100000407, // Insert -> insert + @0x00000073 : @0x00100000306, // Home -> home + @0x00000074 : @0x00100000308, // PageUp -> pageUp + @0x00000075 : @0x0010000007f, // Delete -> delete + @0x00000076 : @0x00100000804, // F4 -> f4 + @0x00000077 : @0x00100000305, // End -> end + @0x00000078 : @0x00100000802, // F2 -> f2 + @0x00000079 : @0x00100000307, // PageDown -> pageDown + @0x0000007a : @0x00100000801, // F1 -> f1 + @0x0000007b : @0x00100000302, // ArrowLeft -> arrowLeft + @0x0000007c : @0x00100000303, // ArrowRight -> arrowRight + @0x0000007d : @0x00100000301, // ArrowDown -> arrowDown + @0x0000007e : @0x00100000304, // ArrowUp -> arrowUp +}; + +const NSDictionary* keyCodeToModifierFlag = @{ + @0x00000038 : @(kModifierFlagShiftLeft), + @0x0000003c : @(kModifierFlagShiftRight), + @0x0000003b : @(kModifierFlagControlLeft), + @0x0000003e : @(kModifierFlagControlRight), + @0x0000003a : @(kModifierFlagAltLeft), + @0x0000003d : @(kModifierFlagAltRight), + @0x00000037 : @(kModifierFlagMetaLeft), + @0x00000036 : @(kModifierFlagMetaRight), +}; + +const NSDictionary* modifierFlagToKeyCode = @{ + @(kModifierFlagShiftLeft) : @0x00000038, + @(kModifierFlagShiftRight) : @0x0000003c, + @(kModifierFlagControlLeft) : @0x0000003b, + @(kModifierFlagControlRight) : @0x0000003e, + @(kModifierFlagAltLeft) : @0x0000003a, + @(kModifierFlagAltRight) : @0x0000003d, + @(kModifierFlagMetaLeft) : @0x00000037, + @(kModifierFlagMetaRight) : @0x00000036, +}; + +const uint64_t kCapsLockPhysicalKey = 0x00070039; +const uint64_t kCapsLockLogicalKey = 0x100000104; + +const std::vector kLayoutGoals = { + LayoutGoal{0x31, 0x20, false}, // Space + LayoutGoal{0x27, 0x22, false}, // Quote + LayoutGoal{0x2b, 0x2c, false}, // Comma + LayoutGoal{0x1b, 0x2d, false}, // Minus + LayoutGoal{0x2f, 0x2e, false}, // Period + LayoutGoal{0x2c, 0x2f, false}, // Slash + LayoutGoal{0x1d, 0x30, true}, // Digit0 + LayoutGoal{0x12, 0x31, true}, // Digit1 + LayoutGoal{0x13, 0x32, true}, // Digit2 + LayoutGoal{0x14, 0x33, true}, // Digit3 + LayoutGoal{0x15, 0x34, true}, // Digit4 + LayoutGoal{0x17, 0x35, true}, // Digit5 + LayoutGoal{0x16, 0x36, true}, // Digit6 + LayoutGoal{0x1a, 0x37, true}, // Digit7 + LayoutGoal{0x1c, 0x38, true}, // Digit8 + LayoutGoal{0x19, 0x39, true}, // Digit9 + LayoutGoal{0x29, 0x3b, false}, // Semicolon + LayoutGoal{0x18, 0x3d, false}, // Equal + LayoutGoal{0x21, 0x5b, false}, // BracketLeft + LayoutGoal{0x2a, 0x5c, false}, // Backslash + LayoutGoal{0x1e, 0x5d, false}, // BracketRight + LayoutGoal{0x32, 0x60, false}, // Backquote + LayoutGoal{0x00, 0x61, true}, // KeyA + LayoutGoal{0x0b, 0x62, true}, // KeyB + LayoutGoal{0x08, 0x63, true}, // KeyC + LayoutGoal{0x02, 0x64, true}, // KeyD + LayoutGoal{0x0e, 0x65, true}, // KeyE + LayoutGoal{0x03, 0x66, true}, // KeyF + LayoutGoal{0x05, 0x67, true}, // KeyG + LayoutGoal{0x04, 0x68, true}, // KeyH + LayoutGoal{0x22, 0x69, true}, // KeyI + LayoutGoal{0x26, 0x6a, true}, // KeyJ + LayoutGoal{0x28, 0x6b, true}, // KeyK + LayoutGoal{0x25, 0x6c, true}, // KeyL + LayoutGoal{0x2e, 0x6d, true}, // KeyM + LayoutGoal{0x2d, 0x6e, true}, // KeyN + LayoutGoal{0x1f, 0x6f, true}, // KeyO + LayoutGoal{0x23, 0x70, true}, // KeyP + LayoutGoal{0x0c, 0x71, true}, // KeyQ + LayoutGoal{0x0f, 0x72, true}, // KeyR + LayoutGoal{0x01, 0x73, true}, // KeyS + LayoutGoal{0x11, 0x74, true}, // KeyT + LayoutGoal{0x20, 0x75, true}, // KeyU + LayoutGoal{0x09, 0x76, true}, // KeyV + LayoutGoal{0x0d, 0x77, true}, // KeyW + LayoutGoal{0x07, 0x78, true}, // KeyX + LayoutGoal{0x10, 0x79, true}, // KeyY + LayoutGoal{0x06, 0x7a, true}, // KeyZ + LayoutGoal{0x0a, 0x200000020, false}, // IntlBackslash +}; + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/KeyCodeMapTest.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/KeyCodeMapTest.mm new file mode 100644 index 0000000000000000000000000000000000000000..aebacdfd9da3a825b8126f8d9b59f99e7a6c405a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/KeyCodeMapTest.mm @@ -0,0 +1,39 @@ +// 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. + +#import "KeyCodeMap_Internal.h" + +#import "flutter/testing/testing.h" +#include "third_party/googletest/googletest/include/gtest/gtest.h" + +namespace flutter { + +bool operator==(const LayoutGoal& a, const LayoutGoal& b) { + return a.keyCode == b.keyCode && a.keyChar == b.keyChar && a.mandatory == b.mandatory; +} + +namespace testing { + +// Spot check some expected values so that we know that some classes of key +// aren't excluded. +TEST(KeyMappingTest, HasExpectedValues) { + // Has Space + EXPECT_NE(std::find(kLayoutGoals.begin(), kLayoutGoals.end(), LayoutGoal{0x31, 0x20, false}), + kLayoutGoals.end()); + // Has Digit0 + EXPECT_NE(std::find(kLayoutGoals.begin(), kLayoutGoals.end(), LayoutGoal{0x1d, 0x30, true}), + kLayoutGoals.end()); + // Has KeyA + EXPECT_NE(std::find(kLayoutGoals.begin(), kLayoutGoals.end(), LayoutGoal{0x00, 0x61, true}), + kLayoutGoals.end()); + // Has Equal + EXPECT_NE(std::find(kLayoutGoals.begin(), kLayoutGoals.end(), LayoutGoal{0x18, 0x3d, false}), + kLayoutGoals.end()); + // Has IntlBackslash + EXPECT_NE( + std::find(kLayoutGoals.begin(), kLayoutGoals.end(), LayoutGoal{0x0a, 0x200000020, false}), + kLayoutGoals.end()); +} +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/KeyCodeMap_Internal.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/KeyCodeMap_Internal.h new file mode 100644 index 0000000000000000000000000000000000000000..a612d06190655351132d7c9704d5d9bd17c9c5c0 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/KeyCodeMap_Internal.h @@ -0,0 +1,114 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_KEYCODEMAP_INTERNAL_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_KEYCODEMAP_INTERNAL_H_ + +#import +#include +#include + +namespace flutter { + +/** + * Maps macOS-specific key code values representing |PhysicalKeyboardKey|. + * + * MacOS doesn't provide a scan code, but a virtual keycode to represent a physical key. + */ +extern const NSDictionary* keyCodeToPhysicalKey; + +/** + * A map from macOS key codes to Flutter's logical key values. + * + * This is used to derive logical keys that can't or shouldn't be derived from + * |charactersIgnoringModifiers|. + */ +extern const NSDictionary* keyCodeToLogicalKey; + +// Several mask constants. See KeyCodeMap.g.mm for their descriptions. + +/** + * Mask for the 32-bit value portion of the key code. + */ +extern const uint64_t kValueMask; + +/** + * The plane value for keys which have a Unicode representation. + */ +extern const uint64_t kUnicodePlane; + +/** + * The plane value for the private keys defined by the macOS embedding. + */ +extern const uint64_t kMacosPlane; + +/** + * Map |NSEvent.keyCode| to its corresponding bitmask of NSEventModifierFlags. + * + * This does not include CapsLock, for it is handled specially. + */ +extern const NSDictionary* keyCodeToModifierFlag; + +/** + * Map a bit of bitmask of NSEventModifierFlags to its corresponding + * |NSEvent.keyCode|. + * + * This does not include CapsLock, for it is handled specially. + */ +extern const NSDictionary* modifierFlagToKeyCode; + +/** + * The physical key for CapsLock, which needs special handling. + */ +extern const uint64_t kCapsLockPhysicalKey; + +/** + * The logical key for CapsLock, which needs special handling. + */ +extern const uint64_t kCapsLockLogicalKey; + +/** + * Bits in |NSEvent.modifierFlags| indicating whether a modifier key is pressed. + * + * These constants are not written in the official documentation, but derived + * from experiments. This is currently the only way to know whether a one-side + * modifier key (such as ShiftLeft) is pressed, instead of the general combined + * modifier state (such as Shift). + */ +typedef enum { + kModifierFlagControlLeft = 0x1, + kModifierFlagShiftLeft = 0x2, + kModifierFlagShiftRight = 0x4, + kModifierFlagMetaLeft = 0x8, + kModifierFlagMetaRight = 0x10, + kModifierFlagAltLeft = 0x20, + kModifierFlagAltRight = 0x40, + kModifierFlagControlRight = 0x200, +} ModifierFlag; + +/** + * A character that Flutter wants to derive layout for, and guides on how to + * derive it. + */ +typedef struct { + // The key code for a key that prints `keyChar` in the US keyboard layout. + uint16_t keyCode; + + // The printable string to derive logical key for. + uint64_t keyChar; + + // If the goal is mandatory, the keyboard manager will make sure to find a + // logical key for this character, falling back to the US keyboard layout. + bool mandatory; +} LayoutGoal; + +/** + * All keys that Flutter wants to derive layout for, and guides on how to derive + * them. + */ +extern const std::vector kLayoutGoals; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_KEYCODEMAP_INTERNAL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/NSView+ClipsToBounds.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/NSView+ClipsToBounds.h new file mode 100644 index 0000000000000000000000000000000000000000..49f332247d2e397c0721e1a1bc3795a004b321cd --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/NSView+ClipsToBounds.h @@ -0,0 +1,15 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_NSVIEW_CLIPSTOBOUNDS_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_NSVIEW_CLIPSTOBOUNDS_H_ + +#import + +@interface NSView (ClipsToBounds) +// This property is available since macOS 10.9 but only declared in macOS 14 SDK. +@property BOOL clipsToBounds API_AVAILABLE(macos(10.9)); +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_NSVIEW_CLIPSTOBOUNDS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/TestFlutterPlatformView.h b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/TestFlutterPlatformView.h new file mode 100644 index 0000000000000000000000000000000000000000..3f256ea3af3a004f4d0b8162e1eef52e4050786c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/TestFlutterPlatformView.h @@ -0,0 +1,22 @@ +// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_TESTFLUTTERPLATFORMVIEW_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_TESTFLUTTERPLATFORMVIEW_H_ + +#import + +#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h" + +@interface TestFlutterPlatformView : NSView + +/// Arguments passed via the params value in the create method call. +@property(nonatomic, copy) id args; + +@end + +@interface TestFlutterPlatformViewFactory : NSObject +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_TESTFLUTTERPLATFORMVIEW_H_ diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/TestFlutterPlatformView.mm b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/TestFlutterPlatformView.mm new file mode 100644 index 0000000000000000000000000000000000000000..b1bd763b25c4ac7416a5d2ef823471e866bb2432 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/TestFlutterPlatformView.mm @@ -0,0 +1,29 @@ +// 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. + +#import +#import + +#import "flutter/shell/platform/darwin/macos/framework/Source/TestFlutterPlatformView.h" + +@implementation TestFlutterPlatformView + +- (instancetype)initWithFrame:(CGRect)frame arguments:(nullable NSDictionary*)args { + self = [super initWithFrame:frame]; + _args = args; + return self; +} + +@end + +@implementation TestFlutterPlatformViewFactory +- (NSView*)createWithViewIdentifier:(int64_t)viewId arguments:(nullable id)args { + return [[TestFlutterPlatformView alloc] initWithFrame:CGRectZero arguments:args]; +} + +- (NSObject*)createArgsCodec { + return [FlutterStandardMessageCodec sharedInstance]; +} + +@end diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/fixtures/flutter_desktop_test.dart b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/fixtures/flutter_desktop_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..208d466cbf4876b9862d466460fea8ac6e06df16 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/Source/fixtures/flutter_desktop_test.dart @@ -0,0 +1,95 @@ +// 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. + +// ignore_for_file: avoid_print + +import 'dart:io'; +import 'dart:typed_data'; +import 'dart:ui'; + +@pragma('vm:external-name', 'SignalNativeTest') +external void signalNativeTest(); + +void main() {} + +@pragma('vm:entry-point') +void empty() {} + +/// Notifies the test of a string value. +/// +/// This is used to notify the native side of the test of a string value from +/// the Dart fixture under test. +@pragma('vm:external-name', 'NotifyStringValue') +external void notifyStringValue(String s); + +@pragma('vm:entry-point') +void executableNameNotNull() { + notifyStringValue(Platform.executable); +} + +@pragma('vm:entry-point') +void canLogToStdout() { + // Emit hello world message to output then signal the test. + print('Hello logging'); + signalNativeTest(); +} + +@pragma('vm:entry-point') +void canCompositePlatformViews() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + final builder = SceneBuilder(); + builder.addPicture(const Offset(1.0, 1.0), _createSimplePicture()); + builder.pushOffset(1.0, 2.0); + builder.addPlatformView(42, width: 123.0, height: 456.0); + builder.addPicture(const Offset(1.0, 1.0), _createSimplePicture()); + builder.pop(); // offset + PlatformDispatcher.instance.views.first.render(builder.build()); + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +void drawIntoAllViews() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + final builder = SceneBuilder(); + builder.addPicture(const Offset(1.0, 1.0), _createSimplePicture()); + for (final FlutterView view in PlatformDispatcher.instance.views) { + view.render(builder.build()); + } + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +/// Returns a [Picture] of a simple black square. +Picture _createSimplePicture() { + final blackPaint = Paint(); + final baseRecorder = PictureRecorder(); + final canvas = Canvas(baseRecorder); + canvas.drawRect(const Rect.fromLTRB(0.0, 0.0, 1000.0, 1000.0), blackPaint); + return baseRecorder.endRecording(); +} + +@pragma('vm:entry-point') +void nativeCallback() { + signalNativeTest(); +} + +@pragma('vm:entry-point') +void backgroundTest() { + PlatformDispatcher.instance.views.first.render(SceneBuilder().build()); + signalNativeTest(); // should look black +} + +@pragma('vm:entry-point') +void sendFooMessage() { + PlatformDispatcher.instance.sendPlatformMessage('foo', null, (ByteData? result) {}); +} + +@pragma('vm:external-name', 'NotifyEngineId') +external void notifyEngineId(int? engineId); + +@pragma('vm:entry-point') +void testEngineId() { + notifyEngineId(PlatformDispatcher.instance.engineId); +} diff --git a/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/module.modulemap b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/module.modulemap new file mode 100644 index 0000000000000000000000000000000000000000..3e70a88b7c220a6d2e82a2d79ebddd5f09252cff --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/macos/framework/module.modulemap @@ -0,0 +1,6 @@ +framework module FlutterMacOS { + umbrella header "FlutterMacOS.h" + + export * + module * { export * } +} diff --git a/flutter/engine/src/flutter/shell/platform/embedder/assets/EmbedderInfo.plist b/flutter/engine/src/flutter/shell/platform/embedder/assets/EmbedderInfo.plist new file mode 100644 index 0000000000000000000000000000000000000000..2c37b435d362b988a59d7f6fad1cc1162b7d00aa --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/assets/EmbedderInfo.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + FlutterEmbedder + CFBundleIdentifier + io.flutter.flutter-embedder + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + FlutterEmbedder + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSupportedPlatforms + + MacOSX + + CFBundleVersion + 1 + NSHumanReadableCopyright + Copyright 2013 The Flutter Authors. All rights reserved. + FlutterEngine + {revision} + ClangVersion + {clang_version} + + diff --git a/flutter/engine/src/flutter/shell/platform/embedder/assets/embedder.modulemap b/flutter/engine/src/flutter/shell/platform/embedder/assets/embedder.modulemap new file mode 100644 index 0000000000000000000000000000000000000000..60328fe17e31b27dc4cfa9a8628fdfa5f2ca284e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/assets/embedder.modulemap @@ -0,0 +1,6 @@ +framework module FlutterEmbedder { + umbrella header "FlutterEmbedder.h" + + export * + module * { export * } +} diff --git a/flutter/engine/src/flutter/shell/platform/embedder/fixtures/README.md b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/README.md new file mode 100644 index 0000000000000000000000000000000000000000..eed3fe6b865a17655e14900a97e2ac0f91ce5212 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/README.md @@ -0,0 +1,83 @@ +# `platform/embedder/fixtures` + +The files in this directory are golden-file outputss of [`tests`](../tests), +but lack a simple way to be re-generated. + +For example, here is what a failure might look like on CI: + +```txt +[0;32m[ RUN ] EmbedderTest.VerifyB143464703WithSoftwareBackend +[ERROR:flutter/shell/platform/embedder/tests/embedder_unittests_util.cc(199)] Image did not match expectation. +Expected:/b/s/w/ir/cache/builder/src/out/host_debug_unopt/gen/flutter/shell/platform/embedder/assets/expectation_verifyb143464703_soft_noxform.png +Got:/b/s/w/ir/cache/builder/src/out/host_debug_unopt/gen/flutter/shell/platform/embedder/assets/actual_verifyb143464703_soft_noxform.png + +../../flutter/shell/platform/embedder/tests/embedder_unittests.cc:1335: Failure +Value of: ImageMatchesFixture("verifyb143464703_soft_noxform.png", rendered_scene) + Actual: false +Expected: true +[ FAILED ] EmbedderTest.VerifyB143464703WithSoftwareBackend (8077 ms) +[----------] 1 test from EmbedderTest (8080 ms total) + +[----------] Global test environment tear-down +[==========] 1 test from 1 test suite ran. (8080 ms total) +[ PASSED ] 0 tests. +[ FAILED ] 1 test, listed below: +[ FAILED ] EmbedderTest.VerifyB143464703WithSoftwareBackend + + 1 FAILED TEST +[13/296] EmbedderTest.VerifyB143464703WithSoftwareBackend returned/aborted with exit code 1 (8226 ms) +[14/296] EmbedderTest.VerifyB143464703WithSoftwareBackend (8484 ms) +[INFO:test_timeout_listener.cc(76)] Test timeout of 300 seconds per test case will be enforced. +Note: Google Test filter = EmbedderTest.VerifyB143464703WithSoftwareBackend +[==========] Running 1 test from 1 test suite. +[----------] Global test environment set-up. +[----------] 1 test from EmbedderTest +[ DISABLED ] EmbedderTest.DISABLED_CanLaunchAndShutdownMultipleTimes +[ RUN ] EmbedderTest.VerifyB143464703WithSoftwareBackend +[ERROR:flutter/shell/platform/embedder/tests/embedder_unittests_util.cc(199)] Image did not match expectation. +Expected:/b/s/w/ir/cache/builder/src/out/host_debug_unopt/gen/flutter/shell/platform/embedder/assets/expectation_verifyb143464703_soft_noxform.png +Got:/b/s/w/ir/cache/builder/src/out/host_debug_unopt/gen/flutter/shell/platform/embedder/assets/actual_verifyb143464703_soft_noxform.png + +../../flutter/shell/platform/embedder/tests/embedder_unittests.cc:1335: Failure +Value of: ImageMatchesFixture("verifyb143464703_soft_noxform.png", rendered_scene) + Actual: false +Expected: true +[ FAILED ] EmbedderTest.VerifyB143464703WithSoftwareBackend (8348 ms) +[----------] 1 test from EmbedderTest (8350 ms total) + +[----------] Global test environment tear-down +[==========] 1 test from 1 test suite ran. (8350 ms total) +[ PASSED ] 0 tests. +[ FAILED ] 1 test, listed below: +[ FAILED ] EmbedderTest.VerifyB143464703WithSoftwareBackend +``` + +In order to update `verifyb143464703_soft_noxform.png`: + +```shell +# The examples below assume: +# $ENGINE = /path/to/engine/src +# $TARGET = /path/to/engine/src/out/{{host_you_want_to_build}} + +# 1. Make sure you have built the engine: +$ ninja -j1000 -C $ENGINE/out/$TARGET + +# 2. Run the test locally (assuming you have built the engine). +$ $ENGINE/out/$TARGET/embedder_unittests* + +# Or, to run just a single test: +$ $ENGINE/out/$TARGET/embedder_unittests --gtest_filter="EmbedderTest.VerifyB143464703WithSoftwareBackend" + +# Or, a suite of tests: +$ $ENGINE/out/$TARGET/embedder_unittests --gtest_filter="EmbedderTest.*" + +# 3. Now, copy the output to the golden file (notice the "actual_" prefix): +$ cp \ + $ENGINE/out/$TARGET/gen/flutter/shell/platform/embedder/assets/actual_verifyb143464703_soft_noxform.png \ + $ENGINE/flutter/shell/platform/embedder/fixtures/verifyb143464703_soft_noxform.png +``` + +⚠️ **WARNING**: Some of the golden tests do not run on non-Linux OSes, which +means its not currently possible to re-generate them on non-Linux OSes +(). So uh, setup a Linux VM +or find a friend with a Linux machine. diff --git a/flutter/engine/src/flutter/shell/platform/embedder/fixtures/arc_end_caps.png b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/arc_end_caps.png new file mode 100644 index 0000000000000000000000000000000000000000..b9701b3a48c50a4a80baeeabc7ebf87492e13d48 Binary files /dev/null and b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/arc_end_caps.png differ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/fixtures/compositor.png b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/compositor.png new file mode 100644 index 0000000000000000000000000000000000000000..038efaab9d8a880b028523437e52b400957d4993 Binary files /dev/null and b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/compositor.png differ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/fixtures/compositor_platform_layer_with_no_overlay.png b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/compositor_platform_layer_with_no_overlay.png new file mode 100644 index 0000000000000000000000000000000000000000..20109dfd893d43cbfb373abb4496677d87e58c97 Binary files /dev/null and b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/compositor_platform_layer_with_no_overlay.png differ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/fixtures/compositor_root_surface_xformation.png b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/compositor_root_surface_xformation.png new file mode 100644 index 0000000000000000000000000000000000000000..8191fa524b45bac91fd0069f47c9bd660f101ad6 Binary files /dev/null and b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/compositor_root_surface_xformation.png differ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/fixtures/compositor_software.png b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/compositor_software.png new file mode 100644 index 0000000000000000000000000000000000000000..f2efa1343cc2c91333b7411a2a07b8d12c1f349b Binary files /dev/null and b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/compositor_software.png differ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/fixtures/compositor_with_platform_layer_on_bottom.png b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/compositor_with_platform_layer_on_bottom.png new file mode 100644 index 0000000000000000000000000000000000000000..ee67d2226a186e21d438c01efc2b34df080a36ec Binary files /dev/null and b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/compositor_with_platform_layer_on_bottom.png differ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/fixtures/compositor_with_root_layer_only.png b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/compositor_with_root_layer_only.png new file mode 100644 index 0000000000000000000000000000000000000000..de57a88e518cfd49096263da42648d283802a492 Binary files /dev/null and b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/compositor_with_root_layer_only.png differ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/fixtures/dpr_noxform.png b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/dpr_noxform.png new file mode 100644 index 0000000000000000000000000000000000000000..ba557532583c3d6246f69949046b28bcf59137fe Binary files /dev/null and b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/dpr_noxform.png differ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/fixtures/dpr_xform.png b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/dpr_xform.png new file mode 100644 index 0000000000000000000000000000000000000000..12e48fae67a4f1728b6f9c79faeb9c83bfa73c46 Binary files /dev/null and b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/dpr_xform.png differ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/fixtures/external_texture_metal.png b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/external_texture_metal.png new file mode 100644 index 0000000000000000000000000000000000000000..89f889b95dcb75ae7a60517e086d71ae98dec8b5 Binary files /dev/null and b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/external_texture_metal.png differ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/fixtures/gradient.png b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/gradient.png new file mode 100644 index 0000000000000000000000000000000000000000..c4ae3b511f879a9bdc1c2950184faeb92a0ba0d4 Binary files /dev/null and b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/gradient.png differ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/fixtures/gradient_metal.png b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/gradient_metal.png new file mode 100644 index 0000000000000000000000000000000000000000..618a31cbfad98a37ec24766ef263956094f8a9ab Binary files /dev/null and b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/gradient_metal.png differ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/fixtures/gradient_xform.png b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/gradient_xform.png new file mode 100644 index 0000000000000000000000000000000000000000..575a82c27aafd607137d4d75a885bbe0134c69d2 Binary files /dev/null and b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/gradient_xform.png differ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/fixtures/impeller_test.png b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/impeller_test.png new file mode 100644 index 0000000000000000000000000000000000000000..ed1fdb37ef1518e8bf88abd2696b1eb570abb4ba Binary files /dev/null and b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/impeller_test.png differ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/fixtures/impeller_text_test.png b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/impeller_text_test.png new file mode 100644 index 0000000000000000000000000000000000000000..72ee258c101a2e84c4b2f92f0758b4bb87ce7ad4 Binary files /dev/null and b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/impeller_text_test.png differ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/fixtures/main.dart b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/main.dart new file mode 100644 index 0000000000000000000000000000000000000000..c83292dc23d607c19ef066ba01562c40beacd8cd --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/main.dart @@ -0,0 +1,1713 @@ +// 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. + +// ignore_for_file: avoid_print + +import 'dart:async'; +import 'dart:convert'; +import 'dart:core'; +import 'dart:ffi' as ffi; +import 'dart:io'; +import 'dart:isolate'; +import 'dart:typed_data'; +import 'dart:ui'; + +void main() {} + +@pragma('vm:entry-point') +void customEntrypoint() { + sayHiFromCustomEntrypoint(); +} + +@pragma('vm:external-name', 'SayHiFromCustomEntrypoint') +external void sayHiFromCustomEntrypoint(); + +@pragma('vm:entry-point') +void customEntrypoint1() { + sayHiFromCustomEntrypoint1(); + sayHiFromCustomEntrypoint2(); + sayHiFromCustomEntrypoint3(); +} + +@pragma('vm:external-name', 'SayHiFromCustomEntrypoint1') +external void sayHiFromCustomEntrypoint1(); +@pragma('vm:external-name', 'SayHiFromCustomEntrypoint2') +external void sayHiFromCustomEntrypoint2(); +@pragma('vm:external-name', 'SayHiFromCustomEntrypoint3') +external void sayHiFromCustomEntrypoint3(); + +@pragma('vm:entry-point') +void terminateExitCodeHandler() { + Process.runSync('ls', []); +} + +@pragma('vm:entry-point') +void executableNameNotNull() { + notifyStringValue(Platform.executable); +} + +@pragma('vm:entry-point') +void implicitViewNotNull() { + notifyBoolValue(PlatformDispatcher.instance.implicitView != null); +} + +@pragma('vm:external-name', 'NotifyStringValue') +external void notifyStringValue(String value); +@pragma('vm:external-name', 'NotifyBoolValue') +external void notifyBoolValue(bool value); + +@pragma('vm:entry-point') +void invokePlatformTaskRunner() { + PlatformDispatcher.instance.sendPlatformMessage('OhHi', null, null); +} + +@pragma('vm:entry-point') +void canSpecifyCustomUITaskRunner() { + signalNativeTest(); + PlatformDispatcher.instance.sendPlatformMessage('OhHi', null, null); +} + +@pragma('vm:entry-point') +void mergedPlatformUIThread() { + signalNativeTest(); + PlatformDispatcher.instance.sendPlatformMessage('OhHi', null, null); +} + +@pragma('vm:entry-point') +void uiTaskRunnerFlushesMicrotasks() { + // Microtasks are always flushed at the beginning of the frame, hence the delay. + Future.delayed(const Duration(milliseconds: 50), () { + Future.microtask(() { + signalNativeTest(); + }); + }); +} + +@pragma('vm:entry-point') +void invokePlatformThreadIsolate() { + signalNativeTest(); + runOnPlatformThread(ffiSignalNativeTest); +} + +Float64List kTestTransform = () { + final Float64List values = Float64List(16); + values[0] = 1.0; // scaleX + values[4] = 2.0; // skewX + values[12] = 3.0; // transX + values[1] = 4.0; // skewY + values[5] = 5.0; // scaleY + values[13] = 6.0; // transY + values[3] = 7.0; // pers0 + values[7] = 8.0; // pers1 + values[15] = 9.0; // pers2 + return values; +}(); + +@pragma('vm:external-name', 'SignalNativeTest') +external void signalNativeTest(); +@pragma('vm:external-name', 'SignalNativeCount') +external void signalNativeCount(int count); +@pragma('vm:external-name', 'SignalNativeMessage') +external void signalNativeMessage(String message); +@pragma('vm:external-name', 'NotifySemanticsEnabled') +external void notifySemanticsEnabled(bool enabled); +@pragma('vm:external-name', 'NotifyAccessibilityFeatures') +external void notifyAccessibilityFeatures(bool reduceMotion); +@pragma('vm:external-name', 'NotifySemanticsAction') +external void notifySemanticsAction(int nodeId, int action, List data); + +@ffi.Native(symbol: 'FFISignalNativeTest') +external void ffiSignalNativeTest(); + +/// Returns a future that completes when +/// `PlatformDispatcher.instance.onSemanticsEnabledChanged` fires. +Future get semanticsChanged { + final Completer semanticsChanged = Completer(); + PlatformDispatcher.instance.onSemanticsEnabledChanged = semanticsChanged.complete; + return semanticsChanged.future; +} + +/// Returns a future that completes when +/// `PlatformDispatcher.instance.onAccessibilityFeaturesChanged` fires. +Future get accessibilityFeaturesChanged { + final Completer featuresChanged = Completer(); + PlatformDispatcher.instance.onAccessibilityFeaturesChanged = featuresChanged.complete; + return featuresChanged.future; +} + +Future get semanticsActionEvent { + final Completer actionReceived = Completer(); + PlatformDispatcher.instance.onSemanticsActionEvent = (SemanticsActionEvent action) { + actionReceived.complete(action); + }; + return actionReceived.future; +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +Future a11y_main() async { + // 1: Return initial state (semantics disabled). + notifySemanticsEnabled(PlatformDispatcher.instance.semanticsEnabled); + + // 2: Await semantics enabled from embedder. + await semanticsChanged; + notifySemanticsEnabled(PlatformDispatcher.instance.semanticsEnabled); + + // 3: Return initial state of accessibility features. + notifyAccessibilityFeatures(PlatformDispatcher.instance.accessibilityFeatures.reduceMotion); + + // 4: Await accessibility features changed from embedder. + await accessibilityFeaturesChanged; + notifyAccessibilityFeatures(PlatformDispatcher.instance.accessibilityFeatures.reduceMotion); + + // 5: Fire semantics update. + final SemanticsUpdateBuilder builder = + SemanticsUpdateBuilder() + ..updateNode( + id: 42, + identifier: '', + label: 'A: root', + labelAttributes: [], + rect: const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0), + transform: kTestTransform, + childrenInTraversalOrder: Int32List.fromList([84, 96]), + childrenInHitTestOrder: Int32List.fromList([96, 84]), + actions: 0, + flags: 0, + maxValueLength: 0, + currentValueLength: 0, + textSelectionBase: 0, + textSelectionExtent: 0, + platformViewId: 0, + scrollChildren: 0, + scrollIndex: 0, + scrollPosition: 0.0, + scrollExtentMax: 0.0, + scrollExtentMin: 0.0, + elevation: 0.0, + thickness: 0.0, + hint: '', + hintAttributes: [], + value: '', + valueAttributes: [], + increasedValue: '', + increasedValueAttributes: [], + decreasedValue: '', + decreasedValueAttributes: [], + tooltip: 'tooltip', + textDirection: TextDirection.ltr, + additionalActions: Int32List(0), + controlsNodes: null, + inputType: SemanticsInputType.none, + ) + ..updateNode( + id: 84, + identifier: '', + label: 'B: leaf', + labelAttributes: [], + rect: const Rect.fromLTRB(40.0, 40.0, 80.0, 80.0), + transform: kTestTransform, + actions: 0, + flags: 0, + maxValueLength: 0, + currentValueLength: 0, + textSelectionBase: 0, + textSelectionExtent: 0, + platformViewId: 0, + scrollChildren: 0, + scrollIndex: 0, + scrollPosition: 0.0, + scrollExtentMax: 0.0, + scrollExtentMin: 0.0, + elevation: 0.0, + thickness: 0.0, + hint: '', + hintAttributes: [], + value: '', + valueAttributes: [], + increasedValue: '', + increasedValueAttributes: [], + decreasedValue: '', + decreasedValueAttributes: [], + tooltip: 'tooltip', + textDirection: TextDirection.ltr, + additionalActions: Int32List(0), + childrenInHitTestOrder: Int32List(0), + childrenInTraversalOrder: Int32List(0), + controlsNodes: null, + inputType: SemanticsInputType.none, + ) + ..updateNode( + id: 96, + identifier: '', + label: 'C: branch', + labelAttributes: [], + rect: const Rect.fromLTRB(40.0, 40.0, 80.0, 80.0), + transform: kTestTransform, + childrenInTraversalOrder: Int32List.fromList([128]), + childrenInHitTestOrder: Int32List.fromList([128]), + actions: 0, + flags: 0, + maxValueLength: 0, + currentValueLength: 0, + textSelectionBase: 0, + textSelectionExtent: 0, + platformViewId: 0, + scrollChildren: 0, + scrollIndex: 0, + scrollPosition: 0.0, + scrollExtentMax: 0.0, + scrollExtentMin: 0.0, + elevation: 0.0, + thickness: 0.0, + hint: '', + hintAttributes: [], + value: '', + valueAttributes: [], + increasedValue: '', + increasedValueAttributes: [], + decreasedValue: '', + decreasedValueAttributes: [], + tooltip: 'tooltip', + textDirection: TextDirection.ltr, + additionalActions: Int32List(0), + controlsNodes: null, + inputType: SemanticsInputType.none, + ) + ..updateNode( + id: 128, + identifier: '', + label: 'D: leaf', + labelAttributes: [], + rect: const Rect.fromLTRB(40.0, 40.0, 80.0, 80.0), + transform: kTestTransform, + additionalActions: Int32List.fromList([21]), + platformViewId: 0x3f3, + actions: 0, + flags: 0, + maxValueLength: 0, + currentValueLength: 0, + textSelectionBase: 0, + textSelectionExtent: 0, + scrollChildren: 0, + scrollIndex: 0, + scrollPosition: 0.0, + scrollExtentMax: 0.0, + scrollExtentMin: 0.0, + elevation: 0.0, + thickness: 0.0, + hint: '', + hintAttributes: [], + value: '', + valueAttributes: [], + increasedValue: '', + increasedValueAttributes: [], + decreasedValue: '', + decreasedValueAttributes: [], + tooltip: 'tooltip', + textDirection: TextDirection.ltr, + childrenInHitTestOrder: Int32List(0), + childrenInTraversalOrder: Int32List(0), + controlsNodes: null, + inputType: SemanticsInputType.none, + ) + ..updateCustomAction(id: 21, label: 'Archive', hint: 'archive message'); + + PlatformDispatcher.instance.views.first.updateSemantics(builder.build()); + + signalNativeTest(); + + // 6: Await semantics action from embedder. + final SemanticsActionEvent data = await semanticsActionEvent; + final List actionArgs = [ + (data.arguments! as ByteData).getInt8(0), + (data.arguments! as ByteData).getInt8(1), + ]; + notifySemanticsAction(data.nodeId, data.type.index, actionArgs); + + // 7: Await semantics disabled from embedder. + await semanticsChanged; + notifySemanticsEnabled(PlatformDispatcher.instance.semanticsEnabled); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +Future a11y_string_attributes() async { + // 1: Wait until semantics are enabled. + if (!PlatformDispatcher.instance.semanticsEnabled) { + await semanticsChanged; + } + + // 2: Update semantics with string attributes. + final SemanticsUpdateBuilder builder = + SemanticsUpdateBuilder()..updateNode( + id: 42, + identifier: 'identifier', + label: 'What is the meaning of life?', + labelAttributes: [ + LocaleStringAttribute( + range: const TextRange(start: 0, end: 'What is the meaning of life?'.length), + locale: const Locale('en'), + ), + SpellOutStringAttribute(range: const TextRange(start: 0, end: 1)), + ], + rect: const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0), + transform: kTestTransform, + childrenInTraversalOrder: Int32List.fromList([84, 96]), + childrenInHitTestOrder: Int32List.fromList([96, 84]), + actions: 0, + flags: 0, + maxValueLength: 0, + currentValueLength: 0, + textSelectionBase: 0, + textSelectionExtent: 0, + platformViewId: 0, + scrollChildren: 0, + scrollIndex: 0, + scrollPosition: 0.0, + scrollExtentMax: 0.0, + scrollExtentMin: 0.0, + elevation: 0.0, + thickness: 0.0, + hint: "It's a number", + hintAttributes: [ + LocaleStringAttribute( + range: const TextRange(start: 0, end: 1), + locale: const Locale('en'), + ), + LocaleStringAttribute( + range: const TextRange(start: 2, end: 3), + locale: const Locale('fr'), + ), + ], + value: '42', + valueAttributes: [ + LocaleStringAttribute( + range: const TextRange(start: 0, end: '42'.length), + locale: const Locale('en', 'US'), + ), + ], + increasedValue: '43', + increasedValueAttributes: [ + SpellOutStringAttribute(range: const TextRange(start: 0, end: 1)), + SpellOutStringAttribute(range: const TextRange(start: 1, end: 2)), + ], + decreasedValue: '41', + decreasedValueAttributes: [], + tooltip: 'tooltip', + textDirection: TextDirection.ltr, + additionalActions: Int32List(0), + controlsNodes: null, + inputType: SemanticsInputType.none, + ); + + PlatformDispatcher.instance.views.first.updateSemantics(builder.build()); + signalNativeTest(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void platform_messages_response() { + PlatformDispatcher.instance.onPlatformMessage = ( + String name, + ByteData? data, + PlatformMessageResponseCallback? callback, + ) { + callback!(data); + }; + signalNativeTest(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void platform_messages_no_response() { + PlatformDispatcher.instance.onPlatformMessage = ( + String name, + ByteData? data, + PlatformMessageResponseCallback? callback, + ) { + final Uint8List list = data!.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes); + signalNativeMessage(utf8.decode(list)); + // This does nothing because no one is listening on the other side. But complete the loop anyway + // to make sure all null checking on response handles in the engine is in place. + callback!(data); + }; + signalNativeTest(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void null_platform_messages() { + PlatformDispatcher.instance.onPlatformMessage = ( + String name, + ByteData? data, + PlatformMessageResponseCallback? callback, + ) { + // This checks if the platform_message null data is converted to Flutter null. + signalNativeMessage((null == data).toString()); + callback!(data); + }; + signalNativeTest(); +} + +Picture createSimplePicture() { + final Paint blackPaint = Paint(); + final Paint whitePaint = Paint()..color = const Color.fromARGB(255, 255, 255, 255); + final PictureRecorder baseRecorder = PictureRecorder(); + final Canvas canvas = Canvas(baseRecorder); + canvas.drawRect(const Rect.fromLTRB(0.0, 0.0, 1000.0, 1000.0), blackPaint); + canvas.drawRect(const Rect.fromLTRB(10.0, 10.0, 990.0, 990.0), whitePaint); + return baseRecorder.endRecording(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void can_composite_platform_views() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + final SceneBuilder builder = SceneBuilder(); + builder.addPicture(const Offset(1.0, 1.0), createSimplePicture()); + builder.pushOffset(1.0, 2.0); + builder.addPlatformView(42, width: 123.0, height: 456.0); + builder.addPicture(const Offset(1.0, 1.0), createSimplePicture()); + builder.pop(); // offset + signalNativeTest(); // Signal 2 + PlatformDispatcher.instance.views.first.render(builder.build()); + }; + signalNativeTest(); // Signal 1 + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void can_composite_platform_views_with_opacity() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + final SceneBuilder builder = SceneBuilder(); + + // Root node + builder.pushOffset(1.0, 2.0); + + // First sibling layer (no platform view, should be cached) + builder.pushOpacity(127); + builder.addPicture(const Offset(1.0, 1.0), createSimplePicture()); + builder.pop(); + + // Second sibling layer (platform view, should not be cached) + builder.pushOpacity(127); + builder.addPlatformView(42, width: 123.0, height: 456.0); + builder.pop(); + + // Third sibling layer (no platform view, should be cached) + builder.pushOpacity(127); + builder.addPicture(const Offset(2.0, 1.0), createSimplePicture()); + builder.pop(); + + signalNativeTest(); // Signal 2 + PlatformDispatcher.instance.views.first.render(builder.build()); + }; + signalNativeTest(); // Signal 1 + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void can_composite_with_opacity() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + final SceneBuilder builder = SceneBuilder(); + builder.pushOpacity(127); + builder.addPicture(const Offset(1.0, 1.0), createSimplePicture()); + builder.pop(); // offset + signalNativeTest(); // Signal 2 + PlatformDispatcher.instance.views.first.render(builder.build()); + }; + signalNativeTest(); // Signal 1 + PlatformDispatcher.instance.scheduleFrame(); +} + +Picture createColoredBox(Color color, Size size) { + final Paint paint = Paint(); + paint.color = color; + final PictureRecorder baseRecorder = PictureRecorder(); + final Canvas canvas = Canvas(baseRecorder); + canvas.drawRect(Rect.fromLTRB(0.0, 0.0, size.width, size.height), paint); + return baseRecorder.endRecording(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void can_composite_platform_views_with_known_scene() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + const Color red = Color.fromARGB(127, 255, 0, 0); + const Color blue = Color.fromARGB(127, 0, 0, 255); + const Color gray = Color.fromARGB(127, 127, 127, 127); + + const Size size = Size(50.0, 150.0); + + final SceneBuilder builder = SceneBuilder(); + builder.pushOffset(0.0, 0.0); + + // 10 (Index 0) + builder.addPicture(const Offset(10.0, 10.0), createColoredBox(red, size)); // red - flutter + + builder.pushOffset(20.0, 20.0); + // 20 (Index 1) + builder.addPlatformView(1, width: size.width, height: size.height); // green - platform + builder.pop(); + + // 30 (Index 2) + builder.addPicture(const Offset(30.0, 30.0), createColoredBox(blue, size)); // blue - flutter + + builder.pushOffset(40.0, 40.0); + // 40 (Index 3) + builder.addPlatformView(2, width: size.width, height: size.height); // magenta - platform + builder.pop(); + + // 50 (Index 4) + builder.addPicture(const Offset(50.0, 50.0), createColoredBox(gray, size)); // gray - flutter + + builder.pop(); + + PlatformDispatcher.instance.views.first.render(builder.build()); + + signalNativeTest(); // Signal 2 + }; + signalNativeTest(); // Signal 1 + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void can_composite_platform_views_transparent_overlay() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + const Color red = Color.fromARGB(127, 255, 0, 0); + const Color transparent = Color(0x00ffffff); + + const Size size = Size(50.0, 150.0); + + final SceneBuilder builder = SceneBuilder(); + builder.pushOffset(0.0, 0.0); + + // 10 (Index 0) + builder.addPicture(const Offset(10.0, 10.0), createColoredBox(red, size)); // red - flutter + + builder.pushOffset(20.0, 20.0); + // 20 (Index 1) + builder.addPlatformView(1, width: size.width, height: size.height); // green - platform + builder.pop(); + + // 30 (Index 2) + builder.addPicture( + const Offset(30.0, 30.0), + createColoredBox(transparent, size), + ); // transparent picture, no layer should be created. + + builder.pop(); + + PlatformDispatcher.instance.views.first.render(builder.build()); + + signalNativeTest(); // Signal 2 + }; + signalNativeTest(); // Signal 1 + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void can_composite_platform_views_no_overlay() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + const Color red = Color.fromARGB(127, 255, 0, 0); + const Size size = Size(50.0, 150.0); + + final SceneBuilder builder = SceneBuilder(); + builder.pushOffset(0.0, 0.0); + + // 10 (Index 0) + builder.addPicture(const Offset(10.0, 10.0), createColoredBox(red, size)); // red - flutter + + builder.pushOffset(20.0, 20.0); + // 20 (Index 1) + builder.addPlatformView(1, width: size.width, height: size.height); // green - platform + builder.pop(); + builder.pop(); + + PlatformDispatcher.instance.views.first.render(builder.build()); + + signalNativeTest(); // Signal 2 + }; + signalNativeTest(); // Signal 1 + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void can_composite_platform_views_with_root_layer_only() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + const Color red = Color.fromARGB(127, 255, 0, 0); + const Size size = Size(50.0, 150.0); + + final SceneBuilder builder = SceneBuilder(); + builder.pushOffset(0.0, 0.0); + + // 10 (Index 0) + builder.addPicture(const Offset(10.0, 10.0), createColoredBox(red, size)); // red - flutter + builder.pop(); + + PlatformDispatcher.instance.views.first.render(builder.build()); + + signalNativeTest(); // Signal 2 + }; + signalNativeTest(); // Signal 1 + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void can_composite_platform_views_with_platform_layer_on_bottom() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + const Color red = Color.fromARGB(127, 255, 0, 0); + const Size size = Size(50.0, 150.0); + + final SceneBuilder builder = SceneBuilder(); + builder.pushOffset(0.0, 0.0); + + // 10 (Index 0) + builder.addPicture(const Offset(10.0, 10.0), createColoredBox(red, size)); // red - flutter + + builder.pushOffset(20.0, 20.0); + // 20 (Index 1) + builder.addPlatformView(1, width: size.width, height: size.height); // green - platform + builder.pop(); + builder.pop(); + + PlatformDispatcher.instance.views.first.render(builder.build()); + + signalNativeTest(); // Signal 2 + }; + signalNativeTest(); // Signal 1 + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:external-name', 'SignalBeginFrame') +// ignore: unreachable_from_main +external void signalBeginFrame(); + +@pragma('vm:entry-point') +Future +// ignore: non_constant_identifier_names +texture_destruction_callback_called_without_custom_compositor() async { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + const Color red = Color.fromARGB(127, 255, 0, 0); + const Size size = Size(50.0, 150.0); + final SceneBuilder builder = SceneBuilder(); + builder.pushOffset(0.0, 0.0); + builder.addPicture(const Offset(10.0, 10.0), createColoredBox(red, size)); // red - flutter + builder.pop(); + PlatformDispatcher.instance.views.first.render(builder.build()); + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void can_render_scene_without_custom_compositor() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + const Color red = Color.fromARGB(127, 255, 0, 0); + const Color green = Color.fromARGB(127, 0, 255, 0); + const Color blue = Color.fromARGB(127, 0, 0, 255); + const Color magenta = Color.fromARGB(127, 255, 0, 255); + const Color gray = Color.fromARGB(127, 127, 127, 127); + + const Size size = Size(50.0, 150.0); + + final SceneBuilder builder = SceneBuilder(); + + builder.pushOffset(0.0, 0.0); + + builder.addPicture(const Offset(10.0, 10.0), createColoredBox(red, size)); // red - flutter + + builder.addPicture(const Offset(20.0, 20.0), createColoredBox(green, size)); // green - flutter + + builder.addPicture(const Offset(30.0, 30.0), createColoredBox(blue, size)); // blue - flutter + + builder.addPicture( + const Offset(40.0, 40.0), + createColoredBox(magenta, size), + ); // magenta - flutter + + builder.addPicture(const Offset(50.0, 50.0), createColoredBox(gray, size)); // gray - flutter + + builder.pop(); + + PlatformDispatcher.instance.views.first.render(builder.build()); + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +Picture createGradientBox(Size size) { + final Paint paint = Paint(); + final List rainbow = [ + const Color.fromARGB(255, 255, 0, 0), // red + const Color.fromARGB(255, 255, 165, 0), // orange + const Color.fromARGB(255, 255, 255, 0), // yellow + const Color.fromARGB(255, 0, 255, 0), // green + const Color.fromARGB(255, 0, 0, 255), // blue + const Color.fromARGB(255, 75, 0, 130), // indigo + const Color.fromARGB(255, 238, 130, 238), // violet + ]; + final List stops = [ + (1.0 / 7.0), + (2.0 / 7.0), + (3.0 / 7.0), + (4.0 / 7.0), + (5.0 / 7.0), + (6.0 / 7.0), + (7.0 / 7.0), + ]; + paint.shader = Gradient.linear(Offset.zero, Offset(size.width, size.height), rainbow, stops); + final PictureRecorder baseRecorder = PictureRecorder(); + final Canvas canvas = Canvas(baseRecorder); + canvas.drawRect(Rect.fromLTRB(0.0, 0.0, size.width, size.height), paint); + return baseRecorder.endRecording(); +} + +@pragma('vm:external-name', 'EchoKeyEvent') +external void _echoKeyEvent( + int change, + int timestamp, + int physical, + int logical, + int charCode, + bool synthesized, + int deviceType, +); + +// Convert `kind` in enum form to its integer form. +// +// It performs a reversed mapping from `UnserializeKeyEventType` +// in shell/platform/embedder/tests/embedder_unittests.cc. +int _serializeKeyEventType(KeyEventType change) { + switch (change) { + case KeyEventType.up: + return 1; + case KeyEventType.down: + return 2; + case KeyEventType.repeat: + return 3; + } +} + +// Convert `deviceType` in enum form to its integer form. +// +// It performs a reversed mapping from `UnserializeKeyEventDeviceType` +// in shell/platform/embedder/tests/embedder_unittests.cc. +int _serializeKeyEventDeviceType(KeyEventDeviceType deviceType) { + switch (deviceType) { + case KeyEventDeviceType.keyboard: + return 1; + case KeyEventDeviceType.directionalPad: + return 2; + case KeyEventDeviceType.gamepad: + return 3; + case KeyEventDeviceType.joystick: + return 4; + case KeyEventDeviceType.hdmi: + return 5; + } +} + +// Echo the event data with `_echoKeyEvent`, and returns synthesized as handled. +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +Future key_data_echo() async { + PlatformDispatcher.instance.onKeyData = (KeyData data) { + _echoKeyEvent( + _serializeKeyEventType(data.type), + data.timeStamp.inMicroseconds, + data.physical, + data.logical, + data.character == null ? 0 : data.character!.codeUnitAt(0), + data.synthesized, + _serializeKeyEventDeviceType(data.deviceType), + ); + return data.synthesized; + }; + signalNativeTest(); +} + +// After platform channel 'test/starts_echo' receives a message, starts echoing +// the event data with `_echoKeyEvent`, and returns synthesized as handled. +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +Future key_data_late_echo() async { + channelBuffers.setListener('test/starts_echo', ( + ByteData? data, + PlatformMessageResponseCallback callback, + ) { + PlatformDispatcher.instance.onKeyData = (KeyData data) { + _echoKeyEvent( + _serializeKeyEventType(data.type), + data.timeStamp.inMicroseconds, + data.physical, + data.logical, + data.character == null ? 0 : data.character!.codeUnitAt(0), + data.synthesized, + _serializeKeyEventDeviceType(data.deviceType), + ); + return data.synthesized; + }; + callback(null); + }); + signalNativeTest(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void render_implicit_view() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + const Size size = Size(800.0, 600.0); + const Color red = Color.fromARGB(127, 255, 0, 0); + + final SceneBuilder builder = SceneBuilder(); + + builder.pushOffset(0.0, 0.0); + + builder.addPicture(Offset.zero, createColoredBox(red, size)); + + builder.pop(); + + PlatformDispatcher.instance.implicitView?.render(builder.build()); + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void render_all_views() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + for (final FlutterView view in PlatformDispatcher.instance.views) { + const Size size = Size(800.0, 600.0); + const Color red = Color.fromARGB(127, 255, 0, 0); + + final SceneBuilder builder = SceneBuilder(); + + builder.pushOffset(0.0, 0.0); + + builder.addPicture(Offset.zero, createColoredBox(red, size)); + + builder.pop(); + + view.render(builder.build()); + } + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void render_gradient() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + const Size size = Size(800.0, 600.0); + + final SceneBuilder builder = SceneBuilder(); + + builder.pushOffset(0.0, 0.0); + + builder.addPicture(Offset.zero, createGradientBox(size)); // gradient - flutter + + builder.pop(); + + PlatformDispatcher.instance.views.first.render(builder.build()); + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void render_texture() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + const Size size = Size(800.0, 600.0); + + final SceneBuilder builder = SceneBuilder(); + + builder.pushOffset(0.0, 0.0); + + builder.addTexture(/*textureId*/ 1, width: size.width, height: size.height); + + builder.pop(); + + PlatformDispatcher.instance.views.first.render(builder.build()); + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void render_gradient_on_non_root_backing_store() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + const Size size = Size(800.0, 600.0); + const Color red = Color.fromARGB(127, 255, 0, 0); + + final SceneBuilder builder = SceneBuilder(); + + builder.pushOffset(0.0, 0.0); + + // Even though this is occluded, add something so it is not elided. + builder.addPicture(const Offset(10.0, 10.0), createColoredBox(red, size)); // red - flutter + + builder.addPlatformView(1, width: 100, height: 200); // undefined - platform + + builder.addPicture(Offset.zero, createGradientBox(size)); // gradient - flutter + + builder.pop(); + + PlatformDispatcher.instance.views.first.render(builder.build()); + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void verify_b141980393() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + // The platform view in the test case is screen sized but with margins of 31 + // and 37 points from the top and bottom. + const double topMargin = 31.0; + const double bottomMargin = 37.0; + const Size platformViewSize = Size(800.0, 600.0 - topMargin - bottomMargin); + + final SceneBuilder builder = SceneBuilder(); + + builder.pushOffset( + 0.0, // x + topMargin, // y + ); + + // The web view in example. + builder.addPlatformView(1337, width: platformViewSize.width, height: platformViewSize.height); + + builder.pop(); + + PlatformDispatcher.instance.views.first.render(builder.build()); + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void can_display_platform_view_with_pixel_ratio() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + final SceneBuilder builder = SceneBuilder(); + builder.pushTransform( + Float64List.fromList([ + 2.0, + 0.0, + 0.0, + 0.0, + 0.0, + 2.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + ]), + ); // base + builder.addPicture(Offset.zero, createGradientBox(const Size(400.0, 300.0))); + builder.pushOffset(0.0, 20.0); // offset + builder.addPlatformView(42, width: 400.0, height: 280.0); + builder.pop(); // offset + builder.addPicture( + Offset.zero, + createColoredBox(const Color.fromARGB(128, 255, 0, 0), const Size(400.0, 300.0)), + ); + builder.pop(); // base + PlatformDispatcher.instance.views.first.render(builder.build()); + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void can_receive_locale_updates() { + PlatformDispatcher.instance.onLocaleChanged = () { + signalNativeCount(PlatformDispatcher.instance.locales.length); + }; + signalNativeTest(); +} + +// Verifies behavior tracked in https://github.com/flutter/flutter/issues/43732 +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void verify_b143464703() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + final SceneBuilder builder = SceneBuilder(); + builder.pushOffset(0.0, 0.0); // base + + // Background + builder.addPicture( + Offset.zero, + createColoredBox(const Color.fromARGB(255, 128, 128, 128), const Size(1024.0, 600.0)), + ); + + builder.pushOpacity(128); + builder.addPicture( + const Offset(10.0, 10.0), + createColoredBox(const Color.fromARGB(255, 0, 0, 255), const Size(25.0, 25.0)), + ); + builder.pop(); // opacity 128 + + // The top bar and the platform view are pushed to the side. + builder.pushOffset(135.0, 0.0); // 1 + builder.pushOpacity(128); // opacity + + // Platform view offset from the top + builder.pushOffset(0.0, 60.0); // 2 + builder.addPlatformView(42, width: 1024.0, height: 540.0); + builder.pop(); // 2 + + // Top bar + builder.addPicture(Offset.zero, createGradientBox(const Size(1024.0, 60.0))); + + builder.pop(); // opacity + builder.pop(); // 1 + + builder.pop(); // base + PlatformDispatcher.instance.views.first.render(builder.build()); + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void push_frames_over_and_over() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + final SceneBuilder builder = SceneBuilder(); + builder.pushOffset(0.0, 0.0); + builder.addPicture( + Offset.zero, + createColoredBox(const Color.fromARGB(255, 128, 128, 128), const Size(1024.0, 600.0)), + ); + builder.pushOpacity(128); + builder.addPlatformView(42, width: 1024.0, height: 540.0); + builder.pop(); + builder.pop(); + PlatformDispatcher.instance.views.first.render(builder.build()); + signalNativeTest(); + PlatformDispatcher.instance.scheduleFrame(); + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void platform_view_mutators() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + final SceneBuilder builder = SceneBuilder(); + builder.pushOffset(0.0, 0.0); // base + builder.addPicture(Offset.zero, createGradientBox(const Size(800.0, 600.0))); + + builder.pushOpacity(128); + builder.pushClipRect(const Rect.fromLTWH(10.0, 10.0, 800.0 - 20.0, 600.0 - 20.0)); + builder.pushClipRRect( + RRect.fromLTRBR(10.0, 10.0, 800.0 - 10.0, 600.0 - 10.0, const Radius.circular(14.0)), + ); + builder.addPlatformView(42, width: 800.0, height: 600.0); + builder.pop(); // clip rrect + builder.pop(); // clip rect + builder.pop(); // opacity + + builder.pop(); // base + PlatformDispatcher.instance.views.first.render(builder.build()); + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void platform_view_mutators_with_pixel_ratio() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + final SceneBuilder builder = SceneBuilder(); + builder.pushOffset(0.0, 0.0); // base + builder.addPicture(Offset.zero, createGradientBox(const Size(400.0, 300.0))); + + builder.pushOpacity(128); + builder.pushClipRect(const Rect.fromLTWH(5.0, 5.0, 400.0 - 10.0, 300.0 - 10.0)); + builder.pushClipRRect( + RRect.fromLTRBR(5.0, 5.0, 400.0 - 5.0, 300.0 - 5.0, const Radius.circular(7.0)), + ); + builder.addPlatformView(42, width: 400.0, height: 300.0); + builder.pop(); // clip rrect + builder.pop(); // clip rect + builder.pop(); // opacity + + builder.pop(); // base + PlatformDispatcher.instance.views.first.render(builder.build()); + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void empty_scene() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + PlatformDispatcher.instance.views.first.render(SceneBuilder().build()); + signalNativeTest(); + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void scene_with_no_container() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + final SceneBuilder builder = SceneBuilder(); + builder.addPicture(Offset.zero, createGradientBox(const Size(400.0, 300.0))); + PlatformDispatcher.instance.views.first.render(builder.build()); + signalNativeTest(); + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +Picture createArcEndCapsPicture() { + final PictureRecorder baseRecorder = PictureRecorder(); + final Canvas canvas = Canvas(baseRecorder); + + final style = + Paint() + ..strokeWidth = 12.0 + ..style = PaintingStyle.stroke + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.miter; + + style.color = const Color.fromARGB(255, 255, 0, 0); + canvas.drawArc(const Rect.fromLTRB(0.0, 0.0, 500.0, 500.0), 1.57, 1.0, false, style); + + return baseRecorder.endRecording(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void arc_end_caps_correct() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + final SceneBuilder builder = SceneBuilder(); + builder.addPicture(Offset.zero, createArcEndCapsPicture()); + PlatformDispatcher.instance.views.first.render(builder.build()); + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void scene_builder_with_clips() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + final SceneBuilder builder = SceneBuilder(); + builder.pushClipRect(const Rect.fromLTRB(10.0, 10.0, 390.0, 290.0)); + builder.addPlatformView(42, width: 400.0, height: 300.0); + builder.addPicture(Offset.zero, createGradientBox(const Size(400.0, 300.0))); + PlatformDispatcher.instance.views.first.render(builder.build()); + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void scene_builder_with_complex_clips() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + final SceneBuilder builder = SceneBuilder(); + + builder.pushClipRect(const Rect.fromLTRB(0.0, 0.0, 1024.0, 600.0)); + builder.pushOffset(512.0, 0.0); + builder.pushClipRect(const Rect.fromLTRB(0.0, 0.0, 512.0, 600.0)); + builder.pushOffset(-256.0, 0.0); + builder.pushClipRect(const Rect.fromLTRB(0.0, 0.0, 1024.0, 600.0)); + builder.addPlatformView(42, width: 1024.0, height: 600.0); + + builder.addPicture(Offset.zero, createGradientBox(const Size(1024.0, 600.0))); + PlatformDispatcher.instance.views.first.render(builder.build()); + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:external-name', 'SendObjectToNativeCode') +external void sendObjectToNativeCode(dynamic object); + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void objects_can_be_posted() { + final ReceivePort port = ReceivePort(); + port.listen((dynamic message) { + sendObjectToNativeCode(message); + }); + signalNativeCount(port.sendPort.nativePort); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void empty_scene_posts_zero_layers_to_compositor() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + final SceneBuilder builder = SceneBuilder(); + // Should not render anything. + builder.pushClipRect(const Rect.fromLTRB(0.0, 0.0, 300.0, 200.0)); + PlatformDispatcher.instance.views.first.render(builder.build()); + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void compositor_can_post_only_platform_views() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + final SceneBuilder builder = SceneBuilder(); + builder.addPlatformView(42, width: 300.0, height: 200.0); + builder.addPlatformView(24, width: 300.0, height: 200.0); + PlatformDispatcher.instance.views.first.render(builder.build()); + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void render_targets_are_recycled() { + int frameCount = 0; + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + final SceneBuilder builder = SceneBuilder(); + for (int i = 0; i < 10; i++) { + builder.addPicture(Offset.zero, createGradientBox(const Size(30.0, 20.0))); + builder.addPlatformView(42 + i, width: 30.0, height: 20.0); + } + PlatformDispatcher.instance.views.first.render(builder.build()); + frameCount++; + if (frameCount == 8) { + signalNativeTest(); + } else { + PlatformDispatcher.instance.scheduleFrame(); + } + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void render_targets_are_in_stable_order() { + int frameCount = 0; + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + final SceneBuilder builder = SceneBuilder(); + for (int i = 0; i < 10; i++) { + builder.addPicture(Offset.zero, createGradientBox(const Size(30.0, 20.0))); + builder.addPlatformView(42 + i, width: 30.0, height: 20.0); + } + PlatformDispatcher.instance.views.first.render(builder.build()); + PlatformDispatcher.instance.scheduleFrame(); + frameCount++; + if (frameCount == 8) { + signalNativeTest(); + } + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:external-name', 'NativeArgumentsCallback') +external void nativeArgumentsCallback(List args); + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void custom_logger(List args) { + print('hello world'); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void dart_entrypoint_args(List args) { + nativeArgumentsCallback(args); +} + +@pragma('vm:external-name', 'SnapshotsCallback') +external void snapshotsCallback(Image bigImage, Image smallImage); + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +Future snapshot_large_scene(int maxSize) async { + // Set width to double the max size, which will result in height being half the max size after scaling. + final width = maxSize * 2.0, height = maxSize.toDouble(); + + PictureRecorder recorder = PictureRecorder(); + { + final Canvas canvas = Canvas(recorder, Rect.fromLTWH(0, 0, width, height)); + final Paint paint = Paint(); + // Bottom left + paint.color = const Color.fromARGB(255, 100, 255, 100); + canvas.drawRect(Rect.fromLTWH(0, height / 2, width / 2, height / 2), paint); + // Top right + paint.color = const Color.fromARGB(255, 100, 100, 255); + canvas.drawRect(Rect.fromLTWH(width / 2, 0, width / 2, height / 2), paint); + } + Picture picture = recorder.endRecording(); + final Image bigImage = await picture.toImage(width.toInt(), height.toInt()); + + // The max size varies across hardware/drivers, so normalize the result to a smaller target size in + // order to reliably test against an image fixture. + const smallWidth = 128.0; + const smallHeight = 64.0; + recorder = PictureRecorder(); + { + final Canvas canvas = Canvas(recorder, const Rect.fromLTWH(0, 0, smallWidth, smallHeight)); + canvas.scale(smallWidth / bigImage.width); + canvas.drawImage(bigImage, Offset.zero, Paint()); + } + picture = recorder.endRecording(); + final Image smallImage = await picture.toImage(smallWidth.toInt(), smallHeight.toInt()); + + snapshotsCallback(bigImage, smallImage); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void invalid_backingstore() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + const Color red = Color.fromARGB(127, 255, 0, 0); + const Size size = Size(50.0, 150.0); + final SceneBuilder builder = SceneBuilder(); + builder.pushOffset(0.0, 0.0); + builder.addPicture(const Offset(10.0, 10.0), createColoredBox(red, size)); // red - flutter + builder.pop(); + PlatformDispatcher.instance.views.first.render(builder.build()); + }; + PlatformDispatcher.instance.onDrawFrame = () { + signalNativeTest(); + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void can_schedule_frame() { + PlatformDispatcher.instance.onBeginFrame = (Duration beginTime) { + signalNativeCount(beginTime.inMicroseconds); + }; + signalNativeTest(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void add_view_schedules_frame() { + PlatformDispatcher.instance.onBeginFrame = (Duration beginTime) { + for (final FlutterView view in PlatformDispatcher.instance.views) { + if (view.viewId == 123) { + signalNativeCount(beginTime.inMicroseconds); + } + } + }; + signalNativeTest(); +} + +void drawSolidColor(Color c) { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + final SceneBuilder builder = SceneBuilder(); + builder.pushOffset(0.0, 0.0); + builder.addPicture( + Offset.zero, + createColoredBox(c, PlatformDispatcher.instance.views.first.physicalSize), + ); + builder.pop(); + PlatformDispatcher.instance.views.first.render(builder.build()); + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void draw_solid_red() { + drawSolidColor(const Color.fromARGB(255, 255, 0, 0)); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void draw_solid_green() { + drawSolidColor(const Color.fromARGB(255, 0, 255, 0)); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void draw_solid_blue() { + drawSolidColor(const Color.fromARGB(255, 0, 0, 255)); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void pointer_data_packet() { + PlatformDispatcher.instance.onPointerDataPacket = (PointerDataPacket packet) { + signalNativeCount(packet.data.length); + + for (final PointerData pointerData in packet.data) { + signalNativeMessage(pointerData.toString()); + } + }; + + signalNativeTest(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void pointer_data_packet_view_id() { + PlatformDispatcher.instance.onPointerDataPacket = (PointerDataPacket packet) { + assert(packet.data.length == 1); + + for (final PointerData pointerData in packet.data) { + signalNativeMessage('ViewID: ${pointerData.viewId}'); + } + }; + + signalNativeTest(); +} + +Map _getAllViewSizes() { + final Map result = {}; + for (final FlutterView view in PlatformDispatcher.instance.views) { + result[view.viewId] = view.physicalSize; + } + return result; +} + +List _findDifferences(Map a, Map b) { + final Set result = {}; + a.forEach((int viewId, Size sizeA) { + if (!b.containsKey(viewId) || b[viewId] != sizeA) { + result.add(viewId); + } + }); + b.forEach((int viewId, Size sizeB) { + if (!a.containsKey(viewId)) { + result.add(viewId); + } + }); + return result.toList()..sort(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void window_metrics_event_view_id() { + Map sizes = _getAllViewSizes(); + PlatformDispatcher.instance.onMetricsChanged = () { + final Map newSizes = _getAllViewSizes(); + final List differences = _findDifferences(sizes, newSizes); + sizes = newSizes; + signalNativeMessage('Changed: $differences'); + }; + + signalNativeTest(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void window_metrics_event_all_view_ids() { + PlatformDispatcher.instance.onMetricsChanged = () { + final List viewIds = PlatformDispatcher.instance.views.map((view) => view.viewId).toList(); + + viewIds.sort(); + + signalNativeMessage('View IDs: [${viewIds.join(', ')}]'); + }; + + signalNativeTest(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void remove_view_callback_too_early() { + signalNativeTest(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +Future channel_listener_response() async { + channelBuffers.setListener('test/listen', ( + ByteData? data, + PlatformMessageResponseCallback callback, + ) { + callback(null); + }); + signalNativeTest(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void render_gradient_retained() { + OffsetEngineLayer? offsetLayer; // Retain the offset layer. + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + const Size size = Size(800.0, 600.0); + + final SceneBuilder builder = SceneBuilder(); + + offsetLayer = builder.pushOffset(0.0, 0.0, oldLayer: offsetLayer); + + // display_list_layer will comparing the display_list + // no need to retain the picture + builder.addPicture(Offset.zero, createGradientBox(size)); + + builder.pop(); + + PlatformDispatcher.instance.views.first.render(builder.build()); + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void render_impeller_test() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + final SceneBuilder builder = SceneBuilder(); + builder.pushOffset(0.0, 0.0); + final Paint paint = Paint(); + paint.color = const Color.fromARGB(255, 0, 0, 255); + final PictureRecorder baseRecorder = PictureRecorder(); + final Canvas canvas = Canvas(baseRecorder); + canvas.drawPaint(Paint()..color = const Color.fromARGB(255, 255, 0, 0)); + canvas.drawRect(const Rect.fromLTRB(20.0, 20.0, 200.0, 150.0), paint); + builder.addPicture(Offset.zero, baseRecorder.endRecording()); + builder.pop(); + PlatformDispatcher.instance.views.first.render(builder.build()); + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +void render_impeller_text_test() { + PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + final SceneBuilder builder = SceneBuilder(); + builder.pushOffset(0.0, 0.0); + final Paint paint = Paint(); + paint.color = const Color.fromARGB(255, 0, 0, 255); + final PictureRecorder baseRecorder = PictureRecorder(); + final Canvas canvas = Canvas(baseRecorder); + + final ParagraphBuilder paragraphBuilder = ParagraphBuilder( + ParagraphStyle(fontFamily: 'sans-serif'), + )..addText('Flutter is the best!'); + final Paragraph paragraph = + paragraphBuilder.build()..layout(const ParagraphConstraints(width: 400)); + canvas.drawParagraph(paragraph, const Offset(20, 20)); + + builder.addPicture(Offset.zero, baseRecorder.endRecording()); + builder.pop(); + PlatformDispatcher.instance.views.first.render(builder.build()); + }; + PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +Future render_impeller_image_snapshot_test() async { + final PictureRecorder recorder = PictureRecorder(); + final Canvas canvas = Canvas(recorder); + const Color color = Color.fromARGB(255, 0, 0, 123); + canvas.drawPaint(Paint()..color = color); + final Picture picture = recorder.endRecording(); + + final Image image = await picture.toImage(100, 100); + final ByteData? imageData = await image.toByteData(); + final int pixel = imageData!.getInt32(0); + + final bool result = (pixel & 0xFF) == color.alpha && ((pixel >> 8) & 0xFF) == color.blue; + notifyBoolValue(result); +} + +@pragma('vm:entry-point') +void testSendViewFocusEvent() { + PlatformDispatcher.instance.onViewFocusChange = (ViewFocusEvent event) { + notifyStringValue('${event.viewId} ${event.state} ${event.direction}'); + }; + signalNativeTest(); +} + +@pragma('vm:entry-point') +void testSendViewFocusChangeRequest() { + PlatformDispatcher.instance.requestViewFocusChange( + viewId: 1, + state: ViewFocusState.unfocused, + direction: ViewFocusDirection.undefined, + ); + PlatformDispatcher.instance.requestViewFocusChange( + viewId: 2, + state: ViewFocusState.focused, + direction: ViewFocusDirection.forward, + ); + PlatformDispatcher.instance.requestViewFocusChange( + viewId: 3, + state: ViewFocusState.focused, + direction: ViewFocusDirection.backward, + ); +} + +@pragma('vm:entry-point') +// ignore: non_constant_identifier_names +Future a11y_main_multi_view() async { + // 1: Return initial state (semantics disabled). + notifySemanticsEnabled(PlatformDispatcher.instance.semanticsEnabled); + + // 2: Add the first view (implicitly handled by PlatformDispatcher). + // 3: Add the second view (implicitly handled by PlatformDispatcher). + + // 4: Await semantics enabled from embedder. + await semanticsChanged; + notifySemanticsEnabled(PlatformDispatcher.instance.semanticsEnabled); + + // 5: Return initial state of accessibility features. + notifyAccessibilityFeatures(PlatformDispatcher.instance.accessibilityFeatures.reduceMotion); + + // 6: Fire semantics updates. + SemanticsUpdateBuilder createForView(FlutterView view) { + return SemanticsUpdateBuilder()..updateNode( + id: view.viewId + 1, // For simplicity, give each node an id of viewId + 1 + identifier: '', + label: 'A: root', + labelAttributes: [], + rect: const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0), + transform: kTestTransform, + childrenInTraversalOrder: Int32List.fromList([84, 96]), + childrenInHitTestOrder: Int32List.fromList([96, 84]), + actions: 0, + flags: 0, + maxValueLength: 0, + currentValueLength: 0, + textSelectionBase: 0, + textSelectionExtent: 0, + platformViewId: 0, + scrollChildren: 0, + scrollIndex: 0, + scrollPosition: 0.0, + scrollExtentMax: 0.0, + scrollExtentMin: 0.0, + elevation: 0.0, + thickness: 0.0, + hint: '', + hintAttributes: [], + value: '', + valueAttributes: [], + increasedValue: '', + increasedValueAttributes: [], + decreasedValue: '', + decreasedValueAttributes: [], + tooltip: 'tooltip', + textDirection: TextDirection.ltr, + additionalActions: Int32List(0), + controlsNodes: null, + inputType: SemanticsInputType.none, + ); + } + + for (final view in PlatformDispatcher.instance.views) { + view.updateSemantics(createForView(view).build()); + } + + signalNativeTest(); + + // 7: Await semantics disabled from embedder. + await semanticsChanged; + notifySemanticsEnabled(PlatformDispatcher.instance.semanticsEnabled); +} diff --git a/flutter/engine/src/flutter/shell/platform/embedder/fixtures/scene_without_custom_compositor.png b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/scene_without_custom_compositor.png new file mode 100644 index 0000000000000000000000000000000000000000..aa3ee979b179dcbec2f54bb0df4fdadb61cf9bd4 Binary files /dev/null and b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/scene_without_custom_compositor.png differ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/fixtures/scene_without_custom_compositor_with_xform.png b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/scene_without_custom_compositor_with_xform.png new file mode 100644 index 0000000000000000000000000000000000000000..d406fb6dea360caee1ad00abfd36e04c35fa0510 Binary files /dev/null and b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/scene_without_custom_compositor_with_xform.png differ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/fixtures/snapshot_large_scene.png b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/snapshot_large_scene.png new file mode 100644 index 0000000000000000000000000000000000000000..7190c22a0f30d6b2b2311b812f5efeafd8145973 Binary files /dev/null and b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/snapshot_large_scene.png differ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/fixtures/verifyb143464703.png b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/verifyb143464703.png new file mode 100644 index 0000000000000000000000000000000000000000..b55cfb46b944ae85b538e57058d6f44b2158158f Binary files /dev/null and b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/verifyb143464703.png differ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/fixtures/verifyb143464703_soft_noxform.png b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/verifyb143464703_soft_noxform.png new file mode 100644 index 0000000000000000000000000000000000000000..659473eedd28ab9cc2f67222e4b55496c97e3dca Binary files /dev/null and b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/verifyb143464703_soft_noxform.png differ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/fixtures/vk_dpr_noxform.png b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/vk_dpr_noxform.png new file mode 100644 index 0000000000000000000000000000000000000000..0689f1a414b1e33bc0b8c14c9252fac6e87a9e7a Binary files /dev/null and b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/vk_dpr_noxform.png differ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/fixtures/vk_gradient.png b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/vk_gradient.png new file mode 100644 index 0000000000000000000000000000000000000000..540bd8d66db9be38c0033f72750b23b49f536577 Binary files /dev/null and b/flutter/engine/src/flutter/shell/platform/embedder/fixtures/vk_gradient.png differ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/test_utils/key_codes.g.h b/flutter/engine/src/flutter/shell/platform/embedder/test_utils/key_codes.g.h new file mode 100644 index 0000000000000000000000000000000000000000..9a7ae0e96cf0adc7ea355fc0bb19a95efd32de39 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/test_utils/key_codes.g.h @@ -0,0 +1,751 @@ +// 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_SHELL_PLATFORM_EMBEDDER_TEST_UTILS_KEY_CODES_G_H_ +#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TEST_UTILS_KEY_CODES_G_H_ + +#include + +// DO NOT EDIT -- DO NOT EDIT -- DO NOT EDIT +// This file is generated by +// flutter/flutter:dev/tools/gen_keycodes/bin/gen_keycodes.dart and should not +// be edited directly. +// +// Edit the template +// flutter/flutter:dev/tools/gen_keycodes/data/key_codes_cc.tmpl +// instead. +// +// See flutter/flutter:dev/tools/gen_keycodes/README.md for more information. + +// This file contains keyboard constants to be used in unit tests. They should +// not be used in production code. + +namespace flutter { + +namespace testing { + +namespace keycodes { + +constexpr uint64_t kPhysicalHyper = 0x00000010; +constexpr uint64_t kPhysicalSuperKey = 0x00000011; +constexpr uint64_t kPhysicalFn = 0x00000012; +constexpr uint64_t kPhysicalFnLock = 0x00000013; +constexpr uint64_t kPhysicalSuspend = 0x00000014; +constexpr uint64_t kPhysicalResume = 0x00000015; +constexpr uint64_t kPhysicalTurbo = 0x00000016; +constexpr uint64_t kPhysicalPrivacyScreenToggle = 0x00000017; +constexpr uint64_t kPhysicalMicrophoneMuteToggle = 0x00000018; +constexpr uint64_t kPhysicalSleep = 0x00010082; +constexpr uint64_t kPhysicalWakeUp = 0x00010083; +constexpr uint64_t kPhysicalDisplayToggleIntExt = 0x000100b5; +constexpr uint64_t kPhysicalGameButton1 = 0x0005ff01; +constexpr uint64_t kPhysicalGameButton2 = 0x0005ff02; +constexpr uint64_t kPhysicalGameButton3 = 0x0005ff03; +constexpr uint64_t kPhysicalGameButton4 = 0x0005ff04; +constexpr uint64_t kPhysicalGameButton5 = 0x0005ff05; +constexpr uint64_t kPhysicalGameButton6 = 0x0005ff06; +constexpr uint64_t kPhysicalGameButton7 = 0x0005ff07; +constexpr uint64_t kPhysicalGameButton8 = 0x0005ff08; +constexpr uint64_t kPhysicalGameButton9 = 0x0005ff09; +constexpr uint64_t kPhysicalGameButton10 = 0x0005ff0a; +constexpr uint64_t kPhysicalGameButton11 = 0x0005ff0b; +constexpr uint64_t kPhysicalGameButton12 = 0x0005ff0c; +constexpr uint64_t kPhysicalGameButton13 = 0x0005ff0d; +constexpr uint64_t kPhysicalGameButton14 = 0x0005ff0e; +constexpr uint64_t kPhysicalGameButton15 = 0x0005ff0f; +constexpr uint64_t kPhysicalGameButton16 = 0x0005ff10; +constexpr uint64_t kPhysicalGameButtonA = 0x0005ff11; +constexpr uint64_t kPhysicalGameButtonB = 0x0005ff12; +constexpr uint64_t kPhysicalGameButtonC = 0x0005ff13; +constexpr uint64_t kPhysicalGameButtonLeft1 = 0x0005ff14; +constexpr uint64_t kPhysicalGameButtonLeft2 = 0x0005ff15; +constexpr uint64_t kPhysicalGameButtonMode = 0x0005ff16; +constexpr uint64_t kPhysicalGameButtonRight1 = 0x0005ff17; +constexpr uint64_t kPhysicalGameButtonRight2 = 0x0005ff18; +constexpr uint64_t kPhysicalGameButtonSelect = 0x0005ff19; +constexpr uint64_t kPhysicalGameButtonStart = 0x0005ff1a; +constexpr uint64_t kPhysicalGameButtonThumbLeft = 0x0005ff1b; +constexpr uint64_t kPhysicalGameButtonThumbRight = 0x0005ff1c; +constexpr uint64_t kPhysicalGameButtonX = 0x0005ff1d; +constexpr uint64_t kPhysicalGameButtonY = 0x0005ff1e; +constexpr uint64_t kPhysicalGameButtonZ = 0x0005ff1f; +constexpr uint64_t kPhysicalUsbReserved = 0x00070000; +constexpr uint64_t kPhysicalUsbErrorRollOver = 0x00070001; +constexpr uint64_t kPhysicalUsbPostFail = 0x00070002; +constexpr uint64_t kPhysicalUsbErrorUndefined = 0x00070003; +constexpr uint64_t kPhysicalKeyA = 0x00070004; +constexpr uint64_t kPhysicalKeyB = 0x00070005; +constexpr uint64_t kPhysicalKeyC = 0x00070006; +constexpr uint64_t kPhysicalKeyD = 0x00070007; +constexpr uint64_t kPhysicalKeyE = 0x00070008; +constexpr uint64_t kPhysicalKeyF = 0x00070009; +constexpr uint64_t kPhysicalKeyG = 0x0007000a; +constexpr uint64_t kPhysicalKeyH = 0x0007000b; +constexpr uint64_t kPhysicalKeyI = 0x0007000c; +constexpr uint64_t kPhysicalKeyJ = 0x0007000d; +constexpr uint64_t kPhysicalKeyK = 0x0007000e; +constexpr uint64_t kPhysicalKeyL = 0x0007000f; +constexpr uint64_t kPhysicalKeyM = 0x00070010; +constexpr uint64_t kPhysicalKeyN = 0x00070011; +constexpr uint64_t kPhysicalKeyO = 0x00070012; +constexpr uint64_t kPhysicalKeyP = 0x00070013; +constexpr uint64_t kPhysicalKeyQ = 0x00070014; +constexpr uint64_t kPhysicalKeyR = 0x00070015; +constexpr uint64_t kPhysicalKeyS = 0x00070016; +constexpr uint64_t kPhysicalKeyT = 0x00070017; +constexpr uint64_t kPhysicalKeyU = 0x00070018; +constexpr uint64_t kPhysicalKeyV = 0x00070019; +constexpr uint64_t kPhysicalKeyW = 0x0007001a; +constexpr uint64_t kPhysicalKeyX = 0x0007001b; +constexpr uint64_t kPhysicalKeyY = 0x0007001c; +constexpr uint64_t kPhysicalKeyZ = 0x0007001d; +constexpr uint64_t kPhysicalDigit1 = 0x0007001e; +constexpr uint64_t kPhysicalDigit2 = 0x0007001f; +constexpr uint64_t kPhysicalDigit3 = 0x00070020; +constexpr uint64_t kPhysicalDigit4 = 0x00070021; +constexpr uint64_t kPhysicalDigit5 = 0x00070022; +constexpr uint64_t kPhysicalDigit6 = 0x00070023; +constexpr uint64_t kPhysicalDigit7 = 0x00070024; +constexpr uint64_t kPhysicalDigit8 = 0x00070025; +constexpr uint64_t kPhysicalDigit9 = 0x00070026; +constexpr uint64_t kPhysicalDigit0 = 0x00070027; +constexpr uint64_t kPhysicalEnter = 0x00070028; +constexpr uint64_t kPhysicalEscape = 0x00070029; +constexpr uint64_t kPhysicalBackspace = 0x0007002a; +constexpr uint64_t kPhysicalTab = 0x0007002b; +constexpr uint64_t kPhysicalSpace = 0x0007002c; +constexpr uint64_t kPhysicalMinus = 0x0007002d; +constexpr uint64_t kPhysicalEqual = 0x0007002e; +constexpr uint64_t kPhysicalBracketLeft = 0x0007002f; +constexpr uint64_t kPhysicalBracketRight = 0x00070030; +constexpr uint64_t kPhysicalBackslash = 0x00070031; +constexpr uint64_t kPhysicalSemicolon = 0x00070033; +constexpr uint64_t kPhysicalQuote = 0x00070034; +constexpr uint64_t kPhysicalBackquote = 0x00070035; +constexpr uint64_t kPhysicalComma = 0x00070036; +constexpr uint64_t kPhysicalPeriod = 0x00070037; +constexpr uint64_t kPhysicalSlash = 0x00070038; +constexpr uint64_t kPhysicalCapsLock = 0x00070039; +constexpr uint64_t kPhysicalF1 = 0x0007003a; +constexpr uint64_t kPhysicalF2 = 0x0007003b; +constexpr uint64_t kPhysicalF3 = 0x0007003c; +constexpr uint64_t kPhysicalF4 = 0x0007003d; +constexpr uint64_t kPhysicalF5 = 0x0007003e; +constexpr uint64_t kPhysicalF6 = 0x0007003f; +constexpr uint64_t kPhysicalF7 = 0x00070040; +constexpr uint64_t kPhysicalF8 = 0x00070041; +constexpr uint64_t kPhysicalF9 = 0x00070042; +constexpr uint64_t kPhysicalF10 = 0x00070043; +constexpr uint64_t kPhysicalF11 = 0x00070044; +constexpr uint64_t kPhysicalF12 = 0x00070045; +constexpr uint64_t kPhysicalPrintScreen = 0x00070046; +constexpr uint64_t kPhysicalScrollLock = 0x00070047; +constexpr uint64_t kPhysicalPause = 0x00070048; +constexpr uint64_t kPhysicalInsert = 0x00070049; +constexpr uint64_t kPhysicalHome = 0x0007004a; +constexpr uint64_t kPhysicalPageUp = 0x0007004b; +constexpr uint64_t kPhysicalDelete = 0x0007004c; +constexpr uint64_t kPhysicalEnd = 0x0007004d; +constexpr uint64_t kPhysicalPageDown = 0x0007004e; +constexpr uint64_t kPhysicalArrowRight = 0x0007004f; +constexpr uint64_t kPhysicalArrowLeft = 0x00070050; +constexpr uint64_t kPhysicalArrowDown = 0x00070051; +constexpr uint64_t kPhysicalArrowUp = 0x00070052; +constexpr uint64_t kPhysicalNumLock = 0x00070053; +constexpr uint64_t kPhysicalNumpadDivide = 0x00070054; +constexpr uint64_t kPhysicalNumpadMultiply = 0x00070055; +constexpr uint64_t kPhysicalNumpadSubtract = 0x00070056; +constexpr uint64_t kPhysicalNumpadAdd = 0x00070057; +constexpr uint64_t kPhysicalNumpadEnter = 0x00070058; +constexpr uint64_t kPhysicalNumpad1 = 0x00070059; +constexpr uint64_t kPhysicalNumpad2 = 0x0007005a; +constexpr uint64_t kPhysicalNumpad3 = 0x0007005b; +constexpr uint64_t kPhysicalNumpad4 = 0x0007005c; +constexpr uint64_t kPhysicalNumpad5 = 0x0007005d; +constexpr uint64_t kPhysicalNumpad6 = 0x0007005e; +constexpr uint64_t kPhysicalNumpad7 = 0x0007005f; +constexpr uint64_t kPhysicalNumpad8 = 0x00070060; +constexpr uint64_t kPhysicalNumpad9 = 0x00070061; +constexpr uint64_t kPhysicalNumpad0 = 0x00070062; +constexpr uint64_t kPhysicalNumpadDecimal = 0x00070063; +constexpr uint64_t kPhysicalIntlBackslash = 0x00070064; +constexpr uint64_t kPhysicalContextMenu = 0x00070065; +constexpr uint64_t kPhysicalPower = 0x00070066; +constexpr uint64_t kPhysicalNumpadEqual = 0x00070067; +constexpr uint64_t kPhysicalF13 = 0x00070068; +constexpr uint64_t kPhysicalF14 = 0x00070069; +constexpr uint64_t kPhysicalF15 = 0x0007006a; +constexpr uint64_t kPhysicalF16 = 0x0007006b; +constexpr uint64_t kPhysicalF17 = 0x0007006c; +constexpr uint64_t kPhysicalF18 = 0x0007006d; +constexpr uint64_t kPhysicalF19 = 0x0007006e; +constexpr uint64_t kPhysicalF20 = 0x0007006f; +constexpr uint64_t kPhysicalF21 = 0x00070070; +constexpr uint64_t kPhysicalF22 = 0x00070071; +constexpr uint64_t kPhysicalF23 = 0x00070072; +constexpr uint64_t kPhysicalF24 = 0x00070073; +constexpr uint64_t kPhysicalOpen = 0x00070074; +constexpr uint64_t kPhysicalHelp = 0x00070075; +constexpr uint64_t kPhysicalSelect = 0x00070077; +constexpr uint64_t kPhysicalAgain = 0x00070079; +constexpr uint64_t kPhysicalUndo = 0x0007007a; +constexpr uint64_t kPhysicalCut = 0x0007007b; +constexpr uint64_t kPhysicalCopy = 0x0007007c; +constexpr uint64_t kPhysicalPaste = 0x0007007d; +constexpr uint64_t kPhysicalFind = 0x0007007e; +constexpr uint64_t kPhysicalAudioVolumeMute = 0x0007007f; +constexpr uint64_t kPhysicalAudioVolumeUp = 0x00070080; +constexpr uint64_t kPhysicalAudioVolumeDown = 0x00070081; +constexpr uint64_t kPhysicalNumpadComma = 0x00070085; +constexpr uint64_t kPhysicalIntlRo = 0x00070087; +constexpr uint64_t kPhysicalKanaMode = 0x00070088; +constexpr uint64_t kPhysicalIntlYen = 0x00070089; +constexpr uint64_t kPhysicalConvert = 0x0007008a; +constexpr uint64_t kPhysicalNonConvert = 0x0007008b; +constexpr uint64_t kPhysicalLang1 = 0x00070090; +constexpr uint64_t kPhysicalLang2 = 0x00070091; +constexpr uint64_t kPhysicalLang3 = 0x00070092; +constexpr uint64_t kPhysicalLang4 = 0x00070093; +constexpr uint64_t kPhysicalLang5 = 0x00070094; +constexpr uint64_t kPhysicalAbort = 0x0007009b; +constexpr uint64_t kPhysicalProps = 0x000700a3; +constexpr uint64_t kPhysicalNumpadParenLeft = 0x000700b6; +constexpr uint64_t kPhysicalNumpadParenRight = 0x000700b7; +constexpr uint64_t kPhysicalNumpadBackspace = 0x000700bb; +constexpr uint64_t kPhysicalNumpadMemoryStore = 0x000700d0; +constexpr uint64_t kPhysicalNumpadMemoryRecall = 0x000700d1; +constexpr uint64_t kPhysicalNumpadMemoryClear = 0x000700d2; +constexpr uint64_t kPhysicalNumpadMemoryAdd = 0x000700d3; +constexpr uint64_t kPhysicalNumpadMemorySubtract = 0x000700d4; +constexpr uint64_t kPhysicalNumpadSignChange = 0x000700d7; +constexpr uint64_t kPhysicalNumpadClear = 0x000700d8; +constexpr uint64_t kPhysicalNumpadClearEntry = 0x000700d9; +constexpr uint64_t kPhysicalControlLeft = 0x000700e0; +constexpr uint64_t kPhysicalShiftLeft = 0x000700e1; +constexpr uint64_t kPhysicalAltLeft = 0x000700e2; +constexpr uint64_t kPhysicalMetaLeft = 0x000700e3; +constexpr uint64_t kPhysicalControlRight = 0x000700e4; +constexpr uint64_t kPhysicalShiftRight = 0x000700e5; +constexpr uint64_t kPhysicalAltRight = 0x000700e6; +constexpr uint64_t kPhysicalMetaRight = 0x000700e7; +constexpr uint64_t kPhysicalInfo = 0x000c0060; +constexpr uint64_t kPhysicalClosedCaptionToggle = 0x000c0061; +constexpr uint64_t kPhysicalBrightnessUp = 0x000c006f; +constexpr uint64_t kPhysicalBrightnessDown = 0x000c0070; +constexpr uint64_t kPhysicalBrightnessToggle = 0x000c0072; +constexpr uint64_t kPhysicalBrightnessMinimum = 0x000c0073; +constexpr uint64_t kPhysicalBrightnessMaximum = 0x000c0074; +constexpr uint64_t kPhysicalBrightnessAuto = 0x000c0075; +constexpr uint64_t kPhysicalKbdIllumUp = 0x000c0079; +constexpr uint64_t kPhysicalKbdIllumDown = 0x000c007a; +constexpr uint64_t kPhysicalMediaLast = 0x000c0083; +constexpr uint64_t kPhysicalLaunchPhone = 0x000c008c; +constexpr uint64_t kPhysicalProgramGuide = 0x000c008d; +constexpr uint64_t kPhysicalExit = 0x000c0094; +constexpr uint64_t kPhysicalChannelUp = 0x000c009c; +constexpr uint64_t kPhysicalChannelDown = 0x000c009d; +constexpr uint64_t kPhysicalMediaPlay = 0x000c00b0; +constexpr uint64_t kPhysicalMediaPause = 0x000c00b1; +constexpr uint64_t kPhysicalMediaRecord = 0x000c00b2; +constexpr uint64_t kPhysicalMediaFastForward = 0x000c00b3; +constexpr uint64_t kPhysicalMediaRewind = 0x000c00b4; +constexpr uint64_t kPhysicalMediaTrackNext = 0x000c00b5; +constexpr uint64_t kPhysicalMediaTrackPrevious = 0x000c00b6; +constexpr uint64_t kPhysicalMediaStop = 0x000c00b7; +constexpr uint64_t kPhysicalEject = 0x000c00b8; +constexpr uint64_t kPhysicalMediaPlayPause = 0x000c00cd; +constexpr uint64_t kPhysicalSpeechInputToggle = 0x000c00cf; +constexpr uint64_t kPhysicalBassBoost = 0x000c00e5; +constexpr uint64_t kPhysicalMediaSelect = 0x000c0183; +constexpr uint64_t kPhysicalLaunchWordProcessor = 0x000c0184; +constexpr uint64_t kPhysicalLaunchSpreadsheet = 0x000c0186; +constexpr uint64_t kPhysicalLaunchMail = 0x000c018a; +constexpr uint64_t kPhysicalLaunchContacts = 0x000c018d; +constexpr uint64_t kPhysicalLaunchCalendar = 0x000c018e; +constexpr uint64_t kPhysicalLaunchApp2 = 0x000c0192; +constexpr uint64_t kPhysicalLaunchApp1 = 0x000c0194; +constexpr uint64_t kPhysicalLaunchInternetBrowser = 0x000c0196; +constexpr uint64_t kPhysicalLogOff = 0x000c019c; +constexpr uint64_t kPhysicalLockScreen = 0x000c019e; +constexpr uint64_t kPhysicalLaunchControlPanel = 0x000c019f; +constexpr uint64_t kPhysicalSelectTask = 0x000c01a2; +constexpr uint64_t kPhysicalLaunchDocuments = 0x000c01a7; +constexpr uint64_t kPhysicalSpellCheck = 0x000c01ab; +constexpr uint64_t kPhysicalLaunchKeyboardLayout = 0x000c01ae; +constexpr uint64_t kPhysicalLaunchScreenSaver = 0x000c01b1; +constexpr uint64_t kPhysicalLaunchAudioBrowser = 0x000c01b7; +constexpr uint64_t kPhysicalLaunchAssistant = 0x000c01cb; +constexpr uint64_t kPhysicalNewKey = 0x000c0201; +constexpr uint64_t kPhysicalClose = 0x000c0203; +constexpr uint64_t kPhysicalSave = 0x000c0207; +constexpr uint64_t kPhysicalPrint = 0x000c0208; +constexpr uint64_t kPhysicalBrowserSearch = 0x000c0221; +constexpr uint64_t kPhysicalBrowserHome = 0x000c0223; +constexpr uint64_t kPhysicalBrowserBack = 0x000c0224; +constexpr uint64_t kPhysicalBrowserForward = 0x000c0225; +constexpr uint64_t kPhysicalBrowserStop = 0x000c0226; +constexpr uint64_t kPhysicalBrowserRefresh = 0x000c0227; +constexpr uint64_t kPhysicalBrowserFavorites = 0x000c022a; +constexpr uint64_t kPhysicalZoomIn = 0x000c022d; +constexpr uint64_t kPhysicalZoomOut = 0x000c022e; +constexpr uint64_t kPhysicalZoomToggle = 0x000c0232; +constexpr uint64_t kPhysicalRedo = 0x000c0279; +constexpr uint64_t kPhysicalMailReply = 0x000c0289; +constexpr uint64_t kPhysicalMailForward = 0x000c028b; +constexpr uint64_t kPhysicalMailSend = 0x000c028c; +constexpr uint64_t kPhysicalKeyboardLayoutSelect = 0x000c029d; +constexpr uint64_t kPhysicalShowAllWindows = 0x000c029f; + +constexpr uint64_t kLogicalSpace = 0x00000000020; +constexpr uint64_t kLogicalExclamation = 0x00000000021; +constexpr uint64_t kLogicalQuote = 0x00000000022; +constexpr uint64_t kLogicalNumberSign = 0x00000000023; +constexpr uint64_t kLogicalDollar = 0x00000000024; +constexpr uint64_t kLogicalPercent = 0x00000000025; +constexpr uint64_t kLogicalAmpersand = 0x00000000026; +constexpr uint64_t kLogicalQuoteSingle = 0x00000000027; +constexpr uint64_t kLogicalParenthesisLeft = 0x00000000028; +constexpr uint64_t kLogicalParenthesisRight = 0x00000000029; +constexpr uint64_t kLogicalAsterisk = 0x0000000002a; +constexpr uint64_t kLogicalAdd = 0x0000000002b; +constexpr uint64_t kLogicalComma = 0x0000000002c; +constexpr uint64_t kLogicalMinus = 0x0000000002d; +constexpr uint64_t kLogicalPeriod = 0x0000000002e; +constexpr uint64_t kLogicalSlash = 0x0000000002f; +constexpr uint64_t kLogicalDigit0 = 0x00000000030; +constexpr uint64_t kLogicalDigit1 = 0x00000000031; +constexpr uint64_t kLogicalDigit2 = 0x00000000032; +constexpr uint64_t kLogicalDigit3 = 0x00000000033; +constexpr uint64_t kLogicalDigit4 = 0x00000000034; +constexpr uint64_t kLogicalDigit5 = 0x00000000035; +constexpr uint64_t kLogicalDigit6 = 0x00000000036; +constexpr uint64_t kLogicalDigit7 = 0x00000000037; +constexpr uint64_t kLogicalDigit8 = 0x00000000038; +constexpr uint64_t kLogicalDigit9 = 0x00000000039; +constexpr uint64_t kLogicalColon = 0x0000000003a; +constexpr uint64_t kLogicalSemicolon = 0x0000000003b; +constexpr uint64_t kLogicalLess = 0x0000000003c; +constexpr uint64_t kLogicalEqual = 0x0000000003d; +constexpr uint64_t kLogicalGreater = 0x0000000003e; +constexpr uint64_t kLogicalQuestion = 0x0000000003f; +constexpr uint64_t kLogicalAt = 0x00000000040; +constexpr uint64_t kLogicalBracketLeft = 0x0000000005b; +constexpr uint64_t kLogicalBackslash = 0x0000000005c; +constexpr uint64_t kLogicalBracketRight = 0x0000000005d; +constexpr uint64_t kLogicalCaret = 0x0000000005e; +constexpr uint64_t kLogicalUnderscore = 0x0000000005f; +constexpr uint64_t kLogicalBackquote = 0x00000000060; +constexpr uint64_t kLogicalKeyA = 0x00000000061; +constexpr uint64_t kLogicalKeyB = 0x00000000062; +constexpr uint64_t kLogicalKeyC = 0x00000000063; +constexpr uint64_t kLogicalKeyD = 0x00000000064; +constexpr uint64_t kLogicalKeyE = 0x00000000065; +constexpr uint64_t kLogicalKeyF = 0x00000000066; +constexpr uint64_t kLogicalKeyG = 0x00000000067; +constexpr uint64_t kLogicalKeyH = 0x00000000068; +constexpr uint64_t kLogicalKeyI = 0x00000000069; +constexpr uint64_t kLogicalKeyJ = 0x0000000006a; +constexpr uint64_t kLogicalKeyK = 0x0000000006b; +constexpr uint64_t kLogicalKeyL = 0x0000000006c; +constexpr uint64_t kLogicalKeyM = 0x0000000006d; +constexpr uint64_t kLogicalKeyN = 0x0000000006e; +constexpr uint64_t kLogicalKeyO = 0x0000000006f; +constexpr uint64_t kLogicalKeyP = 0x00000000070; +constexpr uint64_t kLogicalKeyQ = 0x00000000071; +constexpr uint64_t kLogicalKeyR = 0x00000000072; +constexpr uint64_t kLogicalKeyS = 0x00000000073; +constexpr uint64_t kLogicalKeyT = 0x00000000074; +constexpr uint64_t kLogicalKeyU = 0x00000000075; +constexpr uint64_t kLogicalKeyV = 0x00000000076; +constexpr uint64_t kLogicalKeyW = 0x00000000077; +constexpr uint64_t kLogicalKeyX = 0x00000000078; +constexpr uint64_t kLogicalKeyY = 0x00000000079; +constexpr uint64_t kLogicalKeyZ = 0x0000000007a; +constexpr uint64_t kLogicalBraceLeft = 0x0000000007b; +constexpr uint64_t kLogicalBar = 0x0000000007c; +constexpr uint64_t kLogicalBraceRight = 0x0000000007d; +constexpr uint64_t kLogicalTilde = 0x0000000007e; +constexpr uint64_t kLogicalUnidentified = 0x00100000001; +constexpr uint64_t kLogicalBackspace = 0x00100000008; +constexpr uint64_t kLogicalTab = 0x00100000009; +constexpr uint64_t kLogicalEnter = 0x0010000000d; +constexpr uint64_t kLogicalEscape = 0x0010000001b; +constexpr uint64_t kLogicalDelete = 0x0010000007f; +constexpr uint64_t kLogicalAccel = 0x00100000101; +constexpr uint64_t kLogicalAltGraph = 0x00100000103; +constexpr uint64_t kLogicalCapsLock = 0x00100000104; +constexpr uint64_t kLogicalFn = 0x00100000106; +constexpr uint64_t kLogicalFnLock = 0x00100000107; +constexpr uint64_t kLogicalHyper = 0x00100000108; +constexpr uint64_t kLogicalNumLock = 0x0010000010a; +constexpr uint64_t kLogicalScrollLock = 0x0010000010c; +constexpr uint64_t kLogicalSuperKey = 0x0010000010e; +constexpr uint64_t kLogicalSymbol = 0x0010000010f; +constexpr uint64_t kLogicalSymbolLock = 0x00100000110; +constexpr uint64_t kLogicalShiftLevel5 = 0x00100000111; +constexpr uint64_t kLogicalArrowDown = 0x00100000301; +constexpr uint64_t kLogicalArrowLeft = 0x00100000302; +constexpr uint64_t kLogicalArrowRight = 0x00100000303; +constexpr uint64_t kLogicalArrowUp = 0x00100000304; +constexpr uint64_t kLogicalEnd = 0x00100000305; +constexpr uint64_t kLogicalHome = 0x00100000306; +constexpr uint64_t kLogicalPageDown = 0x00100000307; +constexpr uint64_t kLogicalPageUp = 0x00100000308; +constexpr uint64_t kLogicalClear = 0x00100000401; +constexpr uint64_t kLogicalCopy = 0x00100000402; +constexpr uint64_t kLogicalCrSel = 0x00100000403; +constexpr uint64_t kLogicalCut = 0x00100000404; +constexpr uint64_t kLogicalEraseEof = 0x00100000405; +constexpr uint64_t kLogicalExSel = 0x00100000406; +constexpr uint64_t kLogicalInsert = 0x00100000407; +constexpr uint64_t kLogicalPaste = 0x00100000408; +constexpr uint64_t kLogicalRedo = 0x00100000409; +constexpr uint64_t kLogicalUndo = 0x0010000040a; +constexpr uint64_t kLogicalAccept = 0x00100000501; +constexpr uint64_t kLogicalAgain = 0x00100000502; +constexpr uint64_t kLogicalAttn = 0x00100000503; +constexpr uint64_t kLogicalCancel = 0x00100000504; +constexpr uint64_t kLogicalContextMenu = 0x00100000505; +constexpr uint64_t kLogicalExecute = 0x00100000506; +constexpr uint64_t kLogicalFind = 0x00100000507; +constexpr uint64_t kLogicalHelp = 0x00100000508; +constexpr uint64_t kLogicalPause = 0x00100000509; +constexpr uint64_t kLogicalPlay = 0x0010000050a; +constexpr uint64_t kLogicalProps = 0x0010000050b; +constexpr uint64_t kLogicalSelect = 0x0010000050c; +constexpr uint64_t kLogicalZoomIn = 0x0010000050d; +constexpr uint64_t kLogicalZoomOut = 0x0010000050e; +constexpr uint64_t kLogicalBrightnessDown = 0x00100000601; +constexpr uint64_t kLogicalBrightnessUp = 0x00100000602; +constexpr uint64_t kLogicalCamera = 0x00100000603; +constexpr uint64_t kLogicalEject = 0x00100000604; +constexpr uint64_t kLogicalLogOff = 0x00100000605; +constexpr uint64_t kLogicalPower = 0x00100000606; +constexpr uint64_t kLogicalPowerOff = 0x00100000607; +constexpr uint64_t kLogicalPrintScreen = 0x00100000608; +constexpr uint64_t kLogicalHibernate = 0x00100000609; +constexpr uint64_t kLogicalStandby = 0x0010000060a; +constexpr uint64_t kLogicalWakeUp = 0x0010000060b; +constexpr uint64_t kLogicalAllCandidates = 0x00100000701; +constexpr uint64_t kLogicalAlphanumeric = 0x00100000702; +constexpr uint64_t kLogicalCodeInput = 0x00100000703; +constexpr uint64_t kLogicalCompose = 0x00100000704; +constexpr uint64_t kLogicalConvert = 0x00100000705; +constexpr uint64_t kLogicalFinalMode = 0x00100000706; +constexpr uint64_t kLogicalGroupFirst = 0x00100000707; +constexpr uint64_t kLogicalGroupLast = 0x00100000708; +constexpr uint64_t kLogicalGroupNext = 0x00100000709; +constexpr uint64_t kLogicalGroupPrevious = 0x0010000070a; +constexpr uint64_t kLogicalModeChange = 0x0010000070b; +constexpr uint64_t kLogicalNextCandidate = 0x0010000070c; +constexpr uint64_t kLogicalNonConvert = 0x0010000070d; +constexpr uint64_t kLogicalPreviousCandidate = 0x0010000070e; +constexpr uint64_t kLogicalProcess = 0x0010000070f; +constexpr uint64_t kLogicalSingleCandidate = 0x00100000710; +constexpr uint64_t kLogicalHangulMode = 0x00100000711; +constexpr uint64_t kLogicalHanjaMode = 0x00100000712; +constexpr uint64_t kLogicalJunjaMode = 0x00100000713; +constexpr uint64_t kLogicalEisu = 0x00100000714; +constexpr uint64_t kLogicalHankaku = 0x00100000715; +constexpr uint64_t kLogicalHiragana = 0x00100000716; +constexpr uint64_t kLogicalHiraganaKatakana = 0x00100000717; +constexpr uint64_t kLogicalKanaMode = 0x00100000718; +constexpr uint64_t kLogicalKanjiMode = 0x00100000719; +constexpr uint64_t kLogicalKatakana = 0x0010000071a; +constexpr uint64_t kLogicalRomaji = 0x0010000071b; +constexpr uint64_t kLogicalZenkaku = 0x0010000071c; +constexpr uint64_t kLogicalZenkakuHankaku = 0x0010000071d; +constexpr uint64_t kLogicalF1 = 0x00100000801; +constexpr uint64_t kLogicalF2 = 0x00100000802; +constexpr uint64_t kLogicalF3 = 0x00100000803; +constexpr uint64_t kLogicalF4 = 0x00100000804; +constexpr uint64_t kLogicalF5 = 0x00100000805; +constexpr uint64_t kLogicalF6 = 0x00100000806; +constexpr uint64_t kLogicalF7 = 0x00100000807; +constexpr uint64_t kLogicalF8 = 0x00100000808; +constexpr uint64_t kLogicalF9 = 0x00100000809; +constexpr uint64_t kLogicalF10 = 0x0010000080a; +constexpr uint64_t kLogicalF11 = 0x0010000080b; +constexpr uint64_t kLogicalF12 = 0x0010000080c; +constexpr uint64_t kLogicalF13 = 0x0010000080d; +constexpr uint64_t kLogicalF14 = 0x0010000080e; +constexpr uint64_t kLogicalF15 = 0x0010000080f; +constexpr uint64_t kLogicalF16 = 0x00100000810; +constexpr uint64_t kLogicalF17 = 0x00100000811; +constexpr uint64_t kLogicalF18 = 0x00100000812; +constexpr uint64_t kLogicalF19 = 0x00100000813; +constexpr uint64_t kLogicalF20 = 0x00100000814; +constexpr uint64_t kLogicalF21 = 0x00100000815; +constexpr uint64_t kLogicalF22 = 0x00100000816; +constexpr uint64_t kLogicalF23 = 0x00100000817; +constexpr uint64_t kLogicalF24 = 0x00100000818; +constexpr uint64_t kLogicalSoft1 = 0x00100000901; +constexpr uint64_t kLogicalSoft2 = 0x00100000902; +constexpr uint64_t kLogicalSoft3 = 0x00100000903; +constexpr uint64_t kLogicalSoft4 = 0x00100000904; +constexpr uint64_t kLogicalSoft5 = 0x00100000905; +constexpr uint64_t kLogicalSoft6 = 0x00100000906; +constexpr uint64_t kLogicalSoft7 = 0x00100000907; +constexpr uint64_t kLogicalSoft8 = 0x00100000908; +constexpr uint64_t kLogicalClose = 0x00100000a01; +constexpr uint64_t kLogicalMailForward = 0x00100000a02; +constexpr uint64_t kLogicalMailReply = 0x00100000a03; +constexpr uint64_t kLogicalMailSend = 0x00100000a04; +constexpr uint64_t kLogicalMediaPlayPause = 0x00100000a05; +constexpr uint64_t kLogicalMediaStop = 0x00100000a07; +constexpr uint64_t kLogicalMediaTrackNext = 0x00100000a08; +constexpr uint64_t kLogicalMediaTrackPrevious = 0x00100000a09; +constexpr uint64_t kLogicalNewKey = 0x00100000a0a; +constexpr uint64_t kLogicalOpen = 0x00100000a0b; +constexpr uint64_t kLogicalPrint = 0x00100000a0c; +constexpr uint64_t kLogicalSave = 0x00100000a0d; +constexpr uint64_t kLogicalSpellCheck = 0x00100000a0e; +constexpr uint64_t kLogicalAudioVolumeDown = 0x00100000a0f; +constexpr uint64_t kLogicalAudioVolumeUp = 0x00100000a10; +constexpr uint64_t kLogicalAudioVolumeMute = 0x00100000a11; +constexpr uint64_t kLogicalLaunchApplication2 = 0x00100000b01; +constexpr uint64_t kLogicalLaunchCalendar = 0x00100000b02; +constexpr uint64_t kLogicalLaunchMail = 0x00100000b03; +constexpr uint64_t kLogicalLaunchMediaPlayer = 0x00100000b04; +constexpr uint64_t kLogicalLaunchMusicPlayer = 0x00100000b05; +constexpr uint64_t kLogicalLaunchApplication1 = 0x00100000b06; +constexpr uint64_t kLogicalLaunchScreenSaver = 0x00100000b07; +constexpr uint64_t kLogicalLaunchSpreadsheet = 0x00100000b08; +constexpr uint64_t kLogicalLaunchWebBrowser = 0x00100000b09; +constexpr uint64_t kLogicalLaunchWebCam = 0x00100000b0a; +constexpr uint64_t kLogicalLaunchWordProcessor = 0x00100000b0b; +constexpr uint64_t kLogicalLaunchContacts = 0x00100000b0c; +constexpr uint64_t kLogicalLaunchPhone = 0x00100000b0d; +constexpr uint64_t kLogicalLaunchAssistant = 0x00100000b0e; +constexpr uint64_t kLogicalLaunchControlPanel = 0x00100000b0f; +constexpr uint64_t kLogicalBrowserBack = 0x00100000c01; +constexpr uint64_t kLogicalBrowserFavorites = 0x00100000c02; +constexpr uint64_t kLogicalBrowserForward = 0x00100000c03; +constexpr uint64_t kLogicalBrowserHome = 0x00100000c04; +constexpr uint64_t kLogicalBrowserRefresh = 0x00100000c05; +constexpr uint64_t kLogicalBrowserSearch = 0x00100000c06; +constexpr uint64_t kLogicalBrowserStop = 0x00100000c07; +constexpr uint64_t kLogicalAudioBalanceLeft = 0x00100000d01; +constexpr uint64_t kLogicalAudioBalanceRight = 0x00100000d02; +constexpr uint64_t kLogicalAudioBassBoostDown = 0x00100000d03; +constexpr uint64_t kLogicalAudioBassBoostUp = 0x00100000d04; +constexpr uint64_t kLogicalAudioFaderFront = 0x00100000d05; +constexpr uint64_t kLogicalAudioFaderRear = 0x00100000d06; +constexpr uint64_t kLogicalAudioSurroundModeNext = 0x00100000d07; +constexpr uint64_t kLogicalAvrInput = 0x00100000d08; +constexpr uint64_t kLogicalAvrPower = 0x00100000d09; +constexpr uint64_t kLogicalChannelDown = 0x00100000d0a; +constexpr uint64_t kLogicalChannelUp = 0x00100000d0b; +constexpr uint64_t kLogicalColorF0Red = 0x00100000d0c; +constexpr uint64_t kLogicalColorF1Green = 0x00100000d0d; +constexpr uint64_t kLogicalColorF2Yellow = 0x00100000d0e; +constexpr uint64_t kLogicalColorF3Blue = 0x00100000d0f; +constexpr uint64_t kLogicalColorF4Grey = 0x00100000d10; +constexpr uint64_t kLogicalColorF5Brown = 0x00100000d11; +constexpr uint64_t kLogicalClosedCaptionToggle = 0x00100000d12; +constexpr uint64_t kLogicalDimmer = 0x00100000d13; +constexpr uint64_t kLogicalDisplaySwap = 0x00100000d14; +constexpr uint64_t kLogicalExit = 0x00100000d15; +constexpr uint64_t kLogicalFavoriteClear0 = 0x00100000d16; +constexpr uint64_t kLogicalFavoriteClear1 = 0x00100000d17; +constexpr uint64_t kLogicalFavoriteClear2 = 0x00100000d18; +constexpr uint64_t kLogicalFavoriteClear3 = 0x00100000d19; +constexpr uint64_t kLogicalFavoriteRecall0 = 0x00100000d1a; +constexpr uint64_t kLogicalFavoriteRecall1 = 0x00100000d1b; +constexpr uint64_t kLogicalFavoriteRecall2 = 0x00100000d1c; +constexpr uint64_t kLogicalFavoriteRecall3 = 0x00100000d1d; +constexpr uint64_t kLogicalFavoriteStore0 = 0x00100000d1e; +constexpr uint64_t kLogicalFavoriteStore1 = 0x00100000d1f; +constexpr uint64_t kLogicalFavoriteStore2 = 0x00100000d20; +constexpr uint64_t kLogicalFavoriteStore3 = 0x00100000d21; +constexpr uint64_t kLogicalGuide = 0x00100000d22; +constexpr uint64_t kLogicalGuideNextDay = 0x00100000d23; +constexpr uint64_t kLogicalGuidePreviousDay = 0x00100000d24; +constexpr uint64_t kLogicalInfo = 0x00100000d25; +constexpr uint64_t kLogicalInstantReplay = 0x00100000d26; +constexpr uint64_t kLogicalLink = 0x00100000d27; +constexpr uint64_t kLogicalListProgram = 0x00100000d28; +constexpr uint64_t kLogicalLiveContent = 0x00100000d29; +constexpr uint64_t kLogicalLock = 0x00100000d2a; +constexpr uint64_t kLogicalMediaApps = 0x00100000d2b; +constexpr uint64_t kLogicalMediaFastForward = 0x00100000d2c; +constexpr uint64_t kLogicalMediaLast = 0x00100000d2d; +constexpr uint64_t kLogicalMediaPause = 0x00100000d2e; +constexpr uint64_t kLogicalMediaPlay = 0x00100000d2f; +constexpr uint64_t kLogicalMediaRecord = 0x00100000d30; +constexpr uint64_t kLogicalMediaRewind = 0x00100000d31; +constexpr uint64_t kLogicalMediaSkip = 0x00100000d32; +constexpr uint64_t kLogicalNextFavoriteChannel = 0x00100000d33; +constexpr uint64_t kLogicalNextUserProfile = 0x00100000d34; +constexpr uint64_t kLogicalOnDemand = 0x00100000d35; +constexpr uint64_t kLogicalPInPDown = 0x00100000d36; +constexpr uint64_t kLogicalPInPMove = 0x00100000d37; +constexpr uint64_t kLogicalPInPToggle = 0x00100000d38; +constexpr uint64_t kLogicalPInPUp = 0x00100000d39; +constexpr uint64_t kLogicalPlaySpeedDown = 0x00100000d3a; +constexpr uint64_t kLogicalPlaySpeedReset = 0x00100000d3b; +constexpr uint64_t kLogicalPlaySpeedUp = 0x00100000d3c; +constexpr uint64_t kLogicalRandomToggle = 0x00100000d3d; +constexpr uint64_t kLogicalRcLowBattery = 0x00100000d3e; +constexpr uint64_t kLogicalRecordSpeedNext = 0x00100000d3f; +constexpr uint64_t kLogicalRfBypass = 0x00100000d40; +constexpr uint64_t kLogicalScanChannelsToggle = 0x00100000d41; +constexpr uint64_t kLogicalScreenModeNext = 0x00100000d42; +constexpr uint64_t kLogicalSettings = 0x00100000d43; +constexpr uint64_t kLogicalSplitScreenToggle = 0x00100000d44; +constexpr uint64_t kLogicalStbInput = 0x00100000d45; +constexpr uint64_t kLogicalStbPower = 0x00100000d46; +constexpr uint64_t kLogicalSubtitle = 0x00100000d47; +constexpr uint64_t kLogicalTeletext = 0x00100000d48; +constexpr uint64_t kLogicalTv = 0x00100000d49; +constexpr uint64_t kLogicalTvInput = 0x00100000d4a; +constexpr uint64_t kLogicalTvPower = 0x00100000d4b; +constexpr uint64_t kLogicalVideoModeNext = 0x00100000d4c; +constexpr uint64_t kLogicalWink = 0x00100000d4d; +constexpr uint64_t kLogicalZoomToggle = 0x00100000d4e; +constexpr uint64_t kLogicalDvr = 0x00100000d4f; +constexpr uint64_t kLogicalMediaAudioTrack = 0x00100000d50; +constexpr uint64_t kLogicalMediaSkipBackward = 0x00100000d51; +constexpr uint64_t kLogicalMediaSkipForward = 0x00100000d52; +constexpr uint64_t kLogicalMediaStepBackward = 0x00100000d53; +constexpr uint64_t kLogicalMediaStepForward = 0x00100000d54; +constexpr uint64_t kLogicalMediaTopMenu = 0x00100000d55; +constexpr uint64_t kLogicalNavigateIn = 0x00100000d56; +constexpr uint64_t kLogicalNavigateNext = 0x00100000d57; +constexpr uint64_t kLogicalNavigateOut = 0x00100000d58; +constexpr uint64_t kLogicalNavigatePrevious = 0x00100000d59; +constexpr uint64_t kLogicalPairing = 0x00100000d5a; +constexpr uint64_t kLogicalMediaClose = 0x00100000d5b; +constexpr uint64_t kLogicalAudioBassBoostToggle = 0x00100000e02; +constexpr uint64_t kLogicalAudioTrebleDown = 0x00100000e04; +constexpr uint64_t kLogicalAudioTrebleUp = 0x00100000e05; +constexpr uint64_t kLogicalMicrophoneToggle = 0x00100000e06; +constexpr uint64_t kLogicalMicrophoneVolumeDown = 0x00100000e07; +constexpr uint64_t kLogicalMicrophoneVolumeUp = 0x00100000e08; +constexpr uint64_t kLogicalMicrophoneVolumeMute = 0x00100000e09; +constexpr uint64_t kLogicalSpeechCorrectionList = 0x00100000f01; +constexpr uint64_t kLogicalSpeechInputToggle = 0x00100000f02; +constexpr uint64_t kLogicalAppSwitch = 0x00100001001; +constexpr uint64_t kLogicalCall = 0x00100001002; +constexpr uint64_t kLogicalCameraFocus = 0x00100001003; +constexpr uint64_t kLogicalEndCall = 0x00100001004; +constexpr uint64_t kLogicalGoBack = 0x00100001005; +constexpr uint64_t kLogicalGoHome = 0x00100001006; +constexpr uint64_t kLogicalHeadsetHook = 0x00100001007; +constexpr uint64_t kLogicalLastNumberRedial = 0x00100001008; +constexpr uint64_t kLogicalNotification = 0x00100001009; +constexpr uint64_t kLogicalMannerMode = 0x0010000100a; +constexpr uint64_t kLogicalVoiceDial = 0x0010000100b; +constexpr uint64_t kLogicalTv3DMode = 0x00100001101; +constexpr uint64_t kLogicalTvAntennaCable = 0x00100001102; +constexpr uint64_t kLogicalTvAudioDescription = 0x00100001103; +constexpr uint64_t kLogicalTvAudioDescriptionMixDown = 0x00100001104; +constexpr uint64_t kLogicalTvAudioDescriptionMixUp = 0x00100001105; +constexpr uint64_t kLogicalTvContentsMenu = 0x00100001106; +constexpr uint64_t kLogicalTvDataService = 0x00100001107; +constexpr uint64_t kLogicalTvInputComponent1 = 0x00100001108; +constexpr uint64_t kLogicalTvInputComponent2 = 0x00100001109; +constexpr uint64_t kLogicalTvInputComposite1 = 0x0010000110a; +constexpr uint64_t kLogicalTvInputComposite2 = 0x0010000110b; +constexpr uint64_t kLogicalTvInputHDMI1 = 0x0010000110c; +constexpr uint64_t kLogicalTvInputHDMI2 = 0x0010000110d; +constexpr uint64_t kLogicalTvInputHDMI3 = 0x0010000110e; +constexpr uint64_t kLogicalTvInputHDMI4 = 0x0010000110f; +constexpr uint64_t kLogicalTvInputVGA1 = 0x00100001110; +constexpr uint64_t kLogicalTvMediaContext = 0x00100001111; +constexpr uint64_t kLogicalTvNetwork = 0x00100001112; +constexpr uint64_t kLogicalTvNumberEntry = 0x00100001113; +constexpr uint64_t kLogicalTvRadioService = 0x00100001114; +constexpr uint64_t kLogicalTvSatellite = 0x00100001115; +constexpr uint64_t kLogicalTvSatelliteBS = 0x00100001116; +constexpr uint64_t kLogicalTvSatelliteCS = 0x00100001117; +constexpr uint64_t kLogicalTvSatelliteToggle = 0x00100001118; +constexpr uint64_t kLogicalTvTerrestrialAnalog = 0x00100001119; +constexpr uint64_t kLogicalTvTerrestrialDigital = 0x0010000111a; +constexpr uint64_t kLogicalTvTimer = 0x0010000111b; +constexpr uint64_t kLogicalKey11 = 0x00100001201; +constexpr uint64_t kLogicalKey12 = 0x00100001202; +constexpr uint64_t kLogicalSuspend = 0x00200000000; +constexpr uint64_t kLogicalResume = 0x00200000001; +constexpr uint64_t kLogicalSleep = 0x00200000002; +constexpr uint64_t kLogicalAbort = 0x00200000003; +constexpr uint64_t kLogicalLang1 = 0x00200000010; +constexpr uint64_t kLogicalLang2 = 0x00200000011; +constexpr uint64_t kLogicalLang3 = 0x00200000012; +constexpr uint64_t kLogicalLang4 = 0x00200000013; +constexpr uint64_t kLogicalLang5 = 0x00200000014; +constexpr uint64_t kLogicalIntlBackslash = 0x00200000020; +constexpr uint64_t kLogicalIntlRo = 0x00200000021; +constexpr uint64_t kLogicalIntlYen = 0x00200000022; +constexpr uint64_t kLogicalControlLeft = 0x00200000100; +constexpr uint64_t kLogicalControlRight = 0x00200000101; +constexpr uint64_t kLogicalShiftLeft = 0x00200000102; +constexpr uint64_t kLogicalShiftRight = 0x00200000103; +constexpr uint64_t kLogicalAltLeft = 0x00200000104; +constexpr uint64_t kLogicalAltRight = 0x00200000105; +constexpr uint64_t kLogicalMetaLeft = 0x00200000106; +constexpr uint64_t kLogicalMetaRight = 0x00200000107; +constexpr uint64_t kLogicalControl = 0x002000001f0; +constexpr uint64_t kLogicalShift = 0x002000001f2; +constexpr uint64_t kLogicalAlt = 0x002000001f4; +constexpr uint64_t kLogicalMeta = 0x002000001f6; +constexpr uint64_t kLogicalNumpadEnter = 0x0020000020d; +constexpr uint64_t kLogicalNumpadParenLeft = 0x00200000228; +constexpr uint64_t kLogicalNumpadParenRight = 0x00200000229; +constexpr uint64_t kLogicalNumpadMultiply = 0x0020000022a; +constexpr uint64_t kLogicalNumpadAdd = 0x0020000022b; +constexpr uint64_t kLogicalNumpadComma = 0x0020000022c; +constexpr uint64_t kLogicalNumpadSubtract = 0x0020000022d; +constexpr uint64_t kLogicalNumpadDecimal = 0x0020000022e; +constexpr uint64_t kLogicalNumpadDivide = 0x0020000022f; +constexpr uint64_t kLogicalNumpad0 = 0x00200000230; +constexpr uint64_t kLogicalNumpad1 = 0x00200000231; +constexpr uint64_t kLogicalNumpad2 = 0x00200000232; +constexpr uint64_t kLogicalNumpad3 = 0x00200000233; +constexpr uint64_t kLogicalNumpad4 = 0x00200000234; +constexpr uint64_t kLogicalNumpad5 = 0x00200000235; +constexpr uint64_t kLogicalNumpad6 = 0x00200000236; +constexpr uint64_t kLogicalNumpad7 = 0x00200000237; +constexpr uint64_t kLogicalNumpad8 = 0x00200000238; +constexpr uint64_t kLogicalNumpad9 = 0x00200000239; +constexpr uint64_t kLogicalNumpadEqual = 0x0020000023d; +constexpr uint64_t kLogicalGameButton1 = 0x00200000301; +constexpr uint64_t kLogicalGameButton2 = 0x00200000302; +constexpr uint64_t kLogicalGameButton3 = 0x00200000303; +constexpr uint64_t kLogicalGameButton4 = 0x00200000304; +constexpr uint64_t kLogicalGameButton5 = 0x00200000305; +constexpr uint64_t kLogicalGameButton6 = 0x00200000306; +constexpr uint64_t kLogicalGameButton7 = 0x00200000307; +constexpr uint64_t kLogicalGameButton8 = 0x00200000308; +constexpr uint64_t kLogicalGameButton9 = 0x00200000309; +constexpr uint64_t kLogicalGameButton10 = 0x0020000030a; +constexpr uint64_t kLogicalGameButton11 = 0x0020000030b; +constexpr uint64_t kLogicalGameButton12 = 0x0020000030c; +constexpr uint64_t kLogicalGameButton13 = 0x0020000030d; +constexpr uint64_t kLogicalGameButton14 = 0x0020000030e; +constexpr uint64_t kLogicalGameButton15 = 0x0020000030f; +constexpr uint64_t kLogicalGameButton16 = 0x00200000310; +constexpr uint64_t kLogicalGameButtonA = 0x00200000311; +constexpr uint64_t kLogicalGameButtonB = 0x00200000312; +constexpr uint64_t kLogicalGameButtonC = 0x00200000313; +constexpr uint64_t kLogicalGameButtonLeft1 = 0x00200000314; +constexpr uint64_t kLogicalGameButtonLeft2 = 0x00200000315; +constexpr uint64_t kLogicalGameButtonMode = 0x00200000316; +constexpr uint64_t kLogicalGameButtonRight1 = 0x00200000317; +constexpr uint64_t kLogicalGameButtonRight2 = 0x00200000318; +constexpr uint64_t kLogicalGameButtonSelect = 0x00200000319; +constexpr uint64_t kLogicalGameButtonStart = 0x0020000031a; +constexpr uint64_t kLogicalGameButtonThumbLeft = 0x0020000031b; +constexpr uint64_t kLogicalGameButtonThumbRight = 0x0020000031c; +constexpr uint64_t kLogicalGameButtonX = 0x0020000031d; +constexpr uint64_t kLogicalGameButtonY = 0x0020000031e; +constexpr uint64_t kLogicalGameButtonZ = 0x0020000031f; + +} // namespace keycodes + +} // namespace testing + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TEST_UTILS_KEY_CODES_G_H_ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/test_utils/proc_table_replacement.h b/flutter/engine/src/flutter/shell/platform/embedder/test_utils/proc_table_replacement.h new file mode 100644 index 0000000000000000000000000000000000000000..b05b1bb963e52dad8a21aa26b7d0b282eeaea720 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/test_utils/proc_table_replacement.h @@ -0,0 +1,29 @@ +// 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_SHELL_PLATFORM_EMBEDDER_TEST_UTILS_PROC_TABLE_REPLACEMENT_H_ +#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TEST_UTILS_PROC_TABLE_REPLACEMENT_H_ + +#include "flutter/shell/platform/embedder/embedder.h" + +// Wraps capturing lambas with non-capturing version that can be assigned to +// FlutterEngineProcTable entries (by using statics) to facilitate mocking in +// tests of code built on top of the embedder API. +// +// This should *ONLY* be used in unit tests as it is leaky by design. +// +// |proc| should be the name of an entry in FlutterEngineProcTable, such as +// "Initialize". |mock_impl| should be a lamba that replaces its implementation, +// taking the same arguments and returning the same type. +#define MOCK_ENGINE_PROC(proc, mock_impl) \ + ([&]() { \ + static std::function< \ + std::remove_pointer_t> \ + closure; \ + closure = mock_impl; \ + static auto non_capturing = [](auto... args) { return closure(args...); }; \ + return non_capturing; \ + })() + +#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TEST_UTILS_PROC_TABLE_REPLACEMENT_H_ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_a11y_unittests.cc b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_a11y_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..091e3dc49a99e75338574a66bf2b36af3ba0d879 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_a11y_unittests.cc @@ -0,0 +1,958 @@ +// 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. + +// Allow access to fml::MessageLoop::GetCurrent() in order to flush platform +// thread tasks. +#define FML_USED_ON_EMBEDDER + +#include + +#include "flutter/fml/macros.h" +#include "flutter/fml/message_loop.h" +#include "flutter/fml/synchronization/waitable_event.h" +#include "flutter/lib/ui/semantics/semantics_node.h" +#include "flutter/shell/platform/embedder/embedder.h" +#include "flutter/shell/platform/embedder/tests/embedder_config_builder.h" +#include "flutter/testing/testing.h" +#include "third_party/tonic/converter/dart_converter.h" + +#include "gmock/gmock.h" // For EXPECT_THAT and matchers +#include "gtest/gtest.h" + +// CREATE_NATIVE_ENTRY is leaky by design +// NOLINTBEGIN(clang-analyzer-core.StackAddressEscape) + +namespace flutter { +namespace testing { + +using EmbedderA11yTest = testing::EmbedderTest; +using ::testing::ElementsAre; + +#if !defined(OS_FUCHSIA) || (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG) +constexpr static char kTooltip[] = "tooltip"; +#endif + +TEST_F(EmbedderTest, CannotProvideMultipleSemanticsCallbacks) { +#if defined(OS_FUCHSIA) && (FLUTTER_RUNTIME_MODE != FLUTTER_RUNTIME_MODE_DEBUG) + GTEST_SKIP() << "Dart_LoadELF is not implemented on Fuchsia."; +#else + { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.GetProjectArgs().update_semantics_callback = + [](const FlutterSemanticsUpdate* update, void* user_data) {}; + builder.GetProjectArgs().update_semantics_callback2 = + [](const FlutterSemanticsUpdate2* update, void* user_data) {}; + auto engine = builder.InitializeEngine(); + ASSERT_FALSE(engine.is_valid()); + engine.reset(); + } + + { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.GetProjectArgs().update_semantics_callback2 = + [](const FlutterSemanticsUpdate2* update, void* user_data) {}; + builder.GetProjectArgs().update_semantics_node_callback = + [](const FlutterSemanticsNode* update, void* user_data) {}; + builder.GetProjectArgs().update_semantics_custom_action_callback = + [](const FlutterSemanticsCustomAction* update, void* user_data) {}; + auto engine = builder.InitializeEngine(); + ASSERT_FALSE(engine.is_valid()); + engine.reset(); + } + + { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.GetProjectArgs().update_semantics_callback = + [](const FlutterSemanticsUpdate* update, void* user_data) {}; + builder.GetProjectArgs().update_semantics_node_callback = + [](const FlutterSemanticsNode* update, void* user_data) {}; + builder.GetProjectArgs().update_semantics_custom_action_callback = + [](const FlutterSemanticsCustomAction* update, void* user_data) {}; + auto engine = builder.InitializeEngine(); + ASSERT_FALSE(engine.is_valid()); + engine.reset(); + } + + { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.GetProjectArgs().update_semantics_callback2 = + [](const FlutterSemanticsUpdate2* update, void* user_data) {}; + builder.GetProjectArgs().update_semantics_callback = + [](const FlutterSemanticsUpdate* update, void* user_data) {}; + builder.GetProjectArgs().update_semantics_node_callback = + [](const FlutterSemanticsNode* update, void* user_data) {}; + builder.GetProjectArgs().update_semantics_custom_action_callback = + [](const FlutterSemanticsCustomAction* update, void* user_data) {}; + auto engine = builder.InitializeEngine(); + ASSERT_FALSE(engine.is_valid()); + engine.reset(); + } +#endif +} + +TEST_F(EmbedderA11yTest, A11yTreeIsConsistentUsingV3Callbacks) { +#if defined(OS_FUCHSIA) && (FLUTTER_RUNTIME_MODE != FLUTTER_RUNTIME_MODE_DEBUG) + GTEST_SKIP() << "Dart_LoadELF is not implemented on Fuchsia."; +#else + auto& context = GetEmbedderContext(); + + fml::AutoResetWaitableEvent signal_native_latch; + + // Called by the Dart text fixture on the UI thread to signal that the C++ + // unittest should resume. + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY(([&signal_native_latch](Dart_NativeArguments) { + signal_native_latch.Signal(); + }))); + + // Called by test fixture on UI thread to pass data back to this test. + NativeEntry notify_semantics_enabled_callback; + context.AddNativeCallback( + "NotifySemanticsEnabled", + CREATE_NATIVE_ENTRY( + ([¬ify_semantics_enabled_callback](Dart_NativeArguments args) { + ASSERT_NE(notify_semantics_enabled_callback, nullptr); + notify_semantics_enabled_callback(args); + }))); + + NativeEntry notify_accessibility_features_callback; + context.AddNativeCallback( + "NotifyAccessibilityFeatures", + CREATE_NATIVE_ENTRY(( + [¬ify_accessibility_features_callback](Dart_NativeArguments args) { + ASSERT_NE(notify_accessibility_features_callback, nullptr); + notify_accessibility_features_callback(args); + }))); + + NativeEntry notify_semantics_action_callback; + context.AddNativeCallback( + "NotifySemanticsAction", + CREATE_NATIVE_ENTRY( + ([¬ify_semantics_action_callback](Dart_NativeArguments args) { + ASSERT_NE(notify_semantics_action_callback, nullptr); + notify_semantics_action_callback(args); + }))); + + fml::AutoResetWaitableEvent semantics_update_latch; + context.SetSemanticsUpdateCallback2( + [&](const FlutterSemanticsUpdate2* update) { + ASSERT_EQ(size_t(4), update->node_count); + ASSERT_EQ(size_t(1), update->custom_action_count); + + for (size_t i = 0; i < update->node_count; i++) { + const FlutterSemanticsNode2* node = update->nodes[i]; + + ASSERT_EQ(1.0, node->transform.scaleX); + ASSERT_EQ(2.0, node->transform.skewX); + ASSERT_EQ(3.0, node->transform.transX); + ASSERT_EQ(4.0, node->transform.skewY); + ASSERT_EQ(5.0, node->transform.scaleY); + ASSERT_EQ(6.0, node->transform.transY); + ASSERT_EQ(7.0, node->transform.pers0); + ASSERT_EQ(8.0, node->transform.pers1); + ASSERT_EQ(9.0, node->transform.pers2); + ASSERT_EQ(std::strncmp(kTooltip, node->tooltip, sizeof(kTooltip) - 1), + 0); + + if (node->id == 128) { + ASSERT_EQ(0x3f3, node->platform_view_id); + } else { + ASSERT_NE(kFlutterSemanticsNodeIdBatchEnd, node->id); + ASSERT_EQ(0, node->platform_view_id); + } + } + + semantics_update_latch.Signal(); + }); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("a11y_main"); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // 1: Wait for initial notifySemanticsEnabled(false). + fml::AutoResetWaitableEvent notify_semantics_enabled_latch; + notify_semantics_enabled_callback = [&](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + bool enabled = + ::tonic::DartConverter::FromArguments(args, 0, exception); + ASSERT_FALSE(enabled); + notify_semantics_enabled_latch.Signal(); + }; + notify_semantics_enabled_latch.Wait(); + + // Prepare notifyAccessibilityFeatures callback. + fml::AutoResetWaitableEvent notify_features_latch; + notify_accessibility_features_callback = [&](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + bool enabled = + ::tonic::DartConverter::FromArguments(args, 0, exception); + ASSERT_FALSE(enabled); + notify_features_latch.Signal(); + }; + + // 2: Enable semantics. Wait for notifySemanticsEnabled(true). + fml::AutoResetWaitableEvent notify_semantics_enabled_latch_2; + notify_semantics_enabled_callback = [&](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + bool enabled = + ::tonic::DartConverter::FromArguments(args, 0, exception); + ASSERT_TRUE(enabled); + notify_semantics_enabled_latch_2.Signal(); + }; + auto result = FlutterEngineUpdateSemanticsEnabled(engine.get(), true); + ASSERT_EQ(result, FlutterEngineResult::kSuccess); + notify_semantics_enabled_latch_2.Wait(); + + // 3: Wait for notifyAccessibilityFeatures (reduce_motion == false) + notify_features_latch.Wait(); + + // 4: Wait for notifyAccessibilityFeatures (reduce_motion == true) + fml::AutoResetWaitableEvent notify_features_latch_2; + notify_accessibility_features_callback = [&](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + bool enabled = + ::tonic::DartConverter::FromArguments(args, 0, exception); + ASSERT_TRUE(enabled); + notify_features_latch_2.Signal(); + }; + result = FlutterEngineUpdateAccessibilityFeatures( + engine.get(), kFlutterAccessibilityFeatureReduceMotion); + ASSERT_EQ(result, FlutterEngineResult::kSuccess); + notify_features_latch_2.Wait(); + + // 5: Wait for UpdateSemantics callback on platform (current) thread. + signal_native_latch.Wait(); + fml::MessageLoop::GetCurrent().RunExpiredTasksNow(); + semantics_update_latch.Wait(); + + // 6: Dispatch a tap to semantics node 42. Wait for NotifySemanticsAction. + fml::AutoResetWaitableEvent notify_semantics_action_latch; + notify_semantics_action_callback = [&](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + int64_t node_id = + ::tonic::DartConverter::FromArguments(args, 0, exception); + ASSERT_EQ(42, node_id); + + int64_t action_id = + ::tonic::DartConverter::FromArguments(args, 1, exception); + ASSERT_EQ(static_cast(flutter::SemanticsAction::kTap), action_id); + + std::vector semantic_args = + ::tonic::DartConverter>::FromArguments(args, 2, + exception); + ASSERT_THAT(semantic_args, ElementsAre(2, 1)); + notify_semantics_action_latch.Signal(); + }; + std::vector bytes({2, 1}); + result = FlutterEngineDispatchSemanticsAction( + engine.get(), 42, kFlutterSemanticsActionTap, &bytes[0], bytes.size()); + ASSERT_EQ(result, FlutterEngineResult::kSuccess); + notify_semantics_action_latch.Wait(); + + // 7: Disable semantics. Wait for NotifySemanticsEnabled(false). + fml::AutoResetWaitableEvent notify_semantics_enabled_latch_3; + notify_semantics_enabled_callback = [&](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + bool enabled = + ::tonic::DartConverter::FromArguments(args, 0, exception); + ASSERT_FALSE(enabled); + notify_semantics_enabled_latch_3.Signal(); + }; + result = FlutterEngineUpdateSemanticsEnabled(engine.get(), false); + ASSERT_EQ(result, FlutterEngineResult::kSuccess); + notify_semantics_enabled_latch_3.Wait(); +#endif +} + +TEST_F(EmbedderA11yTest, A11yStringAttributes) { +#if defined(OS_FUCHSIA) && (FLUTTER_RUNTIME_MODE != FLUTTER_RUNTIME_MODE_DEBUG) + GTEST_SKIP() << "Dart_LoadELF is not implemented on Fuchsia."; +#else + auto& context = GetEmbedderContext(); + + fml::AutoResetWaitableEvent signal_native_latch; + + // Called by the Dart text fixture on the UI thread to signal that the C++ + // unittest should resume. + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY(([&signal_native_latch](Dart_NativeArguments) { + signal_native_latch.Signal(); + }))); + + fml::AutoResetWaitableEvent semantics_update_latch; + context.SetSemanticsUpdateCallback2( + [&](const FlutterSemanticsUpdate2* update) { + ASSERT_EQ(update->node_count, size_t(1)); + ASSERT_EQ(update->custom_action_count, size_t(0)); + + auto node = update->nodes[0]; + + // Verify label + { + ASSERT_EQ(std::string(node->label), "What is the meaning of life?"); + ASSERT_EQ(node->label_attribute_count, size_t(2)); + + ASSERT_EQ(node->label_attributes[0]->start, size_t(0)); + ASSERT_EQ(node->label_attributes[0]->end, size_t(28)); + ASSERT_EQ(node->label_attributes[0]->type, + FlutterStringAttributeType::kLocale); + ASSERT_EQ(std::string(node->label_attributes[0]->locale->locale), + "en"); + + ASSERT_EQ(node->label_attributes[1]->start, size_t(0)); + ASSERT_EQ(node->label_attributes[1]->end, size_t(1)); + ASSERT_EQ(node->label_attributes[1]->type, + FlutterStringAttributeType::kSpellOut); + } + + // Verify hint + { + ASSERT_EQ(std::string(node->hint), "It's a number"); + ASSERT_EQ(node->hint_attribute_count, size_t(2)); + + ASSERT_EQ(node->hint_attributes[0]->start, size_t(0)); + ASSERT_EQ(node->hint_attributes[0]->end, size_t(1)); + ASSERT_EQ(node->hint_attributes[0]->type, + FlutterStringAttributeType::kLocale); + ASSERT_EQ(std::string(node->hint_attributes[0]->locale->locale), + "en"); + + ASSERT_EQ(node->hint_attributes[1]->start, size_t(2)); + ASSERT_EQ(node->hint_attributes[1]->end, size_t(3)); + ASSERT_EQ(node->hint_attributes[1]->type, + FlutterStringAttributeType::kLocale); + ASSERT_EQ(std::string(node->hint_attributes[1]->locale->locale), + "fr"); + } + + // Verify value + { + ASSERT_EQ(std::string(node->value), "42"); + ASSERT_EQ(node->value_attribute_count, size_t(1)); + + ASSERT_EQ(node->value_attributes[0]->start, size_t(0)); + ASSERT_EQ(node->value_attributes[0]->end, size_t(2)); + ASSERT_EQ(node->value_attributes[0]->type, + FlutterStringAttributeType::kLocale); + ASSERT_EQ(std::string(node->value_attributes[0]->locale->locale), + "en-US"); + } + + // Verify increased value + { + ASSERT_EQ(std::string(node->increased_value), "43"); + ASSERT_EQ(node->increased_value_attribute_count, size_t(2)); + + ASSERT_EQ(node->increased_value_attributes[0]->start, size_t(0)); + ASSERT_EQ(node->increased_value_attributes[0]->end, size_t(1)); + ASSERT_EQ(node->increased_value_attributes[0]->type, + FlutterStringAttributeType::kSpellOut); + + ASSERT_EQ(node->increased_value_attributes[1]->start, size_t(1)); + ASSERT_EQ(node->increased_value_attributes[1]->end, size_t(2)); + ASSERT_EQ(node->increased_value_attributes[1]->type, + FlutterStringAttributeType::kSpellOut); + } + + // Verify decreased value + { + ASSERT_EQ(std::string(node->decreased_value), "41"); + ASSERT_EQ(node->decreased_value_attribute_count, size_t(0)); + ASSERT_EQ(node->decreased_value_attributes, nullptr); + } + + semantics_update_latch.Signal(); + }); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("a11y_string_attributes"); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // 1: Enable semantics. + auto result = FlutterEngineUpdateSemanticsEnabled(engine.get(), true); + ASSERT_EQ(result, FlutterEngineResult::kSuccess); + + // 2: Wait for semantics update callback on platform (current) thread. + signal_native_latch.Wait(); + fml::MessageLoop::GetCurrent().RunExpiredTasksNow(); + semantics_update_latch.Wait(); +#endif +} + +TEST_F(EmbedderA11yTest, A11yTreeIsConsistentUsingV2Callbacks) { +#if defined(OS_FUCHSIA) && (FLUTTER_RUNTIME_MODE != FLUTTER_RUNTIME_MODE_DEBUG) + GTEST_SKIP() << "Dart_LoadELF is not implemented on Fuchsia."; +#else + auto& context = GetEmbedderContext(); + + fml::AutoResetWaitableEvent signal_native_latch; + + // Called by the Dart text fixture on the UI thread to signal that the C++ + // unittest should resume. + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY(([&signal_native_latch](Dart_NativeArguments) { + signal_native_latch.Signal(); + }))); + + // Called by test fixture on UI thread to pass data back to this test. + NativeEntry notify_semantics_enabled_callback; + context.AddNativeCallback( + "NotifySemanticsEnabled", + CREATE_NATIVE_ENTRY( + ([¬ify_semantics_enabled_callback](Dart_NativeArguments args) { + ASSERT_NE(notify_semantics_enabled_callback, nullptr); + notify_semantics_enabled_callback(args); + }))); + + NativeEntry notify_accessibility_features_callback; + context.AddNativeCallback( + "NotifyAccessibilityFeatures", + CREATE_NATIVE_ENTRY(( + [¬ify_accessibility_features_callback](Dart_NativeArguments args) { + ASSERT_NE(notify_accessibility_features_callback, nullptr); + notify_accessibility_features_callback(args); + }))); + + NativeEntry notify_semantics_action_callback; + context.AddNativeCallback( + "NotifySemanticsAction", + CREATE_NATIVE_ENTRY( + ([¬ify_semantics_action_callback](Dart_NativeArguments args) { + ASSERT_NE(notify_semantics_action_callback, nullptr); + notify_semantics_action_callback(args); + }))); + + fml::AutoResetWaitableEvent semantics_update_latch; + context.SetSemanticsUpdateCallback([&](const FlutterSemanticsUpdate* update) { + ASSERT_EQ(size_t(4), update->nodes_count); + ASSERT_EQ(size_t(1), update->custom_actions_count); + + for (size_t i = 0; i < update->nodes_count; i++) { + const FlutterSemanticsNode* node = update->nodes + i; + + ASSERT_EQ(1.0, node->transform.scaleX); + ASSERT_EQ(2.0, node->transform.skewX); + ASSERT_EQ(3.0, node->transform.transX); + ASSERT_EQ(4.0, node->transform.skewY); + ASSERT_EQ(5.0, node->transform.scaleY); + ASSERT_EQ(6.0, node->transform.transY); + ASSERT_EQ(7.0, node->transform.pers0); + ASSERT_EQ(8.0, node->transform.pers1); + ASSERT_EQ(9.0, node->transform.pers2); + ASSERT_EQ(std::strncmp(kTooltip, node->tooltip, sizeof(kTooltip) - 1), 0); + + if (node->id == 128) { + ASSERT_EQ(0x3f3, node->platform_view_id); + } else { + ASSERT_NE(kFlutterSemanticsNodeIdBatchEnd, node->id); + ASSERT_EQ(0, node->platform_view_id); + } + } + + semantics_update_latch.Signal(); + }); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("a11y_main"); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // 1: Wait for initial notifySemanticsEnabled(false). + fml::AutoResetWaitableEvent notify_semantics_enabled_latch; + notify_semantics_enabled_callback = [&](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + bool enabled = + ::tonic::DartConverter::FromArguments(args, 0, exception); + ASSERT_FALSE(enabled); + notify_semantics_enabled_latch.Signal(); + }; + notify_semantics_enabled_latch.Wait(); + + // Prepare notifyAccessibilityFeatures callback. + fml::AutoResetWaitableEvent notify_features_latch; + notify_accessibility_features_callback = [&](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + bool enabled = + ::tonic::DartConverter::FromArguments(args, 0, exception); + ASSERT_FALSE(enabled); + notify_features_latch.Signal(); + }; + + // 2: Enable semantics. Wait for notifySemanticsEnabled(true). + fml::AutoResetWaitableEvent notify_semantics_enabled_latch_2; + notify_semantics_enabled_callback = [&](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + bool enabled = + ::tonic::DartConverter::FromArguments(args, 0, exception); + ASSERT_TRUE(enabled); + notify_semantics_enabled_latch_2.Signal(); + }; + auto result = FlutterEngineUpdateSemanticsEnabled(engine.get(), true); + ASSERT_EQ(result, FlutterEngineResult::kSuccess); + notify_semantics_enabled_latch_2.Wait(); + + // 3: Wait for notifyAccessibilityFeatures (reduce_motion == false) + notify_features_latch.Wait(); + + // 4: Wait for notifyAccessibilityFeatures (reduce_motion == true) + fml::AutoResetWaitableEvent notify_features_latch_2; + notify_accessibility_features_callback = [&](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + bool enabled = + ::tonic::DartConverter::FromArguments(args, 0, exception); + ASSERT_TRUE(enabled); + notify_features_latch_2.Signal(); + }; + result = FlutterEngineUpdateAccessibilityFeatures( + engine.get(), kFlutterAccessibilityFeatureReduceMotion); + ASSERT_EQ(result, FlutterEngineResult::kSuccess); + notify_features_latch_2.Wait(); + + // 5: Wait for UpdateSemantics callback on platform (current) thread. + signal_native_latch.Wait(); + fml::MessageLoop::GetCurrent().RunExpiredTasksNow(); + semantics_update_latch.Wait(); + + // 6: Dispatch a tap to semantics node 42. Wait for NotifySemanticsAction. + fml::AutoResetWaitableEvent notify_semantics_action_latch; + notify_semantics_action_callback = [&](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + int64_t node_id = + ::tonic::DartConverter::FromArguments(args, 0, exception); + ASSERT_EQ(42, node_id); + + int64_t action_id = + ::tonic::DartConverter::FromArguments(args, 1, exception); + ASSERT_EQ(static_cast(flutter::SemanticsAction::kTap), action_id); + + std::vector semantic_args = + ::tonic::DartConverter>::FromArguments(args, 2, + exception); + ASSERT_THAT(semantic_args, ElementsAre(2, 1)); + notify_semantics_action_latch.Signal(); + }; + std::vector bytes({2, 1}); + result = FlutterEngineDispatchSemanticsAction( + engine.get(), 42, kFlutterSemanticsActionTap, &bytes[0], bytes.size()); + ASSERT_EQ(result, FlutterEngineResult::kSuccess); + notify_semantics_action_latch.Wait(); + + // 7: Disable semantics. Wait for NotifySemanticsEnabled(false). + fml::AutoResetWaitableEvent notify_semantics_enabled_latch_3; + notify_semantics_enabled_callback = [&](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + bool enabled = + ::tonic::DartConverter::FromArguments(args, 0, exception); + ASSERT_FALSE(enabled); + notify_semantics_enabled_latch_3.Signal(); + }; + result = FlutterEngineUpdateSemanticsEnabled(engine.get(), false); + ASSERT_EQ(result, FlutterEngineResult::kSuccess); + notify_semantics_enabled_latch_3.Wait(); +#endif +} + +TEST_F(EmbedderA11yTest, A11yTreeIsConsistentUsingV1Callbacks) { +#if defined(OS_FUCHSIA) && (FLUTTER_RUNTIME_MODE != FLUTTER_RUNTIME_MODE_DEBUG) + GTEST_SKIP() << "Dart_LoadELF is not implemented on Fuchsia."; +#else + auto& context = GetEmbedderContext(); + + fml::AutoResetWaitableEvent signal_native_latch; + + // Called by the Dart text fixture on the UI thread to signal that the C++ + // unittest should resume. + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY(([&signal_native_latch](Dart_NativeArguments) { + signal_native_latch.Signal(); + }))); + + // Called by test fixture on UI thread to pass data back to this test. + NativeEntry notify_semantics_enabled_callback; + context.AddNativeCallback( + "NotifySemanticsEnabled", + CREATE_NATIVE_ENTRY( + ([¬ify_semantics_enabled_callback](Dart_NativeArguments args) { + ASSERT_NE(notify_semantics_enabled_callback, nullptr); + notify_semantics_enabled_callback(args); + }))); + + NativeEntry notify_accessibility_features_callback; + context.AddNativeCallback( + "NotifyAccessibilityFeatures", + CREATE_NATIVE_ENTRY(( + [¬ify_accessibility_features_callback](Dart_NativeArguments args) { + ASSERT_NE(notify_accessibility_features_callback, nullptr); + notify_accessibility_features_callback(args); + }))); + + NativeEntry notify_semantics_action_callback; + context.AddNativeCallback( + "NotifySemanticsAction", + CREATE_NATIVE_ENTRY( + ([¬ify_semantics_action_callback](Dart_NativeArguments args) { + ASSERT_NE(notify_semantics_action_callback, nullptr); + notify_semantics_action_callback(args); + }))); + + fml::AutoResetWaitableEvent semantics_node_latch; + fml::AutoResetWaitableEvent semantics_action_latch; + + int node_batch_end_count = 0; + int action_batch_end_count = 0; + + int node_count = 0; + context.SetSemanticsNodeCallback([&](const FlutterSemanticsNode* node) { + if (node->id == kFlutterSemanticsNodeIdBatchEnd) { + ++node_batch_end_count; + semantics_node_latch.Signal(); + } else { + // Batches should be completed after all nodes are received. + ASSERT_EQ(0, node_batch_end_count); + ASSERT_EQ(0, action_batch_end_count); + + ++node_count; + ASSERT_EQ(1.0, node->transform.scaleX); + ASSERT_EQ(2.0, node->transform.skewX); + ASSERT_EQ(3.0, node->transform.transX); + ASSERT_EQ(4.0, node->transform.skewY); + ASSERT_EQ(5.0, node->transform.scaleY); + ASSERT_EQ(6.0, node->transform.transY); + ASSERT_EQ(7.0, node->transform.pers0); + ASSERT_EQ(8.0, node->transform.pers1); + ASSERT_EQ(9.0, node->transform.pers2); + ASSERT_EQ(std::strncmp(kTooltip, node->tooltip, sizeof(kTooltip) - 1), 0); + + if (node->id == 128) { + ASSERT_EQ(0x3f3, node->platform_view_id); + } else { + ASSERT_EQ(0, node->platform_view_id); + } + } + }); + + int action_count = 0; + context.SetSemanticsCustomActionCallback( + [&](const FlutterSemanticsCustomAction* action) { + if (action->id == kFlutterSemanticsCustomActionIdBatchEnd) { + ++action_batch_end_count; + semantics_action_latch.Signal(); + } else { + // Batches should be completed after all actions are received. + ASSERT_EQ(0, node_batch_end_count); + ASSERT_EQ(0, action_batch_end_count); + + ++action_count; + } + }); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("a11y_main"); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // 1: Wait for initial notifySemanticsEnabled(false). + fml::AutoResetWaitableEvent notify_semantics_enabled_latch; + notify_semantics_enabled_callback = [&](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + bool enabled = + ::tonic::DartConverter::FromArguments(args, 0, exception); + ASSERT_FALSE(enabled); + notify_semantics_enabled_latch.Signal(); + }; + notify_semantics_enabled_latch.Wait(); + + // Prepare notifyAccessibilityFeatures callback. + fml::AutoResetWaitableEvent notify_features_latch; + notify_accessibility_features_callback = [&](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + bool enabled = + ::tonic::DartConverter::FromArguments(args, 0, exception); + ASSERT_FALSE(enabled); + notify_features_latch.Signal(); + }; + + // 2: Enable semantics. Wait for notifySemanticsEnabled(true). + fml::AutoResetWaitableEvent notify_semantics_enabled_latch_2; + notify_semantics_enabled_callback = [&](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + bool enabled = + ::tonic::DartConverter::FromArguments(args, 0, exception); + ASSERT_TRUE(enabled); + notify_semantics_enabled_latch_2.Signal(); + }; + auto result = FlutterEngineUpdateSemanticsEnabled(engine.get(), true); + ASSERT_EQ(result, FlutterEngineResult::kSuccess); + notify_semantics_enabled_latch_2.Wait(); + + // 3: Wait for notifyAccessibilityFeatures (reduce_motion == false) + notify_features_latch.Wait(); + + // 4: Wait for notifyAccessibilityFeatures (reduce_motion == true) + fml::AutoResetWaitableEvent notify_features_latch_2; + notify_accessibility_features_callback = [&](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + bool enabled = + ::tonic::DartConverter::FromArguments(args, 0, exception); + ASSERT_TRUE(enabled); + notify_features_latch_2.Signal(); + }; + result = FlutterEngineUpdateAccessibilityFeatures( + engine.get(), kFlutterAccessibilityFeatureReduceMotion); + ASSERT_EQ(result, FlutterEngineResult::kSuccess); + notify_features_latch_2.Wait(); + + // 5: Wait for UpdateSemantics callback on platform (current) thread. + signal_native_latch.Wait(); + fml::MessageLoop::GetCurrent().RunExpiredTasksNow(); + semantics_node_latch.Wait(); + semantics_action_latch.Wait(); + ASSERT_EQ(4, node_count); + ASSERT_EQ(1, node_batch_end_count); + ASSERT_EQ(1, action_count); + ASSERT_EQ(1, action_batch_end_count); + + // 6: Dispatch a tap to semantics node 42. Wait for NotifySemanticsAction. + fml::AutoResetWaitableEvent notify_semantics_action_latch; + notify_semantics_action_callback = [&](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + int64_t node_id = + ::tonic::DartConverter::FromArguments(args, 0, exception); + ASSERT_EQ(42, node_id); + + int64_t action_id = + ::tonic::DartConverter::FromArguments(args, 1, exception); + ASSERT_EQ(static_cast(flutter::SemanticsAction::kTap), action_id); + + std::vector semantic_args = + ::tonic::DartConverter>::FromArguments(args, 2, + exception); + ASSERT_THAT(semantic_args, ElementsAre(2, 1)); + notify_semantics_action_latch.Signal(); + }; + std::vector bytes({2, 1}); + result = FlutterEngineDispatchSemanticsAction( + engine.get(), 42, kFlutterSemanticsActionTap, &bytes[0], bytes.size()); + ASSERT_EQ(result, FlutterEngineResult::kSuccess); + notify_semantics_action_latch.Wait(); + + // 7: Disable semantics. Wait for NotifySemanticsEnabled(false). + fml::AutoResetWaitableEvent notify_semantics_enabled_latch_3; + notify_semantics_enabled_callback = [&](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + bool enabled = + ::tonic::DartConverter::FromArguments(args, 0, exception); + ASSERT_FALSE(enabled); + notify_semantics_enabled_latch_3.Signal(); + }; + result = FlutterEngineUpdateSemanticsEnabled(engine.get(), false); + ASSERT_EQ(result, FlutterEngineResult::kSuccess); + notify_semantics_enabled_latch_3.Wait(); +#endif +} + +TEST_F(EmbedderA11yTest, A11yTreesAreConsistentWithMultipleViews) { +#if defined(OS_FUCHSIA) && (FLUTTER_RUNTIME_MODE != FLUTTER_RUNTIME_MODE_DEBUG) + GTEST_SKIP() << "Dart_LoadELF is not implemented on Fuchsia."; +#else + auto& context = GetEmbedderContext(); + + fml::AutoResetWaitableEvent signal_native_latch; + + // Called by the Dart text fixture on the UI thread to signal that the C++ + // unittest should resume. + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY(([&signal_native_latch](Dart_NativeArguments) { + signal_native_latch.Signal(); + }))); + + // Called by test fixture on UI thread to pass data back to this test. + NativeEntry notify_semantics_enabled_callback; + context.AddNativeCallback( + "NotifySemanticsEnabled", + CREATE_NATIVE_ENTRY( + ([¬ify_semantics_enabled_callback](Dart_NativeArguments args) { + ASSERT_NE(notify_semantics_enabled_callback, nullptr); + notify_semantics_enabled_callback(args); + }))); + + NativeEntry notify_accessibility_features_callback; + context.AddNativeCallback( + "NotifyAccessibilityFeatures", + CREATE_NATIVE_ENTRY(( + [¬ify_accessibility_features_callback](Dart_NativeArguments args) { + ASSERT_NE(notify_accessibility_features_callback, nullptr); + notify_accessibility_features_callback(args); + }))); + + int num_times_set_semantics_update_callback2_called = 0; + fml::AutoResetWaitableEvent semantics_update_latch; + context.SetSemanticsUpdateCallback2( + [&](const FlutterSemanticsUpdate2* update) { + num_times_set_semantics_update_callback2_called++; + ASSERT_EQ(size_t(1), update->node_count); + + for (size_t i = 0; i < update->node_count; i++) { + const FlutterSemanticsNode2* node = update->nodes[i]; + + // The node ID should be the view_id + 1 + ASSERT_EQ(node->id, update->view_id + 1); + ASSERT_EQ(1.0, node->transform.scaleX); + ASSERT_EQ(2.0, node->transform.skewX); + ASSERT_EQ(3.0, node->transform.transX); + ASSERT_EQ(4.0, node->transform.skewY); + ASSERT_EQ(5.0, node->transform.scaleY); + ASSERT_EQ(6.0, node->transform.transY); + ASSERT_EQ(7.0, node->transform.pers0); + ASSERT_EQ(8.0, node->transform.pers1); + ASSERT_EQ(9.0, node->transform.pers2); + ASSERT_EQ(std::strncmp(kTooltip, node->tooltip, sizeof(kTooltip) - 1), + 0); + } + + if (num_times_set_semantics_update_callback2_called == 3) { + semantics_update_latch.Signal(); + } + }); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("a11y_main_multi_view"); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // 1: Wait for initial notifySemanticsEnabled(false). + fml::AutoResetWaitableEvent notify_semantics_enabled_latch; + notify_semantics_enabled_callback = [&](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + bool enabled = + ::tonic::DartConverter::FromArguments(args, 0, exception); + ASSERT_FALSE(enabled); + notify_semantics_enabled_latch.Signal(); + }; + notify_semantics_enabled_latch.Wait(); + + const int64_t first_view_id = 1; + const int64_t second_view_id = 2; + + // 2. Add the first view and wait for the add view callback. + FlutterWindowMetricsEvent window_metrics_event; + window_metrics_event.struct_size = sizeof(FlutterWindowMetricsEvent); + window_metrics_event.width = 100; + window_metrics_event.height = 100; + window_metrics_event.pixel_ratio = 1.0; + window_metrics_event.left = 0; + window_metrics_event.top = 0; + window_metrics_event.physical_view_inset_top = 0.0; + window_metrics_event.physical_view_inset_right = 0.0; + window_metrics_event.physical_view_inset_bottom = 0.0; + window_metrics_event.physical_view_inset_left = 0.0; + window_metrics_event.display_id = 0; + window_metrics_event.view_id = first_view_id; + + FlutterAddViewInfo add_view_info; + add_view_info.struct_size = sizeof(FlutterAddViewInfo); + add_view_info.view_id = first_view_id; + add_view_info.view_metrics = &window_metrics_event; + fml::AutoResetWaitableEvent notify_add_view_latch; + add_view_info.user_data = ¬ify_add_view_latch; + add_view_info.add_view_callback = [](const FlutterAddViewResult* result) { + EXPECT_TRUE(result->added); + auto latch = + reinterpret_cast(result->user_data); + latch->Signal(); + }; + FlutterEngineAddView(engine.get(), &add_view_info); + notify_add_view_latch.Wait(); + + // 3. Add the second view and wait for the add view callback. + add_view_info.view_id = second_view_id; + window_metrics_event.view_id = second_view_id; + add_view_info.add_view_callback = [](const FlutterAddViewResult* result) { + EXPECT_TRUE(result->added); + auto latch = + reinterpret_cast(result->user_data); + latch->Signal(); + }; + FlutterEngineAddView(engine.get(), &add_view_info); + notify_add_view_latch.Wait(); + + // Prepare notifyAccessibilityFeatures callback. + fml::AutoResetWaitableEvent notify_features_latch; + notify_accessibility_features_callback = [&](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + bool enabled = + ::tonic::DartConverter::FromArguments(args, 0, exception); + ASSERT_FALSE(enabled); + notify_features_latch.Signal(); + }; + + // 4: Enable semantics. Wait for notifySemanticsEnabled(true). + fml::AutoResetWaitableEvent notify_semantics_enabled_latch_2; + notify_semantics_enabled_callback = [&](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + bool enabled = + ::tonic::DartConverter::FromArguments(args, 0, exception); + ASSERT_TRUE(enabled); + notify_semantics_enabled_latch_2.Signal(); + }; + auto result = FlutterEngineUpdateSemanticsEnabled(engine.get(), true); + ASSERT_EQ(result, FlutterEngineResult::kSuccess); + notify_semantics_enabled_latch_2.Wait(); + + // 5: Wait for notifyAccessibilityFeatures (reduce_motion == false) + notify_features_latch.Wait(); + + // 6: Wait for UpdateSemantics callback on platform (current) thread. + // for all pending updates. Expect that it is called 3 times (once for + // the implicit view and two more times for the views that were manually + // added). + signal_native_latch.Wait(); + fml::MessageLoop::GetCurrent().RunExpiredTasksNow(); + semantics_update_latch.Wait(); + EXPECT_EQ(num_times_set_semantics_update_callback2_called, 3); + + // 7: Disable semantics. Wait for NotifySemanticsEnabled(false). + fml::AutoResetWaitableEvent notify_semantics_enabled_latch_3; + notify_semantics_enabled_callback = [&](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + bool enabled = + ::tonic::DartConverter::FromArguments(args, 0, exception); + ASSERT_FALSE(enabled); + notify_semantics_enabled_latch_3.Signal(); + }; + result = FlutterEngineUpdateSemanticsEnabled(engine.get(), false); + ASSERT_EQ(result, FlutterEngineResult::kSuccess); + notify_semantics_enabled_latch_3.Wait(); +#endif +} + +} // namespace testing +} // namespace flutter + +// NOLINTEND(clang-analyzer-core.StackAddressEscape) diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_assertions.h b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_assertions.h new file mode 100644 index 0000000000000000000000000000000000000000..e8faadc867d5484820fd4ad0a0e4c05aa4939b43 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_assertions.h @@ -0,0 +1,606 @@ +// 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_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_ASSERTIONS_H_ +#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_ASSERTIONS_H_ + +#include + +#include "flutter/fml/logging.h" +#include "flutter/shell/platform/embedder/embedder.h" +#include "flutter/shell/platform/embedder/embedder_engine.h" +#include "flutter/testing/assertions.h" +#include "gtest/gtest.h" +#include "third_party/skia/include/core/SkPoint.h" +#include "third_party/skia/include/core/SkSize.h" + +// NOLINTBEGIN(google-objc-function-naming) + +//------------------------------------------------------------------------------ +// Equality +//------------------------------------------------------------------------------ +inline bool operator==(const FlutterPoint& a, const FlutterPoint& b) { + return flutter::testing::NumberNear(a.x, b.x) && + flutter::testing::NumberNear(a.y, b.y); +} + +inline bool operator==(const FlutterRect& a, const FlutterRect& b) { + return flutter::testing::NumberNear(a.left, b.left) && + flutter::testing::NumberNear(a.top, b.top) && + flutter::testing::NumberNear(a.right, b.right) && + flutter::testing::NumberNear(a.bottom, b.bottom); +} + +inline bool operator==(const FlutterSize& a, const FlutterSize& b) { + return flutter::testing::NumberNear(a.width, b.width) && + flutter::testing::NumberNear(a.height, b.height); +} + +inline bool operator==(const FlutterRoundedRect& a, + const FlutterRoundedRect& b) { + return a.rect == b.rect && + a.upper_left_corner_radius == b.upper_left_corner_radius && + a.upper_right_corner_radius == b.upper_right_corner_radius && + a.lower_right_corner_radius == b.lower_right_corner_radius && + a.lower_left_corner_radius == b.lower_left_corner_radius; +} + +inline bool operator==(const FlutterTransformation& a, + const FlutterTransformation& b) { + return a.scaleX == b.scaleX && a.skewX == b.skewX && a.transX == b.transX && + a.skewY == b.skewY && a.scaleY == b.scaleY && a.transY == b.transY && + a.pers0 == b.pers0 && a.pers1 == b.pers1 && a.pers2 == b.pers2; +} + +inline bool operator==(const FlutterOpenGLTexture& a, + const FlutterOpenGLTexture& b) { + return a.target == b.target && a.name == b.name && a.format == b.format && + a.user_data == b.user_data && + a.destruction_callback == b.destruction_callback; +} + +inline bool operator==(const FlutterOpenGLFramebuffer& a, + const FlutterOpenGLFramebuffer& b) { + return a.target == b.target && a.name == b.name && + a.user_data == b.user_data && + a.destruction_callback == b.destruction_callback; +} + +inline bool operator==(const FlutterOpenGLSurface& a, + const FlutterOpenGLSurface& b) { + return a.make_current_callback == b.make_current_callback && + a.user_data == b.user_data && a.format == b.format && + a.destruction_callback == b.destruction_callback; +} + +inline bool operator==(const FlutterMetalTexture& a, + const FlutterMetalTexture& b) { + return a.texture_id == b.texture_id && a.texture == b.texture; +} + +inline bool operator==(const FlutterVulkanImage& a, + const FlutterVulkanImage& b) { + return a.image == b.image && a.format == b.format; +} + +inline bool operator==(const FlutterVulkanBackingStore& a, + const FlutterVulkanBackingStore& b) { + return a.image == b.image; +} + +inline bool operator==(const FlutterMetalBackingStore& a, + const FlutterMetalBackingStore& b) { + return a.texture == b.texture; +} + +inline bool operator==(const FlutterOpenGLBackingStore& a, + const FlutterOpenGLBackingStore& b) { + if (!(a.type == b.type)) { + return false; + } + + switch (a.type) { + case kFlutterOpenGLTargetTypeTexture: + return a.texture == b.texture; + case kFlutterOpenGLTargetTypeFramebuffer: + return a.framebuffer == b.framebuffer; + case kFlutterOpenGLTargetTypeSurface: + return a.surface == b.surface; + } + + return false; +} + +inline bool operator==(const FlutterSoftwareBackingStore& a, + const FlutterSoftwareBackingStore& b) { + return a.allocation == b.allocation && a.row_bytes == b.row_bytes && + a.height == b.height && a.user_data == b.user_data && + a.destruction_callback == b.destruction_callback; +} + +inline bool operator==(const FlutterSoftwareBackingStore2& a, + const FlutterSoftwareBackingStore2& b) { + return a.allocation == b.allocation && a.row_bytes == b.row_bytes && + a.height == b.height && a.user_data == b.user_data && + a.destruction_callback == b.destruction_callback && + a.pixel_format == b.pixel_format; +} + +inline bool operator==(const FlutterRegion& a, const FlutterRegion& b) { + if (a.struct_size != b.struct_size || a.rects_count != b.rects_count) { + return false; + } + for (size_t i = 0; i < a.rects_count; i++) { + if (!(a.rects[i] == b.rects[i])) { + return false; + } + } + return true; +} + +inline bool operator==(const FlutterBackingStorePresentInfo& a, + const FlutterBackingStorePresentInfo& b) { + return a.struct_size == b.struct_size && *a.paint_region == *b.paint_region; +} + +inline bool operator==(const FlutterBackingStore& a, + const FlutterBackingStore& b) { + if (!(a.struct_size == b.struct_size && a.user_data == b.user_data && + a.type == b.type && a.did_update == b.did_update)) { + return false; + } + + switch (a.type) { + case kFlutterBackingStoreTypeOpenGL: + return a.open_gl == b.open_gl; + case kFlutterBackingStoreTypeSoftware: + return a.software == b.software; + case kFlutterBackingStoreTypeMetal: + return a.metal == b.metal; + case kFlutterBackingStoreTypeVulkan: + return a.vulkan == b.vulkan; + case kFlutterBackingStoreTypeSoftware2: + return a.software2 == b.software2; + } + + return false; +} + +inline bool operator==(const FlutterPlatformViewMutation& a, + const FlutterPlatformViewMutation& b) { + if (a.type != b.type) { + return false; + } + + switch (a.type) { + case kFlutterPlatformViewMutationTypeOpacity: + return flutter::testing::NumberNear(a.opacity, b.opacity); + case kFlutterPlatformViewMutationTypeClipRect: + return a.clip_rect == b.clip_rect; + case kFlutterPlatformViewMutationTypeClipRoundedRect: + return a.clip_rounded_rect == b.clip_rounded_rect; + case kFlutterPlatformViewMutationTypeTransformation: + return a.transformation == b.transformation; + } + + return false; +} + +inline bool operator==(const FlutterPlatformView& a, + const FlutterPlatformView& b) { + if (!(a.struct_size == b.struct_size && a.identifier == b.identifier && + a.mutations_count == b.mutations_count)) { + return false; + } + + for (size_t i = 0; i < a.mutations_count; ++i) { + if (!(*a.mutations[i] == *b.mutations[i])) { + return false; + } + } + + return true; +} + +inline bool operator==(const FlutterLayer& a, const FlutterLayer& b) { + if (!(a.struct_size == b.struct_size && a.type == b.type && + a.offset == b.offset && a.size == b.size)) { + return false; + } + + switch (a.type) { + case kFlutterLayerContentTypeBackingStore: + return *a.backing_store == *b.backing_store && + *a.backing_store_present_info == *b.backing_store_present_info; + case kFlutterLayerContentTypePlatformView: + return *a.platform_view == *b.platform_view; + } + + return false; +} + +//------------------------------------------------------------------------------ +// Printing +//------------------------------------------------------------------------------ + +inline std::ostream& operator<<(std::ostream& out, const FlutterPoint& point) { + return out << "(" << point.x << ", " << point.y << ")"; +} + +inline std::ostream& operator<<(std::ostream& out, const FlutterRect& r) { + return out << "LTRB (" << r.left << ", " << r.top << ", " << r.right << ", " + << r.bottom << ")"; +} + +inline std::ostream& operator<<(std::ostream& out, const FlutterSize& size) { + return out << "(" << size.width << ", " << size.height << ")"; +} + +inline std::ostream& operator<<(std::ostream& out, + const FlutterRoundedRect& r) { + out << "Rect: " << r.rect << ", "; + out << "Upper Left Corner Radius: " << r.upper_left_corner_radius << ", "; + out << "Upper Right Corner Radius: " << r.upper_right_corner_radius << ", "; + out << "Lower Right Corner Radius: " << r.lower_right_corner_radius << ", "; + out << "Lower Left Corner Radius: " << r.lower_left_corner_radius; + return out; +} + +inline std::ostream& operator<<(std::ostream& out, + const FlutterTransformation& t) { + out << "Scale X: " << t.scaleX << ", "; + out << "Skew X: " << t.skewX << ", "; + out << "Trans X: " << t.transX << ", "; + out << "Skew Y: " << t.skewY << ", "; + out << "Scale Y: " << t.scaleY << ", "; + out << "Trans Y: " << t.transY << ", "; + out << "Pers 0: " << t.pers0 << ", "; + out << "Pers 1: " << t.pers1 << ", "; + out << "Pers 2: " << t.pers2; + return out; +} + +inline std::string FlutterLayerContentTypeToString( + FlutterLayerContentType type) { + switch (type) { + case kFlutterLayerContentTypeBackingStore: + return "kFlutterLayerContentTypeBackingStore"; + case kFlutterLayerContentTypePlatformView: + return "kFlutterLayerContentTypePlatformView"; + } + return "Unknown"; +} + +inline std::string FlutterBackingStoreTypeToString( + FlutterBackingStoreType type) { + switch (type) { + case kFlutterBackingStoreTypeOpenGL: + return "kFlutterBackingStoreTypeOpenGL"; + case kFlutterBackingStoreTypeSoftware: + return "kFlutterBackingStoreTypeSoftware"; + case kFlutterBackingStoreTypeMetal: + return "kFlutterBackingStoreTypeMetal"; + case kFlutterBackingStoreTypeVulkan: + return "kFlutterBackingStoreTypeVulkan"; + case kFlutterBackingStoreTypeSoftware2: + return "kFlutterBackingStoreTypeSoftware2"; + } + return "Unknown"; +} + +inline std::ostream& operator<<(std::ostream& out, + const FlutterOpenGLTexture& item) { + return out << "(FlutterOpenGLTexture) Target: 0x" << std::hex << item.target + << std::dec << " Name: " << item.name << " Format: " << item.format + << " User Data: " << item.user_data << " Destruction Callback: " + << reinterpret_cast(item.destruction_callback); +} + +inline std::ostream& operator<<(std::ostream& out, + const FlutterOpenGLFramebuffer& item) { + return out << "(FlutterOpenGLFramebuffer) Target: 0x" << std::hex + << item.target << std::dec << " Name: " << item.name + << " User Data: " << item.user_data << " Destruction Callback: " + << reinterpret_cast(item.destruction_callback); +} + +inline std::ostream& operator<<(std::ostream& out, + const FlutterOpenGLSurface& item) { + return out << "(FlutterOpenGLSurface) Make Current Callback: " + << reinterpret_cast(item.make_current_callback) + << " User Data: " << item.user_data << "Format: " << item.format + << " Destruction Callback: " + << reinterpret_cast(item.destruction_callback); +} + +inline std::ostream& operator<<(std::ostream& out, + const FlutterMetalTexture& item) { + return out << "(FlutterMetalTexture) Texture ID: " << std::hex + << item.texture_id << std::dec << " Handle: 0x" << std::hex + << item.texture; +} + +inline std::ostream& operator<<(std::ostream& out, + const FlutterVulkanImage& item) { + return out << "(FlutterVulkanTexture) Image Handle: " << std::hex + << item.image << std::dec << " Format: " << item.format; +} + +inline std::string FlutterPlatformViewMutationTypeToString( + FlutterPlatformViewMutationType type) { + switch (type) { + case kFlutterPlatformViewMutationTypeOpacity: + return "kFlutterPlatformViewMutationTypeOpacity"; + case kFlutterPlatformViewMutationTypeClipRect: + return "kFlutterPlatformViewMutationTypeClipRect"; + case kFlutterPlatformViewMutationTypeClipRoundedRect: + return "kFlutterPlatformViewMutationTypeClipRoundedRect"; + case kFlutterPlatformViewMutationTypeTransformation: + return "kFlutterPlatformViewMutationTypeTransformation"; + } + return "Unknown"; +} + +inline std::ostream& operator<<(std::ostream& out, + const FlutterPlatformViewMutation& m) { + out << "(FlutterPlatformViewMutation) Type: " + << FlutterPlatformViewMutationTypeToString(m.type) << " "; + switch (m.type) { + case kFlutterPlatformViewMutationTypeOpacity: + out << "Opacity: " << m.opacity; + case kFlutterPlatformViewMutationTypeClipRect: + out << "Clip Rect: " << m.clip_rect; + case kFlutterPlatformViewMutationTypeClipRoundedRect: + out << "Clip Rounded Rect: " << m.clip_rounded_rect; + case kFlutterPlatformViewMutationTypeTransformation: + out << "Transformation: " << m.transformation; + } + return out; +} + +inline std::ostream& operator<<(std::ostream& out, + const FlutterPlatformView& platform_view) { + out << "[" + << "(FlutterPlatformView) Struct Size: " << platform_view.struct_size + << " Identifier: " << platform_view.identifier + << " Mutations Count: " << platform_view.mutations_count; + + if (platform_view.mutations_count > 0) { + out << std::endl; + for (size_t i = 0; i < platform_view.mutations_count; i++) { + out << "Mutation " << i << ": " << *platform_view.mutations[i] + << std::endl; + } + } + + out << "]"; + + return out; +} + +inline std::string FlutterOpenGLTargetTypeToString( + FlutterOpenGLTargetType type) { + switch (type) { + case kFlutterOpenGLTargetTypeTexture: + return "kFlutterOpenGLTargetTypeTexture"; + case kFlutterOpenGLTargetTypeFramebuffer: + return "kFlutterOpenGLTargetTypeFramebuffer"; + case kFlutterOpenGLTargetTypeSurface: + return "kFlutterOpenGLTargetTypeSurface"; + } + return "Unknown"; +} + +inline std::string FlutterSoftwarePixelFormatToString( + FlutterSoftwarePixelFormat pixfmt) { + switch (pixfmt) { + case kFlutterSoftwarePixelFormatGray8: + return "kFlutterSoftwarePixelFormatGray8"; + case kFlutterSoftwarePixelFormatRGB565: + return "kFlutterSoftwarePixelFormatRGB565"; + case kFlutterSoftwarePixelFormatRGBA4444: + return "kFlutterSoftwarePixelFormatRGBA4444"; + case kFlutterSoftwarePixelFormatRGBA8888: + return "kFlutterSoftwarePixelFormatRGBA8888"; + case kFlutterSoftwarePixelFormatRGBX8888: + return "kFlutterSoftwarePixelFormatRGBX8888"; + case kFlutterSoftwarePixelFormatBGRA8888: + return "kFlutterSoftwarePixelFormatBGRA8888"; + case kFlutterSoftwarePixelFormatNative32: + return "kFlutterSoftwarePixelFormatNative32"; + default: + FML_LOG(ERROR) << "Invalid software rendering pixel format"; + } + return "Unknown"; +} + +inline std::ostream& operator<<(std::ostream& out, + const FlutterOpenGLBackingStore& item) { + out << "(FlutterOpenGLBackingStore) Type: " + << FlutterOpenGLTargetTypeToString(item.type) << " "; + switch (item.type) { + case kFlutterOpenGLTargetTypeTexture: + out << item.texture; + break; + case kFlutterOpenGLTargetTypeFramebuffer: + out << item.framebuffer; + break; + case kFlutterOpenGLTargetTypeSurface: + out << item.surface; + break; + } + return out; +} + +inline std::ostream& operator<<(std::ostream& out, + const FlutterSoftwareBackingStore& item) { + return out << "(FlutterSoftwareBackingStore) Allocation: " << item.allocation + << " Row Bytes: " << item.row_bytes << " Height: " << item.height + << " User Data: " << item.user_data << " Destruction Callback: " + << reinterpret_cast(item.destruction_callback); +} + +inline std::ostream& operator<<(std::ostream& out, + const FlutterMetalBackingStore& item) { + return out << "(FlutterMetalBackingStore) Texture: " << item.texture; +} + +inline std::ostream& operator<<(std::ostream& out, + const FlutterVulkanBackingStore& item) { + return out << "(FlutterVulkanBackingStore) Image: " << item.image; +} + +inline std::ostream& operator<<(std::ostream& out, + const FlutterSoftwareBackingStore2& item) { + return out << "(FlutterSoftwareBackingStore2) Allocation: " << item.allocation + << " Row Bytes: " << item.row_bytes << " Height: " << item.height + << " User Data: " << item.user_data << " Destruction Callback: " + << reinterpret_cast(item.destruction_callback) + << " Pixel Format: " + << FlutterSoftwarePixelFormatToString(item.pixel_format); +} + +inline std::ostream& operator<<(std::ostream& out, + const FlutterBackingStore& backing_store) { + out << "(FlutterBackingStore) Struct size: " << backing_store.struct_size + << " User Data: " << backing_store.user_data + << " Type: " << FlutterBackingStoreTypeToString(backing_store.type) + << " "; + + switch (backing_store.type) { + case kFlutterBackingStoreTypeOpenGL: + out << backing_store.open_gl; + break; + + case kFlutterBackingStoreTypeSoftware: + out << backing_store.software; + break; + + case kFlutterBackingStoreTypeMetal: + out << backing_store.metal; + break; + + case kFlutterBackingStoreTypeVulkan: + out << backing_store.vulkan; + break; + + case kFlutterBackingStoreTypeSoftware2: + out << backing_store.software2; + break; + } + + return out; +} + +inline std::ostream& operator<<(std::ostream& out, const FlutterLayer& layer) { + out << "(Flutter Layer) Struct size: " << layer.struct_size + << " Type: " << FlutterLayerContentTypeToString(layer.type); + + switch (layer.type) { + case kFlutterLayerContentTypeBackingStore: + out << *layer.backing_store; + break; + case kFlutterLayerContentTypePlatformView: + out << *layer.platform_view; + break; + } + + return out << " Offset: " << layer.offset << " Size: " << layer.size; +} + +//------------------------------------------------------------------------------ +// Factories and Casts +//------------------------------------------------------------------------------ + +inline FlutterPoint FlutterPointMake(double x, double y) { + FlutterPoint point = {}; + point.x = x; + point.y = y; + return point; +} + +inline FlutterSize FlutterSizeMake(double width, double height) { + FlutterSize size = {}; + size.width = width; + size.height = height; + return size; +} + +inline FlutterSize FlutterSizeMake(const SkVector& vector) { + FlutterSize size = {}; + size.width = vector.x(); + size.height = vector.y(); + return size; +} + +inline FlutterTransformation FlutterTransformationMake(const SkMatrix& matrix) { + FlutterTransformation transformation = {}; + transformation.scaleX = matrix[SkMatrix::kMScaleX]; + transformation.skewX = matrix[SkMatrix::kMSkewX]; + transformation.transX = matrix[SkMatrix::kMTransX]; + transformation.skewY = matrix[SkMatrix::kMSkewY]; + transformation.scaleY = matrix[SkMatrix::kMScaleY]; + transformation.transY = matrix[SkMatrix::kMTransY]; + transformation.pers0 = matrix[SkMatrix::kMPersp0]; + transformation.pers1 = matrix[SkMatrix::kMPersp1]; + transformation.pers2 = matrix[SkMatrix::kMPersp2]; + return transformation; +} + +inline SkMatrix SkMatrixMake(const FlutterTransformation& xformation) { + return SkMatrix::MakeAll(xformation.scaleX, // + xformation.skewX, // + xformation.transX, // + xformation.skewY, // + xformation.scaleY, // + xformation.transY, // + xformation.pers0, // + xformation.pers1, // + xformation.pers2 // + ); +} + +inline flutter::EmbedderEngine* ToEmbedderEngine(const FlutterEngine& engine) { + return reinterpret_cast(engine); +} + +inline FlutterRect FlutterRectMake(const SkRect& rect) { + FlutterRect r = {}; + r.left = rect.left(); + r.top = rect.top(); + r.right = rect.right(); + r.bottom = rect.bottom(); + return r; +} + +inline FlutterRect FlutterRectMakeLTRB(double l, double t, double r, double b) { + FlutterRect rect = {}; + rect.left = l; + rect.top = t; + rect.right = r; + rect.bottom = b; + return rect; +} + +inline SkRect SkRectMake(const FlutterRect& rect) { + return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom); +} + +inline FlutterRoundedRect FlutterRoundedRectMake(const SkRRect& rect) { + FlutterRoundedRect r = {}; + r.rect = FlutterRectMake(rect.rect()); + r.upper_left_corner_radius = + FlutterSizeMake(rect.radii(SkRRect::Corner::kUpperLeft_Corner)); + r.upper_right_corner_radius = + FlutterSizeMake(rect.radii(SkRRect::Corner::kUpperRight_Corner)); + r.lower_right_corner_radius = + FlutterSizeMake(rect.radii(SkRRect::Corner::kLowerRight_Corner)); + r.lower_left_corner_radius = + FlutterSizeMake(rect.radii(SkRRect::Corner::kLowerLeft_Corner)); + return r; +} + +// NOLINTEND(google-objc-function-naming) + +#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_ASSERTIONS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_config_builder.cc b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_config_builder.cc new file mode 100644 index 0000000000000000000000000000000000000000..26dd3ea4d9c45873c7311b74a6d79f705f32a3ce --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_config_builder.cc @@ -0,0 +1,322 @@ +// 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/shell/platform/embedder/tests/embedder_config_builder.h" + +#include "flutter/common/constants.h" +#include "flutter/runtime/dart_vm.h" +#include "flutter/shell/platform/embedder/embedder.h" +#include "tests/embedder_test_context.h" +#include "third_party/skia/include/core/SkImage.h" + +namespace flutter::testing { + +EmbedderConfigBuilder::EmbedderConfigBuilder( + EmbedderTestContext& context, + InitializationPreference preference) + : context_(context) { + project_args_.struct_size = sizeof(project_args_); + project_args_.shutdown_dart_vm_when_done = true; + project_args_.platform_message_callback = + [](const FlutterPlatformMessage* message, void* context) { + reinterpret_cast(context) + ->PlatformMessageCallback(message); + }; + + custom_task_runners_.struct_size = sizeof(FlutterCustomTaskRunners); + + // The first argument is always the executable name. Don't make tests have to + // do this manually. + AddCommandLineArgument("embedder_unittest"); + + if (preference != InitializationPreference::kNoInitialize) { + SetAssetsPath(); + SetIsolateCreateCallbackHook(); + SetSemanticsCallbackHooks(); + SetLogMessageCallbackHook(); + SetLocalizationCallbackHooks(); + SetChannelUpdateCallbackHook(); + SetViewFocusChangeRequestHook(); + AddCommandLineArgument("--disable-vm-service"); + + if (preference == InitializationPreference::kSnapshotsInitialize || + preference == InitializationPreference::kMultiAOTInitialize) { + SetSnapshots(); + } + if (preference == InitializationPreference::kAOTDataInitialize || + preference == InitializationPreference::kMultiAOTInitialize) { + SetAOTDataElf(); + } + } +} + +EmbedderConfigBuilder::~EmbedderConfigBuilder() = default; + +FlutterProjectArgs& EmbedderConfigBuilder::GetProjectArgs() { + return project_args_; +} + +void EmbedderConfigBuilder::SetAssetsPath() { + project_args_.assets_path = context_.GetAssetsPath().c_str(); +} + +void EmbedderConfigBuilder::SetSnapshots() { + if (auto mapping = context_.GetVMSnapshotData()) { + project_args_.vm_snapshot_data = mapping->GetMapping(); + project_args_.vm_snapshot_data_size = mapping->GetSize(); + } + + if (auto mapping = context_.GetVMSnapshotInstructions()) { + project_args_.vm_snapshot_instructions = mapping->GetMapping(); + project_args_.vm_snapshot_instructions_size = mapping->GetSize(); + } + + if (auto mapping = context_.GetIsolateSnapshotData()) { + project_args_.isolate_snapshot_data = mapping->GetMapping(); + project_args_.isolate_snapshot_data_size = mapping->GetSize(); + } + + if (auto mapping = context_.GetIsolateSnapshotInstructions()) { + project_args_.isolate_snapshot_instructions = mapping->GetMapping(); + project_args_.isolate_snapshot_instructions_size = mapping->GetSize(); + } +} + +void EmbedderConfigBuilder::SetAOTDataElf() { + project_args_.aot_data = context_.GetAOTData(); +} + +void EmbedderConfigBuilder::SetIsolateCreateCallbackHook() { + project_args_.root_isolate_create_callback = + EmbedderTestContext::GetIsolateCreateCallbackHook(); +} + +void EmbedderConfigBuilder::SetSemanticsCallbackHooks() { + project_args_.update_semantics_callback2 = + context_.GetUpdateSemanticsCallback2Hook(); + project_args_.update_semantics_callback = + context_.GetUpdateSemanticsCallbackHook(); + project_args_.update_semantics_node_callback = + context_.GetUpdateSemanticsNodeCallbackHook(); + project_args_.update_semantics_custom_action_callback = + context_.GetUpdateSemanticsCustomActionCallbackHook(); +} + +void EmbedderConfigBuilder::SetLogMessageCallbackHook() { + project_args_.log_message_callback = + EmbedderTestContext::GetLogMessageCallbackHook(); +} + +void EmbedderConfigBuilder::SetChannelUpdateCallbackHook() { + project_args_.channel_update_callback = + context_.GetChannelUpdateCallbackHook(); +} + +void EmbedderConfigBuilder::SetViewFocusChangeRequestHook() { + project_args_.view_focus_change_request_callback = + context_.GetViewFocusChangeRequestCallbackHook(); +} + +void EmbedderConfigBuilder::SetLogTag(std::string tag) { + log_tag_ = std::move(tag); + project_args_.log_tag = log_tag_.c_str(); +} + +void EmbedderConfigBuilder::SetLocalizationCallbackHooks() { + project_args_.compute_platform_resolved_locale_callback = + EmbedderTestContext::GetComputePlatformResolvedLocaleCallbackHook(); +} + +void EmbedderConfigBuilder::SetExecutableName(std::string executable_name) { + if (executable_name.empty()) { + return; + } + command_line_arguments_[0] = std::move(executable_name); +} + +void EmbedderConfigBuilder::SetDartEntrypoint(std::string entrypoint) { + if (entrypoint.empty()) { + return; + } + + dart_entrypoint_ = std::move(entrypoint); + project_args_.custom_dart_entrypoint = dart_entrypoint_.c_str(); +} + +void EmbedderConfigBuilder::AddCommandLineArgument(std::string arg) { + if (arg.empty()) { + return; + } + + command_line_arguments_.emplace_back(std::move(arg)); +} + +void EmbedderConfigBuilder::AddDartEntrypointArgument(std::string arg) { + if (arg.empty()) { + return; + } + + dart_entrypoint_arguments_.emplace_back(std::move(arg)); +} + +void EmbedderConfigBuilder::SetPlatformTaskRunner( + const FlutterTaskRunnerDescription* runner) { + if (runner == nullptr) { + return; + } + custom_task_runners_.platform_task_runner = runner; + project_args_.custom_task_runners = &custom_task_runners_; +} + +void EmbedderConfigBuilder::SetUITaskRunner( + const FlutterTaskRunnerDescription* runner) { + if (runner == nullptr) { + return; + } + custom_task_runners_.ui_task_runner = runner; + project_args_.custom_task_runners = &custom_task_runners_; +} + +void EmbedderConfigBuilder::SetupVsyncCallback() { + project_args_.vsync_callback = [](void* user_data, intptr_t baton) { + auto context = reinterpret_cast(user_data); + context->RunVsyncCallback(baton); + }; +} + +void EmbedderConfigBuilder::SetRenderTaskRunner( + const FlutterTaskRunnerDescription* runner) { + if (runner == nullptr) { + return; + } + + custom_task_runners_.render_task_runner = runner; + project_args_.custom_task_runners = &custom_task_runners_; +} + +void EmbedderConfigBuilder::SetPlatformMessageCallback( + const std::function& callback) { + context_.SetPlatformMessageCallback(callback); +} + +void EmbedderConfigBuilder::SetViewFocusChangeRequestCallback( + const std::function& callback) { + context_.SetViewFocusChangeRequestCallback(callback); +} + +void EmbedderConfigBuilder::SetCompositor(bool avoid_backing_store_cache, + bool use_present_layers_callback) { + context_.SetupCompositor(); + auto& compositor = context_.GetCompositor(); + compositor_.struct_size = sizeof(compositor_); + compositor_.user_data = &compositor; + compositor_.create_backing_store_callback = + [](const FlutterBackingStoreConfig* config, // + FlutterBackingStore* backing_store_out, // + void* user_data // + ) { + return reinterpret_cast(user_data) + ->CreateBackingStore(config, backing_store_out); + }; + compositor_.collect_backing_store_callback = + [](const FlutterBackingStore* backing_store, // + void* user_data // + ) { + return reinterpret_cast(user_data) + ->CollectBackingStore(backing_store); + }; + if (use_present_layers_callback) { + compositor_.present_layers_callback = [](const FlutterLayer** layers, + size_t layers_count, + void* user_data) { + auto compositor = reinterpret_cast(user_data); + + // The present layers callback is incompatible with multiple views; + // it can only be used to render the implicit view. + return compositor->Present(kFlutterImplicitViewId, layers, layers_count); + }; + } else { + compositor_.present_view_callback = [](const FlutterPresentViewInfo* info) { + auto compositor = + reinterpret_cast(info->user_data); + + return compositor->Present(info->view_id, info->layers, + info->layers_count); + }; + } + compositor_.avoid_backing_store_cache = avoid_backing_store_cache; + project_args_.compositor = &compositor_; +} + +FlutterCompositor& EmbedderConfigBuilder::GetCompositor() { + return compositor_; +} + +void EmbedderConfigBuilder::SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType type, + FlutterSoftwarePixelFormat software_pixfmt) { + context_.GetCompositor().SetRenderTargetType(type, software_pixfmt); +} + +UniqueEngine EmbedderConfigBuilder::LaunchEngine() const { + return SetupEngine(true); +} + +UniqueEngine EmbedderConfigBuilder::InitializeEngine() const { + return SetupEngine(false); +} + +UniqueEngine EmbedderConfigBuilder::SetupEngine(bool run) const { + FlutterEngine engine = nullptr; + FlutterProjectArgs project_args = project_args_; + + std::vector args; + args.reserve(command_line_arguments_.size()); + + for (const auto& arg : command_line_arguments_) { + args.push_back(arg.c_str()); + } + + if (!args.empty()) { + project_args.command_line_argv = args.data(); + project_args.command_line_argc = args.size(); + } else { + // Clear it out in case this is not the first engine launch from the + // embedder config builder. + project_args.command_line_argv = nullptr; + project_args.command_line_argc = 0; + } + + std::vector dart_args; + dart_args.reserve(dart_entrypoint_arguments_.size()); + + for (const auto& arg : dart_entrypoint_arguments_) { + dart_args.push_back(arg.c_str()); + } + + if (!dart_args.empty()) { + project_args.dart_entrypoint_argv = dart_args.data(); + project_args.dart_entrypoint_argc = dart_args.size(); + } else { + // Clear it out in case this is not the first engine launch from the + // embedder config builder. + project_args.dart_entrypoint_argv = nullptr; + project_args.dart_entrypoint_argc = 0; + } + + auto result = run ? FlutterEngineRun(FLUTTER_ENGINE_VERSION, + &context_.GetRendererConfig(), + &project_args, &context_, &engine) + : FlutterEngineInitialize( + FLUTTER_ENGINE_VERSION, &context_.GetRendererConfig(), + &project_args, &context_, &engine); + + if (result != kSuccess) { + return {}; + } + + return UniqueEngine{engine}; +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_config_builder.h b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_config_builder.h new file mode 100644 index 0000000000000000000000000000000000000000..399f84d3c85263e6d1bd4eb813b6347d48e2add1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_config_builder.h @@ -0,0 +1,130 @@ +// 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_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_CONFIG_BUILDER_H_ +#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_CONFIG_BUILDER_H_ + +#include "flutter/fml/macros.h" +#include "flutter/fml/unique_object.h" +#include "flutter/shell/platform/embedder/embedder.h" +#include "flutter/shell/platform/embedder/tests/embedder_test.h" +#include "flutter/shell/platform/embedder/tests/embedder_test_context_software.h" + +namespace flutter::testing { + +struct UniqueEngineTraits { + static FlutterEngine InvalidValue() { return nullptr; } + + static bool IsValid(const FlutterEngine& value) { return value != nullptr; } + + static void Free(FlutterEngine& engine) { + auto result = FlutterEngineShutdown(engine); + FML_CHECK(result == kSuccess); + } +}; + +using UniqueEngine = fml::UniqueObject; + +class EmbedderConfigBuilder { + public: + enum class InitializationPreference { + kSnapshotsInitialize, + kAOTDataInitialize, + kMultiAOTInitialize, + kNoInitialize, + }; + + explicit EmbedderConfigBuilder( + EmbedderTestContext& context, + InitializationPreference preference = + InitializationPreference::kSnapshotsInitialize); + + ~EmbedderConfigBuilder(); + + FlutterProjectArgs& GetProjectArgs(); + + void SetAssetsPath(); + + void SetSnapshots(); + + void SetAOTDataElf(); + + void SetIsolateCreateCallbackHook(); + + void SetSemanticsCallbackHooks(); + + // Used to set a custom log message handler. + void SetLogMessageCallbackHook(); + + void SetChannelUpdateCallbackHook(); + + void SetViewFocusChangeRequestHook(); + + // Used to set a custom log tag. + void SetLogTag(std::string tag); + + void SetLocalizationCallbackHooks(); + + void SetExecutableName(std::string executable_name); + + void SetDartEntrypoint(std::string entrypoint); + + void AddCommandLineArgument(std::string arg); + + void AddDartEntrypointArgument(std::string arg); + + void SetPlatformTaskRunner(const FlutterTaskRunnerDescription* runner); + + void SetUITaskRunner(const FlutterTaskRunnerDescription* runner); + + void SetRenderTaskRunner(const FlutterTaskRunnerDescription* runner); + + void SetPlatformMessageCallback( + const std::function& callback); + + void SetViewFocusChangeRequestCallback( + const std::function& + callback); + + void SetCompositor(bool avoid_backing_store_cache = false, + bool use_present_layers_callback = false); + + FlutterCompositor& GetCompositor(); + + void SetSurface(SkISize surface_size) { context_.SetSurface(surface_size); } + + void SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType type, + FlutterSoftwarePixelFormat software_pixfmt = + kFlutterSoftwarePixelFormatNative32); + + UniqueEngine LaunchEngine() const; + + UniqueEngine InitializeEngine() const; + + // Sets up the callback for vsync, the callbacks needs to be specified on the + // text context vis `SetVsyncCallback`. + void SetupVsyncCallback(); + + void SetViewFocusChangeRequestCallback( + const FlutterViewFocusChangeRequestCallback& callback); + + private: + EmbedderTestContext& context_; + FlutterProjectArgs project_args_ = {}; + std::string dart_entrypoint_; + FlutterCustomTaskRunners custom_task_runners_ = {}; + FlutterCompositor compositor_ = {}; + std::vector command_line_arguments_; + std::vector dart_entrypoint_arguments_; + std::string log_tag_; + + UniqueEngine SetupEngine(bool run) const; + + FML_DISALLOW_COPY_AND_ASSIGN(EmbedderConfigBuilder); +}; + +} // namespace flutter::testing + +#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_CONFIG_BUILDER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_frozen.h b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_frozen.h new file mode 100644 index 0000000000000000000000000000000000000000..afd66372fdeab2035f8164c53c24b19d98db15d0 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_frozen.h @@ -0,0 +1,114 @@ +// 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_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_FROZEN_H_ +#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_FROZEN_H_ + +#include "flutter/shell/platform/embedder/embedder.h" + +// NO CHANGES ARE PERMITTED TO THE STRUCTS IN THIS FILE. +// +// This file contains the subset of the embedder API that is "frozen". +// "Frozen" APIs are locked and must not be modified to guarantee +// forward and backward ABI compatibility. The order, type, and size +// of the struct members below must remain the same, and members must +// not be added nor removed. +// +// This file serves as a "golden test" for structs in embedder.h +// and contains a snapshot of the expected "frozen" API. Tests +// then verify that these structs match the actual embedder API. + +namespace flutter { +namespace testing { + +// New members must not be added to `FlutterTransformation` +// as it would break the ABI of `FlutterSemanticsNode`. +// See: https://github.com/flutter/flutter/issues/121176 +typedef struct { + double scaleX; + double skewX; + double transX; + double skewY; + double scaleY; + double transY; + double pers0; + double pers1; + double pers2; +} FrozenFlutterTransformation; + +// New members must not be added to `FlutterRect` as it would +// break the ABI of `FlutterSemanticsNode` and `FlutterDamage`. +// See: https://github.com/flutter/flutter/issues/121176 +// See: https://github.com/flutter/flutter/issues/121347 +typedef struct { + double left; + double top; + double right; + double bottom; +} FrozenFlutterRect; + +// New members must not be added to `FlutterPoint` as it would +// break the ABI of `FlutterLayer`. +typedef struct { + double x; + double y; +} FrozenFlutterPoint; + +// New members must not be added to `FlutterDamage` as it would +// break the ABI of `FlutterPresentInfo`. +typedef struct { + size_t struct_size; + size_t num_rects; + FrozenFlutterRect* damage; +} FrozenFlutterDamage; + +// New members must not be added to `FlutterSemanticsNode` +// as it would break the ABI of `FlutterSemanticsUpdate`. +// See: https://github.com/flutter/flutter/issues/121176 +typedef struct { + size_t struct_size; + int32_t id; + FlutterSemanticsFlag flags; + FlutterSemanticsAction actions; + int32_t text_selection_base; + int32_t text_selection_extent; + int32_t scroll_child_count; + int32_t scroll_index; + double scroll_position; + double scroll_extent_max; + double scroll_extent_min; + double elevation; + double thickness; + const char* label; + const char* hint; + const char* value; + const char* increased_value; + const char* decreased_value; + FlutterTextDirection text_direction; + FrozenFlutterRect rect; + FrozenFlutterTransformation transform; + size_t child_count; + const int32_t* children_in_traversal_order; + const int32_t* children_in_hit_test_order; + size_t custom_accessibility_actions_count; + const int32_t* custom_accessibility_actions; + FlutterPlatformViewIdentifier platform_view_id; + const char* tooltip; +} FrozenFlutterSemanticsNode; + +// New members must not be added to `FlutterSemanticsCustomAction` +// as it would break the ABI of `FlutterSemanticsUpdate`. +// See: https://github.com/flutter/flutter/issues/121176 +typedef struct { + size_t struct_size; + int32_t id; + FlutterSemanticsAction override_action; + const char* label; + const char* hint; +} FrozenFlutterSemanticsCustomAction; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_FROZEN_H_ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_frozen_unittests.cc b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_frozen_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..4235547e831a9147a97ca763cf27ff03a00e99f2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_frozen_unittests.cc @@ -0,0 +1,131 @@ +// 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/shell/platform/embedder/embedder.h" +#include "flutter/shell/platform/embedder/tests/embedder_frozen.h" +#include "flutter/testing/testing.h" + +namespace flutter { +namespace testing { + +// Assert that both types have the same member with the same offset. +// This prevents reordering of "frozen" embedder API struct members. +#define ASSERT_EQ_OFFSET(type1, type2, member) \ + ASSERT_EQ(offsetof(type1, member), offsetof(type2, member)) + +// New members must not be added to `FlutterTransformation` +// as it would break the ABI of `FlutterSemanticsNode`. +// See: https://github.com/flutter/flutter/issues/121176 +TEST(EmbedderFrozen, FlutterTransformationIsFrozen) { + ASSERT_EQ_OFFSET(FlutterTransformation, FrozenFlutterTransformation, scaleX); + ASSERT_EQ_OFFSET(FlutterTransformation, FrozenFlutterTransformation, skewX); + ASSERT_EQ_OFFSET(FlutterTransformation, FrozenFlutterTransformation, transX); + ASSERT_EQ_OFFSET(FlutterTransformation, FrozenFlutterTransformation, skewY); + ASSERT_EQ_OFFSET(FlutterTransformation, FrozenFlutterTransformation, scaleY); + ASSERT_EQ_OFFSET(FlutterTransformation, FrozenFlutterTransformation, transY); + ASSERT_EQ_OFFSET(FlutterTransformation, FrozenFlutterTransformation, pers0); + ASSERT_EQ_OFFSET(FlutterTransformation, FrozenFlutterTransformation, pers1); + ASSERT_EQ_OFFSET(FlutterTransformation, FrozenFlutterTransformation, pers2); +} + +// New members must not be added to `FlutterRect` as it would +// break the ABI of `FlutterSemanticsNode` and `FlutterDamage`. +// See: https://github.com/flutter/flutter/issues/121176 +// See: https://github.com/flutter/flutter/issues/121347 +TEST(EmbedderFrozen, FlutterRectIsFrozen) { + ASSERT_EQ_OFFSET(FlutterRect, FrozenFlutterRect, left); + ASSERT_EQ_OFFSET(FlutterRect, FrozenFlutterRect, top); + ASSERT_EQ_OFFSET(FlutterRect, FrozenFlutterRect, right); + ASSERT_EQ_OFFSET(FlutterRect, FrozenFlutterRect, bottom); +} + +// New members must not be added to `FlutterPoint` as it would +// break the ABI of `FlutterLayer`. +TEST(EmbedderFrozen, FlutterPointIsFrozen) { + ASSERT_EQ_OFFSET(FlutterPoint, FrozenFlutterPoint, x); + ASSERT_EQ_OFFSET(FlutterPoint, FrozenFlutterPoint, y); +} + +// New members must not be added to `FlutterDamage` as it would +// break the ABI of `FlutterPresentInfo`. +TEST(EmbedderFrozen, FlutterDamageIsFrozen) { + ASSERT_EQ_OFFSET(FlutterDamage, FrozenFlutterDamage, struct_size); + ASSERT_EQ_OFFSET(FlutterDamage, FrozenFlutterDamage, num_rects); + ASSERT_EQ_OFFSET(FlutterDamage, FrozenFlutterDamage, damage); +} + +// New members must not be added to `FlutterSemanticsNode` +// as it would break the ABI of `FlutterSemanticsUpdate`. +// See: https://github.com/flutter/flutter/issues/121176 +TEST(EmbedderFrozen, FlutterSemanticsNodeIsFrozen) { + ASSERT_EQ(sizeof(FlutterSemanticsNode), sizeof(FrozenFlutterSemanticsNode)); + + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, + struct_size); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, id); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, flags); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, actions); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, + text_selection_base); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, + text_selection_extent); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, + scroll_child_count); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, + scroll_index); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, + scroll_position); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, + scroll_extent_max); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, + scroll_extent_min); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, elevation); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, thickness); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, label); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, hint); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, value); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, + increased_value); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, + decreased_value); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, + text_direction); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, rect); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, transform); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, + child_count); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, + children_in_traversal_order); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, + children_in_hit_test_order); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, + custom_accessibility_actions_count); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, + custom_accessibility_actions); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, + platform_view_id); + ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, tooltip); +} + +// New members must not be added to `FlutterSemanticsCustomAction` +// as it would break the ABI of `FlutterSemanticsUpdate`. +// See: https://github.com/flutter/flutter/issues/121176 +TEST(EmbedderFrozen, FlutterSemanticsCustomActionIsFrozen) { + ASSERT_EQ(sizeof(FlutterSemanticsCustomAction), + sizeof(FrozenFlutterSemanticsCustomAction)); + + ASSERT_EQ_OFFSET(FlutterSemanticsCustomAction, + FrozenFlutterSemanticsCustomAction, struct_size); + ASSERT_EQ_OFFSET(FlutterSemanticsCustomAction, + FrozenFlutterSemanticsCustomAction, id); + ASSERT_EQ_OFFSET(FlutterSemanticsCustomAction, + FrozenFlutterSemanticsCustomAction, override_action); + ASSERT_EQ_OFFSET(FlutterSemanticsCustomAction, + FrozenFlutterSemanticsCustomAction, label); + ASSERT_EQ_OFFSET(FlutterSemanticsCustomAction, + FrozenFlutterSemanticsCustomAction, hint); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_gl_unittests.cc b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_gl_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..ab8cae0c2e5361423819fd4850dcda48ed509281 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_gl_unittests.cc @@ -0,0 +1,5178 @@ +// 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 "tests/embedder_test_context.h" +#define FML_USED_ON_EMBEDDER + +#include +#include +#include + +#include "vulkan/vulkan.h" + +#include "GLES3/gl3.h" +#include "flutter/flow/raster_cache.h" +#include "flutter/fml/file.h" +#include "flutter/fml/make_copyable.h" +#include "flutter/fml/mapping.h" +#include "flutter/fml/message_loop.h" +#include "flutter/fml/message_loop_task_queues.h" +#include "flutter/fml/native_library.h" +#include "flutter/fml/paths.h" +#include "flutter/fml/synchronization/count_down_latch.h" +#include "flutter/fml/synchronization/waitable_event.h" +#include "flutter/fml/task_source.h" +#include "flutter/fml/thread.h" +#include "flutter/lib/ui/painting/image.h" +#include "flutter/runtime/dart_vm.h" +#include "flutter/shell/platform/embedder/embedder_surface_gl_impeller.h" +#include "flutter/shell/platform/embedder/tests/embedder_assertions.h" +#include "flutter/shell/platform/embedder/tests/embedder_config_builder.h" +#include "flutter/shell/platform/embedder/tests/embedder_test.h" +#include "flutter/shell/platform/embedder/tests/embedder_test_context_gl.h" +#include "flutter/shell/platform/embedder/tests/embedder_unittests_util.h" +#include "flutter/testing/assertions_skia.h" +#include "flutter/testing/test_gl_surface.h" +#include "flutter/testing/testing.h" +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/tonic/converter/dart_converter.h" + +// CREATE_NATIVE_ENTRY is leaky by design +// NOLINTBEGIN(clang-analyzer-core.StackAddressEscape) + +namespace flutter::testing { + +using EmbedderTest = testing::EmbedderTest; + +TEST_F(EmbedderTest, CanCreateOpenGLRenderingEngine) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); +} + +//------------------------------------------------------------------------------ +/// If an incorrectly configured compositor is set on the engine, the engine +/// must fail to launch instead of failing to render a frame at a later point in +/// time. +/// +TEST_F(EmbedderTest, + MustPreventEngineLaunchWhenRequiredCompositorArgsAreAbsent) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetCompositor(); + builder.GetCompositor().create_backing_store_callback = nullptr; + builder.GetCompositor().collect_backing_store_callback = nullptr; + builder.GetCompositor().present_layers_callback = nullptr; + builder.GetCompositor().present_view_callback = nullptr; + auto engine = builder.LaunchEngine(); + ASSERT_FALSE(engine.is_valid()); +} + +//------------------------------------------------------------------------------ +/// Either present_layers_callback or present_view_callback must be provided, +/// but not both, otherwise the engine must fail to launch instead of failing to +/// render a frame at a later point in time. +/// +TEST_F(EmbedderTest, LaunchFailsWhenMultiplePresentCallbacks) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetCompositor(); + builder.GetCompositor().present_layers_callback = + [](const FlutterLayer** layers, size_t layers_count, void* user_data) { + return true; + }; + builder.GetCompositor().present_view_callback = + [](const FlutterPresentViewInfo* info) { return true; }; + auto engine = builder.LaunchEngine(); + ASSERT_FALSE(engine.is_valid()); +} + +//------------------------------------------------------------------------------ +/// Must be able to render to a custom compositor whose render targets are fully +/// complete OpenGL textures. +/// +TEST_F(EmbedderTest, CompositorMustBeAbleToRenderToOpenGLFramebuffer) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("can_composite_platform_views"); + + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer); + + fml::CountDownLatch latch(3); + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 3u); + + { + FlutterBackingStore backing_store = *layers[0]->backing_store; + backing_store.struct_size = sizeof(backing_store); + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0, 0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[0], layer); + } + + { + FlutterPlatformView platform_view = *layers[1]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 42; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(123.0, 456.0); + layer.offset = FlutterPointMake(1.0, 2.0); + + ASSERT_EQ(*layers[1], layer); + } + + { + FlutterBackingStore backing_store = *layers[2]->backing_store; + backing_store.struct_size = sizeof(backing_store); + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(2, 3, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[2], layer); + } + + latch.CountDown(); + }); + + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&latch](Dart_NativeArguments args) { latch.CountDown(); })); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + + latch.Wait(); +} + +//------------------------------------------------------------------------------ +/// Layers in a hierarchy containing a platform view should not be cached. The +/// other layers in the hierarchy should be, however. +TEST_F(EmbedderTest, RasterCacheDisabledWithPlatformViews) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("can_composite_platform_views_with_opacity"); + + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer); + + fml::CountDownLatch setup(3); + fml::CountDownLatch verify(1); + + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 3u); + + { + FlutterBackingStore backing_store = *layers[0]->backing_store; + backing_store.struct_size = sizeof(backing_store); + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0, 0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[0], layer); + } + + { + FlutterPlatformView platform_view = *layers[1]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 42; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(123.0, 456.0); + layer.offset = FlutterPointMake(1.0, 2.0); + + ASSERT_EQ(*layers[1], layer); + } + + { + FlutterBackingStore backing_store = *layers[2]->backing_store; + backing_store.struct_size = sizeof(backing_store); + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(3, 3, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[2], layer); + } + + setup.CountDown(); + }); + + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&setup](Dart_NativeArguments args) { setup.CountDown(); })); + + UniqueEngine engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + + setup.Wait(); + const flutter::Shell& shell = ToEmbedderEngine(engine.get())->GetShell(); + shell.GetTaskRunners().GetRasterTaskRunner()->PostTask([&] { + const flutter::RasterCache& raster_cache = + shell.GetRasterizer()->compositor_context()->raster_cache(); + // 3 layers total, but one of them had the platform view. So the cache + // should only have 2 entries. + ASSERT_EQ(raster_cache.GetCachedEntriesCount(), 2u); + verify.CountDown(); + }); + + verify.Wait(); +} + +//------------------------------------------------------------------------------ +/// The RasterCache should normally be enabled. +/// +TEST_F(EmbedderTest, RasterCacheEnabled) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("can_composite_with_opacity"); + + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer); + + fml::CountDownLatch setup(3); + fml::CountDownLatch verify(1); + + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 1u); + + { + FlutterBackingStore backing_store = *layers[0]->backing_store; + backing_store.struct_size = sizeof(backing_store); + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0, 0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[0], layer); + } + + setup.CountDown(); + }); + + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&setup](Dart_NativeArguments args) { setup.CountDown(); })); + + UniqueEngine engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + + setup.Wait(); + const flutter::Shell& shell = ToEmbedderEngine(engine.get())->GetShell(); + shell.GetTaskRunners().GetRasterTaskRunner()->PostTask([&] { + const flutter::RasterCache& raster_cache = + shell.GetRasterizer()->compositor_context()->raster_cache(); + ASSERT_EQ(raster_cache.GetCachedEntriesCount(), 1u); + verify.CountDown(); + }); + + verify.Wait(); +} + +//------------------------------------------------------------------------------ +/// Must be able to render using a custom compositor whose render targets for +/// the individual layers are OpenGL textures. +/// +TEST_F(EmbedderTest, CompositorMustBeAbleToRenderToOpenGLTexture) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("can_composite_platform_views"); + + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); + + fml::CountDownLatch latch(3); + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 3u); + + { + FlutterBackingStore backing_store = *layers[0]->backing_store; + backing_store.struct_size = sizeof(backing_store); + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0, 0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[0], layer); + } + + { + FlutterPlatformView platform_view = *layers[1]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 42; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(123.0, 456.0); + layer.offset = FlutterPointMake(1.0, 2.0); + + ASSERT_EQ(*layers[1], layer); + } + + { + FlutterBackingStore backing_store = *layers[2]->backing_store; + backing_store.struct_size = sizeof(backing_store); + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(2, 3, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[2], layer); + } + + latch.CountDown(); + }); + + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&latch](Dart_NativeArguments args) { latch.CountDown(); })); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + + latch.Wait(); +} + +//------------------------------------------------------------------------------ +/// Must be able to render using a custom compositor whose render target for the +/// individual layers are software buffers. +/// +TEST_F(EmbedderTest, CompositorMustBeAbleToRenderToSoftwareBuffer) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("can_composite_platform_views"); + + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer); + + fml::CountDownLatch latch(3); + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 3u); + + { + FlutterBackingStore backing_store = *layers[0]->backing_store; + backing_store.struct_size = sizeof(backing_store); + backing_store.type = kFlutterBackingStoreTypeSoftware; + backing_store.did_update = true; + ASSERT_FLOAT_EQ( + backing_store.software.row_bytes * backing_store.software.height, + 800 * 4 * 600.0); + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0, 0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[0], layer); + } + + { + FlutterPlatformView platform_view = *layers[1]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 42; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(123.0, 456.0); + layer.offset = FlutterPointMake(1.0, 2.0); + + ASSERT_EQ(*layers[1], layer); + } + + { + FlutterBackingStore backing_store = *layers[2]->backing_store; + backing_store.struct_size = sizeof(backing_store); + backing_store.type = kFlutterBackingStoreTypeSoftware; + backing_store.did_update = true; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(2, 3, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[2], layer); + } + + latch.CountDown(); + }); + + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&latch](Dart_NativeArguments args) { latch.CountDown(); })); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + + latch.Wait(); +} + +//------------------------------------------------------------------------------ +/// Test the layer structure and pixels rendered when using a custom compositor. +/// +TEST_F(EmbedderTest, CompositorMustBeAbleToRenderKnownScene) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("can_composite_platform_views_with_known_scene"); + + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); + + fml::CountDownLatch latch(5); + + auto scene_image = context.GetNextSceneImage(); + + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 5u); + + // Layer Root + { + FlutterBackingStore backing_store = *layers[0]->backing_store; + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[0], layer); + } + + // Layer 1 + { + FlutterPlatformView platform_view = *layers[1]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 1; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(50.0, 150.0); + layer.offset = FlutterPointMake(20.0, 20.0); + + ASSERT_EQ(*layers[1], layer); + } + + // Layer 2 + { + FlutterBackingStore backing_store = *layers[2]->backing_store; + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(30, 30, 80, 180), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[2], layer); + } + + // Layer 3 + { + FlutterPlatformView platform_view = *layers[3]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 2; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(50.0, 150.0); + layer.offset = FlutterPointMake(40.0, 40.0); + + ASSERT_EQ(*layers[3], layer); + } + + // Layer 4 + { + FlutterBackingStore backing_store = *layers[4]->backing_store; + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(50, 50, 100, 200), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[4], layer); + } + + latch.CountDown(); + }); + + context.GetCompositor().SetPlatformViewRendererCallback( + [&](const FlutterLayer& layer, + GrDirectContext* context) -> sk_sp { + auto surface = CreateRenderSurface(layer, context); + auto canvas = surface->getCanvas(); + FML_CHECK(canvas != nullptr); + + switch (layer.platform_view->identifier) { + case 1: { + SkPaint paint; + // See dart test for total order. + paint.setColor(SK_ColorGREEN); + paint.setAlpha(127); + const auto& rect = + SkRect::MakeWH(layer.size.width, layer.size.height); + canvas->drawRect(rect, paint); + latch.CountDown(); + } break; + case 2: { + SkPaint paint; + // See dart test for total order. + paint.setColor(SK_ColorMAGENTA); + paint.setAlpha(127); + const auto& rect = + SkRect::MakeWH(layer.size.width, layer.size.height); + canvas->drawRect(rect, paint); + latch.CountDown(); + } break; + default: + // Asked to render an unknown platform view. + FML_CHECK(false) + << "Test was asked to composite an unknown platform view."; + } + + return surface->makeImageSnapshot(); + }); + + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&latch](Dart_NativeArguments args) { latch.CountDown(); })); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + + latch.Wait(); + + ASSERT_TRUE(ImageMatchesFixture("compositor.png", scene_image)); + + // There should no present calls on the root surface. + ASSERT_EQ(context.GetSurfacePresentCount(), 0u); +} + +//------------------------------------------------------------------------------ +/// Custom compositor must play nicely with a custom task runner. The raster +/// thread merging mechanism must not interfere with the custom compositor. +/// +TEST_F(EmbedderTest, CustomCompositorMustWorkWithCustomTaskRunner) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("can_composite_platform_views"); + + auto platform_task_runner = CreateNewThread("test_platform_thread"); + static std::mutex engine_mutex; + UniqueEngine engine; + fml::AutoResetWaitableEvent sync_latch; + + EmbedderTestTaskRunner test_task_runner( + platform_task_runner, [&](FlutterTask task) { + std::scoped_lock lock(engine_mutex); + if (!engine.is_valid()) { + return; + } + ASSERT_EQ(FlutterEngineRunTask(engine.get(), &task), kSuccess); + }); + + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); + + fml::CountDownLatch latch(3); + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 3u); + + { + FlutterBackingStore backing_store = *layers[0]->backing_store; + backing_store.struct_size = sizeof(backing_store); + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0, 0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[0], layer); + } + + { + FlutterPlatformView platform_view = *layers[1]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 42; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(2, 3, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(123.0, 456.0); + layer.offset = FlutterPointMake(1.0, 2.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[1], layer); + } + + { + FlutterBackingStore backing_store = *layers[2]->backing_store; + backing_store.struct_size = sizeof(backing_store); + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(2, 3, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[2], layer); + } + + latch.CountDown(); + }); + + const auto task_runner_description = + test_task_runner.GetFlutterTaskRunnerDescription(); + + builder.SetPlatformTaskRunner(&task_runner_description); + + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&latch](Dart_NativeArguments args) { latch.CountDown(); })); + + platform_task_runner->PostTask([&]() { + std::scoped_lock lock(engine_mutex); + engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + sync_latch.Signal(); + }); + sync_latch.Wait(); + + latch.Wait(); + + platform_task_runner->PostTask([&]() { + std::scoped_lock lock(engine_mutex); + engine.reset(); + sync_latch.Signal(); + }); + sync_latch.Wait(); +} + +//------------------------------------------------------------------------------ +/// Test the layer structure and pixels rendered when using a custom compositor +/// and a single layer. +/// +TEST_F(EmbedderTest, CompositorMustBeAbleToRenderWithRootLayerOnly) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint( + "can_composite_platform_views_with_root_layer_only"); + + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); + + fml::CountDownLatch latch(3); + + auto scene_image = context.GetNextSceneImage(); + + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 1u); + + // Layer Root + { + FlutterBackingStore backing_store = *layers[0]->backing_store; + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[0], layer); + } + + latch.CountDown(); + }); + + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&latch](Dart_NativeArguments args) { latch.CountDown(); })); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + + latch.Wait(); + + ASSERT_TRUE( + ImageMatchesFixture("compositor_with_root_layer_only.png", scene_image)); +} + +//------------------------------------------------------------------------------ +/// Test the layer structure and pixels rendered when using a custom compositor +/// and ensure that a redundant layer is not added. +/// +TEST_F(EmbedderTest, CompositorMustBeAbleToRenderWithPlatformLayerOnBottom) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint( + "can_composite_platform_views_with_platform_layer_on_bottom"); + + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); + + fml::CountDownLatch latch(3); + + auto scene_image = context.GetNextSceneImage(); + + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 2u); + + // Layer Root + { + FlutterBackingStore backing_store = *layers[0]->backing_store; + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[0], layer); + } + + // Layer 1 + { + FlutterPlatformView platform_view = *layers[1]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 1; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(50.0, 150.0); + layer.offset = FlutterPointMake(20.0, 20.0); + + ASSERT_EQ(*layers[1], layer); + } + + latch.CountDown(); + }); + + context.GetCompositor().SetPlatformViewRendererCallback( + [&](const FlutterLayer& layer, + GrDirectContext* context) -> sk_sp { + auto surface = CreateRenderSurface(layer, context); + auto canvas = surface->getCanvas(); + FML_CHECK(canvas != nullptr); + + switch (layer.platform_view->identifier) { + case 1: { + SkPaint paint; + // See dart test for total order. + paint.setColor(SK_ColorGREEN); + paint.setAlpha(127); + const auto& rect = + SkRect::MakeWH(layer.size.width, layer.size.height); + canvas->drawRect(rect, paint); + latch.CountDown(); + } break; + default: + // Asked to render an unknown platform view. + FML_CHECK(false) + << "Test was asked to composite an unknown platform view."; + } + + return surface->makeImageSnapshot(); + }); + + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&latch](Dart_NativeArguments args) { latch.CountDown(); })); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + + latch.Wait(); + + ASSERT_TRUE(ImageMatchesFixture( + "compositor_with_platform_layer_on_bottom.png", scene_image)); + + ASSERT_EQ(context.GetCompositor().GetPendingBackingStoresCount(), 1u); +} + +//------------------------------------------------------------------------------ +/// Test the layer structure and pixels rendered when using a custom compositor +/// with a root surface transformation. +/// +TEST_F(EmbedderTest, + CompositorMustBeAbleToRenderKnownSceneWithRootSurfaceTransformation) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(600, 800)); + builder.SetCompositor(); + builder.SetDartEntrypoint("can_composite_platform_views_with_known_scene"); + + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); + + // This must match the transformation provided in the + // |CanRenderGradientWithoutCompositorWithXform| test to ensure that + // transforms are consistent respected. + const auto root_surface_transformation = + SkMatrix().preTranslate(0, 800).preRotate(-90, 0, 0); + + context.SetRootSurfaceTransformation(root_surface_transformation); + + fml::CountDownLatch latch(5); + + auto scene_image = context.GetNextSceneImage(); + + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 5u); + + // Layer Root + { + FlutterBackingStore backing_store = *layers[0]->backing_store; + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 600, 800), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(600.0, 800.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[0], layer); + } + + // Layer 1 + { + FlutterPlatformView platform_view = *layers[1]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 1; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(150.0, 50.0); + layer.offset = FlutterPointMake(20.0, 730.0); + + ASSERT_EQ(*layers[1], layer); + } + + // Layer 2 + { + FlutterBackingStore backing_store = *layers[2]->backing_store; + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(30, 720, 180, 770), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(600.0, 800.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[2], layer); + } + + // Layer 3 + { + FlutterPlatformView platform_view = *layers[3]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 2; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(150.0, 50.0); + layer.offset = FlutterPointMake(40.0, 710.0); + + ASSERT_EQ(*layers[3], layer); + } + + // Layer 4 + { + FlutterBackingStore backing_store = *layers[4]->backing_store; + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(50, 700, 200, 750), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(600.0, 800.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[4], layer); + } + + latch.CountDown(); + }); + + context.GetCompositor().SetPlatformViewRendererCallback( + [&](const FlutterLayer& layer, + GrDirectContext* context) -> sk_sp { + auto surface = CreateRenderSurface(layer, context); + auto canvas = surface->getCanvas(); + FML_CHECK(canvas != nullptr); + + switch (layer.platform_view->identifier) { + case 1: { + SkPaint paint; + // See dart test for total order. + paint.setColor(SK_ColorGREEN); + paint.setAlpha(127); + const auto& rect = + SkRect::MakeWH(layer.size.width, layer.size.height); + canvas->drawRect(rect, paint); + latch.CountDown(); + } break; + case 2: { + SkPaint paint; + // See dart test for total order. + paint.setColor(SK_ColorMAGENTA); + paint.setAlpha(127); + const auto& rect = + SkRect::MakeWH(layer.size.width, layer.size.height); + canvas->drawRect(rect, paint); + latch.CountDown(); + } break; + default: + // Asked to render an unknown platform view. + FML_CHECK(false) + << "Test was asked to composite an unknown platform view."; + } + + return surface->makeImageSnapshot(); + }); + + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&latch](Dart_NativeArguments args) { latch.CountDown(); })); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + // Flutter still thinks it is 800 x 600. Only the root surface is rotated. + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + + latch.Wait(); + + ASSERT_TRUE(ImageMatchesFixture("compositor_root_surface_xformation.png", + scene_image)); +} + +TEST_F(EmbedderTest, CanRenderSceneWithoutCustomCompositor) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + + builder.SetDartEntrypoint("can_render_scene_without_custom_compositor"); + builder.SetSurface(SkISize::Make(800, 600)); + + auto rendered_scene = context.GetNextSceneImage(); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + + ASSERT_TRUE(ImageMatchesFixture("scene_without_custom_compositor.png", + rendered_scene)); +} + +TEST_F(EmbedderTest, CanRenderSceneWithoutCustomCompositorWithTransformation) { + auto& context = GetEmbedderContext(); + + const auto root_surface_transformation = + SkMatrix().preTranslate(0, 800).preRotate(-90, 0, 0); + + context.SetRootSurfaceTransformation(root_surface_transformation); + + EmbedderConfigBuilder builder(context); + + builder.SetDartEntrypoint("can_render_scene_without_custom_compositor"); + builder.SetSurface(SkISize::Make(600, 800)); + + auto rendered_scene = context.GetNextSceneImage(); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + + // Flutter still thinks it is 800 x 600. + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + + ASSERT_TRUE(ImageMatchesFixture( + "scene_without_custom_compositor_with_xform.png", rendered_scene)); +} + +TEST_P(EmbedderTestMultiBackend, CanRenderGradientWithoutCompositor) { + EmbedderTestContextType backend = GetParam(); + auto& context = GetEmbedderContext(backend); + EmbedderConfigBuilder builder(context); + builder.SetDartEntrypoint("render_gradient"); + builder.SetSurface(SkISize::Make(800, 600)); + + auto rendered_scene = context.GetNextSceneImage(); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + + ASSERT_TRUE(ImageMatchesFixture( + FixtureNameForBackend(backend, "gradient.png"), rendered_scene)); +} + +TEST_F(EmbedderTest, CanRenderGradientWithoutCompositorWithXform) { + auto& context = GetEmbedderContext(); + + const auto root_surface_transformation = + SkMatrix().preTranslate(0, 800).preRotate(-90, 0, 0); + + context.SetRootSurfaceTransformation(root_surface_transformation); + + EmbedderConfigBuilder builder(context); + + const auto surface_size = SkISize::Make(600, 800); + + builder.SetDartEntrypoint("render_gradient"); + builder.SetSurface(surface_size); + + auto rendered_scene = context.GetNextSceneImage(); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + // Flutter still thinks it is 800 x 600. + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + + ASSERT_TRUE(ImageMatchesFixture("gradient_xform.png", rendered_scene)); +} + +TEST_P(EmbedderTestMultiBackend, CanRenderGradientWithCompositor) { + EmbedderTestContextType backend = GetParam(); + auto& context = GetEmbedderContext(backend); + + EmbedderConfigBuilder builder(context); + builder.SetDartEntrypoint("render_gradient"); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetRenderTargetType(GetRenderTargetFromBackend(backend, true)); + + auto rendered_scene = context.GetNextSceneImage(); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + + ASSERT_TRUE(ImageMatchesFixture( + FixtureNameForBackend(backend, "gradient.png"), rendered_scene)); +} + +TEST_F(EmbedderTest, CanRenderGradientWithCompositorWithXform) { + auto& context = GetEmbedderContext(); + + // This must match the transformation provided in the + // |CanRenderGradientWithoutCompositorWithXform| test to ensure that + // transforms are consistent respected. + const auto root_surface_transformation = + SkMatrix().preTranslate(0, 800).preRotate(-90, 0, 0); + + context.SetRootSurfaceTransformation(root_surface_transformation); + + EmbedderConfigBuilder builder(context); + + builder.SetDartEntrypoint("render_gradient"); + builder.SetSurface(SkISize::Make(600, 800)); + builder.SetCompositor(); + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer); + + auto rendered_scene = context.GetNextSceneImage(); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + // Flutter still thinks it is 800 x 600. + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + + ASSERT_TRUE(ImageMatchesFixture("gradient_xform.png", rendered_scene)); +} + +TEST_P(EmbedderTestMultiBackend, + CanRenderGradientWithCompositorOnNonRootLayer) { + EmbedderTestContextType backend = GetParam(); + auto& context = GetEmbedderContext(backend); + + EmbedderConfigBuilder builder(context); + builder.SetDartEntrypoint("render_gradient_on_non_root_backing_store"); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetRenderTargetType(GetRenderTargetFromBackend(backend, true)); + + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 3u); + + // Layer Root + { + FlutterBackingStore backing_store = *layers[0]->backing_store; + backing_store.did_update = true; + ConfigureBackingStore(backing_store, backend, true); + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[0], layer); + } + + // Layer 1 + { + FlutterPlatformView platform_view = *layers[1]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 1; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(100.0, 200.0); + layer.offset = FlutterPointMake(0.0, 0.0); + + ASSERT_EQ(*layers[1], layer); + } + + // Layer 2 + { + FlutterBackingStore backing_store = *layers[2]->backing_store; + backing_store.did_update = true; + ConfigureBackingStore(backing_store, backend, true); + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[2], layer); + } + }); + + context.GetCompositor().SetPlatformViewRendererCallback( + [&](const FlutterLayer& layer, + GrDirectContext* context) -> sk_sp { + auto surface = CreateRenderSurface(layer, context); + auto canvas = surface->getCanvas(); + FML_CHECK(canvas != nullptr); + + switch (layer.platform_view->identifier) { + case 1: { + FML_CHECK(layer.size.width == 100); + FML_CHECK(layer.size.height == 200); + // This is occluded anyway. We just want to make sure we see this. + } break; + default: + // Asked to render an unknown platform view. + FML_CHECK(false) + << "Test was asked to composite an unknown platform view."; + } + + return surface->makeImageSnapshot(); + }); + + auto rendered_scene = context.GetNextSceneImage(); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + + ASSERT_TRUE(ImageMatchesFixture( + FixtureNameForBackend(backend, "gradient.png"), rendered_scene)); +} + +TEST_F(EmbedderTest, CanRenderGradientWithCompositorOnNonRootLayerWithXform) { + auto& context = GetEmbedderContext(); + + // This must match the transformation provided in the + // |CanRenderGradientWithoutCompositorWithXform| test to ensure that + // transforms are consistent respected. + const auto root_surface_transformation = + SkMatrix().preTranslate(0, 800).preRotate(-90, 0, 0); + + context.SetRootSurfaceTransformation(root_surface_transformation); + + EmbedderConfigBuilder builder(context); + + builder.SetDartEntrypoint("render_gradient_on_non_root_backing_store"); + builder.SetSurface(SkISize::Make(600, 800)); + builder.SetCompositor(); + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer); + + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 3u); + + // Layer Root + { + FlutterBackingStore backing_store = *layers[0]->backing_store; + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 600, 800), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(600.0, 800.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[0], layer); + } + + // Layer 1 + { + FlutterPlatformView platform_view = *layers[1]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 1; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(200.0, 100.0); + layer.offset = FlutterPointMake(0.0, 700.0); + + ASSERT_EQ(*layers[1], layer); + } + + // Layer 2 + { + FlutterBackingStore backing_store = *layers[2]->backing_store; + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 600, 800), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(600.0, 800.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[2], layer); + } + }); + + context.GetCompositor().SetPlatformViewRendererCallback( + [&](const FlutterLayer& layer, + GrDirectContext* context) -> sk_sp { + auto surface = CreateRenderSurface(layer, context); + auto canvas = surface->getCanvas(); + FML_CHECK(canvas != nullptr); + + switch (layer.platform_view->identifier) { + case 1: { + FML_CHECK(layer.size.width == 200); + FML_CHECK(layer.size.height == 100); + // This is occluded anyway. We just want to make sure we see this. + } break; + default: + // Asked to render an unknown platform view. + FML_CHECK(false) + << "Test was asked to composite an unknown platform view."; + } + + return surface->makeImageSnapshot(); + }); + + auto rendered_scene = context.GetNextSceneImage(); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + // Flutter still thinks it is 800 x 600. + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + + ASSERT_TRUE(ImageMatchesFixture("gradient_xform.png", rendered_scene)); +} + +TEST_F(EmbedderTest, VerifyB141980393) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + + // The Flutter application is 800 x 600 but rendering on a surface that is 600 + // x 800 achieved using a root surface transformation. + const auto root_surface_transformation = + SkMatrix().preTranslate(0, 800).preRotate(-90, 0, 0); + const auto flutter_application_rect = SkRect::MakeWH(800, 600); + const auto root_surface_rect = + root_surface_transformation.mapRect(flutter_application_rect); + + ASSERT_DOUBLE_EQ(root_surface_rect.width(), 600.0); + ASSERT_DOUBLE_EQ(root_surface_rect.height(), 800.0); + + // Configure the fixture for the surface transformation. + context.SetRootSurfaceTransformation(root_surface_transformation); + + // Configure the Flutter project args for the root surface transformation. + builder.SetSurface( + SkISize::Make(root_surface_rect.width(), root_surface_rect.height())); + + // Use a compositor instead of rendering directly to the surface. + builder.SetCompositor(); + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer); + + builder.SetDartEntrypoint("verify_b141980393"); + + fml::AutoResetWaitableEvent latch; + + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 1u); + + // Layer Root + { + FlutterPlatformView platform_view = *layers[0]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 1337; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + + // From the Dart side. These dimensions match those specified in Dart + // code and are free of root surface transformations. + const double unxformed_top_margin = 31.0; + const double unxformed_bottom_margin = 37.0; + const auto unxformed_platform_view_rect = SkRect::MakeXYWH( + 0.0, // x + unxformed_top_margin, // y (top margin) + 800, // width + 600 - unxformed_top_margin - unxformed_bottom_margin // height + ); + + // The platform views are in the coordinate space of the root surface + // with top-left origin. The embedder has specified a transformation + // to this surface which it must account for in the coordinates it + // receives here. + const auto xformed_platform_view_rect = + root_surface_transformation.mapRect(unxformed_platform_view_rect); + + // Spell out the value that we are going to be checking below for + // clarity. + ASSERT_EQ(xformed_platform_view_rect, + SkRect::MakeXYWH(31.0, // x + 0.0, // y + 532.0, // width + 800.0 // height + )); + + // Verify that the engine is giving us the right size and offset. + layer.offset = FlutterPointMake(xformed_platform_view_rect.x(), + xformed_platform_view_rect.y()); + layer.size = FlutterSizeMake(xformed_platform_view_rect.width(), + xformed_platform_view_rect.height()); + + ASSERT_EQ(*layers[0], layer); + } + + latch.Signal(); + }); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + + // The Flutter application is 800 x 600 rendering on a surface 600 x 800 + // achieved via a root surface transformation. + event.width = flutter_application_rect.width(); + event.height = flutter_application_rect.height(); + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + + latch.Wait(); +} + +//------------------------------------------------------------------------------ +/// Asserts that embedders can provide a task runner for the render thread. +/// +TEST_F(EmbedderTest, CanCreateEmbedderWithCustomRenderTaskRunner) { + std::mutex engine_mutex; + UniqueEngine engine; + fml::AutoResetWaitableEvent task_latch; + bool task_executed = false; + EmbedderTestTaskRunner render_task_runner( + CreateNewThread("custom_render_thread"), [&](FlutterTask task) { + std::scoped_lock engine_lock(engine_mutex); + if (engine.is_valid()) { + ASSERT_EQ(FlutterEngineRunTask(engine.get(), &task), kSuccess); + task_executed = true; + task_latch.Signal(); + } + }); + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetDartEntrypoint("can_render_scene_without_custom_compositor"); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetRenderTaskRunner( + &render_task_runner.GetFlutterTaskRunnerDescription()); + + { + std::scoped_lock lock(engine_mutex); + engine = builder.InitializeEngine(); + } + + ASSERT_EQ(FlutterEngineRunInitialized(engine.get()), kSuccess); + + ASSERT_TRUE(engine.is_valid()); + + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + task_latch.Wait(); + ASSERT_TRUE(task_executed); + ASSERT_EQ(FlutterEngineDeinitialize(engine.get()), kSuccess); + + { + std::scoped_lock engine_lock(engine_mutex); + engine.reset(); + } +} + +//------------------------------------------------------------------------------ +/// Asserts that the render task runner can be the same as the platform task +/// runner. +/// +TEST_P(EmbedderTestMultiBackend, + CanCreateEmbedderWithCustomRenderTaskRunnerTheSameAsPlatformTaskRunner) { + // A new thread needs to be created for the platform thread because the test + // can't wait for assertions to be completed on the same thread that services + // platform task runner tasks. + auto platform_task_runner = CreateNewThread("platform_thread"); + + static std::mutex engine_mutex; + static UniqueEngine engine; + fml::AutoResetWaitableEvent task_latch; + bool task_executed = false; + EmbedderTestTaskRunner common_task_runner( + platform_task_runner, [&](FlutterTask task) { + std::scoped_lock engine_lock(engine_mutex); + if (engine.is_valid()) { + ASSERT_EQ(FlutterEngineRunTask(engine.get(), &task), kSuccess); + task_executed = true; + task_latch.Signal(); + } + }); + + platform_task_runner->PostTask([&]() { + EmbedderTestContextType backend = GetParam(); + auto& context = GetEmbedderContext(backend); + EmbedderConfigBuilder builder(context); + builder.SetDartEntrypoint("can_render_scene_without_custom_compositor"); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetRenderTaskRunner( + &common_task_runner.GetFlutterTaskRunnerDescription()); + builder.SetPlatformTaskRunner( + &common_task_runner.GetFlutterTaskRunnerDescription()); + + { + std::scoped_lock lock(engine_mutex); + engine = builder.InitializeEngine(); + } + + ASSERT_EQ(FlutterEngineRunInitialized(engine.get()), kSuccess); + + ASSERT_TRUE(engine.is_valid()); + + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + }); + + task_latch.Wait(); + + // Don't use the task latch because that may be called multiple time + // (including during the shutdown process). + fml::AutoResetWaitableEvent shutdown_latch; + + platform_task_runner->PostTask([&]() { + ASSERT_TRUE(task_executed); + ASSERT_EQ(FlutterEngineDeinitialize(engine.get()), kSuccess); + + { + std::scoped_lock engine_lock(engine_mutex); + engine.reset(); + } + shutdown_latch.Signal(); + }); + + shutdown_latch.Wait(); + + { + std::scoped_lock engine_lock(engine_mutex); + // Engine should have been killed by this point. + ASSERT_FALSE(engine.is_valid()); + } +} + +TEST_P(EmbedderTestMultiBackend, + CompositorMustBeAbleToRenderKnownScenePixelRatioOnSurface) { + EmbedderTestContextType backend = GetParam(); + auto& context = GetEmbedderContext(backend); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("can_display_platform_view_with_pixel_ratio"); + + builder.SetRenderTargetType(GetRenderTargetFromBackend(backend, false)); + + fml::CountDownLatch latch(1); + + auto rendered_scene = context.GetNextSceneImage(); + + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 3u); + + // Layer 0 (Root) + { + FlutterBackingStore backing_store = *layers[0]->backing_store; + backing_store.did_update = true; + ConfigureBackingStore(backing_store, backend, false); + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[0], layer); + } + + // Layer 1 + { + FlutterPlatformView platform_view = *layers[1]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 42; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(800.0, 560.0); + layer.offset = FlutterPointMake(0.0, 40.0); + + ASSERT_EQ(*layers[1], layer); + } + + // Layer 2 + { + FlutterBackingStore backing_store = *layers[2]->backing_store; + backing_store.did_update = true; + ConfigureBackingStore(backing_store, backend, false); + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[2], layer); + } + + latch.CountDown(); + }); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 400 * 2.0; + event.height = 300 * 2.0; + event.pixel_ratio = 2.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + + latch.Wait(); + + ASSERT_TRUE(ImageMatchesFixture( + FixtureNameForBackend(backend, "dpr_noxform.png"), rendered_scene)); +} + +TEST_F( + EmbedderTest, + CompositorMustBeAbleToRenderKnownScenePixelRatioOnSurfaceWithRootSurfaceXformation) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(600, 800)); + builder.SetCompositor(); + builder.SetDartEntrypoint("can_display_platform_view_with_pixel_ratio"); + + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); + + const auto root_surface_transformation = + SkMatrix().preTranslate(0, 800).preRotate(-90, 0, 0); + + context.SetRootSurfaceTransformation(root_surface_transformation); + + auto rendered_scene = context.GetNextSceneImage(); + fml::CountDownLatch latch(1); + + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 3u); + + // Layer 0 (Root) + { + FlutterBackingStore backing_store = *layers[0]->backing_store; + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 600, 800), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(600.0, 800.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[0], layer); + } + + // Layer 1 + { + FlutterPlatformView platform_view = *layers[1]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 42; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(560.0, 800.0); + layer.offset = FlutterPointMake(40.0, 0.0); + + ASSERT_EQ(*layers[1], layer); + } + + // Layer 2 + { + FlutterBackingStore backing_store = *layers[2]->backing_store; + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 600, 800), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(600.0, 800.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[2], layer); + } + + latch.CountDown(); + }); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 400 * 2.0; + event.height = 300 * 2.0; + event.pixel_ratio = 2.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + + latch.Wait(); + + ASSERT_TRUE(ImageMatchesFixture("dpr_xform.png", rendered_scene)); +} + +TEST_F(EmbedderTest, + PushingMutlipleFramesSetsUpNewRecordingCanvasWithCustomCompositor) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(600, 1024)); + builder.SetCompositor(); + builder.SetDartEntrypoint("push_frames_over_and_over"); + + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); + + const auto root_surface_transformation = + SkMatrix().preTranslate(0, 1024).preRotate(-90, 0, 0); + + context.SetRootSurfaceTransformation(root_surface_transformation); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 1024; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + + constexpr size_t frames_expected = 10; + fml::CountDownLatch frame_latch(frames_expected); + std::atomic_size_t frames_seen = 0; + context.AddNativeCallback("SignalNativeTest", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + frames_seen++; + frame_latch.CountDown(); + })); + frame_latch.Wait(); + + ASSERT_GE(frames_seen, frames_expected); + + FlutterEngineShutdown(engine.release()); +} + +TEST_F(EmbedderTest, + PushingMutlipleFramesSetsUpNewRecordingCanvasWithoutCustomCompositor) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(600, 1024)); + builder.SetDartEntrypoint("push_frames_over_and_over"); + + const auto root_surface_transformation = + SkMatrix().preTranslate(0, 1024).preRotate(-90, 0, 0); + + context.SetRootSurfaceTransformation(root_surface_transformation); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 1024; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + + constexpr size_t frames_expected = 10; + fml::CountDownLatch frame_latch(frames_expected); + std::atomic_size_t frames_seen = 0; + context.AddNativeCallback("SignalNativeTest", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + frames_seen++; + frame_latch.CountDown(); + })); + frame_latch.Wait(); + + ASSERT_GE(frames_seen, frames_expected); + + FlutterEngineShutdown(engine.release()); +} + +TEST_P(EmbedderTestMultiBackend, PlatformViewMutatorsAreValid) { + EmbedderTestContextType backend = GetParam(); + auto& context = GetEmbedderContext(backend); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("platform_view_mutators"); + + builder.SetRenderTargetType(GetRenderTargetFromBackend(backend, false)); + + fml::CountDownLatch latch(1); + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 2u); + + // Layer 0 (Root) + { + FlutterBackingStore backing_store = *layers[0]->backing_store; + backing_store.did_update = true; + ConfigureBackingStore(backing_store, backend, false); + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[0], layer); + } + + // Layer 2 + { + FlutterPlatformView platform_view = *layers[1]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 42; + platform_view.mutations_count = 3; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + + ASSERT_EQ(*layers[1], layer); + + // There are no ordering guarantees. + for (size_t i = 0; i < platform_view.mutations_count; i++) { + FlutterPlatformViewMutation mutation = *platform_view.mutations[i]; + switch (mutation.type) { + case kFlutterPlatformViewMutationTypeClipRoundedRect: + mutation.clip_rounded_rect = + FlutterRoundedRectMake(SkRRect::MakeRectXY( + SkRect::MakeLTRB(10.0, 10.0, 800.0 - 10.0, + 600.0 - 10.0), + 14.0, 14.0)); + break; + case kFlutterPlatformViewMutationTypeClipRect: + mutation.type = kFlutterPlatformViewMutationTypeClipRect; + mutation.clip_rect = FlutterRectMake( + SkRect::MakeXYWH(10.0, 10.0, 800.0 - 20.0, 600.0 - 20.0)); + break; + case kFlutterPlatformViewMutationTypeOpacity: + mutation.type = kFlutterPlatformViewMutationTypeOpacity; + mutation.opacity = 128.0 / 255.0; + break; + case kFlutterPlatformViewMutationTypeTransformation: + FML_CHECK(false) + << "There should be no transformation in the test."; + break; + } + + ASSERT_EQ(*platform_view.mutations[i], mutation); + } + } + latch.CountDown(); + }); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + + latch.Wait(); +} + +TEST_F(EmbedderTest, PlatformViewMutatorsAreValidWithPixelRatio) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("platform_view_mutators_with_pixel_ratio"); + + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); + + fml::CountDownLatch latch(1); + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 2u); + + // Layer 0 (Root) + { + FlutterBackingStore backing_store = *layers[0]->backing_store; + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[0], layer); + } + + // Layer 2 + { + FlutterPlatformView platform_view = *layers[1]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 42; + platform_view.mutations_count = 3; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + + ASSERT_EQ(*layers[1], layer); + + // There are no ordering guarantees. + for (size_t i = 0; i < platform_view.mutations_count; i++) { + FlutterPlatformViewMutation mutation = *platform_view.mutations[i]; + switch (mutation.type) { + case kFlutterPlatformViewMutationTypeClipRoundedRect: + mutation.clip_rounded_rect = + FlutterRoundedRectMake(SkRRect::MakeRectXY( + SkRect::MakeLTRB(5.0, 5.0, 400.0 - 5.0, 300.0 - 5.0), + 7.0, 7.0)); + break; + case kFlutterPlatformViewMutationTypeClipRect: + mutation.type = kFlutterPlatformViewMutationTypeClipRect; + mutation.clip_rect = FlutterRectMake( + SkRect::MakeXYWH(5.0, 5.0, 400.0 - 10.0, 300.0 - 10.0)); + break; + case kFlutterPlatformViewMutationTypeOpacity: + mutation.type = kFlutterPlatformViewMutationTypeOpacity; + mutation.opacity = 128.0 / 255.0; + break; + case kFlutterPlatformViewMutationTypeTransformation: + mutation.type = kFlutterPlatformViewMutationTypeTransformation; + mutation.transformation = + FlutterTransformationMake(SkMatrix::Scale(2.0, 2.0)); + break; + } + + ASSERT_EQ(*platform_view.mutations[i], mutation); + } + } + latch.CountDown(); + }); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 2.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + + latch.Wait(); +} + +TEST_F(EmbedderTest, + PlatformViewMutatorsAreValidWithPixelRatioAndRootSurfaceTransformation) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("platform_view_mutators_with_pixel_ratio"); + + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); + + static const auto root_surface_transformation = + SkMatrix().preTranslate(0, 800).preRotate(-90, 0, 0); + + context.SetRootSurfaceTransformation(root_surface_transformation); + + fml::CountDownLatch latch(1); + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 2u); + + // Layer 0 (Root) + { + FlutterBackingStore backing_store = *layers[0]->backing_store; + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 600, 800), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(600.0, 800.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[0], layer); + } + + // Layer 2 + { + FlutterPlatformView platform_view = *layers[1]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 42; + platform_view.mutations_count = 4; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(600.0, 800.0); + layer.offset = FlutterPointMake(0.0, 0.0); + + ASSERT_EQ(*layers[1], layer); + + // There are no ordering guarantees. + for (size_t i = 0; i < platform_view.mutations_count; i++) { + FlutterPlatformViewMutation mutation = *platform_view.mutations[i]; + switch (mutation.type) { + case kFlutterPlatformViewMutationTypeClipRoundedRect: + mutation.clip_rounded_rect = + FlutterRoundedRectMake(SkRRect::MakeRectXY( + SkRect::MakeLTRB(5.0, 5.0, 400.0 - 5.0, 300.0 - 5.0), + 7.0, 7.0)); + break; + case kFlutterPlatformViewMutationTypeClipRect: + mutation.type = kFlutterPlatformViewMutationTypeClipRect; + mutation.clip_rect = FlutterRectMake( + SkRect::MakeXYWH(5.0, 5.0, 400.0 - 10.0, 300.0 - 10.0)); + break; + case kFlutterPlatformViewMutationTypeOpacity: + mutation.type = kFlutterPlatformViewMutationTypeOpacity; + mutation.opacity = 128.0 / 255.0; + break; + case kFlutterPlatformViewMutationTypeTransformation: + mutation.type = kFlutterPlatformViewMutationTypeTransformation; + mutation.transformation = + FlutterTransformationMake(root_surface_transformation); + + break; + } + + ASSERT_EQ(*platform_view.mutations[i], mutation); + } + } + latch.CountDown(); + }); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 2.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + + latch.Wait(); +} + +TEST_F(EmbedderTest, EmptySceneIsAcceptable) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("empty_scene"); + fml::AutoResetWaitableEvent latch; + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch.Signal(); })); + + auto engine = builder.LaunchEngine(); + + ASSERT_TRUE(engine.is_valid()); + + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + latch.Wait(); +} + +TEST_F(EmbedderTest, SceneWithNoRootContainerIsAcceptable) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer); + builder.SetDartEntrypoint("scene_with_no_container"); + fml::AutoResetWaitableEvent latch; + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch.Signal(); })); + + auto engine = builder.LaunchEngine(); + + ASSERT_TRUE(engine.is_valid()); + + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + latch.Wait(); +} + +// Verifies that https://skia-review.googlesource.com/c/skia/+/259174 is pulled +// into the engine. +TEST_F(EmbedderTest, ArcEndCapsAreDrawnCorrectly) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 1024)); + builder.SetCompositor(); + builder.SetDartEntrypoint("arc_end_caps_correct"); + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer); + + const auto root_surface_transformation = SkMatrix() + .preScale(1.0, -1.0) + .preTranslate(1024.0, -800.0) + .preRotate(90.0); + + context.SetRootSurfaceTransformation(root_surface_transformation); + + auto engine = builder.LaunchEngine(); + + auto scene_image = context.GetNextSceneImage(); + + ASSERT_TRUE(engine.is_valid()); + + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 1024; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + + ASSERT_TRUE(ImageMatchesFixture("arc_end_caps.png", scene_image)); +} + +TEST_F(EmbedderTest, ClipsAreCorrectlyCalculated) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(400, 300)); + builder.SetCompositor(); + builder.SetDartEntrypoint("scene_builder_with_clips"); + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer); + + const auto root_surface_transformation = + SkMatrix().preTranslate(0, 400).preRotate(-90, 0, 0); + + context.SetRootSurfaceTransformation(root_surface_transformation); + + fml::AutoResetWaitableEvent latch; + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 2u); + + { + FlutterPlatformView platform_view = *layers[0]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 42; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(300.0, 400.0); + layer.offset = FlutterPointMake(0.0, 0.0); + + ASSERT_EQ(*layers[0], layer); + + bool clip_assertions_checked = false; + + // The total transformation on the stack upto the platform view. + const auto total_xformation = + GetTotalMutationTransformationMatrix(layers[0]->platform_view); + + FilterMutationsByType( + layers[0]->platform_view, + kFlutterPlatformViewMutationTypeClipRect, + [&](const auto& mutation) { + FlutterRect clip = mutation.clip_rect; + + // The test is only set up to supply one clip. Make sure it is + // the one we expect. + const auto rect_to_compare = + SkRect::MakeLTRB(10.0, 10.0, 390, 290); + ASSERT_EQ(clip, FlutterRectMake(rect_to_compare)); + + // This maps the clip from device space into surface space. + SkRect mapped; + ASSERT_TRUE(total_xformation.mapRect(&mapped, rect_to_compare)); + ASSERT_EQ(mapped, SkRect::MakeLTRB(10, 10, 290, 390)); + clip_assertions_checked = true; + }); + + ASSERT_TRUE(clip_assertions_checked); + } + + latch.Signal(); + }); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 400; + event.height = 300; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + + latch.Wait(); +} + +TEST_F(EmbedderTest, ComplexClipsAreCorrectlyCalculated) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1024, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("scene_builder_with_complex_clips"); + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer); + + const auto root_surface_transformation = + SkMatrix().preTranslate(0, 1024).preRotate(-90, 0, 0); + + context.SetRootSurfaceTransformation(root_surface_transformation); + + fml::AutoResetWaitableEvent latch; + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 2u); + + { + FlutterPlatformView platform_view = *layers[0]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 42; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(600.0, 1024.0); + layer.offset = FlutterPointMake(0.0, -256.0); + + ASSERT_EQ(*layers[0], layer); + + const auto** mutations = platform_view.mutations; + + ASSERT_EQ(mutations[0]->type, + kFlutterPlatformViewMutationTypeTransformation); + ASSERT_EQ(SkMatrixMake(mutations[0]->transformation), + root_surface_transformation); + + ASSERT_EQ(mutations[1]->type, + kFlutterPlatformViewMutationTypeClipRect); + ASSERT_EQ(SkRectMake(mutations[1]->clip_rect), + SkRect::MakeLTRB(0.0, 0.0, 1024.0, 600.0)); + + ASSERT_EQ(mutations[2]->type, + kFlutterPlatformViewMutationTypeTransformation); + ASSERT_EQ(SkMatrixMake(mutations[2]->transformation), + SkMatrix::Translate(512.0, 0.0)); + + ASSERT_EQ(mutations[3]->type, + kFlutterPlatformViewMutationTypeClipRect); + ASSERT_EQ(SkRectMake(mutations[3]->clip_rect), + SkRect::MakeLTRB(0.0, 0.0, 512.0, 600.0)); + + ASSERT_EQ(mutations[4]->type, + kFlutterPlatformViewMutationTypeTransformation); + ASSERT_EQ(SkMatrixMake(mutations[4]->transformation), + SkMatrix::Translate(-256.0, 0.0)); + + ASSERT_EQ(mutations[5]->type, + kFlutterPlatformViewMutationTypeClipRect); + ASSERT_EQ(SkRectMake(mutations[5]->clip_rect), + SkRect::MakeLTRB(0.0, 0.0, 1024.0, 600.0)); + } + + latch.Signal(); + }); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 1024; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + + latch.Wait(); +} + +TEST_F(EmbedderTest, ObjectsCanBePostedViaPorts) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 1024)); + builder.SetDartEntrypoint("objects_can_be_posted"); + + // Synchronously acquire the send port from the Dart end. We will be using + // this to send message. The Dart end will just echo those messages back to us + // for inspection. + FlutterEngineDartPort port = 0; + fml::AutoResetWaitableEvent event; + context.AddNativeCallback("SignalNativeCount", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + port = tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + event.Signal(); + })); + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + event.Wait(); + ASSERT_NE(port, 0); + + using Trampoline = std::function; + Trampoline trampoline; + + context.AddNativeCallback("SendObjectToNativeCode", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + FML_CHECK(trampoline); + auto trampoline_copy = trampoline; + trampoline = nullptr; + trampoline_copy(Dart_GetNativeArgument(args, 0)); + })); + + // Check null. + { + FlutterEngineDartObject object = {}; + object.type = kFlutterEngineDartObjectTypeNull; + trampoline = [&](Dart_Handle handle) { + ASSERT_TRUE(Dart_IsNull(handle)); + event.Signal(); + }; + ASSERT_EQ(FlutterEnginePostDartObject(engine.get(), port, &object), + kSuccess); + event.Wait(); + } + + // Check bool. + { + FlutterEngineDartObject object = {}; + object.type = kFlutterEngineDartObjectTypeBool; + object.bool_value = true; + trampoline = [&](Dart_Handle handle) { + ASSERT_TRUE(tonic::DartConverter::FromDart(handle)); + event.Signal(); + }; + ASSERT_EQ(FlutterEnginePostDartObject(engine.get(), port, &object), + kSuccess); + event.Wait(); + } + + // Check int32. + { + FlutterEngineDartObject object = {}; + object.type = kFlutterEngineDartObjectTypeInt32; + object.int32_value = 1988; + trampoline = [&](Dart_Handle handle) { + ASSERT_EQ(tonic::DartConverter::FromDart(handle), 1988); + event.Signal(); + }; + ASSERT_EQ(FlutterEnginePostDartObject(engine.get(), port, &object), + kSuccess); + event.Wait(); + } + + // Check int64. + { + FlutterEngineDartObject object = {}; + object.type = kFlutterEngineDartObjectTypeInt64; + object.int64_value = 1988; + trampoline = [&](Dart_Handle handle) { + ASSERT_EQ(tonic::DartConverter::FromDart(handle), 1988); + event.Signal(); + }; + ASSERT_EQ(FlutterEnginePostDartObject(engine.get(), port, &object), + kSuccess); + event.Wait(); + } + + // Check double. + { + FlutterEngineDartObject object = {}; + object.type = kFlutterEngineDartObjectTypeDouble; + object.double_value = 1988.0; + trampoline = [&](Dart_Handle handle) { + ASSERT_DOUBLE_EQ(tonic::DartConverter::FromDart(handle), 1988.0); + event.Signal(); + }; + ASSERT_EQ(FlutterEnginePostDartObject(engine.get(), port, &object), + kSuccess); + event.Wait(); + } + + // Check string. + { + const char* message = "Hello. My name is Inigo Montoya."; + FlutterEngineDartObject object = {}; + object.type = kFlutterEngineDartObjectTypeString; + object.string_value = message; + trampoline = [&](Dart_Handle handle) { + ASSERT_EQ(tonic::DartConverter::FromDart(handle), + std::string{message}); + event.Signal(); + }; + ASSERT_EQ(FlutterEnginePostDartObject(engine.get(), port, &object), + kSuccess); + event.Wait(); + } + + // Check buffer (copied out). + { + std::vector message; + message.resize(1988); + + ASSERT_TRUE(MemsetPatternSetOrCheck( + message, MemsetPatternOp::kMemsetPatternOpSetBuffer)); + + FlutterEngineDartBuffer buffer = {}; + + buffer.struct_size = sizeof(buffer); + buffer.user_data = nullptr; + buffer.buffer_collect_callback = nullptr; + buffer.buffer = message.data(); + buffer.buffer_size = message.size(); + + FlutterEngineDartObject object = {}; + object.type = kFlutterEngineDartObjectTypeBuffer; + object.buffer_value = &buffer; + trampoline = [&](Dart_Handle handle) { + intptr_t length = 0; + Dart_ListLength(handle, &length); + ASSERT_EQ(length, 1988); + // TODO(chinmaygarde); The std::vector specialization for + // DartConvertor in tonic is broken which is preventing the buffer + // being checked here. Fix tonic and strengthen this check. For now, just + // the buffer length is checked. + event.Signal(); + }; + ASSERT_EQ(FlutterEnginePostDartObject(engine.get(), port, &object), + kSuccess); + event.Wait(); + } + + std::vector message; + fml::AutoResetWaitableEvent buffer_released_latch; + + // Check buffer (caller own buffer with zero copy transfer). + { + message.resize(1988); + + ASSERT_TRUE(MemsetPatternSetOrCheck( + message, MemsetPatternOp::kMemsetPatternOpSetBuffer)); + + FlutterEngineDartBuffer buffer = {}; + + buffer.struct_size = sizeof(buffer); + buffer.user_data = &buffer_released_latch; + buffer.buffer_collect_callback = +[](void* user_data) { + reinterpret_cast(user_data)->Signal(); + }; + buffer.buffer = message.data(); + buffer.buffer_size = message.size(); + + FlutterEngineDartObject object = {}; + object.type = kFlutterEngineDartObjectTypeBuffer; + object.buffer_value = &buffer; + trampoline = [&](Dart_Handle handle) { + intptr_t length = 0; + Dart_ListLength(handle, &length); + ASSERT_EQ(length, 1988); + // TODO(chinmaygarde); The std::vector specialization for + // DartConvertor in tonic is broken which is preventing the buffer + // being checked here. Fix tonic and strengthen this check. For now, just + // the buffer length is checked. + event.Signal(); + }; + ASSERT_EQ(FlutterEnginePostDartObject(engine.get(), port, &object), + kSuccess); + event.Wait(); + } + + engine.reset(); + + // We cannot determine when the VM will GC objects that might have external + // typed data finalizers. Since we need to ensure that we correctly wired up + // finalizers from the embedders, we force the VM to collect all objects but + // just shutting it down. + buffer_released_latch.Wait(); +} + +TEST_F(EmbedderTest, CompositorCanPostZeroLayersForPresentation) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(300, 200)); + builder.SetCompositor(); + builder.SetDartEntrypoint("empty_scene_posts_zero_layers_to_compositor"); + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); + + fml::AutoResetWaitableEvent latch; + + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 0u); + latch.Signal(); + }); + + auto engine = builder.LaunchEngine(); + + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 300; + event.height = 200; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + latch.Wait(); + + ASSERT_EQ(context.GetCompositor().GetPendingBackingStoresCount(), 0u); +} + +TEST_F(EmbedderTest, CompositorCanPostOnlyPlatformViews) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(300, 200)); + builder.SetCompositor(); + builder.SetDartEntrypoint("compositor_can_post_only_platform_views"); + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); + + fml::AutoResetWaitableEvent latch; + + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 2u); + + // Layer 0 + { + FlutterPlatformView platform_view = *layers[0]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 42; + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(300.0, 200.0); + layer.offset = FlutterPointMake(0.0, 0.0); + + ASSERT_EQ(*layers[0], layer); + } + + // Layer 1 + { + FlutterPlatformView platform_view = *layers[1]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 24; + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(300.0, 200.0); + layer.offset = FlutterPointMake(0.0, 0.0); + + ASSERT_EQ(*layers[1], layer); + } + latch.Signal(); + }); + + auto engine = builder.LaunchEngine(); + + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 300; + event.height = 200; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + latch.Wait(); + + ASSERT_EQ(context.GetCompositor().GetPendingBackingStoresCount(), 0u); +} + +TEST_F(EmbedderTest, CompositorRenderTargetsAreRecycled) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(300, 200)); + builder.SetCompositor(); + builder.SetDartEntrypoint("render_targets_are_recycled"); + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); + + fml::CountDownLatch latch(2); + + context.AddNativeCallback("SignalNativeTest", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + latch.CountDown(); + })); + + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 20u); + latch.CountDown(); + }); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 300; + event.height = 200; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + + latch.Wait(); + ASSERT_EQ(context.GetCompositor().GetPendingBackingStoresCount(), 10u); + ASSERT_EQ(context.GetCompositor().GetBackingStoresCreatedCount(), 10u); + ASSERT_EQ(context.GetCompositor().GetBackingStoresCollectedCount(), 0u); + // Killing the engine should immediately collect all pending render targets. + engine.reset(); + ASSERT_EQ(context.GetCompositor().GetPendingBackingStoresCount(), 0u); + ASSERT_EQ(context.GetCompositor().GetBackingStoresCreatedCount(), 10u); + ASSERT_EQ(context.GetCompositor().GetBackingStoresCollectedCount(), 10u); +} + +TEST_F(EmbedderTest, CompositorRenderTargetsAreInStableOrder) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(300, 200)); + builder.SetCompositor(); + builder.SetDartEntrypoint("render_targets_are_in_stable_order"); + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); + + fml::CountDownLatch latch(2); + + context.AddNativeCallback("SignalNativeTest", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + latch.CountDown(); + })); + + size_t frame_count = 0; + std::vector first_frame_backing_store_user_data; + context.GetCompositor().SetPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 20u); + + if (first_frame_backing_store_user_data.empty()) { + for (size_t i = 0; i < layers_count; ++i) { + if (layers[i]->type == kFlutterLayerContentTypeBackingStore) { + first_frame_backing_store_user_data.push_back( + layers[i]->backing_store->user_data); + } + } + return; + } + + ASSERT_EQ(first_frame_backing_store_user_data.size(), 10u); + + frame_count++; + std::vector backing_store_user_data; + for (size_t i = 0; i < layers_count; ++i) { + if (layers[i]->type == kFlutterLayerContentTypeBackingStore) { + backing_store_user_data.push_back( + layers[i]->backing_store->user_data); + } + } + + ASSERT_EQ(backing_store_user_data.size(), 10u); + + ASSERT_EQ(first_frame_backing_store_user_data, backing_store_user_data); + + if (frame_count == 20) { + latch.CountDown(); + } + }, + false // one shot + ); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 300; + event.height = 200; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + + latch.Wait(); +} + +TEST_F(EmbedderTest, FrameInfoContainsValidWidthAndHeight) { + auto& context = GetEmbedderContext(); + const auto root_surface_transformation = + SkMatrix().preTranslate(0, 1024).preRotate(-90, 0, 0); + context.SetRootSurfaceTransformation(root_surface_transformation); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(600, 1024)); + builder.SetDartEntrypoint("push_frames_over_and_over"); + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + static FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 1024; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + + static fml::CountDownLatch frame_latch(10); + + context.AddNativeCallback("SignalNativeTest", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + /* Nothing to do. */ + })); + + context.SetGLGetFBOCallback([](FlutterFrameInfo frame_info) { + // width and height are rotated by 90 deg + ASSERT_EQ(frame_info.size.width, event.height); + ASSERT_EQ(frame_info.size.height, event.width); + + frame_latch.CountDown(); + }); + + frame_latch.Wait(); +} + +TEST_F(EmbedderTest, MustNotRunWithBothFBOCallbacksSet) { + auto& context = GetEmbedderContext(); + context.SetOpenGLFBOCallBack(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(600, 1024)); + + auto engine = builder.LaunchEngine(); + ASSERT_FALSE(engine.is_valid()); +} + +TEST_F(EmbedderTest, MustNotRunWithBothPresentCallbacksSet) { + auto& context = GetEmbedderContext(); + context.SetOpenGLPresentCallBack(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(600, 1024)); + + auto engine = builder.LaunchEngine(); + ASSERT_FALSE(engine.is_valid()); +} + +TEST_F(EmbedderTest, MustStillRunWhenPopulateExistingDamageIsNotProvided) { + auto& context = GetEmbedderContext(); + context.GetRendererConfig().open_gl.populate_existing_damage = nullptr; + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); +} + +TEST_F(EmbedderTest, MustRunWhenPopulateExistingDamageIsProvided) { + auto& context = GetEmbedderContext(); + context.GetRendererConfig().open_gl.populate_existing_damage = + [](void* context, const intptr_t id, + FlutterDamage* existing_damage) -> void { + return reinterpret_cast(context) + ->GLPopulateExistingDamage(id, existing_damage); + }; + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); +} + +TEST_F(EmbedderTest, MustRunWithPopulateExistingDamageAndFBOCallback) { + auto& context = GetEmbedderContext(); + context.GetRendererConfig().open_gl.fbo_callback = + [](void* context) -> uint32_t { return 0; }; + context.GetRendererConfig().open_gl.fbo_with_frame_info_callback = nullptr; + context.GetRendererConfig().open_gl.populate_existing_damage = + [](void* context, const intptr_t id, + FlutterDamage* existing_damage) -> void { + return reinterpret_cast(context) + ->GLPopulateExistingDamage(id, existing_damage); + }; + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); +} + +TEST_F(EmbedderTest, + MustNotRunWhenPopulateExistingDamageButNoOtherFBOCallback) { + auto& context = GetEmbedderContext(); + context.GetRendererConfig().open_gl.fbo_callback = nullptr; + context.GetRendererConfig().open_gl.fbo_with_frame_info_callback = nullptr; + context.GetRendererConfig().open_gl.populate_existing_damage = + [](void* context, const intptr_t id, + FlutterDamage* existing_damage) -> void { + return reinterpret_cast(context) + ->GLPopulateExistingDamage(id, existing_damage); + }; + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + auto engine = builder.LaunchEngine(); + ASSERT_FALSE(engine.is_valid()); +} + +TEST_F(EmbedderTest, PresentInfoContainsValidFBOId) { + auto& context = GetEmbedderContext(); + const auto root_surface_transformation = + SkMatrix().preTranslate(0, 1024).preRotate(-90, 0, 0); + context.SetRootSurfaceTransformation(root_surface_transformation); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(600, 1024)); + builder.SetDartEntrypoint("push_frames_over_and_over"); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 1024; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + + static fml::CountDownLatch frame_latch(10); + + context.AddNativeCallback("SignalNativeTest", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + /* Nothing to do. */ + })); + + const uint32_t window_fbo_id = context.GetWindowFBOId(); + context.SetGLPresentCallback( + [window_fbo_id = window_fbo_id](FlutterPresentInfo present_info) { + ASSERT_EQ(present_info.fbo_id, window_fbo_id); + + frame_latch.CountDown(); + }); + + frame_latch.Wait(); +} + +TEST_F(EmbedderTest, + PresentInfoReceivesFullDamageWhenExistingDamageIsWholeScreen) { + auto& context = GetEmbedderContext(); + context.GetRendererConfig().open_gl.populate_existing_damage = + [](void* context, const intptr_t id, + FlutterDamage* existing_damage) -> void { + return reinterpret_cast(context) + ->GLPopulateExistingDamage(id, existing_damage); + }; + // Return existing damage as the entire screen on purpose. + context.SetGLPopulateExistingDamageCallback( + [](const intptr_t id, FlutterDamage* existing_damage_ptr) { + const size_t num_rects = 1; + // The array must be valid after the callback returns. + static FlutterRect existing_damage_rects[num_rects] = { + FlutterRect{0, 0, 800, 600}}; + existing_damage_ptr->num_rects = num_rects; + existing_damage_ptr->damage = existing_damage_rects; + }); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetDartEntrypoint("render_gradient_retained"); + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + fml::AutoResetWaitableEvent latch; + + // First frame should be entirely rerendered. + context.SetGLPresentCallback([&](FlutterPresentInfo present_info) { + const size_t num_rects = 1; + ASSERT_EQ(present_info.frame_damage.num_rects, num_rects); + ASSERT_EQ(present_info.frame_damage.damage->left, 0); + ASSERT_EQ(present_info.frame_damage.damage->top, 0); + ASSERT_EQ(present_info.frame_damage.damage->right, 800); + ASSERT_EQ(present_info.frame_damage.damage->bottom, 600); + + ASSERT_EQ(present_info.buffer_damage.num_rects, num_rects); + ASSERT_EQ(present_info.buffer_damage.damage->left, 0); + ASSERT_EQ(present_info.buffer_damage.damage->top, 0); + ASSERT_EQ(present_info.buffer_damage.damage->right, 800); + ASSERT_EQ(present_info.buffer_damage.damage->bottom, 600); + + latch.Signal(); + }); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + latch.Wait(); + + // Because it's the same as the first frame, the second frame damage should + // be empty but, because there was a full existing buffer damage, the buffer + // damage should be the entire screen. + context.SetGLPresentCallback([&](FlutterPresentInfo present_info) { + const size_t num_rects = 1; + ASSERT_EQ(present_info.frame_damage.num_rects, num_rects); + ASSERT_EQ(present_info.frame_damage.damage->left, 0); + ASSERT_EQ(present_info.frame_damage.damage->top, 0); + ASSERT_EQ(present_info.frame_damage.damage->right, 0); + ASSERT_EQ(present_info.frame_damage.damage->bottom, 0); + + ASSERT_EQ(present_info.buffer_damage.num_rects, num_rects); + ASSERT_EQ(present_info.buffer_damage.damage->left, 0); + ASSERT_EQ(present_info.buffer_damage.damage->top, 0); + ASSERT_EQ(present_info.buffer_damage.damage->right, 800); + ASSERT_EQ(present_info.buffer_damage.damage->bottom, 600); + + latch.Signal(); + }); + + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + latch.Wait(); +} + +TEST_F(EmbedderTest, PresentInfoReceivesEmptyDamage) { + auto& context = GetEmbedderContext(); + context.GetRendererConfig().open_gl.populate_existing_damage = + [](void* context, const intptr_t id, + FlutterDamage* existing_damage) -> void { + return reinterpret_cast(context) + ->GLPopulateExistingDamage(id, existing_damage); + }; + // Return no existing damage on purpose. + context.SetGLPopulateExistingDamageCallback( + [](const intptr_t id, FlutterDamage* existing_damage_ptr) { + const size_t num_rects = 1; + // The array must be valid after the callback returns. + static FlutterRect existing_damage_rects[num_rects] = { + FlutterRect{0, 0, 0, 0}}; + existing_damage_ptr->num_rects = num_rects; + existing_damage_ptr->damage = existing_damage_rects; + }); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetDartEntrypoint("render_gradient_retained"); + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + fml::AutoResetWaitableEvent latch; + + // First frame should be entirely rerendered. + context.SetGLPresentCallback([&](FlutterPresentInfo present_info) { + const size_t num_rects = 1; + ASSERT_EQ(present_info.frame_damage.num_rects, num_rects); + ASSERT_EQ(present_info.frame_damage.damage->left, 0); + ASSERT_EQ(present_info.frame_damage.damage->top, 0); + ASSERT_EQ(present_info.frame_damage.damage->right, 800); + ASSERT_EQ(present_info.frame_damage.damage->bottom, 600); + + ASSERT_EQ(present_info.buffer_damage.num_rects, num_rects); + ASSERT_EQ(present_info.buffer_damage.damage->left, 0); + ASSERT_EQ(present_info.buffer_damage.damage->top, 0); + ASSERT_EQ(present_info.buffer_damage.damage->right, 800); + ASSERT_EQ(present_info.buffer_damage.damage->bottom, 600); + + latch.Signal(); + }); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + latch.Wait(); + + // Because it's the same as the first frame, the second frame should not be + // rerendered assuming there is no existing damage. + context.SetGLPresentCallback([&](FlutterPresentInfo present_info) { + const size_t num_rects = 1; + ASSERT_EQ(present_info.frame_damage.num_rects, num_rects); + ASSERT_EQ(present_info.frame_damage.damage->left, 0); + ASSERT_EQ(present_info.frame_damage.damage->top, 0); + ASSERT_EQ(present_info.frame_damage.damage->right, 0); + ASSERT_EQ(present_info.frame_damage.damage->bottom, 0); + + ASSERT_EQ(present_info.buffer_damage.num_rects, num_rects); + ASSERT_EQ(present_info.buffer_damage.damage->left, 0); + ASSERT_EQ(present_info.buffer_damage.damage->top, 0); + ASSERT_EQ(present_info.buffer_damage.damage->right, 0); + ASSERT_EQ(present_info.buffer_damage.damage->bottom, 0); + + latch.Signal(); + }); + + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + latch.Wait(); +} + +TEST_F(EmbedderTest, PresentInfoReceivesPartialDamage) { + auto& context = GetEmbedderContext(); + context.GetRendererConfig().open_gl.populate_existing_damage = + [](void* context, const intptr_t id, + FlutterDamage* existing_damage) -> void { + return reinterpret_cast(context) + ->GLPopulateExistingDamage(id, existing_damage); + }; + // Return existing damage as only part of the screen on purpose. + context.SetGLPopulateExistingDamageCallback( + [&](const intptr_t id, FlutterDamage* existing_damage_ptr) { + const size_t num_rects = 1; + // The array must be valid after the callback returns. + static FlutterRect existing_damage_rects[num_rects] = { + FlutterRect{200, 150, 400, 300}}; + existing_damage_ptr->num_rects = num_rects; + existing_damage_ptr->damage = existing_damage_rects; + }); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetDartEntrypoint("render_gradient_retained"); + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + fml::AutoResetWaitableEvent latch; + + // First frame should be entirely rerendered. + context.SetGLPresentCallback([&](FlutterPresentInfo present_info) { + const size_t num_rects = 1; + ASSERT_EQ(present_info.frame_damage.num_rects, num_rects); + ASSERT_EQ(present_info.frame_damage.damage->left, 0); + ASSERT_EQ(present_info.frame_damage.damage->top, 0); + ASSERT_EQ(present_info.frame_damage.damage->right, 800); + ASSERT_EQ(present_info.frame_damage.damage->bottom, 600); + + ASSERT_EQ(present_info.buffer_damage.num_rects, num_rects); + ASSERT_EQ(present_info.buffer_damage.damage->left, 0); + ASSERT_EQ(present_info.buffer_damage.damage->top, 0); + ASSERT_EQ(present_info.buffer_damage.damage->right, 800); + ASSERT_EQ(present_info.buffer_damage.damage->bottom, 600); + + latch.Signal(); + }); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + latch.Wait(); + + // Because it's the same as the first frame, the second frame damage should be + // empty but, because there was a partial existing damage, the buffer damage + // should represent that partial damage area. + context.SetGLPresentCallback([&](FlutterPresentInfo present_info) { + const size_t num_rects = 1; + ASSERT_EQ(present_info.frame_damage.num_rects, num_rects); + ASSERT_EQ(present_info.frame_damage.damage->left, 0); + ASSERT_EQ(present_info.frame_damage.damage->top, 0); + ASSERT_EQ(present_info.frame_damage.damage->right, 0); + ASSERT_EQ(present_info.frame_damage.damage->bottom, 0); + + ASSERT_EQ(present_info.buffer_damage.num_rects, num_rects); + ASSERT_EQ(present_info.buffer_damage.damage->left, 200); + ASSERT_EQ(present_info.buffer_damage.damage->top, 150); + ASSERT_EQ(present_info.buffer_damage.damage->right, 400); + ASSERT_EQ(present_info.buffer_damage.damage->bottom, 300); + + latch.Signal(); + }); + + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + latch.Wait(); +} + +TEST_F(EmbedderTest, PopulateExistingDamageReceivesValidID) { + auto& context = GetEmbedderContext(); + context.GetRendererConfig().open_gl.populate_existing_damage = + [](void* context, const intptr_t id, + FlutterDamage* existing_damage) -> void { + return reinterpret_cast(context) + ->GLPopulateExistingDamage(id, existing_damage); + }; + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetDartEntrypoint("render_gradient_retained"); + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + const uint32_t window_fbo_id = context.GetWindowFBOId(); + context.SetGLPopulateExistingDamageCallback( + [window_fbo_id = window_fbo_id](intptr_t id, + FlutterDamage* existing_damage) { + ASSERT_EQ(id, window_fbo_id); + existing_damage->num_rects = 0; + existing_damage->damage = nullptr; + }); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); +} + +TEST_F(EmbedderTest, PopulateExistingDamageReceivesInvalidID) { + auto& context = GetEmbedderContext(); + context.GetRendererConfig().open_gl.populate_existing_damage = + [](void* context, const intptr_t id, + FlutterDamage* existing_damage) -> void { + return reinterpret_cast(context) + ->GLPopulateExistingDamage(id, existing_damage); + }; + // Return a bad FBO ID on purpose. + context.GetRendererConfig().open_gl.fbo_with_frame_info_callback = + [](void* context, const FlutterFrameInfo* frame_info) -> uint32_t { + return 123; + }; + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetDartEntrypoint("render_gradient_retained"); + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + context.AddNativeCallback("SignalNativeTest", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + /* Nothing to do. */ + })); + + const uint32_t window_fbo_id = context.GetWindowFBOId(); + context.SetGLPopulateExistingDamageCallback( + [window_fbo_id = window_fbo_id](intptr_t id, + FlutterDamage* existing_damage) { + ASSERT_NE(id, window_fbo_id); + existing_damage->num_rects = 0; + existing_damage->damage = nullptr; + }); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); +} + +TEST_F(EmbedderTest, SetSingleDisplayConfigurationWithDisplayId) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("empty_scene"); + fml::AutoResetWaitableEvent latch; + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch.Signal(); })); + + auto engine = builder.LaunchEngine(); + + ASSERT_TRUE(engine.is_valid()); + + FlutterEngineDisplay display; + display.struct_size = sizeof(FlutterEngineDisplay); + display.display_id = 1; + display.refresh_rate = 20; + + std::vector displays = {display}; + + const FlutterEngineResult result = FlutterEngineNotifyDisplayUpdate( + engine.get(), kFlutterEngineDisplaysUpdateTypeStartup, displays.data(), + displays.size()); + ASSERT_EQ(result, kSuccess); + + flutter::Shell& shell = ToEmbedderEngine(engine.get())->GetShell(); + ASSERT_EQ(shell.GetMainDisplayRefreshRate(), display.refresh_rate); + + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + + latch.Wait(); +} + +TEST_F(EmbedderTest, SetSingleDisplayConfigurationWithoutDisplayId) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("empty_scene"); + fml::AutoResetWaitableEvent latch; + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch.Signal(); })); + + auto engine = builder.LaunchEngine(); + + ASSERT_TRUE(engine.is_valid()); + + FlutterEngineDisplay display; + display.struct_size = sizeof(FlutterEngineDisplay); + display.single_display = true; + display.refresh_rate = 20; + + std::vector displays = {display}; + + const FlutterEngineResult result = FlutterEngineNotifyDisplayUpdate( + engine.get(), kFlutterEngineDisplaysUpdateTypeStartup, displays.data(), + displays.size()); + ASSERT_EQ(result, kSuccess); + + flutter::Shell& shell = ToEmbedderEngine(engine.get())->GetShell(); + ASSERT_EQ(shell.GetMainDisplayRefreshRate(), display.refresh_rate); + + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + + latch.Wait(); +} + +TEST_F(EmbedderTest, SetValidMultiDisplayConfiguration) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("empty_scene"); + fml::AutoResetWaitableEvent latch; + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch.Signal(); })); + + auto engine = builder.LaunchEngine(); + + ASSERT_TRUE(engine.is_valid()); + + FlutterEngineDisplay display_1; + display_1.struct_size = sizeof(FlutterEngineDisplay); + display_1.display_id = 1; + display_1.single_display = false; + display_1.refresh_rate = 20; + + FlutterEngineDisplay display_2; + display_2.struct_size = sizeof(FlutterEngineDisplay); + display_2.display_id = 2; + display_2.single_display = false; + display_2.refresh_rate = 60; + + std::vector displays = {display_1, display_2}; + + const FlutterEngineResult result = FlutterEngineNotifyDisplayUpdate( + engine.get(), kFlutterEngineDisplaysUpdateTypeStartup, displays.data(), + displays.size()); + ASSERT_EQ(result, kSuccess); + + flutter::Shell& shell = ToEmbedderEngine(engine.get())->GetShell(); + ASSERT_EQ(shell.GetMainDisplayRefreshRate(), display_1.refresh_rate); + + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + + latch.Wait(); +} + +TEST_F(EmbedderTest, MultipleDisplaysWithSingleDisplayTrueIsInvalid) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("empty_scene"); + fml::AutoResetWaitableEvent latch; + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch.Signal(); })); + + auto engine = builder.LaunchEngine(); + + ASSERT_TRUE(engine.is_valid()); + + FlutterEngineDisplay display_1; + display_1.struct_size = sizeof(FlutterEngineDisplay); + display_1.display_id = 1; + display_1.single_display = true; + display_1.refresh_rate = 20; + + FlutterEngineDisplay display_2; + display_2.struct_size = sizeof(FlutterEngineDisplay); + display_2.display_id = 2; + display_2.single_display = true; + display_2.refresh_rate = 60; + + std::vector displays = {display_1, display_2}; + + const FlutterEngineResult result = FlutterEngineNotifyDisplayUpdate( + engine.get(), kFlutterEngineDisplaysUpdateTypeStartup, displays.data(), + displays.size()); + ASSERT_NE(result, kSuccess); + + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + + latch.Wait(); +} + +TEST_F(EmbedderTest, MultipleDisplaysWithSameDisplayIdIsInvalid) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("empty_scene"); + fml::AutoResetWaitableEvent latch; + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch.Signal(); })); + + auto engine = builder.LaunchEngine(); + + ASSERT_TRUE(engine.is_valid()); + + FlutterEngineDisplay display_1; + display_1.struct_size = sizeof(FlutterEngineDisplay); + display_1.display_id = 1; + display_1.single_display = false; + display_1.refresh_rate = 20; + + FlutterEngineDisplay display_2; + display_2.struct_size = sizeof(FlutterEngineDisplay); + display_2.display_id = 1; + display_2.single_display = false; + display_2.refresh_rate = 60; + + std::vector displays = {display_1, display_2}; + + const FlutterEngineResult result = FlutterEngineNotifyDisplayUpdate( + engine.get(), kFlutterEngineDisplaysUpdateTypeStartup, displays.data(), + displays.size()); + ASSERT_NE(result, kSuccess); + + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + + latch.Wait(); +} + +TEST_F(EmbedderTest, CompositorRenderTargetsNotRecycledWhenAvoidsCacheSet) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(300, 200)); + builder.SetCompositor(/*avoid_backing_store_cache=*/true); + builder.SetDartEntrypoint("render_targets_are_recycled"); + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); + + const unsigned num_frames = 8; + const unsigned num_engine_layers = 10; + const unsigned num_backing_stores = num_frames * num_engine_layers; + fml::CountDownLatch latch(1 + num_frames); // 1 for native test signal. + + context.AddNativeCallback("SignalNativeTest", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + latch.CountDown(); + })); + + context.GetCompositor().SetPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 20u); + latch.CountDown(); + }, + /*one_shot=*/false); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 300; + event.height = 200; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + + latch.Wait(); + + ASSERT_EQ(context.GetCompositor().GetBackingStoresCreatedCount(), + num_backing_stores); + // Killing the engine should collect all the frames. + engine.reset(); + ASSERT_EQ(context.GetCompositor().GetPendingBackingStoresCount(), 0u); +} + +TEST_F(EmbedderTest, SnapshotRenderTargetScalesDownToDriverMax) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + + auto max_size = context.GetCompositor().GetGrContext()->maxRenderTargetSize(); + + context.AddIsolateCreateCallback([&]() { + Dart_Handle snapshot_large_scene = Dart_GetField( + Dart_RootLibrary(), tonic::ToDart("snapshot_large_scene")); + tonic::DartInvoke(snapshot_large_scene, {tonic::ToDart(max_size)}); + }); + + fml::AutoResetWaitableEvent latch; + context.AddNativeCallback( + "SnapshotsCallback", CREATE_NATIVE_ENTRY(([&](Dart_NativeArguments args) { + auto get_arg = [&args](int index) { + Dart_Handle dart_image = Dart_GetNativeArgument(args, index); + Dart_Handle internal_image = + Dart_GetField(dart_image, tonic::ToDart("_image")); + return tonic::DartConverter::FromDart( + internal_image); + }; + + CanvasImage* big_image = get_arg(0); + ASSERT_EQ(big_image->width(), max_size); + ASSERT_EQ(big_image->height(), max_size / 2); + + CanvasImage* small_image = get_arg(1); + ASSERT_TRUE(ImageMatchesFixture("snapshot_large_scene.png", + small_image->image()->skia_image())); + + latch.Signal(); + }))); + + UniqueEngine engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + latch.Wait(); +} + +TEST_F(EmbedderTest, ObjectsPostedViaPortsServicedOnSecondaryTaskHeap) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 1024)); + builder.SetDartEntrypoint("objects_can_be_posted"); + + // Synchronously acquire the send port from the Dart end. We will be using + // this to send message. The Dart end will just echo those messages back to us + // for inspection. + FlutterEngineDartPort port = 0; + fml::AutoResetWaitableEvent event; + context.AddNativeCallback("SignalNativeCount", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + port = tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + event.Signal(); + })); + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + event.Wait(); + ASSERT_NE(port, 0); + + using Trampoline = std::function; + Trampoline trampoline; + + context.AddNativeCallback("SendObjectToNativeCode", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + FML_CHECK(trampoline); + auto trampoline_copy = trampoline; + trampoline = nullptr; + trampoline_copy(Dart_GetNativeArgument(args, 0)); + })); + + // Send a boolean value and assert that it's received by the right heap. + { + FlutterEngineDartObject object = {}; + object.type = kFlutterEngineDartObjectTypeBool; + object.bool_value = true; + trampoline = [&](Dart_Handle handle) { + ASSERT_TRUE(tonic::DartConverter::FromDart(handle)); + auto task_grade = fml::MessageLoopTaskQueues::GetCurrentTaskSourceGrade(); + EXPECT_EQ(task_grade, fml::TaskSourceGrade::kDartEventLoop); + event.Signal(); + }; + ASSERT_EQ(FlutterEnginePostDartObject(engine.get(), port, &object), + kSuccess); + event.Wait(); + } +} + +TEST_F(EmbedderTest, CreateInvalidBackingstoreOpenGLTexture) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture); + builder.SetDartEntrypoint("invalid_backingstore"); + + class TestCollectOnce { + public: + // Collect() should only be called once + void Collect() { + ASSERT_FALSE(collected_); + collected_ = true; + } + + private: + bool collected_ = false; + }; + fml::AutoResetWaitableEvent latch; + + builder.GetCompositor().create_backing_store_callback = + [](const FlutterBackingStoreConfig* config, // + FlutterBackingStore* backing_store_out, // + void* user_data // + ) { + backing_store_out->type = kFlutterBackingStoreTypeOpenGL; + // Deliberately set this to be invalid + backing_store_out->user_data = nullptr; + backing_store_out->open_gl.type = kFlutterOpenGLTargetTypeTexture; + backing_store_out->open_gl.texture.target = 0; + backing_store_out->open_gl.texture.name = 0; + backing_store_out->open_gl.texture.format = 0; + static TestCollectOnce collect_once_user_data; + collect_once_user_data = {}; + backing_store_out->open_gl.texture.user_data = &collect_once_user_data; + backing_store_out->open_gl.texture.destruction_callback = + [](void* user_data) { + reinterpret_cast(user_data)->Collect(); + }; + return true; + }; + + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&latch](Dart_NativeArguments args) { latch.Signal(); })); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + latch.Wait(); +} + +TEST_F(EmbedderTest, CreateInvalidBackingstoreOpenGLFramebuffer) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer); + builder.SetDartEntrypoint("invalid_backingstore"); + + class TestCollectOnce { + public: + // Collect() should only be called once + void Collect() { + ASSERT_FALSE(collected_); + collected_ = true; + } + + private: + bool collected_ = false; + }; + fml::AutoResetWaitableEvent latch; + + builder.GetCompositor().create_backing_store_callback = + [](const FlutterBackingStoreConfig* config, // + FlutterBackingStore* backing_store_out, // + void* user_data // + ) { + backing_store_out->type = kFlutterBackingStoreTypeOpenGL; + // Deliberately set this to be invalid + backing_store_out->user_data = nullptr; + backing_store_out->open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; + backing_store_out->open_gl.framebuffer.target = 0; + backing_store_out->open_gl.framebuffer.name = 0; + static TestCollectOnce collect_once_user_data; + collect_once_user_data = {}; + backing_store_out->open_gl.framebuffer.user_data = + &collect_once_user_data; + backing_store_out->open_gl.framebuffer.destruction_callback = + [](void* user_data) { + reinterpret_cast(user_data)->Collect(); + }; + return true; + }; + + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&latch](Dart_NativeArguments args) { latch.Signal(); })); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + latch.Wait(); +} + +TEST_F(EmbedderTest, CreateInvalidBackingstoreOpenGLSurface) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLSurface); + builder.SetDartEntrypoint("invalid_backingstore"); + + fml::AutoResetWaitableEvent latch; + + builder.GetCompositor().create_backing_store_callback = + [](const FlutterBackingStoreConfig* config, // + FlutterBackingStore* backing_store_out, // + void* user_data // + ) { + backing_store_out->type = kFlutterBackingStoreTypeOpenGL; + backing_store_out->user_data = user_data; + backing_store_out->open_gl.type = kFlutterOpenGLTargetTypeSurface; + backing_store_out->open_gl.surface.user_data = user_data; + // Deliberately set this to an invalid format + backing_store_out->open_gl.surface.format = 0; + backing_store_out->open_gl.surface.make_current_callback = [](void*, + bool*) { + ADD_FAILURE() << "make_current_callback method should not be called"; + return true; + }; + backing_store_out->open_gl.surface.clear_current_callback = [](void*, + bool*) { + ADD_FAILURE() << "clear_current_callback method should not be called"; + return true; + }; + backing_store_out->open_gl.surface.destruction_callback = + [](void* user_data) { + FAIL() << "destruction_callback method should not be called"; + }; + + return true; + }; + + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&latch](Dart_NativeArguments args) { latch.Signal(); })); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + latch.Wait(); +} + +TEST_F(EmbedderTest, ExternalTextureGLRefreshedTooOften) { + TestGLSurface surface(SkISize::Make(100, 100)); + auto context = surface.GetGrContext(); + + typedef void (*glGenTexturesProc)(uint32_t n, uint32_t* textures); + typedef void (*glFinishProc)(); + + glGenTexturesProc glGenTextures; + glFinishProc glFinish; + + glGenTextures = reinterpret_cast( + surface.GetProcAddress("glGenTextures")); + glFinish = reinterpret_cast(surface.GetProcAddress("glFinish")); + + uint32_t name; + glGenTextures(1, &name); + + bool resolve_called = false; + + EmbedderExternalTextureGL::ExternalTextureCallback callback( + [&](int64_t, size_t, size_t) { + resolve_called = true; + auto res = std::make_unique(); + res->target = GL_TEXTURE_2D; + res->name = name; + res->format = GL_RGBA8; + res->user_data = nullptr; + res->destruction_callback = [](void*) {}; + res->width = res->height = 100; + return res; + }); + EmbedderExternalTextureGL texture(1, callback); + + auto skia_surface = surface.GetOnscreenSurface(); + DlSkCanvasAdapter canvas(skia_surface->getCanvas()); + + Texture* texture_ = &texture; + Texture::PaintContext ctx{ + .canvas = &canvas, + .gr_context = context.get(), + }; + texture_->Paint(ctx, DlRect::MakeXYWH(0, 0, 100, 100), false, + DlImageSampling::kLinear); + + EXPECT_TRUE(resolve_called); + resolve_called = false; + + texture_->Paint(ctx, DlRect::MakeXYWH(0, 0, 100, 100), false, + DlImageSampling::kLinear); + + EXPECT_FALSE(resolve_called); + + texture_->MarkNewFrameAvailable(); + texture_->Paint(ctx, DlRect::MakeXYWH(0, 0, 100, 100), false, + DlImageSampling::kLinear); + + EXPECT_TRUE(resolve_called); + + glFinish(); +} + +TEST_F( + EmbedderTest, + PresentInfoReceivesFullScreenDamageWhenPopulateExistingDamageIsNotProvided) { + auto& context = GetEmbedderContext(); + context.GetRendererConfig().open_gl.populate_existing_damage = nullptr; + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetDartEntrypoint("render_gradient_retained"); + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + fml::AutoResetWaitableEvent latch; + + // First frame should be entirely rerendered. + context.SetGLPresentCallback([&](FlutterPresentInfo present_info) { + const size_t num_rects = 1; + ASSERT_EQ(present_info.frame_damage.num_rects, num_rects); + ASSERT_EQ(present_info.frame_damage.damage->left, 0); + ASSERT_EQ(present_info.frame_damage.damage->top, 0); + ASSERT_EQ(present_info.frame_damage.damage->right, 800); + ASSERT_EQ(present_info.frame_damage.damage->bottom, 600); + + ASSERT_EQ(present_info.buffer_damage.num_rects, num_rects); + ASSERT_EQ(present_info.buffer_damage.damage->left, 0); + ASSERT_EQ(present_info.buffer_damage.damage->top, 0); + ASSERT_EQ(present_info.buffer_damage.damage->right, 800); + ASSERT_EQ(present_info.buffer_damage.damage->bottom, 600); + + latch.Signal(); + }); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + latch.Wait(); + + // Since populate_existing_damage is not provided, the partial repaint + // functionality is actually disabled. So, the next frame should be entirely + // new frame. + context.SetGLPresentCallback([&](FlutterPresentInfo present_info) { + const size_t num_rects = 1; + ASSERT_EQ(present_info.frame_damage.num_rects, num_rects); + ASSERT_EQ(present_info.frame_damage.damage->left, 0); + ASSERT_EQ(present_info.frame_damage.damage->top, 0); + ASSERT_EQ(present_info.frame_damage.damage->right, 800); + ASSERT_EQ(present_info.frame_damage.damage->bottom, 600); + + ASSERT_EQ(present_info.buffer_damage.num_rects, num_rects); + ASSERT_EQ(present_info.buffer_damage.damage->left, 0); + ASSERT_EQ(present_info.buffer_damage.damage->top, 0); + ASSERT_EQ(present_info.buffer_damage.damage->right, 800); + ASSERT_EQ(present_info.buffer_damage.damage->bottom, 600); + + latch.Signal(); + }); + + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + latch.Wait(); +} + +TEST_F(EmbedderTest, + PresentInfoReceivesJoinedDamageWhenExistingDamageContainsMultipleRects) { + auto& context = GetEmbedderContext(); + context.GetRendererConfig().open_gl.populate_existing_damage = + [](void* context, const intptr_t id, + FlutterDamage* existing_damage) -> void { + return reinterpret_cast(context) + ->GLPopulateExistingDamage(id, existing_damage); + }; + // Return existing damage as the entire screen on purpose. + context.SetGLPopulateExistingDamageCallback( + [](const intptr_t id, FlutterDamage* existing_damage_ptr) { + const size_t num_rects = 2; + // The array must be valid after the callback returns. + static FlutterRect existing_damage_rects[num_rects] = { + FlutterRect{100, 150, 200, 250}, + FlutterRect{200, 250, 300, 350}, + }; + existing_damage_ptr->num_rects = num_rects; + existing_damage_ptr->damage = existing_damage_rects; + }); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetDartEntrypoint("render_gradient_retained"); + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + fml::AutoResetWaitableEvent latch; + + // First frame should be entirely rerendered. + context.SetGLPresentCallback([&](FlutterPresentInfo present_info) { + const size_t num_rects = 1; + ASSERT_EQ(present_info.frame_damage.num_rects, num_rects); + ASSERT_EQ(present_info.frame_damage.damage->left, 0); + ASSERT_EQ(present_info.frame_damage.damage->top, 0); + ASSERT_EQ(present_info.frame_damage.damage->right, 800); + ASSERT_EQ(present_info.frame_damage.damage->bottom, 600); + + ASSERT_EQ(present_info.buffer_damage.num_rects, num_rects); + ASSERT_EQ(present_info.buffer_damage.damage->left, 0); + ASSERT_EQ(present_info.buffer_damage.damage->top, 0); + ASSERT_EQ(present_info.buffer_damage.damage->right, 800); + ASSERT_EQ(present_info.buffer_damage.damage->bottom, 600); + + latch.Signal(); + }); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + latch.Wait(); + + // Because it's the same as the first frame, the second frame damage should + // be empty but, because there was a full existing buffer damage, the buffer + // damage should be the entire screen. + context.SetGLPresentCallback([&](FlutterPresentInfo present_info) { + const size_t num_rects = 1; + ASSERT_EQ(present_info.frame_damage.num_rects, num_rects); + ASSERT_EQ(present_info.frame_damage.damage->left, 0); + ASSERT_EQ(present_info.frame_damage.damage->top, 0); + ASSERT_EQ(present_info.frame_damage.damage->right, 0); + ASSERT_EQ(present_info.frame_damage.damage->bottom, 0); + + ASSERT_EQ(present_info.buffer_damage.num_rects, num_rects); + ASSERT_EQ(present_info.buffer_damage.damage->left, 100); + ASSERT_EQ(present_info.buffer_damage.damage->top, 150); + ASSERT_EQ(present_info.buffer_damage.damage->right, 300); + ASSERT_EQ(present_info.buffer_damage.damage->bottom, 350); + + latch.Signal(); + }); + + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + latch.Wait(); +} + +TEST_F(EmbedderTest, CanRenderWithImpellerOpenGL) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + + bool present_called = false; + context.SetGLPresentCallback( + [&present_called](FlutterPresentInfo present_info) { + present_called = true; + }); + + builder.AddCommandLineArgument("--enable-impeller"); + builder.SetDartEntrypoint("render_impeller_test"); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer); + + auto rendered_scene = context.GetNextSceneImage(); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // Bind to an arbitrary FBO in order to verify that Impeller binds to the + // provided FBO during rendering. + typedef void (*glGenFramebuffersProc)(GLsizei n, GLuint* ids); + typedef void (*glBindFramebufferProc)(GLenum target, GLuint framebuffer); + auto glGenFramebuffers = reinterpret_cast( + context.GLGetProcAddress("glGenFramebuffers")); + auto glBindFramebuffer = reinterpret_cast( + context.GLGetProcAddress("glBindFramebuffer")); + const flutter::Shell& shell = ToEmbedderEngine(engine.get())->GetShell(); + fml::AutoResetWaitableEvent raster_event; + shell.GetTaskRunners().GetRasterTaskRunner()->PostTask([&] { + GLuint fbo; + glGenFramebuffers(1, &fbo); + glBindFramebuffer(GL_FRAMEBUFFER, fbo); + raster_event.Signal(); + }); + raster_event.Wait(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + + ASSERT_TRUE(ImageMatchesFixture( + FixtureNameForBackend(EmbedderTestContextType::kOpenGLContext, + "impeller_test.png"), + rendered_scene)); + + // The scene will be rendered by the compositor, and the surface present + // callback should not be invoked. + ASSERT_FALSE(present_called); +} + +TEST_F(EmbedderTest, ImpellerOpenGLImageSnapshot) { + auto& context = GetEmbedderContext(); + + bool result = false; + fml::AutoResetWaitableEvent latch; + context.AddNativeCallback("NotifyBoolValue", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + result = tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + latch.Signal(); + })); + + EmbedderConfigBuilder builder(context); + builder.AddCommandLineArgument("--enable-impeller"); + builder.SetDartEntrypoint("render_impeller_image_snapshot_test"); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + latch.Wait(); + + ASSERT_TRUE(result); +} + +TEST_F(EmbedderTest, CompositorMustBeAbleToRenderToOpenGLSurface) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("can_composite_platform_views"); + + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLSurface); + + fml::CountDownLatch latch(3); + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 3u); + + { + FlutterBackingStore backing_store = *layers[0]->backing_store; + backing_store.struct_size = sizeof(backing_store); + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeSurface; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0, 0); + layer.backing_store_present_info = &present_info; + ASSERT_EQ(*layers[0], layer); + } + + { + FlutterPlatformView platform_view = *layers[1]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 42; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(123.0, 456.0); + layer.offset = FlutterPointMake(1.0, 2.0); + + ASSERT_EQ(*layers[1], layer); + } + + { + FlutterBackingStore backing_store = *layers[2]->backing_store; + backing_store.struct_size = sizeof(backing_store); + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeSurface; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(2, 3, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[2], layer); + } + + latch.CountDown(); + }); + + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&latch](Dart_NativeArguments args) { latch.CountDown(); })); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + + latch.Wait(); +} + +TEST_F(EmbedderTest, CompositorMustBeAbleToRenderKnownSceneToOpenGLSurfaces) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("can_composite_platform_views_with_known_scene"); + + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLSurface); + + fml::CountDownLatch latch(5); + + auto scene_image = context.GetNextSceneImage(); + + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 5u); + + // Layer Root + { + FlutterBackingStore backing_store = *layers[0]->backing_store; + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeSurface; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[0], layer); + } + + // Layer 1 + { + FlutterPlatformView platform_view = *layers[1]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 1; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(50.0, 150.0); + layer.offset = FlutterPointMake(20.0, 20.0); + + ASSERT_EQ(*layers[1], layer); + } + + // Layer 2 + { + FlutterBackingStore backing_store = *layers[2]->backing_store; + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeSurface; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(30, 30, 80, 180), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[2], layer); + } + + // Layer 3 + { + FlutterPlatformView platform_view = *layers[3]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 2; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(50.0, 150.0); + layer.offset = FlutterPointMake(40.0, 40.0); + + ASSERT_EQ(*layers[3], layer); + } + + // Layer 4 + { + FlutterBackingStore backing_store = *layers[4]->backing_store; + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.did_update = true; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeSurface; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(50, 50, 100, 200), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[4], layer); + } + + latch.CountDown(); + }); + + context.GetCompositor().SetPlatformViewRendererCallback( + [&](const FlutterLayer& layer, + GrDirectContext* context) -> sk_sp { + auto surface = CreateRenderSurface(layer, context); + auto canvas = surface->getCanvas(); + FML_CHECK(canvas != nullptr); + + switch (layer.platform_view->identifier) { + case 1: { + SkPaint paint; + // See dart test for total order. + paint.setColor(SK_ColorGREEN); + paint.setAlpha(127); + const auto& rect = + SkRect::MakeWH(layer.size.width, layer.size.height); + canvas->drawRect(rect, paint); + latch.CountDown(); + } break; + case 2: { + SkPaint paint; + // See dart test for total order. + paint.setColor(SK_ColorMAGENTA); + paint.setAlpha(127); + const auto& rect = + SkRect::MakeWH(layer.size.width, layer.size.height); + canvas->drawRect(rect, paint); + latch.CountDown(); + } break; + default: + // Asked to render an unknown platform view. + FML_CHECK(false) + << "Test was asked to composite an unknown platform view."; + } + + return surface->makeImageSnapshot(); + }); + + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&latch](Dart_NativeArguments args) { latch.CountDown(); })); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + + latch.Wait(); + + ASSERT_TRUE(ImageMatchesFixture("compositor.png", scene_image)); + + // There should no present calls on the root surface. + ASSERT_EQ(context.GetSurfacePresentCount(), 0u); +} + +INSTANTIATE_TEST_SUITE_P( + EmbedderTestGlVk, + EmbedderTestMultiBackend, + ::testing::Values(EmbedderTestContextType::kOpenGLContext, + EmbedderTestContextType::kVulkanContext)); + +} // namespace flutter::testing + +// NOLINTEND(clang-analyzer-core.StackAddressEscape) diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_metal_unittests.mm b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_metal_unittests.mm new file mode 100644 index 0000000000000000000000000000000000000000..67a0e626e7c7c78b789bd122d895cd3cb7e3a577 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_metal_unittests.mm @@ -0,0 +1,695 @@ +// 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. + +#define FML_USED_ON_EMBEDDER + +#include +#include + +#import + +#include "embedder.h" +#include "flutter/display_list/skia/dl_sk_canvas.h" +#include "flutter/fml/synchronization/count_down_latch.h" +#include "flutter/shell/platform/embedder/tests/embedder_assertions.h" +#include "flutter/shell/platform/embedder/tests/embedder_config_builder.h" +#include "flutter/shell/platform/embedder/tests/embedder_test.h" +#include "flutter/shell/platform/embedder/tests/embedder_test_context_metal.h" +#include "flutter/shell/platform/embedder/tests/embedder_unittests_util.h" +#include "flutter/testing/assertions_skia.h" +#include "flutter/testing/testing.h" + +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/include/gpu/GpuTypes.h" +#include "third_party/skia/include/gpu/ganesh/GrBackendSurface.h" +#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" +#include "third_party/skia/include/gpu/ganesh/mtl/GrMtlBackendSurface.h" +#include "third_party/skia/include/gpu/ganesh/mtl/GrMtlTypes.h" + +// CREATE_NATIVE_ENTRY is leaky by design +// NOLINTBEGIN(clang-analyzer-core.StackAddressEscape) + +namespace flutter { +namespace testing { + +using EmbedderTest = testing::EmbedderTest; + +TEST_F(EmbedderTest, CanRenderGradientWithMetal) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetDartEntrypoint("render_gradient"); + builder.SetSurface(SkISize::Make(800, 600)); + + auto rendered_scene = context.GetNextSceneImage(); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); + + // TODO (https://github.com/flutter/flutter/issues/73590): re-enable once + // we are able to figure out why this fails on the bots. + // ASSERT_TRUE(ImageMatchesFixture("gradient_metal.png", rendered_scene)); +} + +static sk_sp GetSurfaceFromTexture(const sk_sp& skia_context, + SkISize texture_size, + void* texture) { + GrMtlTextureInfo info; + info.fTexture.retain(texture); + GrBackendTexture backend_texture = GrBackendTextures::MakeMtl( + texture_size.width(), texture_size.height(), skgpu::Mipmapped::kNo, info); + + return SkSurfaces::WrapBackendTexture(skia_context.get(), backend_texture, + kTopLeft_GrSurfaceOrigin, 1, kBGRA_8888_SkColorType, + nullptr, nullptr); +} + +TEST_F(EmbedderTest, ExternalTextureMetal) { + auto& context = GetEmbedderContext(); + + const auto texture_size = SkISize::Make(800, 600); + const int64_t texture_id = 1; + + TestMetalContext* metal_context = context.GetTestMetalContext(); + TestMetalContext::TextureInfo texture_info = metal_context->CreateMetalTexture(texture_size); + + sk_sp surface = + GetSurfaceFromTexture(metal_context->GetSkiaContext(), texture_size, texture_info.texture); + auto canvas = surface->getCanvas(); + canvas->clear(SK_ColorRED); + metal_context->GetSkiaContext()->flushAndSubmit(); + + std::vector textures{texture_info.texture}; + + context.SetExternalTextureCallback( + [&](int64_t id, size_t w, size_t h, FlutterMetalExternalTexture* output) { + EXPECT_TRUE(w == texture_size.width()); + EXPECT_TRUE(h == texture_size.height()); + EXPECT_TRUE(texture_id == id); + output->num_textures = 1; + output->height = h; + output->width = w; + output->pixel_format = FlutterMetalExternalTexturePixelFormat::kRGBA; + output->textures = textures.data(); + return true; + }); + + EmbedderConfigBuilder builder(context); + + builder.SetDartEntrypoint("render_texture"); + builder.SetSurface(texture_size); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + ASSERT_EQ(FlutterEngineRegisterExternalTexture(engine.get(), texture_id), kSuccess); + + auto rendered_scene = context.GetNextSceneImage(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = texture_size.width(); + event.height = texture_size.height(); + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); + + ASSERT_TRUE(ImageMatchesFixture("external_texture_metal.png", rendered_scene)); +} + +TEST_F(EmbedderTest, MetalCompositorMustBeAbleToRenderPlatformViews) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("can_composite_platform_views"); + + builder.SetRenderTargetType(EmbedderTestBackingStoreProducer::RenderTargetType::kMetalTexture); + + fml::CountDownLatch latch(3); + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { + ASSERT_EQ(layers_count, 3u); + + { + FlutterBackingStore backing_store = *layers[0]->backing_store; + backing_store.struct_size = sizeof(backing_store); + backing_store.type = kFlutterBackingStoreTypeMetal; + backing_store.did_update = true; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0, 0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[0], layer); + } + + { + FlutterPlatformView platform_view = *layers[1]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 42; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(123.0, 456.0); + layer.offset = FlutterPointMake(1.0, 2.0); + + ASSERT_EQ(*layers[1], layer); + } + + { + FlutterBackingStore backing_store = *layers[2]->backing_store; + backing_store.struct_size = sizeof(backing_store); + backing_store.type = kFlutterBackingStoreTypeMetal; + backing_store.did_update = true; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(2, 3, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[2], layer); + } + + latch.CountDown(); + }); + + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY([&latch](Dart_NativeArguments args) { latch.CountDown(); })); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); + ASSERT_TRUE(engine.is_valid()); + + latch.Wait(); +} + +TEST_F(EmbedderTest, CanRenderSceneWithoutCustomCompositorMetal) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + + builder.SetDartEntrypoint("can_render_scene_without_custom_compositor"); + builder.SetSurface(SkISize::Make(800, 600)); + + auto rendered_scene = context.GetNextSceneImage(); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); + + ASSERT_TRUE(ImageMatchesFixture("scene_without_custom_compositor.png", rendered_scene)); +} + +TEST_F(EmbedderTest, TextureDestructionCallbackCalledWithoutCustomCompositorMetal) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetDartEntrypoint("texture_destruction_callback_called_without_custom_compositor"); + + struct CollectContext { + int present_count = 0; + int collect_count = 0; + fml::AutoResetWaitableEvent latch; + }; + + auto collect_context = std::make_unique(); + context.SetNextDrawableCallback([&context, &collect_context](const FlutterFrameInfo* frame_info) { + auto texture_info = context.GetTestMetalSurface()->GetTextureInfo(); + + FlutterMetalTexture texture; + texture.struct_size = sizeof(FlutterMetalTexture); + texture.texture_id = texture_info.texture_id; + texture.texture = reinterpret_cast(texture_info.texture); + texture.user_data = collect_context.get(); + texture.destruction_callback = [](void* user_data) { + CollectContext* callback_collect_context = reinterpret_cast(user_data); + ASSERT_TRUE(callback_collect_context->present_count > 0); + callback_collect_context->collect_count++; + callback_collect_context->latch.Signal(); + }; + return texture; + }); + context.SetPresentCallback([&context, &collect_context](int64_t texture_id) { + collect_context->present_count++; + return context.GetTestMetalContext()->Present(texture_id); + }); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); + ASSERT_TRUE(engine.is_valid()); + + collect_context->latch.Wait(); + EXPECT_EQ(collect_context->collect_count, 1); +} + +TEST_F(EmbedderTest, CompositorMustBeAbleToRenderKnownSceneMetal) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("can_composite_platform_views_with_known_scene"); + + builder.SetRenderTargetType(EmbedderTestBackingStoreProducer::RenderTargetType::kMetalTexture); + + fml::CountDownLatch latch(5); + + auto scene_image = context.GetNextSceneImage(); + + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { + ASSERT_EQ(layers_count, 5u); + + // Layer Root + { + FlutterBackingStore backing_store = *layers[0]->backing_store; + backing_store.type = kFlutterBackingStoreTypeMetal; + backing_store.did_update = true; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[0], layer); + } + + // Layer 1 + { + FlutterPlatformView platform_view = *layers[1]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 1; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(50.0, 150.0); + layer.offset = FlutterPointMake(20.0, 20.0); + + ASSERT_EQ(*layers[1], layer); + } + + // Layer 2 + { + FlutterBackingStore backing_store = *layers[2]->backing_store; + backing_store.type = kFlutterBackingStoreTypeMetal; + backing_store.did_update = true; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(30, 30, 80, 180), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[2], layer); + } + + // Layer 3 + { + FlutterPlatformView platform_view = *layers[3]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 2; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(50.0, 150.0); + layer.offset = FlutterPointMake(40.0, 40.0); + + ASSERT_EQ(*layers[3], layer); + } + + // Layer 4 + { + FlutterBackingStore backing_store = *layers[4]->backing_store; + backing_store.type = kFlutterBackingStoreTypeMetal; + backing_store.did_update = true; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(50, 50, 100, 200), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[4], layer); + } + + latch.CountDown(); + }); + + context.GetCompositor().SetPlatformViewRendererCallback( + [&](const FlutterLayer& layer, GrDirectContext* context) -> sk_sp { + auto surface = CreateRenderSurface(layer, context); + auto canvas = surface->getCanvas(); + FML_CHECK(canvas != nullptr); + + switch (layer.platform_view->identifier) { + case 1: { + SkPaint paint; + // See dart test for total order. + paint.setColor(SK_ColorGREEN); + paint.setAlpha(127); + const auto& rect = SkRect::MakeWH(layer.size.width, layer.size.height); + canvas->drawRect(rect, paint); + latch.CountDown(); + } break; + case 2: { + SkPaint paint; + // See dart test for total order. + paint.setColor(SK_ColorMAGENTA); + paint.setAlpha(127); + const auto& rect = SkRect::MakeWH(layer.size.width, layer.size.height); + canvas->drawRect(rect, paint); + latch.CountDown(); + } break; + default: + // Asked to render an unknown platform view. + FML_CHECK(false) << "Test was asked to composite an unknown platform view."; + } + + return surface->makeImageSnapshot(); + }); + + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY([&latch](Dart_NativeArguments args) { latch.CountDown(); })); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + // Flutter still thinks it is 800 x 600. Only the root surface is rotated. + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); + ASSERT_TRUE(engine.is_valid()); + + latch.Wait(); + + ASSERT_TRUE(ImageMatchesFixture("compositor.png", scene_image)); +} + +TEST_F(EmbedderTest, CreateInvalidBackingstoreMetalTexture) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetRenderTargetType(EmbedderTestBackingStoreProducer::RenderTargetType::kMetalTexture); + builder.SetDartEntrypoint("invalid_backingstore"); + + class TestCollectOnce { + public: + // Collect() should only be called once + void Collect() { + ASSERT_FALSE(collected_); + collected_ = true; + } + + private: + bool collected_ = false; + }; + fml::AutoResetWaitableEvent latch; + + builder.GetCompositor().create_backing_store_callback = + [](const FlutterBackingStoreConfig* config, // + FlutterBackingStore* backing_store_out, // + void* user_data // + ) { + backing_store_out->type = kFlutterBackingStoreTypeMetal; + // Deliberately set this to be invalid + backing_store_out->user_data = nullptr; + backing_store_out->metal.texture.texture = 0; + backing_store_out->metal.struct_size = sizeof(FlutterMetalBackingStore); + backing_store_out->metal.texture.user_data = new TestCollectOnce(); + backing_store_out->metal.texture.destruction_callback = [](void* user_data) { + reinterpret_cast(user_data)->Collect(); + }; + return true; + }; + + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY([&latch](Dart_NativeArguments args) { latch.Signal(); })); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); + ASSERT_TRUE(engine.is_valid()); + latch.Wait(); +} + +TEST_F(EmbedderTest, ExternalTextureMetalRefreshedTooOften) { + auto& context = GetEmbedderContext(); + + TestMetalContext* metal_context = context.GetTestMetalContext(); + auto metal_texture = metal_context->CreateMetalTexture(SkISize::Make(100, 100)); + + std::vector textures{metal_texture.texture}; + + bool resolve_called = false; + + EmbedderExternalTextureMetal::ExternalTextureCallback callback([&](int64_t id, size_t, size_t) { + resolve_called = true; + auto res = std::make_unique(); + res->struct_size = sizeof(FlutterMetalExternalTexture); + res->width = res->height = 100; + res->pixel_format = FlutterMetalExternalTexturePixelFormat::kRGBA; + res->textures = textures.data(); + res->num_textures = 1; + return res; + }); + EmbedderExternalTextureMetal texture(1, callback); + + auto surface = TestMetalSurface::Create(*metal_context, SkISize::Make(100, 100)); + auto skia_surface = surface->GetSurface(); + DlSkCanvasAdapter canvas(skia_surface->getCanvas()); + + Texture* texture_ = &texture; + DlImageSampling sampling = DlImageSampling::kLinear; + Texture::PaintContext ctx{ + .canvas = &canvas, + .gr_context = surface->GetGrContext().get(), + }; + texture_->Paint(ctx, DlRect::MakeXYWH(0, 0, 100, 100), false, sampling); + + EXPECT_TRUE(resolve_called); + resolve_called = false; + + texture_->Paint(ctx, DlRect::MakeXYWH(0, 0, 100, 100), false, sampling); + + EXPECT_FALSE(resolve_called); + + texture_->MarkNewFrameAvailable(); + + texture_->Paint(ctx, DlRect::MakeXYWH(0, 0, 100, 100), false, sampling); + + EXPECT_TRUE(resolve_called); +} + +TEST_F(EmbedderTest, CanRenderWithImpellerMetal) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + + builder.AddCommandLineArgument("--enable-impeller"); + builder.SetDartEntrypoint("render_impeller_test"); + builder.SetSurface(SkISize::Make(800, 600)); + + auto rendered_scene = context.GetNextSceneImage(); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); + + ASSERT_TRUE(ImageMatchesFixture("impeller_test.png", rendered_scene)); +} + +TEST_F(EmbedderTest, CanRenderTextWithImpellerMetal) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + + builder.AddCommandLineArgument("--enable-impeller"); + builder.SetDartEntrypoint("render_impeller_text_test"); + builder.SetSurface(SkISize::Make(800, 600)); + + auto rendered_scene = context.GetNextSceneImage(); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); + + ASSERT_TRUE(ImageMatchesFixture("impeller_text_test.png", rendered_scene)); +} + +TEST_F(EmbedderTest, CanRenderTextWithImpellerAndCompositorMetal) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + + builder.AddCommandLineArgument("--enable-impeller"); + builder.SetDartEntrypoint("render_impeller_text_test"); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + + builder.SetRenderTargetType(EmbedderTestBackingStoreProducer::RenderTargetType::kMetalTexture); + + auto rendered_scene = context.GetNextSceneImage(); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); + + ASSERT_TRUE(ImageMatchesFixture("impeller_text_test.png", rendered_scene)); +} + +} // namespace testing +} // namespace flutter + +// NOLINTEND(clang-analyzer-core.StackAddressEscape) diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test.cc b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..fbed2d29a8566c6ceb8f507a2f3f640f7c9d9465 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test.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/shell/platform/embedder/tests/embedder_test.h" + +#include +#include + +#include "flutter/shell/platform/embedder/tests/embedder_test_context_software.h" + +namespace flutter::testing { + +EmbedderTest::EmbedderTest() = default; + +std::string EmbedderTest::GetFixturesDirectory() const { + return GetFixturesPath(); +} + +EmbedderTestContext& EmbedderTest::GetSoftwareContext() { + if (!software_context_) { + software_context_ = + std::make_unique(GetFixturesDirectory()); + } + return *software_context_.get(); +} + +#ifndef SHELL_ENABLE_GL +// Fallback implementation. +// See: flutter/shell/platform/embedder/tests/embedder_test_gl.cc. +EmbedderTestContext& EmbedderTest::GetGLContext() { + FML_LOG(FATAL) << "OpenGL is not supported in this build"; + std::terminate(); +} +#endif + +#ifndef SHELL_ENABLE_METAL +// Fallback implementation. +// See: flutter/shell/platform/embedder/tests/embedder_test_metal.mm. +EmbedderTestContext& EmbedderTest::GetMetalContext() { + FML_LOG(FATAL) << "Metal is not supported in this build"; + std::terminate(); +} +#endif + +#ifndef SHELL_ENABLE_VULKAN +// Fallback implementation. +// See: flutter/shell/platform/embedder/tests/embedder_test_vulkan.cc. +EmbedderTestContext& EmbedderTest::GetVulkanContext() { + FML_LOG(FATAL) << "Vulkan is not supported in this build"; + std::terminate(); +} +#endif + +EmbedderTestContext& EmbedderTestMultiBackend::GetEmbedderContext( + EmbedderTestContextType type) { + switch (type) { + case EmbedderTestContextType::kOpenGLContext: + return GetGLContext(); + case EmbedderTestContextType::kMetalContext: + return GetMetalContext(); + case EmbedderTestContextType::kSoftwareContext: + return GetSoftwareContext(); + case EmbedderTestContextType::kVulkanContext: + return GetVulkanContext(); + } +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test.h b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test.h new file mode 100644 index 0000000000000000000000000000000000000000..066fd535dac3d71b0c2f8e6422179c3d6a1edf11 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test.h @@ -0,0 +1,85 @@ +// 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_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_H_ +#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_H_ + +#include +#include + +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/embedder/tests/embedder_test_context.h" +#include "flutter/testing/testing.h" +#include "flutter/testing/thread_test.h" +#include "gtest/gtest.h" + +namespace flutter::testing { + +class EmbedderTestContextGL; +class EmbedderTestContextMetal; +class EmbedderTestContextSoftware; +class EmbedderTestContextVulkan; + +class EmbedderTest : public ThreadTest { + public: + EmbedderTest(); + + std::string GetFixturesDirectory() const; + + template + T& GetEmbedderContext() { + static_assert(false, "Unsupported test context type"); + } + + template <> + EmbedderTestContextGL& GetEmbedderContext() { + return reinterpret_cast(GetGLContext()); + } + + template <> + EmbedderTestContextMetal& GetEmbedderContext() { + return reinterpret_cast(GetMetalContext()); + } + + template <> + EmbedderTestContextSoftware& + GetEmbedderContext() { + return reinterpret_cast(GetSoftwareContext()); + } + + template <> + EmbedderTestContextVulkan& GetEmbedderContext() { + return reinterpret_cast(GetVulkanContext()); + } + + protected: + // We return the base class here and reinterpret_cast in the template + // specializations because we're using forward declarations rather than + // including the headers directly, and thus the relationship between the base + // class and subclasses is unknown to the compiler here. We avoid including + // the headers directly because the Metal headers include Objective-C types, + // and thus cannot be included in pure C++ translation units. + EmbedderTestContext& GetGLContext(); + EmbedderTestContext& GetMetalContext(); + EmbedderTestContext& GetSoftwareContext(); + EmbedderTestContext& GetVulkanContext(); + + std::unique_ptr gl_context_; + std::unique_ptr metal_context_; + std::unique_ptr software_context_; + std::unique_ptr vulkan_context_; + + FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTest); +}; + +class EmbedderTestMultiBackend + : public EmbedderTest, + public ::testing::WithParamInterface { + public: + EmbedderTestContext& GetEmbedderContext(EmbedderTestContextType type); +}; + +} // namespace flutter::testing + +#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_H_ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer.cc b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer.cc new file mode 100644 index 0000000000000000000000000000000000000000..3bea53bcb925d0c9a0381ab77afbcc8c651dffe6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer.cc @@ -0,0 +1,21 @@ +// 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/shell/platform/embedder/tests/embedder_test_backingstore_producer.h" + +// TODO(zanderso): https://github.com/flutter/flutter/issues/127701 +// NOLINTBEGIN(bugprone-unchecked-optional-access) + +namespace flutter::testing { + +EmbedderTestBackingStoreProducer::EmbedderTestBackingStoreProducer( + sk_sp context, + RenderTargetType type) + : context_(std::move(context)), type_(type) {} + +EmbedderTestBackingStoreProducer::~EmbedderTestBackingStoreProducer() = default; + +} // namespace flutter::testing + +// NOLINTEND(bugprone-unchecked-optional-access) diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer.h b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer.h new file mode 100644 index 0000000000000000000000000000000000000000..dd6b02b436a786ed7befdc84643e9d5141537119 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer.h @@ -0,0 +1,52 @@ +// 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_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_BACKINGSTORE_PRODUCER_H_ +#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_BACKINGSTORE_PRODUCER_H_ + +#include + +#include "flutter/fml/macros.h" +#include "flutter/fml/memory/ref_ptr_internal.h" +#include "flutter/shell/platform/embedder/embedder.h" +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/include/gpu/ganesh/GrDirectContext.h" + +namespace flutter::testing { + +class EmbedderTestBackingStoreProducer { + public: + enum class RenderTargetType { + kSoftwareBuffer, + kSoftwareBuffer2, + kOpenGLFramebuffer, + kOpenGLTexture, + kOpenGLSurface, + kMetalTexture, + kVulkanImage, + }; + + EmbedderTestBackingStoreProducer(sk_sp context, + RenderTargetType type); + virtual ~EmbedderTestBackingStoreProducer(); + + virtual bool Create(const FlutterBackingStoreConfig* config, + FlutterBackingStore* backing_store_out) = 0; + + virtual sk_sp GetSurface( + const FlutterBackingStore* backing_store) const = 0; + + virtual sk_sp MakeImageSnapshot( + const FlutterBackingStore* backing_store) const = 0; + + protected: + sk_sp context_; + RenderTargetType type_; + + FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestBackingStoreProducer); +}; + +} // namespace flutter::testing + +#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_BACKINGSTORE_PRODUCER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_gl.cc b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_gl.cc new file mode 100644 index 0000000000000000000000000000000000000000..aae057f282e002ee1cfb34c4e4ac72290cfd6308 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_gl.cc @@ -0,0 +1,214 @@ +// 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/shell/platform/embedder/tests/embedder_test_backingstore_producer_gl.h" + +#include "flutter/fml/logging.h" +#include "flutter/testing/test_gl_surface.h" +#include "third_party/skia/include/core/SkColorSpace.h" +#include "third_party/skia/include/gpu/ganesh/GrBackendSurface.h" +#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" +#include "third_party/skia/include/gpu/ganesh/gl/GrGLBackendSurface.h" +#include "third_party/skia/include/gpu/ganesh/gl/GrGLTypes.h" + +namespace flutter::testing { + +namespace { +struct UserData { + sk_sp surface; + std::unique_ptr gl_surface; +}; +} // namespace + +EmbedderTestBackingStoreProducerGL::EmbedderTestBackingStoreProducerGL( + sk_sp context, + RenderTargetType type, + std::shared_ptr egl_context) + : EmbedderTestBackingStoreProducer(std::move(context), type), + test_egl_context_(std::move(egl_context)) {} + +EmbedderTestBackingStoreProducerGL::~EmbedderTestBackingStoreProducerGL() = + default; + +bool EmbedderTestBackingStoreProducerGL::Create( + const FlutterBackingStoreConfig* config, + FlutterBackingStore* backing_store_out) { + switch (type_) { + case RenderTargetType::kOpenGLTexture: + return CreateTexture(config, backing_store_out); + case RenderTargetType::kOpenGLFramebuffer: + return CreateFramebuffer(config, backing_store_out); + case RenderTargetType::kOpenGLSurface: + return CreateSurface(config, backing_store_out); + default: + return false; + }; +} + +sk_sp EmbedderTestBackingStoreProducerGL::GetSurface( + const FlutterBackingStore* backing_store) const { + UserData* user_data = reinterpret_cast(backing_store->user_data); + return user_data->surface; +} + +sk_sp EmbedderTestBackingStoreProducerGL::MakeImageSnapshot( + const FlutterBackingStore* backing_store) const { + UserData* user_data = reinterpret_cast(backing_store->user_data); + if (user_data->gl_surface != nullptr) { + // This backing store is an OpenGL Surface. + // We need to make it current so we can snapshot it. + user_data->gl_surface->MakeCurrent(); + + // GetRasterSurfaceSnapshot() does two + // gl_surface->makeImageSnapshot()'s. Doing a single + // ->makeImageSnapshot() will not work. + return user_data->gl_surface->GetRasterSurfaceSnapshot(); + } + + // Otherwise, it's a GL Texture or FrameBuffer. + return user_data->surface->makeImageSnapshot(); +} + +bool EmbedderTestBackingStoreProducerGL::CreateFramebuffer( + const FlutterBackingStoreConfig* config, + FlutterBackingStore* backing_store_out) { + const auto image_info = + SkImageInfo::MakeN32Premul(config->size.width, config->size.height); + + auto surface = + SkSurfaces::RenderTarget(context_.get(), // context + skgpu::Budgeted::kNo, // budgeted + image_info, // image info + 1, // sample count + kBottomLeft_GrSurfaceOrigin, // surface origin + nullptr, // surface properties + false // mipmaps + ); + + if (!surface) { + FML_LOG(ERROR) << "Could not create render target for compositor layer."; + return false; + } + + GrBackendRenderTarget render_target = SkSurfaces::GetBackendRenderTarget( + surface.get(), SkSurfaces::BackendHandleAccess::kDiscardWrite); + + if (!render_target.isValid()) { + FML_LOG(ERROR) << "Backend render target was invalid."; + return false; + } + + GrGLFramebufferInfo framebuffer_info = {}; + if (!GrBackendRenderTargets::GetGLFramebufferInfo(render_target, + &framebuffer_info)) { + FML_LOG(ERROR) << "Could not access backend framebuffer info."; + return false; + } + + auto user_data = new UserData{.surface = surface}; + backing_store_out->type = kFlutterBackingStoreTypeOpenGL; + backing_store_out->user_data = user_data; + backing_store_out->open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; + backing_store_out->open_gl.framebuffer.target = framebuffer_info.fFormat; + backing_store_out->open_gl.framebuffer.name = framebuffer_info.fFBOID; + backing_store_out->open_gl.framebuffer.user_data = user_data; + backing_store_out->open_gl.framebuffer.destruction_callback = + [](void* user_data) { delete reinterpret_cast(user_data); }; + + return true; +} + +bool EmbedderTestBackingStoreProducerGL::CreateTexture( + const FlutterBackingStoreConfig* config, + FlutterBackingStore* backing_store_out) { + const auto image_info = + SkImageInfo::MakeN32Premul(config->size.width, config->size.height); + + auto surface = + SkSurfaces::RenderTarget(context_.get(), // context + skgpu::Budgeted::kNo, // budgeted + image_info, // image info + 1, // sample count + kBottomLeft_GrSurfaceOrigin, // surface origin + nullptr, // surface properties + false // mipmaps + ); + + if (!surface) { + FML_LOG(ERROR) << "Could not create render target for compositor layer."; + return false; + } + + GrBackendTexture render_texture = SkSurfaces::GetBackendTexture( + surface.get(), SkSurfaces::BackendHandleAccess::kDiscardWrite); + + if (!render_texture.isValid()) { + FML_LOG(ERROR) << "Backend render texture was invalid."; + return false; + } + + GrGLTextureInfo texture_info = {}; + if (!GrBackendTextures::GetGLTextureInfo(render_texture, &texture_info)) { + FML_LOG(ERROR) << "Could not access backend texture info."; + return false; + } + + auto user_data = new UserData{.surface = surface}; + backing_store_out->type = kFlutterBackingStoreTypeOpenGL; + backing_store_out->user_data = user_data; + backing_store_out->open_gl.type = kFlutterOpenGLTargetTypeTexture; + backing_store_out->open_gl.texture.target = texture_info.fTarget; + backing_store_out->open_gl.texture.name = texture_info.fID; + backing_store_out->open_gl.texture.format = texture_info.fFormat; + backing_store_out->open_gl.texture.user_data = user_data; + backing_store_out->open_gl.texture.destruction_callback = + [](void* user_data) { delete reinterpret_cast(user_data); }; + + return true; +} + +bool EmbedderTestBackingStoreProducerGL::CreateSurface( + const FlutterBackingStoreConfig* config, + FlutterBackingStore* backing_store_out) { + FML_CHECK(test_egl_context_); + auto surface = std::make_unique( + test_egl_context_, + SkSize::Make(config->size.width, config->size.height).toRound()); + + auto make_current = [](void* user_data, bool* invalidate_state) -> bool { + *invalidate_state = false; + return reinterpret_cast(user_data)->gl_surface->MakeCurrent(); + }; + + auto clear_current = [](void* user_data, bool* invalidate_state) -> bool { + *invalidate_state = false; + // return + // reinterpret_cast(user_data)->gl_surface->ClearCurrent(); + return true; + }; + + auto destruction_callback = [](void* user_data) { + delete reinterpret_cast(user_data); + }; + + auto sk_surface = surface->GetOnscreenSurface(); + + auto user_data = new UserData{ + .surface = sk_surface, + .gl_surface = std::move(surface), + }; + backing_store_out->type = kFlutterBackingStoreTypeOpenGL; + backing_store_out->user_data = user_data; + backing_store_out->open_gl.type = kFlutterOpenGLTargetTypeSurface; + backing_store_out->open_gl.surface.user_data = user_data; + backing_store_out->open_gl.surface.make_current_callback = make_current; + backing_store_out->open_gl.surface.clear_current_callback = clear_current; + backing_store_out->open_gl.surface.destruction_callback = + destruction_callback; + backing_store_out->open_gl.surface.format = 0x93A1 /* GL_BGRA8_EXT */; + + return true; +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_gl.h b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_gl.h new file mode 100644 index 0000000000000000000000000000000000000000..1fe57276468ec43939a2a5d60a3f2d0c7c90ea42 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_gl.h @@ -0,0 +1,52 @@ +// 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_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_BACKINGSTORE_PRODUCER_GL_H_ +#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_BACKINGSTORE_PRODUCER_GL_H_ + +#include "flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer.h" + +#include + +#include "flutter/testing/test_gl_context.h" + +namespace flutter::testing { + +class EmbedderTestBackingStoreProducerGL + : public EmbedderTestBackingStoreProducer { + public: + EmbedderTestBackingStoreProducerGL( + sk_sp context, + RenderTargetType type, + std::shared_ptr egl_context); + + virtual ~EmbedderTestBackingStoreProducerGL(); + + bool Create(const FlutterBackingStoreConfig* config, + FlutterBackingStore* backing_store_out) override; + + sk_sp GetSurface( + const FlutterBackingStore* backing_store) const override; + + sk_sp MakeImageSnapshot( + const FlutterBackingStore* backing_store) const override; + + private: + bool CreateFramebuffer(const FlutterBackingStoreConfig* config, + FlutterBackingStore* renderer_out); + + bool CreateTexture(const FlutterBackingStoreConfig* config, + FlutterBackingStore* renderer_out); + + bool CreateSurface(const FlutterBackingStoreConfig* config, + FlutterBackingStore* renderer_out); + + std::shared_ptr test_egl_context_; + + FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestBackingStoreProducerGL); +}; + +} // namespace flutter::testing + +#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_BACKINGSTORE_PRODUCER_GL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_metal.h b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_metal.h new file mode 100644 index 0000000000000000000000000000000000000000..1d89d06f64963c40bdb23fd7e7a4f3a08e1041e7 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_metal.h @@ -0,0 +1,38 @@ +// 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_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_BACKINGSTORE_PRODUCER_METAL_H_ +#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_BACKINGSTORE_PRODUCER_METAL_H_ + +#include "flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer.h" +#include "flutter/testing/test_metal_context.h" + +namespace flutter::testing { + +class EmbedderTestBackingStoreProducerMetal + : public EmbedderTestBackingStoreProducer { + public: + EmbedderTestBackingStoreProducerMetal(sk_sp context, + RenderTargetType type); + + virtual ~EmbedderTestBackingStoreProducerMetal(); + + bool Create(const FlutterBackingStoreConfig* config, + FlutterBackingStore* backing_store_out) override; + + sk_sp GetSurface( + const FlutterBackingStore* backing_store) const override; + + sk_sp MakeImageSnapshot( + const FlutterBackingStore* backing_store) const override; + + private: + std::unique_ptr test_metal_context_; + + FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestBackingStoreProducerMetal); +}; + +} // namespace flutter::testing + +#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_BACKINGSTORE_PRODUCER_METAL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_metal.mm b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_metal.mm new file mode 100644 index 0000000000000000000000000000000000000000..42595e92f6a68f15285474171adeb9508831e0d9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_metal.mm @@ -0,0 +1,73 @@ +// 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/shell/platform/embedder/tests/embedder_test_backingstore_producer_metal.h" + +#include + +#include "flutter/fml/logging.h" +#include "third_party/skia/include/core/SkColorSpace.h" +#include "third_party/skia/include/gpu/ganesh/GrBackendSurface.h" +#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" +#include "third_party/skia/include/gpu/ganesh/mtl/GrMtlBackendSurface.h" +#include "third_party/skia/include/gpu/ganesh/mtl/GrMtlTypes.h" + +namespace flutter::testing { + +EmbedderTestBackingStoreProducerMetal::EmbedderTestBackingStoreProducerMetal( + sk_sp context, + RenderTargetType type) + : EmbedderTestBackingStoreProducer(std::move(context), type), + test_metal_context_(std::make_unique()) {} + +EmbedderTestBackingStoreProducerMetal::~EmbedderTestBackingStoreProducerMetal() = default; + +bool EmbedderTestBackingStoreProducerMetal::Create(const FlutterBackingStoreConfig* config, + FlutterBackingStore* backing_store_out) { + // TODO(gw280): Use SkSurfaces::RenderTarget instead of generating our + // own MTLTexture and wrapping it. + auto surface_size = SkISize::Make(config->size.width, config->size.height); + auto texture_info = test_metal_context_->CreateMetalTexture(surface_size); + + GrMtlTextureInfo skia_texture_info; + skia_texture_info.fTexture.reset(SkCFSafeRetain(texture_info.texture)); + GrBackendTexture backend_texture = GrBackendTextures::MakeMtl( + surface_size.width(), surface_size.height(), skgpu::Mipmapped::kNo, skia_texture_info); + + sk_sp surface = + SkSurfaces::WrapBackendTexture(context_.get(), backend_texture, kTopLeft_GrSurfaceOrigin, 1, + kBGRA_8888_SkColorType, nullptr, nullptr); + + if (!surface) { + FML_LOG(ERROR) << "Could not create Skia surface from a Metal texture."; + return false; + } + + backing_store_out->type = kFlutterBackingStoreTypeMetal; + backing_store_out->user_data = surface.get(); + backing_store_out->metal.texture.texture = texture_info.texture; + // The balancing unref is in the destruction callback. + surface->ref(); + backing_store_out->metal.struct_size = sizeof(FlutterMetalBackingStore); + backing_store_out->metal.texture.user_data = surface.get(); + backing_store_out->metal.texture.destruction_callback = [](void* user_data) { + reinterpret_cast(user_data)->unref(); + }; + + return true; +} + +sk_sp EmbedderTestBackingStoreProducerMetal::GetSurface( + const FlutterBackingStore* backing_store) const { + FML_LOG(FATAL) << "Unimplemented."; + std::terminate(); +} + +sk_sp EmbedderTestBackingStoreProducerMetal::MakeImageSnapshot( + const FlutterBackingStore* backing_store) const { + FML_LOG(FATAL) << "Unimplemented."; + std::terminate(); +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_software.cc b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_software.cc new file mode 100644 index 0000000000000000000000000000000000000000..5b753d82772615e83a7cfaa6d5872aec4ead2530 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_software.cc @@ -0,0 +1,138 @@ +// 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/shell/platform/embedder/tests/embedder_test_backingstore_producer_software.h" + +#include "flutter/fml/logging.h" +#include "flutter/shell/platform/embedder/pixel_formats.h" +#include "third_party/skia/include/core/SkColorSpace.h" +#include "third_party/skia/include/gpu/ganesh/GrBackendSurface.h" +#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" + +namespace flutter::testing { + +namespace { +struct UserData { + sk_sp surface; +}; +} // namespace + +EmbedderTestBackingStoreProducerSoftware:: + EmbedderTestBackingStoreProducerSoftware( + sk_sp context, + RenderTargetType type, + FlutterSoftwarePixelFormat software_pixfmt) + : EmbedderTestBackingStoreProducer(std::move(context), type), + software_pixfmt_(software_pixfmt) { + if (type == RenderTargetType::kSoftwareBuffer && + software_pixfmt_ != kFlutterSoftwarePixelFormatNative32) { + FML_LOG(ERROR) << "Expected pixel format to be the default " + "(kFlutterSoftwarePixelFormatNative32) when" + "backing store producer should produce deprecated v1 " + "software backing " + "stores."; + std::abort(); + }; +} + +EmbedderTestBackingStoreProducerSoftware:: + ~EmbedderTestBackingStoreProducerSoftware() = default; + +bool EmbedderTestBackingStoreProducerSoftware::Create( + const FlutterBackingStoreConfig* config, + FlutterBackingStore* backing_store_out) { + switch (type_) { + case RenderTargetType::kSoftwareBuffer: + return CreateSoftware(config, backing_store_out); + case RenderTargetType::kSoftwareBuffer2: + return CreateSoftware2(config, backing_store_out); + default: + return false; + } +} + +sk_sp EmbedderTestBackingStoreProducerSoftware::GetSurface( + const FlutterBackingStore* backing_store) const { + UserData* user_data = reinterpret_cast(backing_store->user_data); + return user_data->surface; +} + +sk_sp EmbedderTestBackingStoreProducerSoftware::MakeImageSnapshot( + const FlutterBackingStore* backing_store) const { + auto user_data = reinterpret_cast(backing_store->user_data); + return user_data->surface->makeImageSnapshot(); +} + +bool EmbedderTestBackingStoreProducerSoftware::CreateSoftware( + const FlutterBackingStoreConfig* config, + FlutterBackingStore* backing_store_out) { + auto surface = SkSurfaces::Raster( + SkImageInfo::MakeN32Premul(config->size.width, config->size.height)); + + if (!surface) { + FML_LOG(ERROR) + << "Could not create the render target for compositor layer."; + return false; + } + + SkPixmap pixmap; + if (!surface->peekPixels(&pixmap)) { + FML_LOG(ERROR) << "Could not peek pixels of pixmap."; + return false; + } + + auto user_data = new UserData{.surface = surface}; + backing_store_out->type = kFlutterBackingStoreTypeSoftware; + backing_store_out->user_data = user_data; + backing_store_out->software.allocation = pixmap.addr(); + backing_store_out->software.row_bytes = pixmap.rowBytes(); + backing_store_out->software.height = pixmap.height(); + backing_store_out->software.user_data = user_data; + backing_store_out->software.destruction_callback = [](void* user_data) { + delete reinterpret_cast(user_data); + }; + + return true; +} + +bool EmbedderTestBackingStoreProducerSoftware::CreateSoftware2( + const FlutterBackingStoreConfig* config, + FlutterBackingStore* backing_store_out) { + const auto color_info = getSkColorInfo(software_pixfmt_); + if (!color_info) { + return false; + } + + auto surface = SkSurfaces::Raster(SkImageInfo::Make( + SkISize::Make(config->size.width, config->size.height), *color_info)); + if (!surface) { + FML_LOG(ERROR) + << "Could not create the render target for compositor layer."; + return false; + } + + SkPixmap pixmap; + if (!surface->peekPixels(&pixmap)) { + FML_LOG(ERROR) << "Could not peek pixels of pixmap."; + return false; + } + + auto user_data = new UserData{.surface = surface}; + backing_store_out->type = kFlutterBackingStoreTypeSoftware2; + backing_store_out->user_data = user_data; + backing_store_out->software2.struct_size = + sizeof(FlutterSoftwareBackingStore2); + backing_store_out->software2.allocation = pixmap.writable_addr(); + backing_store_out->software2.row_bytes = pixmap.rowBytes(); + backing_store_out->software2.height = pixmap.height(); + backing_store_out->software2.user_data = user_data; + backing_store_out->software2.destruction_callback = [](void* user_data) { + delete reinterpret_cast(user_data); + }; + backing_store_out->software2.pixel_format = software_pixfmt_; + + return true; +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_software.h b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_software.h new file mode 100644 index 0000000000000000000000000000000000000000..0fdce10136f2ea215608a415e3eaa631e8e6aecb --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_software.h @@ -0,0 +1,46 @@ +// 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_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_BACKINGSTORE_PRODUCER_SOFTWARE_H_ +#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_BACKINGSTORE_PRODUCER_SOFTWARE_H_ + +#include "flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer.h" + +namespace flutter::testing { + +class EmbedderTestBackingStoreProducerSoftware + : public EmbedderTestBackingStoreProducer { + public: + EmbedderTestBackingStoreProducerSoftware( + sk_sp context, + RenderTargetType type, + FlutterSoftwarePixelFormat software_pixfmt = + kFlutterSoftwarePixelFormatNative32); + + virtual ~EmbedderTestBackingStoreProducerSoftware(); + + bool Create(const FlutterBackingStoreConfig* config, + FlutterBackingStore* backing_store_out) override; + + sk_sp GetSurface( + const FlutterBackingStore* backing_store) const override; + + sk_sp MakeImageSnapshot( + const FlutterBackingStore* backing_store) const override; + + private: + bool CreateSoftware(const FlutterBackingStoreConfig* config, + FlutterBackingStore* backing_store_out); + + bool CreateSoftware2(const FlutterBackingStoreConfig* config, + FlutterBackingStore* backing_store_out); + + FlutterSoftwarePixelFormat software_pixfmt_; + + FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestBackingStoreProducerSoftware); +}; + +} // namespace flutter::testing + +#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_BACKINGSTORE_PRODUCER_SOFTWARE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_vulkan.cc b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_vulkan.cc new file mode 100644 index 0000000000000000000000000000000000000000..195b68be4d0d86c4a78e959f418f3af8cde85d95 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_vulkan.cc @@ -0,0 +1,118 @@ +// 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/shell/platform/embedder/tests/embedder_test_backingstore_producer_vulkan.h" + +#include "flutter/fml/logging.h" +#include "third_party/skia/include/core/SkColorSpace.h" +#include "third_party/skia/include/gpu/ganesh/GrBackendSurface.h" +#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" +#include "third_party/skia/include/gpu/ganesh/vk/GrVkBackendSurface.h" +#include "third_party/skia/include/gpu/ganesh/vk/GrVkTypes.h" + +namespace flutter::testing { + +namespace { +struct UserData { + sk_sp surface; + FlutterVulkanImage* image; +}; +} // namespace + +EmbedderTestBackingStoreProducerVulkan::EmbedderTestBackingStoreProducerVulkan( + sk_sp context, + RenderTargetType type) + : EmbedderTestBackingStoreProducer(std::move(context), type), + test_vulkan_context_(nullptr) {} + +EmbedderTestBackingStoreProducerVulkan:: + ~EmbedderTestBackingStoreProducerVulkan() = default; + +bool EmbedderTestBackingStoreProducerVulkan::Create( + const FlutterBackingStoreConfig* config, + FlutterBackingStore* backing_store_out) { + if (!test_vulkan_context_) { + test_vulkan_context_ = fml::MakeRefCounted(); + } + + auto surface_size = SkISize::Make(config->size.width, config->size.height); + auto optional_image = test_vulkan_context_->CreateImage(surface_size); + if (!optional_image.has_value()) { + FML_LOG(ERROR) << "Could not create Vulkan image."; + return false; + } + TestVulkanImage* test_image = new TestVulkanImage(std::move(*optional_image)); + + GrVkImageInfo image_info = { + .fImage = test_image->GetImage(), + .fImageTiling = VK_IMAGE_TILING_OPTIMAL, + .fImageLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .fFormat = VK_FORMAT_R8G8B8A8_UNORM, + .fImageUsageFlags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | + VK_IMAGE_USAGE_TRANSFER_SRC_BIT | + VK_IMAGE_USAGE_TRANSFER_DST_BIT | + VK_IMAGE_USAGE_SAMPLED_BIT, + .fSampleCount = 1, + .fLevelCount = 1, + }; + auto backend_texture = GrBackendTextures::MakeVk( + surface_size.width(), surface_size.height(), image_info); + + SkSurfaceProps surface_properties(0, kUnknown_SkPixelGeometry); + + SkSurfaces::TextureReleaseProc release_vktexture = [](void* user_data) { + delete reinterpret_cast(user_data); + }; + + sk_sp surface = SkSurfaces::WrapBackendTexture( + context_.get(), // context + backend_texture, // back-end texture + kTopLeft_GrSurfaceOrigin, // surface origin + 1, // sample count + kRGBA_8888_SkColorType, // color type + SkColorSpace::MakeSRGB(), // color space + &surface_properties, // surface properties + release_vktexture, // texture release proc + test_image // release context + ); + + if (!surface) { + FML_LOG(ERROR) << "Could not create Skia surface from Vulkan image."; + return false; + } + backing_store_out->type = kFlutterBackingStoreTypeVulkan; + + FlutterVulkanImage* image = new FlutterVulkanImage(); + image->image = reinterpret_cast(image_info.fImage); + image->format = VK_FORMAT_R8G8B8A8_UNORM; + backing_store_out->vulkan.image = image; + + // Collect all allocated resources in the destruction_callback. + { + auto user_data = new UserData{.surface = surface, .image = image}; + backing_store_out->user_data = user_data; + backing_store_out->vulkan.user_data = user_data; + backing_store_out->vulkan.destruction_callback = [](void* user_data) { + UserData* d = reinterpret_cast(user_data); + delete d->image; + delete d; + }; + } + + return true; +} + +sk_sp EmbedderTestBackingStoreProducerVulkan::GetSurface( + const FlutterBackingStore* backing_store) const { + UserData* user_data = reinterpret_cast(backing_store->user_data); + return user_data->surface; +} + +sk_sp EmbedderTestBackingStoreProducerVulkan::MakeImageSnapshot( + const FlutterBackingStore* backing_store) const { + UserData* user_data = reinterpret_cast(backing_store->user_data); + return user_data->surface->makeImageSnapshot(); +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_vulkan.h b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_vulkan.h new file mode 100644 index 0000000000000000000000000000000000000000..08a11282eb17e4670c6362a6339e823b77d9dff6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_vulkan.h @@ -0,0 +1,39 @@ +// 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_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_BACKINGSTORE_PRODUCER_VULKAN_H_ +#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_BACKINGSTORE_PRODUCER_VULKAN_H_ + +#include "flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer.h" + +#include "flutter/testing/test_vulkan_context.h" + +namespace flutter::testing { + +class EmbedderTestBackingStoreProducerVulkan + : public EmbedderTestBackingStoreProducer { + public: + EmbedderTestBackingStoreProducerVulkan(sk_sp context, + RenderTargetType type); + + virtual ~EmbedderTestBackingStoreProducerVulkan(); + + bool Create(const FlutterBackingStoreConfig* config, + FlutterBackingStore* backing_store_out) override; + + sk_sp GetSurface( + const FlutterBackingStore* backing_store) const override; + + sk_sp MakeImageSnapshot( + const FlutterBackingStore* backing_store) const override; + + private: + fml::RefPtr test_vulkan_context_; + + FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestBackingStoreProducerVulkan); +}; + +} // namespace flutter::testing + +#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_BACKINGSTORE_PRODUCER_VULKAN_H_ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor.cc b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor.cc new file mode 100644 index 0000000000000000000000000000000000000000..ab6963b44e722f127fe5aee021ab114aa36ed413 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor.cc @@ -0,0 +1,143 @@ +// 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/shell/platform/embedder/tests/embedder_test_compositor.h" + +#include + +#include "flutter/fml/logging.h" +#include "flutter/shell/platform/embedder/tests/embedder_assertions.h" +#include "third_party/skia/include/core/SkSurface.h" + +namespace flutter { +namespace testing { + +EmbedderTestCompositor::EmbedderTestCompositor(SkISize surface_size, + sk_sp context) + : surface_size_(surface_size), context_(std::move(context)) { + FML_CHECK(!surface_size_.isEmpty()) << "Surface size must not be empty"; +} + +EmbedderTestCompositor::~EmbedderTestCompositor() = default; + +static void InvokeAllCallbacks(const std::vector& callbacks) { + for (const auto& callback : callbacks) { + if (callback) { + callback(); + } + } +} + +bool EmbedderTestCompositor::CreateBackingStore( + const FlutterBackingStoreConfig* config, + FlutterBackingStore* backing_store_out) { + bool success = backingstore_producer_->Create(config, backing_store_out); + if (success) { + backing_stores_created_++; + InvokeAllCallbacks(on_create_render_target_callbacks_); + } + return success; +} + +bool EmbedderTestCompositor::CollectBackingStore( + const FlutterBackingStore* backing_store) { + // We have already set the destruction callback for the various backing + // stores. Our user_data is just the canvas from that backing store and does + // not need to be explicitly collected. Embedders might have some other state + // they want to collect though. + backing_stores_collected_++; + InvokeAllCallbacks(on_collect_render_target_callbacks_); + return true; +} + +sk_sp EmbedderTestCompositor::GetSurface( + const FlutterBackingStore* backing_store) const { + return backingstore_producer_->GetSurface(backing_store); +} + +sk_sp EmbedderTestCompositor::GetLastComposition() { + return last_composition_; +} + +bool EmbedderTestCompositor::Present(FlutterViewId view_id, + const FlutterLayer** layers, + size_t layers_count) { + if (!UpdateOffscrenComposition(layers, layers_count)) { + FML_LOG(ERROR) + << "Could not update the off-screen composition in the test compositor"; + return false; + } + + // If the test has asked to access the layers and renderers being presented. + // Access the same and present it to the test for its test assertions. + if (present_callback_) { + auto callback = present_callback_; + if (present_callback_is_one_shot_) { + present_callback_ = nullptr; + } + callback(view_id, layers, layers_count); + } + + InvokeAllCallbacks(on_present_callbacks_); + return true; +} + +void EmbedderTestCompositor::SetNextPresentCallback( + const PresentCallback& next_present_callback) { + SetPresentCallback(next_present_callback, true); +} + +void EmbedderTestCompositor::SetPresentCallback( + const PresentCallback& present_callback, + bool one_shot) { + FML_CHECK(!present_callback_); + present_callback_ = present_callback; + present_callback_is_one_shot_ = one_shot; +} + +void EmbedderTestCompositor::SetNextSceneCallback( + const NextSceneCallback& next_scene_callback) { + FML_CHECK(!next_scene_callback_); + next_scene_callback_ = next_scene_callback; +} + +void EmbedderTestCompositor::SetPlatformViewRendererCallback( + const PlatformViewRendererCallback& callback) { + platform_view_renderer_callback_ = callback; +} + +size_t EmbedderTestCompositor::GetPendingBackingStoresCount() const { + FML_CHECK(backing_stores_created_ >= backing_stores_collected_); + return backing_stores_created_ - backing_stores_collected_; +} + +size_t EmbedderTestCompositor::GetBackingStoresCreatedCount() const { + return backing_stores_created_; +} + +size_t EmbedderTestCompositor::GetBackingStoresCollectedCount() const { + return backing_stores_collected_; +} + +void EmbedderTestCompositor::AddOnCreateRenderTargetCallback( + const fml::closure& callback) { + on_create_render_target_callbacks_.push_back(callback); +} + +void EmbedderTestCompositor::AddOnCollectRenderTargetCallback( + const fml::closure& callback) { + on_collect_render_target_callbacks_.push_back(callback); +} + +void EmbedderTestCompositor::AddOnPresentCallback( + const fml::closure& callback) { + on_present_callbacks_.push_back(callback); +} + +sk_sp EmbedderTestCompositor::GetGrContext() { + return context_; +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor.h b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor.h new file mode 100644 index 0000000000000000000000000000000000000000..67992deed1a2290c310196a2948cc04a1e105c25 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor.h @@ -0,0 +1,107 @@ +// 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_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_H_ +#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_H_ + +#include + +#include "flutter/fml/closure.h" +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/embedder/embedder.h" +#include "flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer.h" +#include "third_party/skia/include/gpu/ganesh/GrDirectContext.h" + +namespace flutter { +namespace testing { + +class EmbedderTestCompositor { + public: + using PlatformViewRendererCallback = + std::function(const FlutterLayer& layer, + GrDirectContext* context)>; + using PresentCallback = std::function; + + EmbedderTestCompositor(SkISize surface_size, sk_sp context); + + virtual ~EmbedderTestCompositor(); + + virtual void SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType type, + FlutterSoftwarePixelFormat software_pixfmt) = 0; + + bool CreateBackingStore(const FlutterBackingStoreConfig* config, + FlutterBackingStore* backing_store_out); + + bool CollectBackingStore(const FlutterBackingStore* backing_store); + + bool Present(FlutterViewId view_id, + const FlutterLayer** layers, + size_t layers_count); + + void SetPlatformViewRendererCallback( + const PlatformViewRendererCallback& callback); + + sk_sp GetSurface(const FlutterBackingStore* backing_store) const; + + //---------------------------------------------------------------------------- + /// @brief Allows tests to install a callback to notify them when the + /// entire render tree has been finalized so they can run their + /// assertions. + /// + /// @param[in] next_present_callback The next present callback + /// + void SetNextPresentCallback(const PresentCallback& next_present_callback); + + void SetPresentCallback(const PresentCallback& present_callback, + bool one_shot); + + using NextSceneCallback = std::function image)>; + void SetNextSceneCallback(const NextSceneCallback& next_scene_callback); + + sk_sp GetLastComposition(); + + size_t GetPendingBackingStoresCount() const; + + size_t GetBackingStoresCreatedCount() const; + + size_t GetBackingStoresCollectedCount() const; + + void AddOnCreateRenderTargetCallback(const fml::closure& callback); + + void AddOnCollectRenderTargetCallback(const fml::closure& callback); + + void AddOnPresentCallback(const fml::closure& callback); + + sk_sp GetGrContext(); + + protected: + virtual bool UpdateOffscrenComposition(const FlutterLayer** layers, + size_t layers_count) = 0; + + // TODO(gw280): encapsulate these properly for subclasses to use + std::unique_ptr backingstore_producer_; + const SkISize surface_size_; + sk_sp context_; + + PlatformViewRendererCallback platform_view_renderer_callback_; + bool present_callback_is_one_shot_ = false; + PresentCallback present_callback_; + NextSceneCallback next_scene_callback_; + sk_sp last_composition_; + size_t backing_stores_created_ = 0; + size_t backing_stores_collected_ = 0; + std::vector on_create_render_target_callbacks_; + std::vector on_collect_render_target_callbacks_; + std::vector on_present_callbacks_; + + FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestCompositor); +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_H_ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor_gl.cc b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor_gl.cc new file mode 100644 index 0000000000000000000000000000000000000000..1404b653dddfcc59f1aa543d0eb0ca28b7e7dd9a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor_gl.cc @@ -0,0 +1,144 @@ +// 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/shell/platform/embedder/tests/embedder_test_compositor_gl.h" + +#include + +#include "flutter/fml/logging.h" +#include "flutter/shell/platform/embedder/tests/embedder_assertions.h" +#include "flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_gl.h" +#include "flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_software.h" +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" + +namespace flutter { +namespace testing { + +EmbedderTestCompositorGL::EmbedderTestCompositorGL( + std::shared_ptr egl_context, + SkISize surface_size, + sk_sp context) + : EmbedderTestCompositor(surface_size, std::move(context)), + egl_context_(std::move(egl_context)) {} + +EmbedderTestCompositorGL::~EmbedderTestCompositorGL() = default; + +void EmbedderTestCompositorGL::SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType type, + FlutterSoftwarePixelFormat software_pixfmt) { + switch (type) { + case EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer: + case EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLSurface: + case EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture: { + backingstore_producer_ = + std::make_unique(context_, type, + egl_context_); + return; + } + case EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer: + case EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer2: + backingstore_producer_ = + std::make_unique( + context_, type, software_pixfmt); + return; + case EmbedderTestBackingStoreProducer::RenderTargetType::kMetalTexture: + case EmbedderTestBackingStoreProducer::RenderTargetType::kVulkanImage: + FML_LOG(FATAL) << "Unsupported render target type: " + << static_cast(type); + return; + } +} + +bool EmbedderTestCompositorGL::UpdateOffscrenComposition( + const FlutterLayer** layers, + size_t layers_count) { + last_composition_ = nullptr; + + const auto image_info = SkImageInfo::MakeN32Premul(surface_size_); + + auto surface = + SkSurfaces::RenderTarget(context_.get(), // context + skgpu::Budgeted::kNo, // budgeted + image_info, // image info + 1, // sample count + kTopLeft_GrSurfaceOrigin, // surface origin + nullptr, // surface properties + false // create mipmaps + ); + + if (!surface) { + FML_LOG(ERROR) << "Could not update the off-screen composition."; + return false; + } + + auto canvas = surface->getCanvas(); + + // This has to be transparent because we are going to be compositing this + // sub-hierarchy onto the on-screen surface. + canvas->clear(SK_ColorTRANSPARENT); + + for (size_t i = 0; i < layers_count; ++i) { + const auto* layer = layers[i]; + + sk_sp platform_rendered_contents; + + sk_sp layer_image; + SkIPoint canvas_offset = SkIPoint::Make(0, 0); + + switch (layer->type) { + case kFlutterLayerContentTypeBackingStore: { + layer_image = + backingstore_producer_->MakeImageSnapshot(layer->backing_store); + // We don't clear the current surface here because we need the + // EGL context to be current for surface->makeImageSnapshot() below. + break; + } + case kFlutterLayerContentTypePlatformView: + layer_image = + platform_view_renderer_callback_ + ? platform_view_renderer_callback_(*layer, context_.get()) + : nullptr; + canvas_offset = SkIPoint::Make(layer->offset.x, layer->offset.y); + break; + }; + + // If the layer is not a platform view but the engine did not specify an + // image for the backing store, it is an error. + if (!layer_image && layer->type != kFlutterLayerContentTypePlatformView) { + FML_LOG(ERROR) << "Could not snapshot layer in test compositor: " + << *layer; + return false; + } + + // The test could have just specified no contents to be rendered in place of + // a platform view. This is not an error. + if (layer_image) { + // The image rendered by Flutter already has the correct offset and + // transformation applied. The layers offset is meant for the platform. + canvas->drawImage(layer_image.get(), canvas_offset.x(), + canvas_offset.y()); + } + } + + last_composition_ = surface->makeImageSnapshot(); + + if (!last_composition_) { + FML_LOG(ERROR) << "Could not update the contents of the sub-composition."; + return false; + } + + if (next_scene_callback_) { + auto last_composition_snapshot = last_composition_->makeRasterImage(); + FML_CHECK(last_composition_snapshot); + auto callback = next_scene_callback_; + next_scene_callback_ = nullptr; + callback(std::move(last_composition_snapshot)); + } + + return true; +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor_gl.h b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor_gl.h new file mode 100644 index 0000000000000000000000000000000000000000..b3b9647b05a23bfe3e1c06ec04f7ae0f13565305 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor_gl.h @@ -0,0 +1,41 @@ +// 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_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_GL_H_ +#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_GL_H_ + +#include + +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/embedder/embedder.h" +#include "flutter/shell/platform/embedder/tests/embedder_test_compositor.h" +#include "flutter/testing/test_gl_context.h" + +namespace flutter { +namespace testing { + +class EmbedderTestCompositorGL : public EmbedderTestCompositor { + public: + EmbedderTestCompositorGL(std::shared_ptr egl_context, + SkISize surface_size, + sk_sp context); + + ~EmbedderTestCompositorGL() override; + + void SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType type, + FlutterSoftwarePixelFormat software_pixfmt) override; + + private: + std::shared_ptr egl_context_; + bool UpdateOffscrenComposition(const FlutterLayer** layers, + size_t layers_count) override; + + FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestCompositorGL); +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_GL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor_metal.h b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor_metal.h new file mode 100644 index 0000000000000000000000000000000000000000..4bd134ac3b445e06071839238b8928b59f2f9726 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor_metal.h @@ -0,0 +1,36 @@ +// 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_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_METAL_H_ +#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_METAL_H_ + +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/embedder/embedder.h" +#include "flutter/shell/platform/embedder/tests/embedder_test_compositor.h" + +namespace flutter { +namespace testing { + +class EmbedderTestCompositorMetal : public EmbedderTestCompositor { + public: + EmbedderTestCompositorMetal(SkISize surface_size, + sk_sp context); + + ~EmbedderTestCompositorMetal() override; + + void SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType type, + FlutterSoftwarePixelFormat software_pixfmt) override; + + private: + bool UpdateOffscrenComposition(const FlutterLayer** layers, + size_t layers_count) override; + + FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestCompositorMetal); +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_METAL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor_metal.mm b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor_metal.mm new file mode 100644 index 0000000000000000000000000000000000000000..cb3c2548e988a4a88a947b5be5e7604a2b4c04d3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor_metal.mm @@ -0,0 +1,125 @@ +// 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/shell/platform/embedder/tests/embedder_test_compositor_metal.h" + +#include + +#include "flutter/fml/logging.h" +#include "flutter/shell/platform/embedder/tests/embedder_assertions.h" +#include "flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_metal.h" +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" + +namespace flutter { +namespace testing { + +EmbedderTestCompositorMetal::EmbedderTestCompositorMetal(SkISize surface_size, + sk_sp context) + : EmbedderTestCompositor(surface_size, std::move(context)) {} + +EmbedderTestCompositorMetal::~EmbedderTestCompositorMetal() = default; + +void EmbedderTestCompositorMetal::SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType type, + FlutterSoftwarePixelFormat software_pixfmt) { + switch (type) { + case EmbedderTestBackingStoreProducer::RenderTargetType::kMetalTexture: + backingstore_producer_ = + std::make_unique(context_, type); + return; + case EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer: + case EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLSurface: + case EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture: + case EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer: + case EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer2: + case EmbedderTestBackingStoreProducer::RenderTargetType::kVulkanImage: + FML_LOG(FATAL) << "Unsupported render target type: " << static_cast(type); + return; + } +} + +bool EmbedderTestCompositorMetal::UpdateOffscrenComposition(const FlutterLayer** layers, + size_t layers_count) { + last_composition_ = nullptr; + + const auto image_info = SkImageInfo::MakeN32Premul(surface_size_); + + auto surface = SkSurfaces::RenderTarget(context_.get(), // context + skgpu::Budgeted::kNo, // budgeted + image_info, // image info + 1, // sample count + kTopLeft_GrSurfaceOrigin, // surface origin + nullptr, // surface properties + false // create mipmaps + ); + + if (!surface) { + FML_LOG(ERROR) << "Could not update the off-screen composition."; + return false; + } + + auto canvas = surface->getCanvas(); + + // This has to be transparent because we are going to be compositing this + // sub-hierarchy onto the on-screen surface. + canvas->clear(SK_ColorTRANSPARENT); + + for (size_t i = 0; i < layers_count; ++i) { + const auto* layer = layers[i]; + + sk_sp platform_rendered_contents; + + sk_sp layer_image; + SkIPoint canvas_offset = SkIPoint::Make(0, 0); + + switch (layer->type) { + case kFlutterLayerContentTypeBackingStore: + layer_image = + reinterpret_cast(layer->backing_store->user_data)->makeImageSnapshot(); + break; + case kFlutterLayerContentTypePlatformView: + layer_image = platform_view_renderer_callback_ + ? platform_view_renderer_callback_(*layer, context_.get()) + : nullptr; + canvas_offset = SkIPoint::Make(layer->offset.x, layer->offset.y); + break; + }; + + // If the layer is not a platform view but the engine did not specify an + // image for the backing store, it is an error. + if (!layer_image && layer->type != kFlutterLayerContentTypePlatformView) { + FML_LOG(ERROR) << "Could not snapshot layer in test compositor: " << *layer; + return false; + } + + // The test could have just specified no contents to be rendered in place of + // a platform view. This is not an error. + if (layer_image) { + // The image rendered by Flutter already has the correct offset and + // transformation applied. The layers offset is meant for the platform. + canvas->drawImage(layer_image.get(), canvas_offset.x(), canvas_offset.y()); + } + } + + last_composition_ = surface->makeImageSnapshot(); + + if (!last_composition_) { + FML_LOG(ERROR) << "Could not update the contents of the sub-composition."; + return false; + } + + if (next_scene_callback_) { + auto last_composition_snapshot = last_composition_->makeRasterImage(); + FML_CHECK(last_composition_snapshot); + auto callback = next_scene_callback_; + next_scene_callback_ = nullptr; + callback(std::move(last_composition_snapshot)); + } + + return true; +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor_software.cc b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor_software.cc new file mode 100644 index 0000000000000000000000000000000000000000..369a4f89e676fd1607856ff4ec8b950df5bd884b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor_software.cc @@ -0,0 +1,121 @@ +// 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/shell/platform/embedder/tests/embedder_test_compositor_software.h" + +#include "flutter/fml/logging.h" +#include "flutter/shell/platform/embedder/tests/embedder_assertions.h" +#include "flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_software.h" +#include "third_party/skia/include/core/SkSurface.h" + +namespace flutter { +namespace testing { + +EmbedderTestCompositorSoftware::EmbedderTestCompositorSoftware( + SkISize surface_size) + : EmbedderTestCompositor(surface_size, nullptr) {} + +EmbedderTestCompositorSoftware::~EmbedderTestCompositorSoftware() = default; + +void EmbedderTestCompositorSoftware::SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType type, + FlutterSoftwarePixelFormat software_pixfmt) { + switch (type) { + case EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer: + case EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer2: + backingstore_producer_ = + std::make_unique( + context_, type, software_pixfmt); + return; + case EmbedderTestBackingStoreProducer::RenderTargetType::kMetalTexture: + case EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer: + case EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLSurface: + case EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture: + case EmbedderTestBackingStoreProducer::RenderTargetType::kVulkanImage: + FML_LOG(FATAL) << "Unsupported render target type: " + << static_cast(type); + return; + } +} + +bool EmbedderTestCompositorSoftware::UpdateOffscrenComposition( + const FlutterLayer** layers, + size_t layers_count) { + last_composition_ = nullptr; + + const auto image_info = SkImageInfo::MakeN32Premul(surface_size_); + + auto surface = SkSurfaces::Raster(image_info); + + if (!surface) { + FML_LOG(ERROR) << "Could not update the off-screen composition."; + return false; + } + + auto canvas = surface->getCanvas(); + + // This has to be transparent because we are going to be compositing this + // sub-hierarchy onto the on-screen surface. + canvas->clear(SK_ColorTRANSPARENT); + + for (size_t i = 0; i < layers_count; ++i) { + const auto* layer = layers[i]; + + sk_sp platform_rendered_contents; + + sk_sp layer_image; + SkIPoint canvas_offset = SkIPoint::Make(0, 0); + + switch (layer->type) { + case kFlutterLayerContentTypeBackingStore: { + layer_image = + backingstore_producer_->MakeImageSnapshot(layer->backing_store); + break; + } + case kFlutterLayerContentTypePlatformView: + layer_image = platform_view_renderer_callback_ + ? platform_view_renderer_callback_(*layer, nullptr) + : nullptr; + canvas_offset = SkIPoint::Make(layer->offset.x, layer->offset.y); + break; + }; + + // If the layer is not a platform view but the engine did not specify an + // image for the backing store, it is an error. + if (!layer_image && layer->type != kFlutterLayerContentTypePlatformView) { + FML_LOG(ERROR) << "Could not snapshot layer in test compositor: " + << *layer; + return false; + } + + // The test could have just specified no contents to be rendered in place of + // a platform view. This is not an error. + if (layer_image) { + // The image rendered by Flutter already has the correct offset and + // transformation applied. The layers offset is meant for the platform. + canvas->drawImage(layer_image.get(), canvas_offset.x(), + canvas_offset.y()); + } + } + + last_composition_ = surface->makeImageSnapshot(); + + if (!last_composition_) { + FML_LOG(ERROR) << "Could not update the contents of the sub-composition."; + return false; + } + + if (next_scene_callback_) { + auto last_composition_snapshot = last_composition_->makeRasterImage(); + FML_CHECK(last_composition_snapshot); + auto callback = next_scene_callback_; + next_scene_callback_ = nullptr; + callback(std::move(last_composition_snapshot)); + } + + return true; +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor_software.h b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor_software.h new file mode 100644 index 0000000000000000000000000000000000000000..d076d29106e3ef7438b067dbc798744197cb6200 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor_software.h @@ -0,0 +1,33 @@ +// 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_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_SOFTWARE_H_ +#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_SOFTWARE_H_ + +#include "flutter/shell/platform/embedder/tests/embedder_test_compositor.h" + +namespace flutter { +namespace testing { + +class EmbedderTestCompositorSoftware : public EmbedderTestCompositor { + public: + explicit EmbedderTestCompositorSoftware(SkISize surface_size); + + ~EmbedderTestCompositorSoftware() override; + + void SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType type, + FlutterSoftwarePixelFormat software_pixfmt) override; + + private: + bool UpdateOffscrenComposition(const FlutterLayer** layers, + size_t layers_count); + + FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestCompositorSoftware); +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_SOFTWARE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor_vulkan.cc b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor_vulkan.cc new file mode 100644 index 0000000000000000000000000000000000000000..480c8c88b757504a14471b0670a5a3c56a18129f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor_vulkan.cc @@ -0,0 +1,133 @@ +// 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/shell/platform/embedder/tests/embedder_test_compositor_vulkan.h" + +#include + +#include "flutter/fml/logging.h" +#include "flutter/shell/platform/embedder/tests/embedder_assertions.h" +#include "flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_vulkan.h" +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" + +namespace flutter { +namespace testing { + +EmbedderTestCompositorVulkan::EmbedderTestCompositorVulkan( + SkISize surface_size, + sk_sp context) + : EmbedderTestCompositor(surface_size, std::move(context)) {} + +EmbedderTestCompositorVulkan::~EmbedderTestCompositorVulkan() = default; + +void EmbedderTestCompositorVulkan::SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType type, + FlutterSoftwarePixelFormat software_pixfmt) { + switch (type) { + case EmbedderTestBackingStoreProducer::RenderTargetType::kVulkanImage: + backingstore_producer_ = + std::make_unique(context_, + type); + return; + case EmbedderTestBackingStoreProducer::RenderTargetType::kMetalTexture: + case EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLFramebuffer: + case EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLSurface: + case EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture: + case EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer: + case EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer2: + FML_LOG(FATAL) << "Unsupported render target type: " + << static_cast(type); + return; + } +} + +bool EmbedderTestCompositorVulkan::UpdateOffscrenComposition( + const FlutterLayer** layers, + size_t layers_count) { + last_composition_ = nullptr; + + const auto image_info = SkImageInfo::MakeN32Premul(surface_size_); + + sk_sp surface = + SkSurfaces::RenderTarget(context_.get(), // context + skgpu::Budgeted::kNo, // budgeted + image_info, // image info + 1, // sample count + kTopLeft_GrSurfaceOrigin, // surface origin + nullptr, // surface properties + false // create mipmaps + ); + + if (!surface) { + FML_LOG(ERROR) << "Could not update the off-screen composition."; + return false; + } + + auto canvas = surface->getCanvas(); + + // This has to be transparent because we are going to be compositing this + // sub-hierarchy onto the on-screen surface. + canvas->clear(SK_ColorTRANSPARENT); + + for (size_t i = 0; i < layers_count; ++i) { + const auto* layer = layers[i]; + + sk_sp platform_rendered_contents; + + sk_sp layer_image; + SkIPoint canvas_offset = SkIPoint::Make(0, 0); + + switch (layer->type) { + case kFlutterLayerContentTypeBackingStore: + layer_image = + backingstore_producer_->MakeImageSnapshot(layer->backing_store); + break; + case kFlutterLayerContentTypePlatformView: + layer_image = + platform_view_renderer_callback_ + ? platform_view_renderer_callback_(*layer, context_.get()) + : nullptr; + canvas_offset = SkIPoint::Make(layer->offset.x, layer->offset.y); + break; + }; + + // If the layer is not a platform view but the engine did not specify an + // image for the backing store, it is an error. + if (!layer_image && layer->type != kFlutterLayerContentTypePlatformView) { + FML_LOG(ERROR) << "Could not snapshot layer in test compositor: " + << *layer; + return false; + } + + // The test could have just specified no contents to be rendered in place of + // a platform view. This is not an error. + if (layer_image) { + // The image rendered by Flutter already has the correct offset and + // transformation applied. The layers offset is meant for the platform. + canvas->drawImage(layer_image.get(), canvas_offset.x(), + canvas_offset.y()); + } + } + + last_composition_ = surface->makeImageSnapshot(); + + if (!last_composition_) { + FML_LOG(ERROR) << "Could not update the contents of the sub-composition."; + return false; + } + + if (next_scene_callback_) { + auto last_composition_snapshot = last_composition_->makeRasterImage(); + FML_CHECK(last_composition_snapshot); + auto callback = next_scene_callback_; + next_scene_callback_ = nullptr; + callback(std::move(last_composition_snapshot)); + } + + return true; +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor_vulkan.h b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor_vulkan.h new file mode 100644 index 0000000000000000000000000000000000000000..46d54fe728fefd6bfeb1c0e5675a134561ff230b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_compositor_vulkan.h @@ -0,0 +1,36 @@ +// 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_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_VULKAN_H_ +#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_VULKAN_H_ + +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/embedder/embedder.h" +#include "flutter/shell/platform/embedder/tests/embedder_test_compositor.h" + +namespace flutter { +namespace testing { + +class EmbedderTestCompositorVulkan : public EmbedderTestCompositor { + public: + EmbedderTestCompositorVulkan(SkISize surface_size, + sk_sp context); + + ~EmbedderTestCompositorVulkan() override; + + void SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType type, + FlutterSoftwarePixelFormat software_pixfmt) override; + + private: + bool UpdateOffscrenComposition(const FlutterLayer** layers, + size_t layers_count) override; + + FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestCompositorVulkan); +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_VULKAN_H_ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context.cc b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context.cc new file mode 100644 index 0000000000000000000000000000000000000000..78ffd1ed0cf0205f700fe9b388df08cfdb9373fc --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context.cc @@ -0,0 +1,324 @@ +// 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/shell/platform/embedder/tests/embedder_test_context.h" + +#include + +#include "flutter/fml/make_copyable.h" +#include "flutter/fml/paths.h" +#include "flutter/runtime/dart_vm.h" +#include "flutter/shell/platform/embedder/tests/embedder_assertions.h" +#include "flutter/testing/testing.h" +#include "third_party/dart/runtime/bin/elf_loader.h" +#include "third_party/skia/include/core/SkSurface.h" + +namespace flutter { +namespace testing { + +EmbedderTestContext::EmbedderTestContext(std::string assets_path) + : assets_path_(std::move(assets_path)), + aot_symbols_( + LoadELFSymbolFromFixturesIfNeccessary(kDefaultAOTAppELFFileName)), + native_resolver_(std::make_shared()) { + SetupAOTMappingsIfNecessary(); + SetupAOTDataIfNecessary(); + isolate_create_callbacks_.push_back( + [weak_resolver = + std::weak_ptr{native_resolver_}]() { + if (auto resolver = weak_resolver.lock()) { + resolver->SetNativeResolverForIsolate(); + } + }); +} + +EmbedderTestContext::~EmbedderTestContext() = default; + +void EmbedderTestContext::SetupAOTMappingsIfNecessary() { + if (!DartVM::IsRunningPrecompiledCode()) { + return; + } + vm_snapshot_data_ = + std::make_unique(aot_symbols_.vm_snapshot_data, 0u); + vm_snapshot_instructions_ = std::make_unique( + aot_symbols_.vm_snapshot_instrs, 0u); + isolate_snapshot_data_ = + std::make_unique(aot_symbols_.vm_isolate_data, 0u); + isolate_snapshot_instructions_ = std::make_unique( + aot_symbols_.vm_isolate_instrs, 0u); +} + +void EmbedderTestContext::SetupAOTDataIfNecessary() { + if (!DartVM::IsRunningPrecompiledCode()) { + return; + } + FlutterEngineAOTDataSource data_in = {}; + FlutterEngineAOTData data_out = nullptr; + + const auto elf_path = fml::paths::JoinPaths( + {GetFixturesPath(), testing::kDefaultAOTAppELFFileName}); + + data_in.type = kFlutterEngineAOTDataSourceTypeElfPath; + data_in.elf_path = elf_path.c_str(); + + ASSERT_EQ(FlutterEngineCreateAOTData(&data_in, &data_out), kSuccess); + + aot_data_.reset(data_out); +} + +const std::string& EmbedderTestContext::GetAssetsPath() const { + return assets_path_; +} + +const fml::Mapping* EmbedderTestContext::GetVMSnapshotData() const { + return vm_snapshot_data_.get(); +} + +const fml::Mapping* EmbedderTestContext::GetVMSnapshotInstructions() const { + return vm_snapshot_instructions_.get(); +} + +const fml::Mapping* EmbedderTestContext::GetIsolateSnapshotData() const { + return isolate_snapshot_data_.get(); +} + +const fml::Mapping* EmbedderTestContext::GetIsolateSnapshotInstructions() + const { + return isolate_snapshot_instructions_.get(); +} + +FlutterEngineAOTData EmbedderTestContext::GetAOTData() const { + return aot_data_.get(); +} + +void EmbedderTestContext::SetRootSurfaceTransformation(SkMatrix matrix) { + root_surface_transformation_ = matrix; +} + +FlutterRendererConfig& EmbedderTestContext::GetRendererConfig() { + return renderer_config_; +} + +void EmbedderTestContext::AddIsolateCreateCallback( + const fml::closure& closure) { + if (closure) { + isolate_create_callbacks_.push_back(closure); + } +} + +VoidCallback EmbedderTestContext::GetIsolateCreateCallbackHook() { + return [](void* user_data) { + reinterpret_cast(user_data) + ->FireIsolateCreateCallbacks(); + }; +} + +void EmbedderTestContext::FireIsolateCreateCallbacks() { + for (const auto& closure : isolate_create_callbacks_) { + closure(); + } +} + +void EmbedderTestContext::AddNativeCallback(const char* name, + Dart_NativeFunction function) { + native_resolver_->AddNativeCallback({name}, function); +} + +void EmbedderTestContext::SetSemanticsUpdateCallback2( + SemanticsUpdateCallback2 update_semantics_callback) { + update_semantics_callback2_ = std::move(update_semantics_callback); +} + +void EmbedderTestContext::SetSemanticsUpdateCallback( + SemanticsUpdateCallback update_semantics_callback) { + update_semantics_callback_ = std::move(update_semantics_callback); +} + +void EmbedderTestContext::SetSemanticsNodeCallback( + SemanticsNodeCallback update_semantics_node_callback) { + update_semantics_node_callback_ = std::move(update_semantics_node_callback); +} + +void EmbedderTestContext::SetSemanticsCustomActionCallback( + SemanticsActionCallback update_semantics_custom_action_callback) { + update_semantics_custom_action_callback_ = + std::move(update_semantics_custom_action_callback); +} + +void EmbedderTestContext::SetPlatformMessageCallback( + const std::function& callback) { + platform_message_callback_ = callback; +} + +void EmbedderTestContext::SetChannelUpdateCallback( + const ChannelUpdateCallback& callback) { + channel_update_callback_ = callback; +} + +void EmbedderTestContext::SetViewFocusChangeRequestCallback( + const ViewFocusChangeRequestCallback& callback) { + view_focus_change_request_callback_ = callback; +} + +void EmbedderTestContext::PlatformMessageCallback( + const FlutterPlatformMessage* message) { + if (platform_message_callback_) { + platform_message_callback_(message); + } +} + +void EmbedderTestContext::SetLogMessageCallback( + const LogMessageCallback& callback) { + log_message_callback_ = callback; +} + +FlutterUpdateSemanticsCallback2 +EmbedderTestContext::GetUpdateSemanticsCallback2Hook() { + if (update_semantics_callback2_ == nullptr) { + return nullptr; + } + + return [](const FlutterSemanticsUpdate2* update, void* user_data) { + auto context = reinterpret_cast(user_data); + if (context->update_semantics_callback2_) { + context->update_semantics_callback2_(update); + } + }; +} + +FlutterUpdateSemanticsCallback +EmbedderTestContext::GetUpdateSemanticsCallbackHook() { + if (update_semantics_callback_ == nullptr) { + return nullptr; + } + + return [](const FlutterSemanticsUpdate* update, void* user_data) { + auto context = reinterpret_cast(user_data); + if (context->update_semantics_callback_) { + context->update_semantics_callback_(update); + } + }; +} + +FlutterUpdateSemanticsNodeCallback +EmbedderTestContext::GetUpdateSemanticsNodeCallbackHook() { + if (update_semantics_node_callback_ == nullptr) { + return nullptr; + } + + return [](const FlutterSemanticsNode* semantics_node, void* user_data) { + auto context = reinterpret_cast(user_data); + if (context->update_semantics_node_callback_) { + context->update_semantics_node_callback_(semantics_node); + } + }; +} + +FlutterUpdateSemanticsCustomActionCallback +EmbedderTestContext::GetUpdateSemanticsCustomActionCallbackHook() { + if (update_semantics_custom_action_callback_ == nullptr) { + return nullptr; + } + + return [](const FlutterSemanticsCustomAction* action, void* user_data) { + auto context = reinterpret_cast(user_data); + if (context->update_semantics_custom_action_callback_) { + context->update_semantics_custom_action_callback_(action); + } + }; +} + +FlutterLogMessageCallback EmbedderTestContext::GetLogMessageCallbackHook() { + return [](const char* tag, const char* message, void* user_data) { + auto context = reinterpret_cast(user_data); + if (context->log_message_callback_) { + context->log_message_callback_(tag, message); + } + }; +} + +FlutterComputePlatformResolvedLocaleCallback +EmbedderTestContext::GetComputePlatformResolvedLocaleCallbackHook() { + return [](const FlutterLocale** supported_locales, + size_t length) -> const FlutterLocale* { + return supported_locales[0]; + }; +} + +FlutterChannelUpdateCallback +EmbedderTestContext::GetChannelUpdateCallbackHook() { + if (channel_update_callback_ == nullptr) { + return nullptr; + } + + return [](const FlutterChannelUpdate* update, void* user_data) { + auto context = reinterpret_cast(user_data); + if (context->channel_update_callback_) { + context->channel_update_callback_(update); + } + }; +} + +FlutterViewFocusChangeRequestCallback +EmbedderTestContext::GetViewFocusChangeRequestCallbackHook() { + return [](const FlutterViewFocusChangeRequest* request, void* user_data) { + auto context = reinterpret_cast(user_data); + if (context->view_focus_change_request_callback_) { + context->view_focus_change_request_callback_(request); + } + }; +} + +FlutterTransformation EmbedderTestContext::GetRootSurfaceTransformation() { + return FlutterTransformationMake(root_surface_transformation_); +} + +EmbedderTestCompositor& EmbedderTestContext::GetCompositor() { + FML_CHECK(compositor_) + << "Accessed the compositor on a context where one was not set up. Use " + "the config builder to set up a context with a custom compositor."; + return *compositor_; +} + +void EmbedderTestContext::SetNextSceneCallback( + const NextSceneCallback& next_scene_callback) { + if (compositor_) { + compositor_->SetNextSceneCallback(next_scene_callback); + return; + } + next_scene_callback_ = next_scene_callback; +} + +std::future> EmbedderTestContext::GetNextSceneImage() { + std::promise> promise; + auto future = promise.get_future(); + SetNextSceneCallback( + fml::MakeCopyable([promise = std::move(promise)](auto image) mutable { + promise.set_value(image); + })); + return future; +} + +/// @note Procedure doesn't copy all closures. +void EmbedderTestContext::FireRootSurfacePresentCallbackIfPresent( + const std::function(void)>& image_callback) { + if (!next_scene_callback_) { + return; + } + auto callback = next_scene_callback_; + next_scene_callback_ = nullptr; + callback(image_callback()); +} + +void EmbedderTestContext::SetVsyncCallback( + std::function callback) { + vsync_callback_ = std::move(callback); +} + +void EmbedderTestContext::RunVsyncCallback(intptr_t baton) { + vsync_callback_(baton); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context.h b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context.h new file mode 100644 index 0000000000000000000000000000000000000000..15421ef8dd5d695e4171906f92e303baf26269d9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context.h @@ -0,0 +1,196 @@ +// 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_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_H_ +#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_H_ + +#include +#include +#include +#include +#include +#include + +#include "flutter/fml/closure.h" +#include "flutter/fml/macros.h" +#include "flutter/fml/mapping.h" +#include "flutter/shell/platform/embedder/embedder.h" +#include "flutter/shell/platform/embedder/tests/embedder_test_compositor.h" +#include "flutter/testing/elf_loader.h" +#include "flutter/testing/test_dart_native_resolver.h" +#include "third_party/skia/include/core/SkImage.h" + +namespace flutter { +namespace testing { + +using SemanticsUpdateCallback2 = + std::function; +using SemanticsUpdateCallback = + std::function; +using SemanticsNodeCallback = std::function; +using SemanticsActionCallback = + std::function; +using LogMessageCallback = + std::function; +using ChannelUpdateCallback = std::function; +using ViewFocusChangeRequestCallback = + std::function; + +struct AOTDataDeleter { + void operator()(FlutterEngineAOTData aot_data) { + if (aot_data) { + FlutterEngineCollectAOTData(aot_data); + } + } +}; + +using UniqueAOTData = std::unique_ptr<_FlutterEngineAOTData, AOTDataDeleter>; + +enum class EmbedderTestContextType { + kSoftwareContext, + kOpenGLContext, + kMetalContext, + kVulkanContext, +}; + +class EmbedderTestContext { + public: + explicit EmbedderTestContext(std::string assets_path = ""); + + virtual ~EmbedderTestContext(); + + const std::string& GetAssetsPath() const; + + const fml::Mapping* GetVMSnapshotData() const; + + const fml::Mapping* GetVMSnapshotInstructions() const; + + const fml::Mapping* GetIsolateSnapshotData() const; + + const fml::Mapping* GetIsolateSnapshotInstructions() const; + + FlutterEngineAOTData GetAOTData() const; + + void SetRootSurfaceTransformation(SkMatrix matrix); + + FlutterRendererConfig& GetRendererConfig(); + + void AddIsolateCreateCallback(const fml::closure& closure); + + void SetSemanticsUpdateCallback2(SemanticsUpdateCallback2 update_semantics); + + void SetSemanticsUpdateCallback(SemanticsUpdateCallback update_semantics); + + void AddNativeCallback(const char* name, Dart_NativeFunction function); + + void SetSemanticsNodeCallback(SemanticsNodeCallback update_semantics_node); + + void SetSemanticsCustomActionCallback( + SemanticsActionCallback semantics_custom_action); + + void SetPlatformMessageCallback( + const std::function& callback); + + void SetLogMessageCallback(const LogMessageCallback& log_message_callback); + + void SetChannelUpdateCallback(const ChannelUpdateCallback& callback); + + void SetViewFocusChangeRequestCallback( + const ViewFocusChangeRequestCallback& callback); + + std::future> GetNextSceneImage(); + + EmbedderTestCompositor& GetCompositor(); + + virtual size_t GetSurfacePresentCount() const = 0; + + virtual EmbedderTestContextType GetContextType() const = 0; + + // Sets up the callback for vsync. This callback will be invoked + // for every vsync. This should be used in conjunction with SetupVsyncCallback + // on the EmbedderConfigBuilder. Any callback setup here must call + // `FlutterEngineOnVsync` from the platform task runner. + void SetVsyncCallback(std::function callback); + + // Runs the vsync callback. + void RunVsyncCallback(intptr_t baton); + + // TODO(gw280): encapsulate these properly for subclasses to use + protected: + // This allows the builder to access the hooks. + friend class EmbedderConfigBuilder; + + using NextSceneCallback = std::function image)>; + + std::string assets_path_; + ELFAOTSymbols aot_symbols_; + std::unique_ptr vm_snapshot_data_; + std::unique_ptr vm_snapshot_instructions_; + std::unique_ptr isolate_snapshot_data_; + std::unique_ptr isolate_snapshot_instructions_; + UniqueAOTData aot_data_; + std::vector isolate_create_callbacks_; + std::shared_ptr native_resolver_; + FlutterRendererConfig renderer_config_ = {}; + SemanticsUpdateCallback2 update_semantics_callback2_; + SemanticsUpdateCallback update_semantics_callback_; + SemanticsNodeCallback update_semantics_node_callback_; + SemanticsActionCallback update_semantics_custom_action_callback_; + ChannelUpdateCallback channel_update_callback_; + ViewFocusChangeRequestCallback view_focus_change_request_callback_; + std::function platform_message_callback_; + LogMessageCallback log_message_callback_; + std::unique_ptr compositor_; + NextSceneCallback next_scene_callback_; + SkMatrix root_surface_transformation_; + std::function vsync_callback_ = nullptr; + + static VoidCallback GetIsolateCreateCallbackHook(); + + FlutterUpdateSemanticsCallback2 GetUpdateSemanticsCallback2Hook(); + + FlutterUpdateSemanticsCallback GetUpdateSemanticsCallbackHook(); + + FlutterUpdateSemanticsNodeCallback GetUpdateSemanticsNodeCallbackHook(); + + FlutterUpdateSemanticsCustomActionCallback + GetUpdateSemanticsCustomActionCallbackHook(); + + static FlutterLogMessageCallback GetLogMessageCallbackHook(); + + static FlutterComputePlatformResolvedLocaleCallback + GetComputePlatformResolvedLocaleCallbackHook(); + + FlutterChannelUpdateCallback GetChannelUpdateCallbackHook(); + + FlutterViewFocusChangeRequestCallback GetViewFocusChangeRequestCallbackHook(); + + void SetupAOTMappingsIfNecessary(); + + void SetupAOTDataIfNecessary(); + + virtual void SetSurface(SkISize surface_size) = 0; + + virtual void SetupCompositor() = 0; + + void FireIsolateCreateCallbacks(); + + void SetNativeResolver(); + + FlutterTransformation GetRootSurfaceTransformation(); + + void PlatformMessageCallback(const FlutterPlatformMessage* message); + + void FireRootSurfacePresentCallbackIfPresent( + const std::function(void)>& image_callback); + + void SetNextSceneCallback(const NextSceneCallback& next_scene_callback); + + FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestContext); +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_H_ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context_gl.cc b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context_gl.cc new file mode 100644 index 0000000000000000000000000000000000000000..055c2f2ace8026ef6512944bb0b3be81a35b85a5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context_gl.cc @@ -0,0 +1,213 @@ +// 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/shell/platform/embedder/tests/embedder_test_context_gl.h" + +#include +#include + +#include "flutter/fml/make_copyable.h" +#include "flutter/fml/paths.h" +#include "flutter/runtime/dart_vm.h" +#include "flutter/shell/platform/embedder/tests/embedder_assertions.h" +#include "flutter/shell/platform/embedder/tests/embedder_test_compositor_gl.h" +#include "flutter/testing/testing.h" +#include "tests/embedder_test.h" +#include "third_party/dart/runtime/bin/elf_loader.h" +#include "third_party/skia/include/core/SkSurface.h" + +namespace flutter::testing { + +EmbedderTestContextGL::EmbedderTestContextGL(std::string assets_path) + : EmbedderTestContext(std::move(assets_path)), + egl_context_(std::make_shared()) { + renderer_config_.type = FlutterRendererType::kOpenGL; + renderer_config_.open_gl = { + .struct_size = sizeof(FlutterOpenGLRendererConfig), + .make_current = [](void* context) -> bool { + return reinterpret_cast(context) + ->GLMakeCurrent(); + }, + .clear_current = [](void* context) -> bool { + return reinterpret_cast(context) + ->GLClearCurrent(); + }, + .make_resource_current = [](void* context) -> bool { + return reinterpret_cast(context) + ->GLMakeResourceCurrent(); + }, + .fbo_reset_after_present = true, + .surface_transformation = [](void* context) -> FlutterTransformation { + return reinterpret_cast(context) + ->GetRootSurfaceTransformation(); + }, + .gl_proc_resolver = [](void* context, const char* name) -> void* { + return reinterpret_cast(context) + ->GLGetProcAddress(name); + }, + .fbo_with_frame_info_callback = + [](void* context, const FlutterFrameInfo* frame_info) -> uint32_t { + return reinterpret_cast(context) + ->GLGetFramebuffer(*frame_info); + }, + .present_with_info = [](void* context, + const FlutterPresentInfo* present_info) -> bool { + return reinterpret_cast(context)->GLPresent( + *present_info); + }, + .populate_existing_damage = nullptr, + }; +} + +EmbedderTestContextGL::~EmbedderTestContextGL() { + SetGLGetFBOCallback(nullptr); +} + +void EmbedderTestContextGL::SetOpenGLFBOCallBack() { + // SetOpenGLRendererConfig must be called before this. + FML_CHECK(renderer_config_.type == FlutterRendererType::kOpenGL); + + renderer_config_.open_gl.fbo_callback = [](void* context) -> uint32_t { + FlutterFrameInfo frame_info = {}; + // fbo_callback doesn't use the frame size information, only + // fbo_callback_with_frame_info does. + frame_info.struct_size = sizeof(FlutterFrameInfo); + frame_info.size.width = 0; + frame_info.size.height = 0; + return reinterpret_cast(context)->GLGetFramebuffer( + frame_info); + }; +} + +void EmbedderTestContextGL::SetOpenGLPresentCallBack() { + // SetOpenGLRendererConfig must be called before this. + FML_CHECK(renderer_config_.type == FlutterRendererType::kOpenGL); + + renderer_config_.open_gl.present = [](void* context) -> bool { + // passing a placeholder fbo_id. + return reinterpret_cast(context)->GLPresent( + FlutterPresentInfo{ + .fbo_id = 0, + }); + }; +} + +bool EmbedderTestContextGL::GLMakeCurrent() { + FML_CHECK(gl_surface_) << "GL surface must be initialized."; + return gl_surface_->MakeCurrent(); +} + +bool EmbedderTestContextGL::GLClearCurrent() { + FML_CHECK(gl_surface_) << "GL surface must be initialized."; + return gl_surface_->ClearCurrent(); +} + +bool EmbedderTestContextGL::GLPresent(FlutterPresentInfo present_info) { + FML_CHECK(gl_surface_) << "GL surface must be initialized."; + gl_surface_present_count_++; + + GLPresentCallback callback; + { + std::scoped_lock lock(gl_callback_mutex_); + callback = gl_present_callback_; + } + + if (callback) { + callback(present_info); + } + + FireRootSurfacePresentCallbackIfPresent( + [&]() { return gl_surface_->GetRasterSurfaceSnapshot(); }); + + return gl_surface_->Present(); +} + +void EmbedderTestContextGL::SetGLGetFBOCallback( + const GLGetFBOCallback& callback) { + std::scoped_lock lock(gl_callback_mutex_); + gl_get_fbo_callback_ = callback; +} + +void EmbedderTestContextGL::SetGLPopulateExistingDamageCallback( + GLPopulateExistingDamageCallback callback) { + std::scoped_lock lock(gl_callback_mutex_); + gl_populate_existing_damage_callback_ = std::move(callback); +} + +void EmbedderTestContextGL::SetGLPresentCallback(GLPresentCallback callback) { + std::scoped_lock lock(gl_callback_mutex_); + gl_present_callback_ = std::move(callback); +} + +uint32_t EmbedderTestContextGL::GLGetFramebuffer(FlutterFrameInfo frame_info) { + FML_CHECK(gl_surface_) << "GL surface must be initialized."; + + GLGetFBOCallback callback; + { + std::scoped_lock lock(gl_callback_mutex_); + callback = gl_get_fbo_callback_; + } + + if (callback) { + callback(frame_info); + } + + const auto size = frame_info.size; + return gl_surface_->GetFramebuffer(size.width, size.height); +} + +void EmbedderTestContextGL::GLPopulateExistingDamage( + const intptr_t id, + FlutterDamage* existing_damage) { + FML_CHECK(gl_surface_) << "GL surface must be initialized."; + + GLPopulateExistingDamageCallback callback; + { + std::scoped_lock lock(gl_callback_mutex_); + callback = gl_populate_existing_damage_callback_; + } + + if (callback) { + callback(id, existing_damage); + } +} + +bool EmbedderTestContextGL::GLMakeResourceCurrent() { + FML_CHECK(gl_surface_) << "GL surface must be initialized."; + return gl_surface_->MakeResourceCurrent(); +} + +void* EmbedderTestContextGL::GLGetProcAddress(const char* name) { + FML_CHECK(gl_surface_) << "GL surface must be initialized."; + return gl_surface_->GetProcAddress(name); +} + +size_t EmbedderTestContextGL::GetSurfacePresentCount() const { + return gl_surface_present_count_; +} + +EmbedderTestContextType EmbedderTestContextGL::GetContextType() const { + return EmbedderTestContextType::kOpenGLContext; +} + +uint32_t EmbedderTestContextGL::GetWindowFBOId() const { + FML_CHECK(gl_surface_); + return gl_surface_->GetWindowFBOId(); +} + +void EmbedderTestContextGL::SetSurface(SkISize surface_size) { + FML_CHECK(!gl_surface_); + gl_surface_ = std::make_unique(egl_context_, surface_size); +} + +void EmbedderTestContextGL::SetupCompositor() { + FML_CHECK(!compositor_) << "Already set up a compositor in this context."; + FML_CHECK(gl_surface_) + << "Set up the GL surface before setting up a compositor."; + compositor_ = std::make_unique( + egl_context_, gl_surface_->GetSurfaceSize(), gl_surface_->GetGrContext()); + GLClearCurrent(); +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context_gl.h b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context_gl.h new file mode 100644 index 0000000000000000000000000000000000000000..c7f61ca7757e0b5cf82a0a217dca97c5c91ed201 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context_gl.h @@ -0,0 +1,112 @@ +// 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_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_GL_H_ +#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_GL_H_ + +#include "flutter/shell/platform/embedder/tests/embedder_test_context.h" + +#include "flutter/testing/test_gl_context.h" +#include "flutter/testing/test_gl_surface.h" + +namespace flutter { +namespace testing { + +class EmbedderTestContextGL : public EmbedderTestContext { + public: + using GLGetFBOCallback = std::function; + using GLPopulateExistingDamageCallback = + std::function; + using GLPresentCallback = + std::function; + + explicit EmbedderTestContextGL(std::string assets_path = ""); + + ~EmbedderTestContextGL() override; + + size_t GetSurfacePresentCount() const override; + + // |EmbedderTestContext| + EmbedderTestContextType GetContextType() const override; + + // Used to explicitly set an `open_gl.fbo_callback`. Using this method will + // cause your test to fail since the ctor for this class sets + // `open_gl.fbo_callback_with_frame_info`. This method exists as a utility to + // explicitly test this behavior. + void SetOpenGLFBOCallBack(); + + // Used to explicitly set an `open_gl.present`. Using this method will cause + // your test to fail since the ctor for this class sets + // `open_gl.present_with_info`. This method exists as a utility to explicitly + // test this behavior. + void SetOpenGLPresentCallBack(); + + //---------------------------------------------------------------------------- + /// @brief Sets a callback that will be invoked (on the raster task + /// runner) when the engine asks the embedder for a new FBO ID at + /// the updated size. + /// + /// @attention The callback will be invoked on the raster task runner. The + /// callback can be set on the tests host thread. + /// + /// @param[in] callback The callback to set. The previous callback will be + /// un-registered. + /// + void SetGLGetFBOCallback(const GLGetFBOCallback& callback); + + void SetGLPopulateExistingDamageCallback( + GLPopulateExistingDamageCallback callback); + + uint32_t GetWindowFBOId() const; + + //---------------------------------------------------------------------------- + /// @brief Sets a callback that will be invoked (on the raster task + /// runner) when the engine presents an fbo that was given by the + /// embedder. + /// + /// @attention The callback will be invoked on the raster task runner. The + /// callback can be set on the tests host thread. + /// + /// @param[in] callback The callback to set. The previous callback will be + /// un-registered. + /// + void SetGLPresentCallback(GLPresentCallback callback); + + void GLPopulateExistingDamage(const intptr_t id, + FlutterDamage* existing_damage); + + void* GLGetProcAddress(const char* name); + + private: + // |EmbedderTestContext| + void SetSurface(SkISize surface_size) override; + + // |EmbedderTestContext| + void SetupCompositor() override; + + std::shared_ptr egl_context_; + std::unique_ptr gl_surface_; + size_t gl_surface_present_count_ = 0; + std::mutex gl_callback_mutex_; + GLGetFBOCallback gl_get_fbo_callback_; + GLPresentCallback gl_present_callback_; + GLPopulateExistingDamageCallback gl_populate_existing_damage_callback_; + + bool GLMakeCurrent(); + + bool GLClearCurrent(); + + bool GLPresent(FlutterPresentInfo present_info); + + uint32_t GLGetFramebuffer(FlutterFrameInfo frame_info); + + bool GLMakeResourceCurrent(); + + FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestContextGL); +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_GL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context_metal.h b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context_metal.h new file mode 100644 index 0000000000000000000000000000000000000000..b063db6973be2035e4c77cd8a09405d598463d48 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context_metal.h @@ -0,0 +1,81 @@ +// 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_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_METAL_H_ +#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_METAL_H_ + +#include "flutter/shell/platform/embedder/tests/embedder_test_context.h" +#include "flutter/testing/test_metal_context.h" +#include "flutter/testing/test_metal_surface.h" + +namespace flutter { +namespace testing { + +class EmbedderTestContextMetal : public EmbedderTestContext { + public: + using TestExternalTextureCallback = + std::function; + + using NextDrawableCallback = + std::function; + + using PresentCallback = std::function; + + explicit EmbedderTestContextMetal(std::string assets_path = ""); + + ~EmbedderTestContextMetal() override; + + // |EmbedderTestContext| + EmbedderTestContextType GetContextType() const override; + + // |EmbedderTestContext| + size_t GetSurfacePresentCount() const override; + + void SetExternalTextureCallback( + TestExternalTextureCallback external_texture_frame_callback); + + // Override the default handling for Present. + void SetPresentCallback(PresentCallback present_callback); + + bool Present(int64_t texture_id); + + bool PopulateExternalTexture(int64_t texture_id, + size_t w, + size_t h, + FlutterMetalExternalTexture* output); + + TestMetalContext* GetTestMetalContext(); + + TestMetalSurface* GetTestMetalSurface(); + + // Override the default handling for GetNextDrawable. + void SetNextDrawableCallback(NextDrawableCallback next_drawable_callback); + + FlutterMetalTexture GetNextDrawable(const FlutterFrameInfo* frame_info); + + private: + // |EmbedderTestContext| + void SetSurface(SkISize surface_size) override; + + // |EmbedderTestContext| + void SetupCompositor() override; + + TestExternalTextureCallback external_texture_frame_callback_ = nullptr; + SkISize surface_size_ = SkISize::MakeEmpty(); + std::unique_ptr metal_context_; + std::unique_ptr metal_surface_; + size_t present_count_ = 0; + PresentCallback present_callback_ = nullptr; + NextDrawableCallback next_drawable_callback_ = nullptr; + + FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestContextMetal); +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_METAL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context_metal.mm b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context_metal.mm new file mode 100644 index 0000000000000000000000000000000000000000..d50016d8ea383a57a0137cee5a8700019af89d70 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context_metal.mm @@ -0,0 +1,121 @@ +// 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/shell/platform/embedder/tests/embedder_test_context_metal.h" + +#include +#include + +#include "embedder.h" +#include "flutter/fml/logging.h" +#include "flutter/shell/platform/embedder/tests/embedder_test_compositor_metal.h" + +namespace flutter::testing { + +EmbedderTestContextMetal::EmbedderTestContextMetal(std::string assets_path) + : EmbedderTestContext(std::move(assets_path)) { + metal_context_ = std::make_unique(); + renderer_config_.type = FlutterRendererType::kMetal; + renderer_config_.metal = { + .struct_size = sizeof(FlutterMetalRendererConfig), + .device = (__bridge FlutterMetalDeviceHandle)metal_context_->GetMetalDevice(), + .present_command_queue = + (__bridge FlutterMetalCommandQueueHandle)metal_context_->GetMetalCommandQueue(), + .get_next_drawable_callback = + [](void* user_data, const FlutterFrameInfo* frame_info) { + return reinterpret_cast(user_data)->GetNextDrawable( + frame_info); + }, + .present_drawable_callback = [](void* user_data, const FlutterMetalTexture* texture) -> bool { + return reinterpret_cast(user_data)->Present(texture->texture_id); + }, + .external_texture_frame_callback = [](void* user_data, int64_t texture_id, size_t width, + size_t height, + FlutterMetalExternalTexture* texture_out) -> bool { + return reinterpret_cast(user_data)->PopulateExternalTexture( + texture_id, width, height, texture_out); + }, + }; +} + +EmbedderTestContextMetal::~EmbedderTestContextMetal() {} + +EmbedderTestContextType EmbedderTestContextMetal::GetContextType() const { + return EmbedderTestContextType::kMetalContext; +} + +size_t EmbedderTestContextMetal::GetSurfacePresentCount() const { + return present_count_; +} + +TestMetalContext* EmbedderTestContextMetal::GetTestMetalContext() { + return metal_context_.get(); +} + +TestMetalSurface* EmbedderTestContextMetal::GetTestMetalSurface() { + return metal_surface_.get(); +} + +void EmbedderTestContextMetal::SetPresentCallback(PresentCallback present_callback) { + present_callback_ = std::move(present_callback); +} + +bool EmbedderTestContextMetal::Present(int64_t texture_id) { + FireRootSurfacePresentCallbackIfPresent( + [&]() { return metal_surface_->GetRasterSurfaceSnapshot(); }); + present_count_++; + if (present_callback_ != nullptr) { + return present_callback_(texture_id); + } + return metal_context_->Present(texture_id); +} + +void EmbedderTestContextMetal::SetExternalTextureCallback( + TestExternalTextureCallback external_texture_frame_callback) { + external_texture_frame_callback_ = std::move(external_texture_frame_callback); +} + +bool EmbedderTestContextMetal::PopulateExternalTexture(int64_t texture_id, + size_t w, + size_t h, + FlutterMetalExternalTexture* output) { + if (external_texture_frame_callback_ != nullptr) { + return external_texture_frame_callback_(texture_id, w, h, output); + } else { + return false; + } +} + +void EmbedderTestContextMetal::SetNextDrawableCallback( + NextDrawableCallback next_drawable_callback) { + next_drawable_callback_ = std::move(next_drawable_callback); +} + +FlutterMetalTexture EmbedderTestContextMetal::GetNextDrawable(const FlutterFrameInfo* frame_info) { + if (next_drawable_callback_ != nullptr) { + return next_drawable_callback_(frame_info); + } + + auto texture_info = metal_surface_->GetTextureInfo(); + FlutterMetalTexture texture = {}; + texture.struct_size = sizeof(FlutterMetalTexture); + texture.texture_id = texture_info.texture_id; + texture.texture = reinterpret_cast(texture_info.texture); + return texture; +} + +void EmbedderTestContextMetal::SetSurface(SkISize surface_size) { + FML_CHECK(surface_size_.isEmpty()); + surface_size_ = surface_size; + metal_surface_ = TestMetalSurface::Create(*metal_context_, surface_size_); +} + +void EmbedderTestContextMetal::SetupCompositor() { + FML_CHECK(!compositor_) << "Already set up a compositor in this context."; + FML_CHECK(metal_surface_) << "Set up the Metal surface before setting up a compositor."; + compositor_ = + std::make_unique(surface_size_, metal_surface_->GetGrContext()); +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context_software.cc b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context_software.cc new file mode 100644 index 0000000000000000000000000000000000000000..1f06890abb725c99ec6c7a6bfaa429726f73fa2c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context_software.cc @@ -0,0 +1,71 @@ +// 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/shell/platform/embedder/tests/embedder_test_context_software.h" + +#include + +#include "flutter/fml/make_copyable.h" +#include "flutter/fml/paths.h" +#include "flutter/runtime/dart_vm.h" +#include "flutter/shell/platform/embedder/tests/embedder_assertions.h" +#include "flutter/shell/platform/embedder/tests/embedder_test_compositor_software.h" +#include "flutter/testing/testing.h" +#include "third_party/dart/runtime/bin/elf_loader.h" +#include "third_party/skia/include/core/SkBitmap.h" +#include "third_party/skia/include/core/SkSurface.h" + +namespace flutter::testing { + +EmbedderTestContextSoftware::EmbedderTestContextSoftware( + std::string assets_path) + : EmbedderTestContext(std::move(assets_path)) { + renderer_config_.type = FlutterRendererType::kSoftware; + renderer_config_.software = { + .struct_size = sizeof(FlutterSoftwareRendererConfig), + .surface_present_callback = + [](void* context, const void* allocation, size_t row_bytes, + size_t height) { + auto image_info = SkImageInfo::MakeN32Premul( + SkISize::Make(row_bytes / 4, height)); + SkBitmap bitmap; + if (!bitmap.installPixels(image_info, const_cast(allocation), + row_bytes)) { + FML_LOG(ERROR) << "Could not copy pixels for the software " + "composition from the engine."; + return false; + } + bitmap.setImmutable(); + return reinterpret_cast(context) + ->Present(SkImages::RasterFromBitmap(bitmap)); + }, + }; +} + +EmbedderTestContextSoftware::~EmbedderTestContextSoftware() = default; + +EmbedderTestContextType EmbedderTestContextSoftware::GetContextType() const { + return EmbedderTestContextType::kSoftwareContext; +} + +void EmbedderTestContextSoftware::SetSurface(SkISize surface_size) { + surface_size_ = surface_size; +} + +void EmbedderTestContextSoftware::SetupCompositor() { + FML_CHECK(!compositor_) << "Already set up a compositor in this context."; + compositor_ = std::make_unique(surface_size_); +} + +size_t EmbedderTestContextSoftware::GetSurfacePresentCount() const { + return software_surface_present_count_; +} + +bool EmbedderTestContextSoftware::Present(const sk_sp& image) { + software_surface_present_count_++; + FireRootSurfacePresentCallbackIfPresent([image] { return image; }); + return true; +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context_software.h b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context_software.h new file mode 100644 index 0000000000000000000000000000000000000000..05396b160352bcee20e80e8d2cd0490198c6e8c8 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context_software.h @@ -0,0 +1,46 @@ +// 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_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_SOFTWARE_H_ +#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_SOFTWARE_H_ + +#include "flutter/shell/platform/embedder/tests/embedder_test_context.h" + +#include "third_party/skia/include/core/SkSurface.h" + +namespace flutter { +namespace testing { + +class EmbedderTestContextSoftware : public EmbedderTestContext { + public: + explicit EmbedderTestContextSoftware(std::string assets_path = ""); + + ~EmbedderTestContextSoftware() override; + + // |EmbedderTestContext| + EmbedderTestContextType GetContextType() const override; + + // |EmbedderTestContext| + size_t GetSurfacePresentCount() const override; + + bool Present(const sk_sp& image); + + private: + // |EmbedderTestContext| + void SetSurface(SkISize surface_size) override; + + // |EmbedderTestContext| + void SetupCompositor() override; + + sk_sp surface_; + SkISize surface_size_; + size_t software_surface_present_count_ = 0; + + FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestContextSoftware); +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_SOFTWARE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context_vulkan.cc b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context_vulkan.cc new file mode 100644 index 0000000000000000000000000000000000000000..09bb264a38616d0c6a4a2f4077e80f7936d25ee6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context_vulkan.cc @@ -0,0 +1,105 @@ +// 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/shell/platform/embedder/tests/embedder_test_context_vulkan.h" + +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/shell/platform/embedder/tests/embedder_test_compositor_vulkan.h" +#include "flutter/testing/test_vulkan_context.h" +#include "flutter/testing/test_vulkan_surface.h" +#include "flutter/vulkan/procs/vulkan_proc_table.h" +#include "flutter/vulkan/vulkan_device.h" +#include "third_party/skia/include/core/SkSurface.h" + +namespace flutter::testing { + +EmbedderTestContextVulkan::EmbedderTestContextVulkan(std::string assets_path) + : EmbedderTestContext(std::move(assets_path)), surface_() { + vulkan_context_ = fml::MakeRefCounted(); + renderer_config_.type = FlutterRendererType::kVulkan; + renderer_config_.vulkan = { + .struct_size = sizeof(FlutterVulkanRendererConfig), + .version = vulkan_context_->application_->GetAPIVersion(), + .instance = vulkan_context_->application_->GetInstance(), + .physical_device = vulkan_context_->device_->GetPhysicalDeviceHandle(), + .device = vulkan_context_->device_->GetHandle(), + .queue_family_index = vulkan_context_->device_->GetGraphicsQueueIndex(), + .queue = vulkan_context_->device_->GetQueueHandle(), + .get_instance_proc_address_callback = + EmbedderTestContextVulkan::InstanceProcAddr, + .get_next_image_callback = + [](void* context, + const FlutterFrameInfo* frame_info) -> FlutterVulkanImage { + VkImage image = + reinterpret_cast(context)->GetNextImage( + {static_cast(frame_info->size.width), + static_cast(frame_info->size.height)}); + return { + .struct_size = sizeof(FlutterVulkanImage), + .image = reinterpret_cast(image), + .format = VK_FORMAT_R8G8B8A8_UNORM, + }; + }, + .present_image_callback = [](void* context, + const FlutterVulkanImage* image) -> bool { + return reinterpret_cast(context) + ->PresentImage(reinterpret_cast(image->image)); + }, + }; +} + +EmbedderTestContextVulkan::~EmbedderTestContextVulkan() {} + +EmbedderTestContextType EmbedderTestContextVulkan::GetContextType() const { + return EmbedderTestContextType::kVulkanContext; +} + +void EmbedderTestContextVulkan::SetVulkanInstanceProcAddressCallback( + FlutterVulkanInstanceProcAddressCallback callback) { + renderer_config_.vulkan.get_instance_proc_address_callback = callback; +} + +size_t EmbedderTestContextVulkan::GetSurfacePresentCount() const { + return present_count_; +} + +VkImage EmbedderTestContextVulkan::GetNextImage(const SkISize& size) { + return surface_->GetImage(); +} + +bool EmbedderTestContextVulkan::PresentImage(VkImage image) { + FireRootSurfacePresentCallbackIfPresent( + [&]() { return surface_->GetSurfaceSnapshot(); }); + present_count_++; + return true; +} + +void* EmbedderTestContextVulkan::InstanceProcAddr( + void* user_data, + FlutterVulkanInstanceHandle instance, + const char* name) { + auto proc_addr = reinterpret_cast(user_data) + ->vulkan_context_->vk_->GetInstanceProcAddr( + reinterpret_cast(instance), name); + return reinterpret_cast(proc_addr); +} + +void EmbedderTestContextVulkan::SetSurface(SkISize surface_size) { + FML_CHECK(surface_size_.isEmpty()); + surface_size_ = surface_size; + surface_ = TestVulkanSurface::Create(*vulkan_context_, surface_size_); +} + +void EmbedderTestContextVulkan::SetupCompositor() { + FML_CHECK(!compositor_) << "Already set up a compositor in this context."; + FML_CHECK(surface_) + << "Set up the Vulkan surface before setting up a compositor."; + compositor_ = std::make_unique( + surface_size_, vulkan_context_->GetGrDirectContext()); +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context_vulkan.h b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context_vulkan.h new file mode 100644 index 0000000000000000000000000000000000000000..2fde79996207d3a667c0a4c768ff2d3e8461823e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_context_vulkan.h @@ -0,0 +1,62 @@ +// 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_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_VULKAN_H_ +#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_VULKAN_H_ + +#include +#include "flutter/shell/platform/embedder/tests/embedder_test_context.h" +#include "flutter/testing/test_vulkan_context.h" +#include "flutter/vulkan/vulkan_application.h" +#include "testing/test_vulkan_surface.h" + +namespace flutter { +namespace testing { + +class EmbedderTestContextVulkan : public EmbedderTestContext { + public: + explicit EmbedderTestContextVulkan(std::string assets_path = ""); + + ~EmbedderTestContextVulkan() override; + + // |EmbedderTestContext| + EmbedderTestContextType GetContextType() const override; + + // |EmbedderTestContext| + size_t GetSurfacePresentCount() const override; + + VkImage GetNextImage(const SkISize& size); + + bool PresentImage(VkImage image); + + void SetVulkanInstanceProcAddressCallback( + FlutterVulkanInstanceProcAddressCallback callback); + + static void* InstanceProcAddr(void* user_data, + FlutterVulkanInstanceHandle instance, + const char* name); + + private: + // |EmbedderTestContext| + void SetSurface(SkISize surface_size) override; + + // |EmbedderTestContext| + void SetupCompositor() override; + + // The TestVulkanContext destructor must be called _after_ the compositor is + // freed. + fml::RefPtr vulkan_context_ = nullptr; + + std::unique_ptr surface_; + + SkISize surface_size_ = SkISize::MakeEmpty(); + size_t present_count_ = 0; + + FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestContextVulkan); +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_VULKAN_H_ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_gl.cc b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_gl.cc new file mode 100644 index 0000000000000000000000000000000000000000..0136947962bb565643b9a8112ebce2d2320cc96d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_gl.cc @@ -0,0 +1,19 @@ +// 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/shell/platform/embedder/tests/embedder_test.h" + +#include "flutter/shell/platform/embedder/tests/embedder_test_context_gl.h" + +namespace flutter::testing { + +EmbedderTestContext& EmbedderTest::GetGLContext() { + if (!gl_context_) { + gl_context_ = + std::make_unique(GetFixturesDirectory()); + } + return *gl_context_.get(); +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_metal.mm b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_metal.mm new file mode 100644 index 0000000000000000000000000000000000000000..86edf931e1cb37c30e656e2358582393fd209194 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_metal.mm @@ -0,0 +1,18 @@ +// 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/shell/platform/embedder/tests/embedder_test.h" + +#include "flutter/shell/platform/embedder/tests/embedder_test_context_metal.h" + +namespace flutter::testing { + +EmbedderTestContext& EmbedderTest::GetMetalContext() { + if (!metal_context_) { + metal_context_ = std::make_unique(GetFixturesDirectory()); + } + return *metal_context_.get(); +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_vulkan.cc b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_vulkan.cc new file mode 100644 index 0000000000000000000000000000000000000000..63b69d2eb2cc7b5b24ff9c3a60f10a2329a3cef8 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_test_vulkan.cc @@ -0,0 +1,19 @@ +// 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/shell/platform/embedder/tests/embedder_test.h" + +#include "flutter/shell/platform/embedder/tests/embedder_test_context_vulkan.h" + +namespace flutter::testing { + +EmbedderTestContext& EmbedderTest::GetVulkanContext() { + if (!vulkan_context_) { + vulkan_context_ = + std::make_unique(GetFixturesDirectory()); + } + return *vulkan_context_.get(); +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_unittests.cc b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..bec8c937924a6db6d3e027cbe792961111cc6619 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_unittests.cc @@ -0,0 +1,4225 @@ +// 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. + +#define FML_USED_ON_EMBEDDER + +#include +#include +#include + +#include "embedder.h" +#include "embedder_engine.h" +#include "flutter/common/constants.h" +#include "flutter/flow/raster_cache.h" +#include "flutter/fml/file.h" +#include "flutter/fml/make_copyable.h" +#include "flutter/fml/mapping.h" +#include "flutter/fml/message_loop.h" +#include "flutter/fml/paths.h" +#include "flutter/fml/synchronization/count_down_latch.h" +#include "flutter/fml/synchronization/waitable_event.h" +#include "flutter/fml/task_runner.h" +#include "flutter/fml/thread.h" +#include "flutter/fml/time/time_delta.h" +#include "flutter/fml/time/time_point.h" +#include "flutter/runtime/dart_vm.h" +#include "flutter/shell/platform/embedder/tests/embedder_assertions.h" +#include "flutter/shell/platform/embedder/tests/embedder_config_builder.h" +#include "flutter/shell/platform/embedder/tests/embedder_test.h" +#include "flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer_software.h" +#include "flutter/shell/platform/embedder/tests/embedder_unittests_util.h" +#include "flutter/testing/assertions_skia.h" +#include "flutter/testing/testing.h" +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/tonic/converter/dart_converter.h" + +#if defined(FML_OS_MACOSX) +#include +#endif + +// CREATE_NATIVE_ENTRY is leaky by design +// NOLINTBEGIN(clang-analyzer-core.StackAddressEscape) + +namespace { + +static uint64_t NanosFromEpoch(int millis_from_now) { + const auto now = fml::TimePoint::Now(); + const auto delta = fml::TimeDelta::FromMilliseconds(millis_from_now); + return (now + delta).ToEpochDelta().ToNanoseconds(); +} + +} // namespace + +namespace flutter { +namespace testing { + +using EmbedderTest = testing::EmbedderTest; + +TEST(EmbedderTestNoFixture, MustNotRunWithInvalidArgs) { + EmbedderTestContextSoftware context; + EmbedderConfigBuilder builder( + context, EmbedderConfigBuilder::InitializationPreference::kNoInitialize); + auto engine = builder.LaunchEngine(); + ASSERT_FALSE(engine.is_valid()); +} + +TEST_F(EmbedderTest, CanLaunchAndShutdownWithValidProjectArgs) { + auto& context = GetEmbedderContext(); + fml::AutoResetWaitableEvent latch; + context.AddIsolateCreateCallback([&latch]() { latch.Signal(); }); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + // Wait for the root isolate to launch. + latch.Wait(); + engine.reset(); +} + +// TODO(41999): Disabled because flaky. +TEST_F(EmbedderTest, DISABLED_CanLaunchAndShutdownMultipleTimes) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + for (size_t i = 0; i < 3; ++i) { + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + FML_LOG(INFO) << "Engine launch count: " << i + 1; + } +} + +TEST_F(EmbedderTest, CanInvokeCustomEntrypoint) { + auto& context = GetEmbedderContext(); + static fml::AutoResetWaitableEvent latch; + Dart_NativeFunction entrypoint = [](Dart_NativeArguments args) { + latch.Signal(); + }; + context.AddNativeCallback("SayHiFromCustomEntrypoint", entrypoint); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("customEntrypoint"); + auto engine = builder.LaunchEngine(); + latch.Wait(); + ASSERT_TRUE(engine.is_valid()); +} + +TEST_F(EmbedderTest, CanInvokeCustomEntrypointMacro) { + auto& context = GetEmbedderContext(); + + fml::AutoResetWaitableEvent latch1; + fml::AutoResetWaitableEvent latch2; + fml::AutoResetWaitableEvent latch3; + + // Can be defined separately. + auto entry1 = [&latch1](Dart_NativeArguments args) { + FML_LOG(INFO) << "In Callback 1"; + latch1.Signal(); + }; + auto native_entry1 = CREATE_NATIVE_ENTRY(entry1); + context.AddNativeCallback("SayHiFromCustomEntrypoint1", native_entry1); + + // Can be wrapped in the args. + auto entry2 = [&latch2](Dart_NativeArguments args) { + FML_LOG(INFO) << "In Callback 2"; + latch2.Signal(); + }; + context.AddNativeCallback("SayHiFromCustomEntrypoint2", + CREATE_NATIVE_ENTRY(entry2)); + + // Everything can be inline. + context.AddNativeCallback( + "SayHiFromCustomEntrypoint3", + CREATE_NATIVE_ENTRY([&latch3](Dart_NativeArguments args) { + FML_LOG(INFO) << "In Callback 3"; + latch3.Signal(); + })); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("customEntrypoint1"); + auto engine = builder.LaunchEngine(); + latch1.Wait(); + latch2.Wait(); + latch3.Wait(); + ASSERT_TRUE(engine.is_valid()); +} + +TEST_F(EmbedderTest, CanTerminateCleanly) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("terminateExitCodeHandler"); + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); +} + +TEST_F(EmbedderTest, ExecutableNameNotNull) { + auto& context = GetEmbedderContext(); + + // Supply a callback to Dart for the test fixture to pass Platform.executable + // back to us. + fml::AutoResetWaitableEvent latch; + context.AddNativeCallback( + "NotifyStringValue", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + const auto dart_string = tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + EXPECT_EQ("/path/to/binary", dart_string); + latch.Signal(); + })); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("executableNameNotNull"); + builder.SetExecutableName("/path/to/binary"); + auto engine = builder.LaunchEngine(); + latch.Wait(); +} + +TEST_F(EmbedderTest, ImplicitViewNotNull) { + // TODO(loicsharma): Update this test when embedders can opt-out + // of the implicit view. + // See: https://github.com/flutter/flutter/issues/120306 + auto& context = GetEmbedderContext(); + + bool implicitViewNotNull = false; + fml::AutoResetWaitableEvent latch; + context.AddNativeCallback( + "NotifyBoolValue", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + implicitViewNotNull = tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + latch.Signal(); + })); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("implicitViewNotNull"); + auto engine = builder.LaunchEngine(); + latch.Wait(); + + EXPECT_TRUE(implicitViewNotNull); +} + +std::atomic_size_t EmbedderTestTaskRunner::sEmbedderTaskRunnerIdentifiers = {}; + +TEST_F(EmbedderTest, CanSpecifyCustomUITaskRunner) { + auto& context = GetEmbedderContext(); + auto ui_task_runner = CreateNewThread("test_ui_thread"); + auto platform_task_runner = CreateNewThread("test_platform_thread"); + static std::mutex engine_mutex; + UniqueEngine engine; + + EmbedderTestTaskRunner test_ui_task_runner( + ui_task_runner, [&](FlutterTask task) { + std::scoped_lock lock(engine_mutex); + if (!engine.is_valid()) { + return; + } + FlutterEngineRunTask(engine.get(), &task); + }); + EmbedderTestTaskRunner test_platform_task_runner( + platform_task_runner, [&](FlutterTask task) { + std::scoped_lock lock(engine_mutex); + if (!engine.is_valid()) { + return; + } + FlutterEngineRunTask(engine.get(), &task); + }); + + fml::AutoResetWaitableEvent signal_latch_ui; + fml::AutoResetWaitableEvent signal_latch_platform; + + context.AddNativeCallback( + "SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + // Assert that the UI isolate is running on platform thread. + ASSERT_TRUE(ui_task_runner->RunsTasksOnCurrentThread()); + signal_latch_ui.Signal(); + })); + + platform_task_runner->PostTask([&]() { + EmbedderConfigBuilder builder(context); + const auto ui_task_runner_description = + test_ui_task_runner.GetFlutterTaskRunnerDescription(); + const auto platform_task_runner_description = + test_platform_task_runner.GetFlutterTaskRunnerDescription(); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetUITaskRunner(&ui_task_runner_description); + builder.SetPlatformTaskRunner(&platform_task_runner_description); + builder.SetDartEntrypoint("canSpecifyCustomUITaskRunner"); + builder.SetPlatformMessageCallback( + [&](const FlutterPlatformMessage* message) { + ASSERT_TRUE(platform_task_runner->RunsTasksOnCurrentThread()); + signal_latch_platform.Signal(); + }); + { + std::scoped_lock lock(engine_mutex); + engine = builder.InitializeEngine(); + } + ASSERT_EQ(FlutterEngineRunInitialized(engine.get()), kSuccess); + ASSERT_TRUE(engine.is_valid()); + }); + signal_latch_ui.Wait(); + signal_latch_platform.Wait(); + + fml::AutoResetWaitableEvent kill_latch; + platform_task_runner->PostTask([&] { + engine.reset(); + platform_task_runner->PostTask([&kill_latch] { kill_latch.Signal(); }); + }); + kill_latch.Wait(); +} + +TEST_F(EmbedderTest, IgnoresStaleTasks) { + auto& context = GetEmbedderContext(); + auto ui_task_runner = CreateNewThread("test_ui_thread"); + auto platform_task_runner = CreateNewThread("test_platform_thread"); + static std::mutex engine_mutex; + UniqueEngine engine; + FlutterEngine engine_ptr; + + EmbedderTestTaskRunner test_ui_task_runner( + ui_task_runner, [&](FlutterTask task) { + // The check for engine.is_valid() is intentionally absent here. + // FlutterEngineRunTask must be able to detect and ignore stale tasks + // without crashing even if the engine pointer is not null. + // Because the engine is destroyed on platform thread, + // relying solely on engine.is_valid() in UI thread is not safe. + FlutterEngineRunTask(engine_ptr, &task); + }); + EmbedderTestTaskRunner test_platform_task_runner( + platform_task_runner, [&](FlutterTask task) { + std::scoped_lock lock(engine_mutex); + if (!engine.is_valid()) { + return; + } + FlutterEngineRunTask(engine.get(), &task); + }); + + fml::AutoResetWaitableEvent init_latch; + + platform_task_runner->PostTask([&]() { + EmbedderConfigBuilder builder(context); + const auto ui_task_runner_description = + test_ui_task_runner.GetFlutterTaskRunnerDescription(); + const auto platform_task_runner_description = + test_platform_task_runner.GetFlutterTaskRunnerDescription(); + builder.SetUITaskRunner(&ui_task_runner_description); + builder.SetPlatformTaskRunner(&platform_task_runner_description); + { + std::scoped_lock lock(engine_mutex); + engine = builder.InitializeEngine(); + } + init_latch.Signal(); + }); + + init_latch.Wait(); + engine_ptr = engine.get(); + + auto flutter_engine = reinterpret_cast(engine.get()); + + // Schedule task on UI thread that will likely run after the engine has shut + // down. + flutter_engine->GetTaskRunners().GetUITaskRunner()->PostDelayedTask( + []() {}, fml::TimeDelta::FromMilliseconds(50)); + + fml::AutoResetWaitableEvent kill_latch; + platform_task_runner->PostTask([&] { + engine.reset(); + platform_task_runner->PostTask([&kill_latch] { kill_latch.Signal(); }); + }); + kill_latch.Wait(); + + // Ensure that the schedule task indeed runs. + kill_latch.Reset(); + ui_task_runner->PostDelayedTask([&]() { kill_latch.Signal(); }, + fml::TimeDelta::FromMilliseconds(50)); + kill_latch.Wait(); +} + +TEST_F(EmbedderTest, MergedPlatformUIThread) { + auto& context = GetEmbedderContext(); + auto task_runner = CreateNewThread("test_thread"); + UniqueEngine engine; + + EmbedderTestTaskRunner test_task_runner(task_runner, [&](FlutterTask task) { + if (!engine.is_valid()) { + return; + } + FlutterEngineRunTask(engine.get(), &task); + }); + + fml::AutoResetWaitableEvent signal_latch_ui; + fml::AutoResetWaitableEvent signal_latch_platform; + + context.AddNativeCallback( + "SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + // Assert that the UI isolate is running on platform thread. + ASSERT_TRUE(task_runner->RunsTasksOnCurrentThread()); + signal_latch_ui.Signal(); + })); + + task_runner->PostTask([&]() { + EmbedderConfigBuilder builder(context); + const auto task_runner_description = + test_task_runner.GetFlutterTaskRunnerDescription(); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetUITaskRunner(&task_runner_description); + builder.SetPlatformTaskRunner(&task_runner_description); + builder.SetDartEntrypoint("mergedPlatformUIThread"); + builder.SetPlatformMessageCallback( + [&](const FlutterPlatformMessage* message) { + ASSERT_TRUE(task_runner->RunsTasksOnCurrentThread()); + signal_latch_platform.Signal(); + }); + engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + }); + signal_latch_ui.Wait(); + signal_latch_platform.Wait(); + + fml::AutoResetWaitableEvent kill_latch; + task_runner->PostTask([&] { + engine.reset(); + task_runner->PostTask([&kill_latch] { kill_latch.Signal(); }); + }); + kill_latch.Wait(); +} + +TEST_F(EmbedderTest, UITaskRunnerFlushesMicrotasks) { + auto& context = GetEmbedderContext(); + auto ui_task_runner = CreateNewThread("test_ui_thread"); + UniqueEngine engine; + + EmbedderTestTaskRunner test_task_runner( + // Assert that the UI isolate is running on platform thread. + ui_task_runner, [&](FlutterTask task) { + if (!engine.is_valid()) { + return; + } + FlutterEngineRunTask(engine.get(), &task); + }); + + fml::AutoResetWaitableEvent signal_latch; + + context.AddNativeCallback( + "SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + ASSERT_TRUE(ui_task_runner->RunsTasksOnCurrentThread()); + signal_latch.Signal(); + })); + + ui_task_runner->PostTask([&]() { + EmbedderConfigBuilder builder(context); + const auto task_runner_description = + test_task_runner.GetFlutterTaskRunnerDescription(); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetUITaskRunner(&task_runner_description); + builder.SetDartEntrypoint("uiTaskRunnerFlushesMicrotasks"); + engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + }); + signal_latch.Wait(); + + fml::AutoResetWaitableEvent kill_latch; + ui_task_runner->PostTask([&] { + engine.reset(); + ui_task_runner->PostTask([&kill_latch] { kill_latch.Signal(); }); + }); + kill_latch.Wait(); +} + +TEST_F(EmbedderTest, CanSpecifyCustomPlatformTaskRunner) { + auto& context = GetEmbedderContext(); + fml::AutoResetWaitableEvent latch; + + // Run the test on its own thread with a message loop so that it can safely + // pump its event loop while we wait for all the conditions to be checked. + auto platform_task_runner = CreateNewThread("test_platform_thread"); + static std::mutex engine_mutex; + static bool signaled_once = false; + static std::atomic destruction_callback_called = false; + UniqueEngine engine; + + EmbedderTestTaskRunner test_task_runner( + platform_task_runner, [&](FlutterTask task) { + std::scoped_lock lock(engine_mutex); + if (!engine.is_valid()) { + return; + } + // There may be multiple tasks posted but we only need to check + // assertions once. + if (signaled_once) { + FlutterEngineRunTask(engine.get(), &task); + return; + } + + signaled_once = true; + ASSERT_TRUE(engine.is_valid()); + ASSERT_EQ(FlutterEngineRunTask(engine.get(), &task), kSuccess); + latch.Signal(); + }); + test_task_runner.SetDestructionCallback( + [](void* user_data) { destruction_callback_called = true; }); + + platform_task_runner->PostTask([&]() { + EmbedderConfigBuilder builder(context); + const auto task_runner_description = + test_task_runner.GetFlutterTaskRunnerDescription(); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetPlatformTaskRunner(&task_runner_description); + builder.SetDartEntrypoint("invokePlatformTaskRunner"); + std::scoped_lock lock(engine_mutex); + engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + }); + + // Signaled when all the assertions are checked. + latch.Wait(); + ASSERT_TRUE(engine.is_valid()); + + // Since the engine was started on its own thread, it must be killed there as + // well. + fml::AutoResetWaitableEvent kill_latch; + platform_task_runner->PostTask(fml::MakeCopyable([&]() mutable { + std::scoped_lock lock(engine_mutex); + engine.reset(); + + // There may still be pending tasks on the platform thread that were queued + // by the test_task_runner. Signal the latch after these tasks have been + // consumed. + platform_task_runner->PostTask([&kill_latch] { kill_latch.Signal(); }); + })); + kill_latch.Wait(); + + ASSERT_TRUE(signaled_once); + signaled_once = false; + + ASSERT_TRUE(destruction_callback_called); + destruction_callback_called = false; +} + +TEST(EmbedderTestNoFixture, CanGetCurrentTimeInNanoseconds) { + auto point1 = fml::TimePoint::FromEpochDelta( + fml::TimeDelta::FromNanoseconds(FlutterEngineGetCurrentTime())); + auto point2 = fml::TimePoint::Now(); + + ASSERT_LT((point2 - point1), fml::TimeDelta::FromMilliseconds(1)); +} + +TEST_F(EmbedderTest, CanReloadSystemFonts) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + auto result = FlutterEngineReloadSystemFonts(engine.get()); + ASSERT_EQ(result, kSuccess); +} + +TEST_F(EmbedderTest, IsolateServiceIdSent) { + auto& context = GetEmbedderContext(); + fml::AutoResetWaitableEvent latch; + + fml::Thread thread; + UniqueEngine engine; + std::string isolate_message; + + thread.GetTaskRunner()->PostTask([&]() { + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("main"); + builder.SetPlatformMessageCallback( + [&](const FlutterPlatformMessage* message) { + if (strcmp(message->channel, "flutter/isolate") == 0) { + isolate_message = {reinterpret_cast(message->message), + message->message_size}; + latch.Signal(); + } + }); + engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + }); + + // Wait for the isolate ID message and check its format. + latch.Wait(); + ASSERT_EQ(isolate_message.find("isolates/"), 0ul); + + // Since the engine was started on its own thread, it must be killed there as + // well. + fml::AutoResetWaitableEvent kill_latch; + thread.GetTaskRunner()->PostTask( + fml::MakeCopyable([&engine, &kill_latch]() mutable { + engine.reset(); + kill_latch.Signal(); + })); + kill_latch.Wait(); +} + +//------------------------------------------------------------------------------ +/// Creates a platform message response callbacks, does NOT send them, and +/// immediately collects the same. +/// +TEST_F(EmbedderTest, CanCreateAndCollectCallbacks) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("platform_messages_response"); + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY([](Dart_NativeArguments args) {})); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + FlutterPlatformMessageResponseHandle* response_handle = nullptr; + auto callback = [](const uint8_t* data, size_t size, + void* user_data) -> void {}; + auto result = FlutterPlatformMessageCreateResponseHandle( + engine.get(), callback, nullptr, &response_handle); + ASSERT_EQ(result, kSuccess); + ASSERT_NE(response_handle, nullptr); + + result = FlutterPlatformMessageReleaseResponseHandle(engine.get(), + response_handle); + ASSERT_EQ(result, kSuccess); +} + +//------------------------------------------------------------------------------ +/// Sends platform messages to Dart code than simply echoes the contents of the +/// message back to the embedder. The embedder registers a native callback to +/// intercept that message. +/// +TEST_F(EmbedderTest, PlatformMessagesCanReceiveResponse) { + struct Captures { + fml::AutoResetWaitableEvent latch; + std::thread::id thread_id; + }; + Captures captures; + + CreateNewThread()->PostTask([&]() { + captures.thread_id = std::this_thread::get_id(); + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("platform_messages_response"); + + fml::AutoResetWaitableEvent ready; + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&ready](Dart_NativeArguments args) { ready.Signal(); })); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + static std::string kMessageData = "Hello from embedder."; + + FlutterPlatformMessageResponseHandle* response_handle = nullptr; + auto callback = [](const uint8_t* data, size_t size, + void* user_data) -> void { + ASSERT_EQ(size, kMessageData.size()); + ASSERT_EQ(strncmp(reinterpret_cast(kMessageData.data()), + reinterpret_cast(data), size), + 0); + auto captures = reinterpret_cast(user_data); + ASSERT_EQ(captures->thread_id, std::this_thread::get_id()); + captures->latch.Signal(); + }; + auto result = FlutterPlatformMessageCreateResponseHandle( + engine.get(), callback, &captures, &response_handle); + ASSERT_EQ(result, kSuccess); + + FlutterPlatformMessage message = {}; + message.struct_size = sizeof(FlutterPlatformMessage); + message.channel = "test_channel"; + message.message = reinterpret_cast(kMessageData.data()); + message.message_size = kMessageData.size(); + message.response_handle = response_handle; + + ready.Wait(); + result = FlutterEngineSendPlatformMessage(engine.get(), &message); + ASSERT_EQ(result, kSuccess); + + result = FlutterPlatformMessageReleaseResponseHandle(engine.get(), + response_handle); + ASSERT_EQ(result, kSuccess); + }); + + captures.latch.Wait(); +} + +//------------------------------------------------------------------------------ +/// Tests that a platform message can be sent with no response handle. Instead +/// of the platform message integrity checked via a response handle, a native +/// callback with the response is invoked to assert integrity. +/// +TEST_F(EmbedderTest, PlatformMessagesCanBeSentWithoutResponseHandles) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("platform_messages_no_response"); + + const std::string message_data = "Hello but don't call me back."; + + fml::AutoResetWaitableEvent ready, message; + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&ready](Dart_NativeArguments args) { ready.Signal(); })); + context.AddNativeCallback( + "SignalNativeMessage", + CREATE_NATIVE_ENTRY( + ([&message, &message_data](Dart_NativeArguments args) { + auto received_message = tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + ASSERT_EQ(received_message, message_data); + message.Signal(); + }))); + + auto engine = builder.LaunchEngine(); + + ASSERT_TRUE(engine.is_valid()); + ready.Wait(); + + FlutterPlatformMessage platform_message = {}; + platform_message.struct_size = sizeof(FlutterPlatformMessage); + platform_message.channel = "test_channel"; + platform_message.message = + reinterpret_cast(message_data.data()); + platform_message.message_size = message_data.size(); + platform_message.response_handle = nullptr; // No response needed. + + auto result = + FlutterEngineSendPlatformMessage(engine.get(), &platform_message); + ASSERT_EQ(result, kSuccess); + message.Wait(); +} + +//------------------------------------------------------------------------------ +/// Tests that a null platform message can be sent. +/// +TEST_F(EmbedderTest, NullPlatformMessagesCanBeSent) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("null_platform_messages"); + + fml::AutoResetWaitableEvent ready, message; + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&ready](Dart_NativeArguments args) { ready.Signal(); })); + context.AddNativeCallback( + "SignalNativeMessage", + CREATE_NATIVE_ENTRY(([&message](Dart_NativeArguments args) { + auto received_message = tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + ASSERT_EQ("true", received_message); + message.Signal(); + }))); + + auto engine = builder.LaunchEngine(); + + ASSERT_TRUE(engine.is_valid()); + ready.Wait(); + + FlutterPlatformMessage platform_message = {}; + platform_message.struct_size = sizeof(FlutterPlatformMessage); + platform_message.channel = "test_channel"; + platform_message.message = nullptr; + platform_message.message_size = 0; + platform_message.response_handle = nullptr; // No response needed. + + auto result = + FlutterEngineSendPlatformMessage(engine.get(), &platform_message); + ASSERT_EQ(result, kSuccess); + message.Wait(); +} + +//------------------------------------------------------------------------------ +/// Tests that a null platform message cannot be send if the message_size +/// isn't equals to 0. +/// +TEST_F(EmbedderTest, InvalidPlatformMessages) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + auto engine = builder.LaunchEngine(); + + ASSERT_TRUE(engine.is_valid()); + + FlutterPlatformMessage platform_message = {}; + platform_message.struct_size = sizeof(FlutterPlatformMessage); + platform_message.channel = "test_channel"; + platform_message.message = nullptr; + platform_message.message_size = 1; + platform_message.response_handle = nullptr; // No response needed. + + auto result = + FlutterEngineSendPlatformMessage(engine.get(), &platform_message); + ASSERT_EQ(result, kInvalidArguments); +} + +//------------------------------------------------------------------------------ +/// Tests that setting a custom log callback works as expected and defaults to +/// using tag "flutter". +TEST_F(EmbedderTest, CanSetCustomLogMessageCallback) { + fml::AutoResetWaitableEvent callback_latch; + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetDartEntrypoint("custom_logger"); + builder.SetSurface(SkISize::Make(1, 1)); + context.SetLogMessageCallback( + [&callback_latch](const char* tag, const char* message) { + EXPECT_EQ(std::string(tag), "flutter"); + EXPECT_EQ(std::string(message), "hello world"); + callback_latch.Signal(); + }); + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + callback_latch.Wait(); +} + +//------------------------------------------------------------------------------ +/// Tests that setting a custom log tag works. +TEST_F(EmbedderTest, CanSetCustomLogTag) { + fml::AutoResetWaitableEvent callback_latch; + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetDartEntrypoint("custom_logger"); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetLogTag("butterfly"); + context.SetLogMessageCallback( + [&callback_latch](const char* tag, const char* message) { + EXPECT_EQ(std::string(tag), "butterfly"); + EXPECT_EQ(std::string(message), "hello world"); + callback_latch.Signal(); + }); + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + callback_latch.Wait(); +} + +//------------------------------------------------------------------------------ +/// Asserts behavior of FlutterProjectArgs::shutdown_dart_vm_when_done (which is +/// set to true by default in these unit-tests). +/// +TEST_F(EmbedderTest, VMShutsDownWhenNoEnginesInProcess) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + const auto launch_count = DartVM::GetVMLaunchCount(); + + { + auto engine = builder.LaunchEngine(); + ASSERT_EQ(launch_count + 1u, DartVM::GetVMLaunchCount()); + } + + { + auto engine = builder.LaunchEngine(); + ASSERT_EQ(launch_count + 2u, DartVM::GetVMLaunchCount()); + } +} + +//------------------------------------------------------------------------------ +/// +TEST_F(EmbedderTest, DartEntrypointArgs) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.AddDartEntrypointArgument("foo"); + builder.AddDartEntrypointArgument("bar"); + builder.SetDartEntrypoint("dart_entrypoint_args"); + fml::AutoResetWaitableEvent callback_latch; + std::vector callback_args; + auto nativeArgumentsCallback = [&callback_args, + &callback_latch](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + callback_args = + tonic::DartConverter>::FromArguments( + args, 0, exception); + callback_latch.Signal(); + }; + context.AddNativeCallback("NativeArgumentsCallback", + CREATE_NATIVE_ENTRY(nativeArgumentsCallback)); + auto engine = builder.LaunchEngine(); + callback_latch.Wait(); + ASSERT_EQ(callback_args[0], "foo"); + ASSERT_EQ(callback_args[1], "bar"); +} + +//------------------------------------------------------------------------------ +/// These snapshots may be materialized from symbols and the size field may not +/// be relevant. Since this information is redundant, engine launch should not +/// be gated on a non-zero buffer size. +/// +TEST_F(EmbedderTest, VMAndIsolateSnapshotSizesAreRedundantInAOTMode) { + if (!DartVM::IsRunningPrecompiledCode()) { + GTEST_SKIP(); + return; + } + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + + // The fixture sets this up correctly. Intentionally mess up the args. + builder.GetProjectArgs().vm_snapshot_data_size = 0; + builder.GetProjectArgs().vm_snapshot_instructions_size = 0; + builder.GetProjectArgs().isolate_snapshot_data_size = 0; + builder.GetProjectArgs().isolate_snapshot_instructions_size = 0; + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); +} + +TEST_F(EmbedderTest, CanRenderImplicitView) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("render_implicit_view"); + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer); + + fml::AutoResetWaitableEvent latch; + + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(view_id, kFlutterImplicitViewId); + latch.Signal(); + }); + + auto engine = builder.LaunchEngine(); + + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 300; + event.height = 200; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + latch.Wait(); +} + +TEST_F(EmbedderTest, CanRenderImplicitViewUsingPresentLayersCallback) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(/* avoid_backing_store_cache = */ false, + /* use_present_layers_callback = */ true); + builder.SetDartEntrypoint("render_implicit_view"); + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer); + + fml::AutoResetWaitableEvent latch; + + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(view_id, kFlutterImplicitViewId); + latch.Signal(); + }); + + auto engine = builder.LaunchEngine(); + + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 300; + event.height = 200; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + latch.Wait(); +} + +//------------------------------------------------------------------------------ +/// Test the layer structure and pixels rendered when using a custom software +/// compositor. +/// +// TODO(143940): Convert this test to use SkiaGold. +#if FML_OS_MACOSX && FML_ARCH_CPU_ARM64 +TEST_F(EmbedderTest, + DISABLED_CompositorMustBeAbleToRenderKnownSceneWithSoftwareCompositor) { +#else +TEST_F(EmbedderTest, + CompositorMustBeAbleToRenderKnownSceneWithSoftwareCompositor) { +#endif // FML_OS_MACOSX && FML_ARCH_CPU_ARM64 + + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("can_composite_platform_views_with_known_scene"); + + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer); + + fml::CountDownLatch latch(5); + + auto scene_image = context.GetNextSceneImage(); + + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 5u); + + // Layer Root + { + FlutterBackingStore backing_store = *layers[0]->backing_store; + backing_store.type = kFlutterBackingStoreTypeSoftware; + backing_store.did_update = true; + backing_store.software.height = 600; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[0], layer); + } + + // Layer 1 + { + FlutterPlatformView platform_view = *layers[1]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 1; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(50.0, 150.0); + layer.offset = FlutterPointMake(20.0, 20.0); + + ASSERT_EQ(*layers[1], layer); + } + + // Layer 2 + { + FlutterBackingStore backing_store = *layers[2]->backing_store; + backing_store.type = kFlutterBackingStoreTypeSoftware; + backing_store.did_update = true; + backing_store.software.height = 600; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(30, 30, 80, 180), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[2], layer); + } + + // Layer 3 + { + FlutterPlatformView platform_view = *layers[3]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 2; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(50.0, 150.0); + layer.offset = FlutterPointMake(40.0, 40.0); + + ASSERT_EQ(*layers[3], layer); + } + + // Layer 4 + { + FlutterBackingStore backing_store = *layers[4]->backing_store; + backing_store.type = kFlutterBackingStoreTypeSoftware; + backing_store.did_update = true; + backing_store.software.height = 600; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(50, 50, 100, 200), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[4], layer); + } + + latch.CountDown(); + }); + + context.GetCompositor().SetPlatformViewRendererCallback( + [&](const FlutterLayer& layer, GrDirectContext* + /* don't use because software compositor */) -> sk_sp { + auto surface = CreateRenderSurface( + layer, nullptr /* null because software compositor */); + auto canvas = surface->getCanvas(); + FML_CHECK(canvas != nullptr); + + switch (layer.platform_view->identifier) { + case 1: { + SkPaint paint; + // See dart test for total order. + paint.setColor(SK_ColorGREEN); + paint.setAlpha(127); + const auto& rect = + SkRect::MakeWH(layer.size.width, layer.size.height); + canvas->drawRect(rect, paint); + latch.CountDown(); + } break; + case 2: { + SkPaint paint; + // See dart test for total order. + paint.setColor(SK_ColorMAGENTA); + paint.setAlpha(127); + const auto& rect = + SkRect::MakeWH(layer.size.width, layer.size.height); + canvas->drawRect(rect, paint); + latch.CountDown(); + } break; + default: + // Asked to render an unknown platform view. + FML_CHECK(false) + << "Test was asked to composite an unknown platform view."; + } + + return surface->makeImageSnapshot(); + }); + + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&latch](Dart_NativeArguments args) { latch.CountDown(); })); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + event.physical_view_inset_top = 0.0; + event.physical_view_inset_right = 0.0; + event.physical_view_inset_bottom = 0.0; + event.physical_view_inset_left = 0.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + + latch.Wait(); + + ASSERT_TRUE(ImageMatchesFixture("compositor_software.png", scene_image)); + + // There should no present calls on the root surface. + ASSERT_EQ(context.GetSurfacePresentCount(), 0u); +} + +//------------------------------------------------------------------------------ +/// Test the layer structure and pixels rendered when using a custom software +/// compositor, with a transparent overlay +/// +TEST_F(EmbedderTest, NoLayerCreatedForTransparentOverlayOnTopOfPlatformLayer) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("can_composite_platform_views_transparent_overlay"); + + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer); + + fml::CountDownLatch latch(4); + + auto scene_image = context.GetNextSceneImage(); + + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 2u); + + // Layer Root + { + FlutterBackingStore backing_store = *layers[0]->backing_store; + backing_store.type = kFlutterBackingStoreTypeSoftware; + backing_store.did_update = true; + backing_store.software.height = 600; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[0], layer); + } + + // Layer 1 + { + FlutterPlatformView platform_view = *layers[1]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 1; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(50.0, 150.0); + layer.offset = FlutterPointMake(20.0, 20.0); + + ASSERT_EQ(*layers[1], layer); + } + + latch.CountDown(); + }); + + context.GetCompositor().SetPlatformViewRendererCallback( + [&](const FlutterLayer& layer, GrDirectContext* + /* don't use because software compositor */) -> sk_sp { + auto surface = CreateRenderSurface( + layer, nullptr /* null because software compositor */); + auto canvas = surface->getCanvas(); + FML_CHECK(canvas != nullptr); + + switch (layer.platform_view->identifier) { + case 1: { + SkPaint paint; + // See dart test for total order. + paint.setColor(SK_ColorGREEN); + paint.setAlpha(127); + const auto& rect = + SkRect::MakeWH(layer.size.width, layer.size.height); + canvas->drawRect(rect, paint); + latch.CountDown(); + } break; + default: + // Asked to render an unknown platform view. + FML_CHECK(false) + << "Test was asked to composite an unknown platform view."; + } + + return surface->makeImageSnapshot(); + }); + + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&latch](Dart_NativeArguments args) { latch.CountDown(); })); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + event.physical_view_inset_top = 0.0; + event.physical_view_inset_right = 0.0; + event.physical_view_inset_bottom = 0.0; + event.physical_view_inset_left = 0.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + + latch.Wait(); + + // TODO(https://github.com/flutter/flutter/issues/53784): enable this on all + // platforms. +#if !defined(FML_OS_LINUX) + GTEST_SKIP() << "Skipping golden tests on non-Linux OSes"; +#endif // FML_OS_LINUX + ASSERT_TRUE(ImageMatchesFixture( + "compositor_platform_layer_with_no_overlay.png", scene_image)); + + // There should no present calls on the root surface. + ASSERT_EQ(context.GetSurfacePresentCount(), 0u); +} + +//------------------------------------------------------------------------------ +/// Test the layer structure and pixels rendered when using a custom software +/// compositor, with a no overlay +/// +TEST_F(EmbedderTest, NoLayerCreatedForNoOverlayOnTopOfPlatformLayer) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("can_composite_platform_views_no_overlay"); + + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer); + + fml::CountDownLatch latch(4); + + auto scene_image = context.GetNextSceneImage(); + + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 2u); + + // Layer Root + { + FlutterBackingStore backing_store = *layers[0]->backing_store; + backing_store.type = kFlutterBackingStoreTypeSoftware; + backing_store.did_update = true; + backing_store.software.height = 600; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 800, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(800.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[0], layer); + } + + // Layer 1 + { + FlutterPlatformView platform_view = *layers[1]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 1; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(50.0, 150.0); + layer.offset = FlutterPointMake(20.0, 20.0); + + ASSERT_EQ(*layers[1], layer); + } + + latch.CountDown(); + }); + + context.GetCompositor().SetPlatformViewRendererCallback( + [&](const FlutterLayer& layer, GrDirectContext* + /* don't use because software compositor */) -> sk_sp { + auto surface = CreateRenderSurface( + layer, nullptr /* null because software compositor */); + auto canvas = surface->getCanvas(); + FML_CHECK(canvas != nullptr); + + switch (layer.platform_view->identifier) { + case 1: { + SkPaint paint; + // See dart test for total order. + paint.setColor(SK_ColorGREEN); + paint.setAlpha(127); + const auto& rect = + SkRect::MakeWH(layer.size.width, layer.size.height); + canvas->drawRect(rect, paint); + latch.CountDown(); + } break; + default: + // Asked to render an unknown platform view. + FML_CHECK(false) + << "Test was asked to composite an unknown platform view."; + } + + return surface->makeImageSnapshot(); + }); + + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&latch](Dart_NativeArguments args) { latch.CountDown(); })); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + event.physical_view_inset_top = 0.0; + event.physical_view_inset_right = 0.0; + event.physical_view_inset_bottom = 0.0; + event.physical_view_inset_left = 0.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + + latch.Wait(); + + // TODO(https://github.com/flutter/flutter/issues/53784): enable this on all + // platforms. +#if !defined(FML_OS_LINUX) + GTEST_SKIP() << "Skipping golden tests on non-Linux OSes"; +#endif // FML_OS_LINUX + ASSERT_TRUE(ImageMatchesFixture( + "compositor_platform_layer_with_no_overlay.png", scene_image)); + + // There should no present calls on the root surface. + ASSERT_EQ(context.GetSurfacePresentCount(), 0u); +} + +//------------------------------------------------------------------------------ +/// Test that an engine can be initialized but not run. +/// +TEST_F(EmbedderTest, CanCreateInitializedEngine) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + auto engine = builder.InitializeEngine(); + ASSERT_TRUE(engine.is_valid()); + engine.reset(); +} + +//------------------------------------------------------------------------------ +/// Test that an initialized engine can be run exactly once. +/// +TEST_F(EmbedderTest, CanRunInitializedEngine) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + auto engine = builder.InitializeEngine(); + ASSERT_TRUE(engine.is_valid()); + ASSERT_EQ(FlutterEngineRunInitialized(engine.get()), kSuccess); + // Cannot re-run an already running engine. + ASSERT_EQ(FlutterEngineRunInitialized(engine.get()), kInvalidArguments); + engine.reset(); +} + +//------------------------------------------------------------------------------ +/// Test that an engine can be deinitialized. +/// +TEST_F(EmbedderTest, CanDeinitializeAnEngine) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + auto engine = builder.InitializeEngine(); + ASSERT_TRUE(engine.is_valid()); + ASSERT_EQ(FlutterEngineRunInitialized(engine.get()), kSuccess); + // Cannot re-run an already running engine. + ASSERT_EQ(FlutterEngineRunInitialized(engine.get()), kInvalidArguments); + ASSERT_EQ(FlutterEngineDeinitialize(engine.get()), kSuccess); + // It is ok to deinitialize an engine multiple times. + ASSERT_EQ(FlutterEngineDeinitialize(engine.get()), kSuccess); + + // Sending events to a deinitialized engine fails. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + event.physical_view_inset_top = 0.0; + event.physical_view_inset_right = 0.0; + event.physical_view_inset_bottom = 0.0; + event.physical_view_inset_left = 0.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kInvalidArguments); + engine.reset(); +} + +//------------------------------------------------------------------------------ +/// Test that a view can be added to a running engine. +/// +TEST_F(EmbedderTest, CanAddView) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("window_metrics_event_all_view_ids"); + + fml::AutoResetWaitableEvent ready_latch, message_latch; + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&ready_latch](Dart_NativeArguments args) { ready_latch.Signal(); })); + + std::string message; + context.AddNativeCallback("SignalNativeMessage", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + message = + tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + message_latch.Signal(); + })); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + ready_latch.Wait(); + + FlutterWindowMetricsEvent metrics = {}; + metrics.struct_size = sizeof(FlutterWindowMetricsEvent); + metrics.width = 800; + metrics.height = 600; + metrics.pixel_ratio = 1.0; + metrics.view_id = 123; + + FlutterAddViewInfo info = {}; + info.struct_size = sizeof(FlutterAddViewInfo); + info.view_id = 123; + info.view_metrics = &metrics; + info.add_view_callback = [](const FlutterAddViewResult* result) { + EXPECT_TRUE(result->added); + }; + ASSERT_EQ(FlutterEngineAddView(engine.get(), &info), kSuccess); + message_latch.Wait(); + ASSERT_EQ("View IDs: [0, 123]", message); +} + +//------------------------------------------------------------------------------ +/// Test that adding a view schedules a frame. +/// +TEST_F(EmbedderTest, AddViewSchedulesFrame) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("add_view_schedules_frame"); + fml::AutoResetWaitableEvent latch; + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&latch](Dart_NativeArguments args) { latch.Signal(); })); + + fml::AutoResetWaitableEvent check_latch; + context.AddNativeCallback( + "SignalNativeCount", + CREATE_NATIVE_ENTRY( + [&check_latch](Dart_NativeArguments args) { check_latch.Signal(); })); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // Wait for the application to attach the listener. + latch.Wait(); + + FlutterWindowMetricsEvent metrics = {}; + metrics.struct_size = sizeof(FlutterWindowMetricsEvent); + metrics.width = 800; + metrics.height = 600; + metrics.pixel_ratio = 1.0; + metrics.view_id = 123; + + FlutterAddViewInfo info = {}; + info.struct_size = sizeof(FlutterAddViewInfo); + info.view_id = 123; + info.view_metrics = &metrics; + info.add_view_callback = [](const FlutterAddViewResult* result) { + EXPECT_TRUE(result->added); + }; + ASSERT_EQ(FlutterEngineAddView(engine.get(), &info), kSuccess); + + check_latch.Wait(); +} + +//------------------------------------------------------------------------------ +/// Test that a view that was added can be removed. +/// +TEST_F(EmbedderTest, CanRemoveView) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("window_metrics_event_all_view_ids"); + + fml::AutoResetWaitableEvent ready_latch, message_latch; + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&ready_latch](Dart_NativeArguments args) { ready_latch.Signal(); })); + + std::string message; + context.AddNativeCallback("SignalNativeMessage", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + message = + tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + message_latch.Signal(); + })); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + ready_latch.Wait(); + + // Add view 123. + FlutterWindowMetricsEvent metrics = {}; + metrics.struct_size = sizeof(FlutterWindowMetricsEvent); + metrics.width = 800; + metrics.height = 600; + metrics.pixel_ratio = 1.0; + metrics.view_id = 123; + + FlutterAddViewInfo add_info = {}; + add_info.struct_size = sizeof(FlutterAddViewInfo); + add_info.view_id = 123; + add_info.view_metrics = &metrics; + add_info.add_view_callback = [](const FlutterAddViewResult* result) { + ASSERT_TRUE(result->added); + }; + ASSERT_EQ(FlutterEngineAddView(engine.get(), &add_info), kSuccess); + message_latch.Wait(); + ASSERT_EQ(message, "View IDs: [0, 123]"); + + // Remove view 123. + FlutterRemoveViewInfo remove_info = {}; + remove_info.struct_size = sizeof(FlutterAddViewInfo); + remove_info.view_id = 123; + remove_info.remove_view_callback = [](const FlutterRemoveViewResult* result) { + EXPECT_TRUE(result->removed); + }; + ASSERT_EQ(FlutterEngineRemoveView(engine.get(), &remove_info), kSuccess); + message_latch.Wait(); + ASSERT_EQ(message, "View IDs: [0]"); +} + +// Regression test for: +// https://github.com/flutter/flutter/issues/164564 +TEST_F(EmbedderTest, RemoveViewCallbackIsInvokedAfterRasterThreadIsDone) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + std::mutex engine_mutex; + UniqueEngine engine; + auto render_thread = CreateNewThread("custom_render_thread"); + EmbedderTestTaskRunner render_task_runner( + render_thread, [&](FlutterTask task) { + std::scoped_lock engine_lock(engine_mutex); + if (engine.is_valid()) { + ASSERT_EQ(FlutterEngineRunTask(engine.get(), &task), kSuccess); + } + }); + + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("remove_view_callback_too_early"); + builder.SetRenderTaskRunner( + &render_task_runner.GetFlutterTaskRunnerDescription()); + + fml::AutoResetWaitableEvent ready_latch; + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&ready_latch](Dart_NativeArguments args) { ready_latch.Signal(); })); + + { + std::scoped_lock lock(engine_mutex); + engine = builder.InitializeEngine(); + } + ASSERT_EQ(FlutterEngineRunInitialized(engine.get()), kSuccess); + ASSERT_TRUE(engine.is_valid()); + + ready_latch.Wait(); + + fml::AutoResetWaitableEvent add_view_latch; + // Add view 123. + FlutterWindowMetricsEvent metrics = {}; + metrics.struct_size = sizeof(FlutterWindowMetricsEvent); + metrics.width = 800; + metrics.height = 600; + metrics.pixel_ratio = 1.0; + metrics.view_id = 123; + + FlutterAddViewInfo add_info = {}; + add_info.struct_size = sizeof(FlutterAddViewInfo); + add_info.view_id = 123; + add_info.view_metrics = &metrics; + add_info.user_data = &add_view_latch; + add_info.add_view_callback = [](const FlutterAddViewResult* result) { + ASSERT_TRUE(result->added); + auto add_view_latch = + reinterpret_cast(result->user_data); + add_view_latch->Signal(); + }; + ASSERT_EQ(FlutterEngineAddView(engine.get(), &add_info), kSuccess); + add_view_latch.Wait(); + + std::atomic_bool view_available = true; + + // Simulate pending rasterization task scheduled before view removal request + // that accesses view resources. + fml::AutoResetWaitableEvent raster_thread_latch; + render_thread->PostTask([&] { + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + // View must be available. + EXPECT_TRUE(view_available); + raster_thread_latch.Signal(); + }); + + fml::AutoResetWaitableEvent remove_view_latch; + FlutterRemoveViewInfo remove_view_info = {}; + remove_view_info.struct_size = sizeof(FlutterRemoveViewInfo); + remove_view_info.view_id = 123; + remove_view_info.user_data = &remove_view_latch; + remove_view_info.remove_view_callback = + [](const FlutterRemoveViewResult* result) { + ASSERT_TRUE(result->removed); + auto remove_view_latch = + reinterpret_cast(result->user_data); + remove_view_latch->Signal(); + }; + + // Remove the view and wait until the callback is called. + ASSERT_EQ(FlutterEngineRemoveView(engine.get(), &remove_view_info), kSuccess); + remove_view_latch.Wait(); + + // After FlutterEngineRemoveViewCallback is called it should be safe to + // remove view - raster thread must not be accessing any view resources. + view_available = false; + raster_thread_latch.Wait(); + + FlutterEngineDeinitialize(engine.get()); +} + +//------------------------------------------------------------------------------ +/// The implicit view is a special view that the engine and framework assume +/// can *always* be rendered to. Test that this view cannot be removed. +/// +TEST_F(EmbedderTest, CannotRemoveImplicitView) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + FlutterRemoveViewInfo info = {}; + info.struct_size = sizeof(FlutterRemoveViewInfo); + info.view_id = kFlutterImplicitViewId; + info.remove_view_callback = [](const FlutterRemoveViewResult* result) { + FAIL(); + }; + ASSERT_EQ(FlutterEngineRemoveView(engine.get(), &info), kInvalidArguments); +} + +//------------------------------------------------------------------------------ +/// Test that a view cannot be added if its ID already exists. +/// +TEST_F(EmbedderTest, CannotAddDuplicateViews) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("window_metrics_event_all_view_ids"); + + fml::AutoResetWaitableEvent ready_latch, message_latch; + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&ready_latch](Dart_NativeArguments args) { ready_latch.Signal(); })); + + std::string message; + context.AddNativeCallback("SignalNativeMessage", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + message = + tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + message_latch.Signal(); + })); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + ready_latch.Wait(); + + // Add view 123. + struct Captures { + std::atomic count = 0; + fml::AutoResetWaitableEvent failure_latch; + }; + Captures captures; + + FlutterWindowMetricsEvent metrics = {}; + metrics.struct_size = sizeof(FlutterWindowMetricsEvent); + metrics.width = 800; + metrics.height = 600; + metrics.pixel_ratio = 1.0; + metrics.view_id = 123; + + FlutterAddViewInfo add_info = {}; + add_info.struct_size = sizeof(FlutterAddViewInfo); + add_info.view_id = 123; + add_info.view_metrics = &metrics; + add_info.user_data = &captures; + add_info.add_view_callback = [](const FlutterAddViewResult* result) { + auto captures = reinterpret_cast(result->user_data); + + int count = captures->count.fetch_add(1); + + if (count == 0) { + ASSERT_TRUE(result->added); + } else { + EXPECT_FALSE(result->added); + captures->failure_latch.Signal(); + } + }; + ASSERT_EQ(FlutterEngineAddView(engine.get(), &add_info), kSuccess); + message_latch.Wait(); + ASSERT_EQ(message, "View IDs: [0, 123]"); + ASSERT_FALSE(captures.failure_latch.IsSignaledForTest()); + + // Add view 123 a second time. + ASSERT_EQ(FlutterEngineAddView(engine.get(), &add_info), kSuccess); + captures.failure_latch.Wait(); + ASSERT_EQ(captures.count, 2); + ASSERT_FALSE(message_latch.IsSignaledForTest()); +} + +//------------------------------------------------------------------------------ +/// Test that a removed view's ID can be reused to add a new view. +/// +TEST_F(EmbedderTest, CanReuseViewIds) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("window_metrics_event_all_view_ids"); + + fml::AutoResetWaitableEvent ready_latch, message_latch; + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&ready_latch](Dart_NativeArguments args) { ready_latch.Signal(); })); + + std::string message; + context.AddNativeCallback("SignalNativeMessage", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + message = + tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + message_latch.Signal(); + })); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + ready_latch.Wait(); + + // Add view 123. + FlutterWindowMetricsEvent metrics = {}; + metrics.struct_size = sizeof(FlutterWindowMetricsEvent); + metrics.width = 800; + metrics.height = 600; + metrics.pixel_ratio = 1.0; + metrics.view_id = 123; + + FlutterAddViewInfo add_info = {}; + add_info.struct_size = sizeof(FlutterAddViewInfo); + add_info.view_id = 123; + add_info.view_metrics = &metrics; + add_info.add_view_callback = [](const FlutterAddViewResult* result) { + ASSERT_TRUE(result->added); + }; + ASSERT_EQ(FlutterEngineAddView(engine.get(), &add_info), kSuccess); + message_latch.Wait(); + ASSERT_EQ(message, "View IDs: [0, 123]"); + + // Remove view 123. + FlutterRemoveViewInfo remove_info = {}; + remove_info.struct_size = sizeof(FlutterAddViewInfo); + remove_info.view_id = 123; + remove_info.remove_view_callback = [](const FlutterRemoveViewResult* result) { + ASSERT_TRUE(result->removed); + }; + ASSERT_EQ(FlutterEngineRemoveView(engine.get(), &remove_info), kSuccess); + message_latch.Wait(); + ASSERT_EQ(message, "View IDs: [0]"); + + // Re-add view 123. + ASSERT_EQ(FlutterEngineAddView(engine.get(), &add_info), kSuccess); + message_latch.Wait(); + ASSERT_EQ(message, "View IDs: [0, 123]"); +} + +//------------------------------------------------------------------------------ +/// Test that attempting to remove a view that does not exist fails as expected. +/// +TEST_F(EmbedderTest, CannotRemoveUnknownView) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + fml::AutoResetWaitableEvent latch; + FlutterRemoveViewInfo info = {}; + info.struct_size = sizeof(FlutterRemoveViewInfo); + info.view_id = 123; + info.user_data = &latch; + info.remove_view_callback = [](const FlutterRemoveViewResult* result) { + EXPECT_FALSE(result->removed); + reinterpret_cast(result->user_data)->Signal(); + }; + ASSERT_EQ(FlutterEngineRemoveView(engine.get(), &info), kSuccess); + latch.Wait(); +} + +//------------------------------------------------------------------------------ +/// View operations - adding, removing, sending window metrics - must execute in +/// order even though they are asynchronous. This is necessary to ensure the +/// embedder's and engine's states remain synchronized. +/// +TEST_F(EmbedderTest, ViewOperationsOrdered) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("window_metrics_event_all_view_ids"); + + fml::AutoResetWaitableEvent ready_latch; + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&ready_latch](Dart_NativeArguments args) { ready_latch.Signal(); })); + + std::atomic message_count = 0; + context.AddNativeCallback("SignalNativeMessage", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + message_count.fetch_add(1); + })); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + ready_latch.Wait(); + + // Enqueue multiple view operations at once: + // + // 1. Add view 123 - This must succeed. + // 2. Add duplicate view 123 - This must fail asynchronously. + // 3. Add second view 456 - This must succeed. + // 4. Remove second view 456 - This must succeed. + // + // The engine must execute view operations asynchronously in serial order. + // If step 2 succeeds instead of step 1, this indicates the engine did not + // execute the view operations in the correct order. If step 4 fails, + // this indicates the engine did not wait until the add second view completed. + FlutterWindowMetricsEvent metrics123 = {}; + metrics123.struct_size = sizeof(FlutterWindowMetricsEvent); + metrics123.width = 800; + metrics123.height = 600; + metrics123.pixel_ratio = 1.0; + metrics123.view_id = 123; + + FlutterWindowMetricsEvent metrics456 = {}; + metrics456.struct_size = sizeof(FlutterWindowMetricsEvent); + metrics456.width = 800; + metrics456.height = 600; + metrics456.pixel_ratio = 1.0; + metrics456.view_id = 456; + + struct Captures { + fml::AutoResetWaitableEvent add_first_view; + fml::AutoResetWaitableEvent add_duplicate_view; + fml::AutoResetWaitableEvent add_second_view; + fml::AutoResetWaitableEvent remove_second_view; + }; + Captures captures; + + // Add view 123. + FlutterAddViewInfo add_view_info = {}; + add_view_info.struct_size = sizeof(FlutterAddViewInfo); + add_view_info.view_id = 123; + add_view_info.view_metrics = &metrics123; + add_view_info.user_data = &captures; + add_view_info.add_view_callback = [](const FlutterAddViewResult* result) { + auto captures = reinterpret_cast(result->user_data); + + ASSERT_TRUE(result->added); + ASSERT_FALSE(captures->add_first_view.IsSignaledForTest()); + ASSERT_FALSE(captures->add_duplicate_view.IsSignaledForTest()); + ASSERT_FALSE(captures->add_second_view.IsSignaledForTest()); + ASSERT_FALSE(captures->remove_second_view.IsSignaledForTest()); + + captures->add_first_view.Signal(); + }; + + // Add duplicate view 123. + FlutterAddViewInfo add_duplicate_view_info = {}; + add_duplicate_view_info.struct_size = sizeof(FlutterAddViewInfo); + add_duplicate_view_info.view_id = 123; + add_duplicate_view_info.view_metrics = &metrics123; + add_duplicate_view_info.user_data = &captures; + add_duplicate_view_info.add_view_callback = + [](const FlutterAddViewResult* result) { + auto captures = reinterpret_cast(result->user_data); + + ASSERT_FALSE(result->added); + ASSERT_TRUE(captures->add_first_view.IsSignaledForTest()); + ASSERT_FALSE(captures->add_duplicate_view.IsSignaledForTest()); + ASSERT_FALSE(captures->add_second_view.IsSignaledForTest()); + ASSERT_FALSE(captures->remove_second_view.IsSignaledForTest()); + + captures->add_duplicate_view.Signal(); + }; + + // Add view 456. + FlutterAddViewInfo add_second_view_info = {}; + add_second_view_info.struct_size = sizeof(FlutterAddViewInfo); + add_second_view_info.view_id = 456; + add_second_view_info.view_metrics = &metrics456; + add_second_view_info.user_data = &captures; + add_second_view_info.add_view_callback = + [](const FlutterAddViewResult* result) { + auto captures = reinterpret_cast(result->user_data); + + ASSERT_TRUE(result->added); + ASSERT_TRUE(captures->add_first_view.IsSignaledForTest()); + ASSERT_TRUE(captures->add_duplicate_view.IsSignaledForTest()); + ASSERT_FALSE(captures->add_second_view.IsSignaledForTest()); + ASSERT_FALSE(captures->remove_second_view.IsSignaledForTest()); + + captures->add_second_view.Signal(); + }; + + // Remove view 456. + FlutterRemoveViewInfo remove_second_view_info = {}; + remove_second_view_info.struct_size = sizeof(FlutterRemoveViewInfo); + remove_second_view_info.view_id = 456; + remove_second_view_info.user_data = &captures; + remove_second_view_info.remove_view_callback = + [](const FlutterRemoveViewResult* result) { + auto captures = reinterpret_cast(result->user_data); + + ASSERT_TRUE(result->removed); + ASSERT_TRUE(captures->add_first_view.IsSignaledForTest()); + ASSERT_TRUE(captures->add_duplicate_view.IsSignaledForTest()); + ASSERT_TRUE(captures->add_second_view.IsSignaledForTest()); + ASSERT_FALSE(captures->remove_second_view.IsSignaledForTest()); + + captures->remove_second_view.Signal(); + }; + + ASSERT_EQ(FlutterEngineAddView(engine.get(), &add_view_info), kSuccess); + ASSERT_EQ(FlutterEngineAddView(engine.get(), &add_duplicate_view_info), + kSuccess); + ASSERT_EQ(FlutterEngineAddView(engine.get(), &add_second_view_info), + kSuccess); + ASSERT_EQ(FlutterEngineRemoveView(engine.get(), &remove_second_view_info), + kSuccess); + captures.remove_second_view.Wait(); + captures.add_second_view.Wait(); + captures.add_duplicate_view.Wait(); + captures.add_first_view.Wait(); + ASSERT_EQ(message_count, 3); +} + +//------------------------------------------------------------------------------ +/// Test the engine can present to multiple views. +/// +TEST_F(EmbedderTest, CanRenderMultipleViews) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetCompositor(); + builder.SetDartEntrypoint("render_all_views"); + + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer); + + fml::AutoResetWaitableEvent latch0, latch123; + context.GetCompositor().SetPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + switch (view_id) { + case 0: + latch0.Signal(); + break; + case 123: + latch123.Signal(); + break; + default: + FML_UNREACHABLE(); + } + }, + /* one_shot= */ false); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // Give the implicit view a non-zero size so that it renders something. + FlutterWindowMetricsEvent metrics0 = {}; + metrics0.struct_size = sizeof(FlutterWindowMetricsEvent); + metrics0.width = 800; + metrics0.height = 600; + metrics0.pixel_ratio = 1.0; + metrics0.view_id = 0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &metrics0), + kSuccess); + + // Add view 123. + FlutterWindowMetricsEvent metrics123 = {}; + metrics123.struct_size = sizeof(FlutterWindowMetricsEvent); + metrics123.width = 800; + metrics123.height = 600; + metrics123.pixel_ratio = 1.0; + metrics123.view_id = 123; + + FlutterAddViewInfo add_view_info = {}; + add_view_info.struct_size = sizeof(FlutterAddViewInfo); + add_view_info.view_id = 123; + add_view_info.view_metrics = &metrics123; + add_view_info.add_view_callback = [](const FlutterAddViewResult* result) { + ASSERT_TRUE(result->added); + }; + + ASSERT_EQ(FlutterEngineAddView(engine.get(), &add_view_info), kSuccess); + + latch0.Wait(); + latch123.Wait(); +} + +bool operator==(const FlutterViewFocusChangeRequest& lhs, + const FlutterViewFocusChangeRequest& rhs) { + return lhs.view_id == rhs.view_id && lhs.state == rhs.state && + lhs.direction == rhs.direction; +} + +TEST_F(EmbedderTest, SendsViewFocusChangeRequest) { + auto& context = GetEmbedderContext(); + auto platform_task_runner = CreateNewThread("test_platform_thread"); + UniqueEngine engine; + static std::mutex engine_mutex; + EmbedderTestTaskRunner test_platform_task_runner( + platform_task_runner, [&](FlutterTask task) { + std::scoped_lock lock(engine_mutex); + if (!engine.is_valid()) { + return; + } + FlutterEngineRunTask(engine.get(), &task); + }); + fml::CountDownLatch latch(3); + std::vector received_requests; + platform_task_runner->PostTask([&]() { + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("testSendViewFocusChangeRequest"); + const auto platform_task_runner_description = + test_platform_task_runner.GetFlutterTaskRunnerDescription(); + builder.SetPlatformTaskRunner(&platform_task_runner_description); + builder.SetViewFocusChangeRequestCallback( + [&](const FlutterViewFocusChangeRequest* request) { + EXPECT_TRUE(platform_task_runner->RunsTasksOnCurrentThread()); + received_requests.push_back(*request); + latch.CountDown(); + }); + engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + }); + latch.Wait(); + + std::vector expected_requests{ + {.view_id = 1, .state = kUnfocused, .direction = kUndefined}, + {.view_id = 2, .state = kFocused, .direction = kForward}, + {.view_id = 3, .state = kFocused, .direction = kBackward}, + }; + + ASSERT_EQ(received_requests.size(), expected_requests.size()); + for (size_t i = 0; i < received_requests.size(); ++i) { + ASSERT_TRUE(received_requests[i] == expected_requests[i]); + } + + fml::AutoResetWaitableEvent kill_latch; + platform_task_runner->PostTask(fml::MakeCopyable([&]() mutable { + std::scoped_lock lock(engine_mutex); + engine.reset(); + + // There may still be pending tasks on the platform thread that were queued + // by the test_task_runner. Signal the latch after these tasks have been + // consumed. + platform_task_runner->PostTask([&kill_latch] { kill_latch.Signal(); }); + })); + kill_latch.Wait(); +} + +TEST_F(EmbedderTest, CanSendViewFocusEvent) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("testSendViewFocusEvent"); + + fml::AutoResetWaitableEvent latch; + std::string last_event; + + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&latch](Dart_NativeArguments args) { latch.Signal(); })); + context.AddNativeCallback("NotifyStringValue", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + const auto message_from_dart = + tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + last_event = message_from_dart; + latch.Signal(); + })); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + // Wait until the focus change handler is attached. + latch.Wait(); + latch.Reset(); + + FlutterViewFocusEvent event1{ + .struct_size = sizeof(FlutterViewFocusEvent), + .view_id = 1, + .state = kFocused, + .direction = kUndefined, + }; + FlutterEngineResult result = + FlutterEngineSendViewFocusEvent(engine.get(), &event1); + ASSERT_EQ(result, kSuccess); + latch.Wait(); + ASSERT_EQ(last_event, + "1 ViewFocusState.focused ViewFocusDirection.undefined"); + + FlutterViewFocusEvent event2{ + .struct_size = sizeof(FlutterViewFocusEvent), + .view_id = 2, + .state = kUnfocused, + .direction = kBackward, + }; + latch.Reset(); + result = FlutterEngineSendViewFocusEvent(engine.get(), &event2); + ASSERT_EQ(result, kSuccess); + latch.Wait(); + ASSERT_EQ(last_event, + "2 ViewFocusState.unfocused ViewFocusDirection.backward"); +} + +//------------------------------------------------------------------------------ +/// Test that the backing store is created with the correct view ID, is used +/// for the correct view, and is cached according to their views. +/// +/// The test involves two frames: +/// 1. The first frame renders the implicit view and the second view. +/// 2. The second frame renders the implicit view and the third view. +/// +/// The test verifies that: +/// - Each backing store is created with a valid view ID. +/// - Each backing store is presented for the view that it was created for. +/// - Both frames render the expected sets of views. +/// - By the end of frame 1, only 2 backing stores were created. +/// - By the end of frame 2, only 3 backing stores were created. This ensures +/// that the backing store for the 2nd view is not reused for the 3rd view. +TEST_F(EmbedderTest, BackingStoresCorrespondToTheirViews) { + constexpr FlutterViewId kSecondViewId = 123; + constexpr FlutterViewId kThirdViewId = 456; + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetDartEntrypoint("render_all_views"); + builder.SetSurface(SkISize::Make(800, 600)); + builder.SetCompositor(); + + EmbedderTestBackingStoreProducerSoftware producer( + context.GetCompositor().GetGrContext(), + EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer); + + // The variables needed by the callbacks of the compositor. + struct CompositorUserData { + EmbedderTestBackingStoreProducer* producer; + // Each latch is signaled when its corresponding view is presented. + fml::AutoResetWaitableEvent latch_implicit; + fml::AutoResetWaitableEvent latch_second; + fml::AutoResetWaitableEvent latch_third; + // Whether the respective view should be rendered in the frame. + bool second_expected; + bool third_expected; + // The total number of backing stores created to verify caching. + int backing_stores_created; + }; + CompositorUserData compositor_user_data{ + .producer = &producer, + .backing_stores_created = 0, + }; + + builder.GetCompositor() = FlutterCompositor{ + .struct_size = sizeof(FlutterCompositor), + .user_data = reinterpret_cast(&compositor_user_data), + .create_backing_store_callback = + [](const FlutterBackingStoreConfig* config, + FlutterBackingStore* backing_store_out, void* user_data) { + // Verify that the backing store comes with the correct view ID. + EXPECT_TRUE(config->view_id == 0 || + config->view_id == kSecondViewId || + config->view_id == kThirdViewId); + auto compositor_user_data = + reinterpret_cast(user_data); + compositor_user_data->backing_stores_created += 1; + bool result = compositor_user_data->producer->Create( + config, backing_store_out); + // The created backing store has a user_data that records the view + // that the store is created for. + backing_store_out->user_data = + reinterpret_cast(config->view_id); + return result; + }, + .collect_backing_store_callback = [](const FlutterBackingStore* renderer, + void* user_data) { return true; }, + .present_layers_callback = nullptr, + .avoid_backing_store_cache = false, + .present_view_callback = + [](const FlutterPresentViewInfo* info) { + EXPECT_EQ(info->layers_count, 1u); + // Verify that the given layer's backing store has the same view ID + // as the target view. + int64_t store_view_id = reinterpret_cast( + info->layers[0]->backing_store->user_data); + EXPECT_EQ(store_view_id, info->view_id); + auto compositor_user_data = + reinterpret_cast(info->user_data); + // Verify that the respective views are rendered. + switch (info->view_id) { + case 0: + compositor_user_data->latch_implicit.Signal(); + break; + case kSecondViewId: + EXPECT_TRUE(compositor_user_data->second_expected); + compositor_user_data->latch_second.Signal(); + break; + case kThirdViewId: + EXPECT_TRUE(compositor_user_data->third_expected); + compositor_user_data->latch_third.Signal(); + break; + default: + FML_UNREACHABLE(); + } + return true; + }, + }; + + compositor_user_data.second_expected = true; + compositor_user_data.third_expected = false; + + /*=== First frame ===*/ + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // Give the implicit view a non-zero size so that it renders something. + FlutterWindowMetricsEvent metrics_implicit = { + .struct_size = sizeof(FlutterWindowMetricsEvent), + .width = 800, + .height = 600, + .pixel_ratio = 1.0, + .view_id = 0, + }; + ASSERT_EQ( + FlutterEngineSendWindowMetricsEvent(engine.get(), &metrics_implicit), + kSuccess); + + // Add the second view. + FlutterWindowMetricsEvent metrics_add = { + .struct_size = sizeof(FlutterWindowMetricsEvent), + .width = 800, + .height = 600, + .pixel_ratio = 1.0, + .view_id = kSecondViewId, + }; + + FlutterAddViewInfo add_view_info = {}; + add_view_info.struct_size = sizeof(FlutterAddViewInfo); + add_view_info.view_id = kSecondViewId; + add_view_info.view_metrics = &metrics_add; + add_view_info.add_view_callback = [](const FlutterAddViewResult* result) { + ASSERT_TRUE(result->added); + }; + + ASSERT_EQ(FlutterEngineAddView(engine.get(), &add_view_info), kSuccess); + + compositor_user_data.latch_implicit.Wait(); + compositor_user_data.latch_second.Wait(); + + /*=== Second frame ===*/ + + compositor_user_data.second_expected = false; + compositor_user_data.third_expected = true; + EXPECT_EQ(compositor_user_data.backing_stores_created, 2); + + // Remove the second view + FlutterRemoveViewInfo remove_view_info = {}; + remove_view_info.struct_size = sizeof(FlutterRemoveViewInfo); + remove_view_info.view_id = kSecondViewId; + remove_view_info.remove_view_callback = + [](const FlutterRemoveViewResult* result) { + ASSERT_TRUE(result->removed); + }; + ASSERT_EQ(FlutterEngineRemoveView(engine.get(), &remove_view_info), kSuccess); + + // Add the third view. + add_view_info.view_id = kThirdViewId; + metrics_add.view_id = kThirdViewId; + ASSERT_EQ(FlutterEngineAddView(engine.get(), &add_view_info), kSuccess); + // Adding the view should have scheduled a frame. + + compositor_user_data.latch_implicit.Wait(); + compositor_user_data.latch_third.Wait(); + EXPECT_EQ(compositor_user_data.backing_stores_created, 3); +} + +TEST_F(EmbedderTest, CanUpdateLocales) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("can_receive_locale_updates"); + fml::AutoResetWaitableEvent latch; + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&latch](Dart_NativeArguments args) { latch.Signal(); })); + + 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(); + })); + + 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); + + check_latch.Wait(); +} + +TEST_F(EmbedderTest, LocalizationCallbacksCalled) { + auto& context = GetEmbedderContext(); + fml::AutoResetWaitableEvent latch; + context.AddIsolateCreateCallback([&latch]() { latch.Signal(); }); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + // Wait for the root isolate to launch. + latch.Wait(); + + flutter::Shell& shell = ToEmbedderEngine(engine.get())->GetShell(); + std::vector supported_locales; + supported_locales.push_back("es"); + supported_locales.push_back("MX"); + supported_locales.push_back(""); + auto result = shell.GetPlatformView()->ComputePlatformResolvedLocales( + supported_locales); + + ASSERT_EQ((*result).size(), supported_locales.size()); // 3 + ASSERT_EQ((*result)[0], supported_locales[0]); + ASSERT_EQ((*result)[1], supported_locales[1]); + ASSERT_EQ((*result)[2], supported_locales[2]); + + engine.reset(); +} + +TEST_F(EmbedderTest, CanQueryDartAOTMode) { + ASSERT_EQ(FlutterEngineRunsAOTCompiledDartCode(), + flutter::DartVM::IsRunningPrecompiledCode()); +} + +TEST_F(EmbedderTest, VerifyB143464703WithSoftwareBackend) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1024, 600)); + builder.SetCompositor(); + builder.SetDartEntrypoint("verify_b143464703"); + + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer); + + // setup the screenshot promise. + auto rendered_scene = context.GetNextSceneImage(); + + fml::CountDownLatch latch(1); + context.GetCompositor().SetNextPresentCallback( + [&](FlutterViewId view_id, const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers_count, 2u); + + // Layer 0 (Root) + { + FlutterBackingStore backing_store = *layers[0]->backing_store; + backing_store.type = kFlutterBackingStoreTypeSoftware; + backing_store.did_update = true; + + FlutterRect paint_region_rects[] = { + FlutterRectMakeLTRB(0, 0, 1024, 600), + }; + FlutterRegion paint_region = { + .struct_size = sizeof(FlutterRegion), + .rects_count = 1, + .rects = paint_region_rects, + }; + FlutterBackingStorePresentInfo present_info = { + .struct_size = sizeof(FlutterBackingStorePresentInfo), + .paint_region = &paint_region, + }; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypeBackingStore; + layer.backing_store = &backing_store; + layer.size = FlutterSizeMake(1024.0, 600.0); + layer.offset = FlutterPointMake(0.0, 0.0); + layer.backing_store_present_info = &present_info; + + ASSERT_EQ(*layers[0], layer); + } + + // Layer 1 + { + FlutterPlatformView platform_view = *layers[1]->platform_view; + platform_view.struct_size = sizeof(platform_view); + platform_view.identifier = 42; + + FlutterLayer layer = {}; + layer.struct_size = sizeof(layer); + layer.type = kFlutterLayerContentTypePlatformView; + layer.platform_view = &platform_view; + layer.size = FlutterSizeMake(1024.0, 540.0); + layer.offset = FlutterPointMake(135.0, 60.0); + + ASSERT_EQ(*layers[1], layer); + } + + latch.CountDown(); + }); + + context.GetCompositor().SetPlatformViewRendererCallback( + [](const FlutterLayer& layer, + GrDirectContext* context) -> sk_sp { + auto surface = CreateRenderSurface( + layer, nullptr /* null because software compositor */); + auto canvas = surface->getCanvas(); + FML_CHECK(canvas != nullptr); + + switch (layer.platform_view->identifier) { + case 42: { + SkPaint paint; + // See dart test for total order. + paint.setColor(SK_ColorGREEN); + paint.setAlpha(127); + const auto& rect = + SkRect::MakeWH(layer.size.width, layer.size.height); + canvas->drawRect(rect, paint); + } break; + default: + // Asked to render an unknown platform view. + FML_CHECK(false) + << "Test was asked to composite an unknown platform view."; + } + + return surface->makeImageSnapshot(); + }); + + auto engine = builder.LaunchEngine(); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 1024; + event.height = 600; + event.pixel_ratio = 1.0; + event.physical_view_inset_top = 0.0; + event.physical_view_inset_right = 0.0; + event.physical_view_inset_bottom = 0.0; + event.physical_view_inset_left = 0.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + ASSERT_TRUE(engine.is_valid()); + + // wait for scene to be rendered. + latch.Wait(); + + // TODO(https://github.com/flutter/flutter/issues/53784): enable this on all + // platforms. +#if !defined(FML_OS_LINUX) + GTEST_SKIP() << "Skipping golden tests on non-Linux OSes"; +#endif // FML_OS_LINUX + ASSERT_TRUE( + ImageMatchesFixture("verifyb143464703_soft_noxform.png", rendered_scene)); +} + +TEST_F(EmbedderTest, CanSendLowMemoryNotification) { + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + + auto engine = builder.LaunchEngine(); + + ASSERT_TRUE(engine.is_valid()); + + // TODO(chinmaygarde): The shell ought to have a mechanism for notification + // dispatch that engine subsystems can register handlers to. This would allow + // the raster cache and the secondary context caches to respond to + // notifications. Once that is in place, this test can be updated to actually + // ensure that the dispatched message is visible to engine subsystems. + ASSERT_EQ(FlutterEngineNotifyLowMemoryWarning(engine.get()), kSuccess); +} + +TEST_F(EmbedderTest, CanPostTaskToAllNativeThreads) { + UniqueEngine engine; + size_t worker_count = 0; + fml::AutoResetWaitableEvent sync_latch; + + // One of the threads that the callback will be posted to is the platform + // thread. So we cannot wait for assertions to complete on the platform + // thread. Create a new thread to manage the engine instance and wait for + // assertions on the test thread. + auto platform_task_runner = CreateNewThread("platform_thread"); + + platform_task_runner->PostTask([&]() { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + + engine = builder.LaunchEngine(); + + ASSERT_TRUE(engine.is_valid()); + + worker_count = ToEmbedderEngine(engine.get()) + ->GetShell() + .GetDartVM() + ->GetConcurrentMessageLoop() + ->GetWorkerCount(); + + sync_latch.Signal(); + }); + + sync_latch.Wait(); + + const auto engine_threads_count = worker_count + 4u; + + struct Captures { + // Waits the adequate number of callbacks to fire. + fml::CountDownLatch latch; + + // This class will be accessed from multiple threads concurrently to track + // thread specific information that is later checked. All updates to fields + // in this struct must be made with this mutex acquired. + + std::mutex captures_mutex; + // Ensures that the expect number of distinct threads were serviced. + std::set thread_ids; + + size_t platform_threads_count = 0; + size_t render_threads_count = 0; + size_t ui_threads_count = 0; + size_t worker_threads_count = 0; + + explicit Captures(size_t count) : latch(count) {} + }; + + Captures captures(engine_threads_count); + + platform_task_runner->PostTask([&]() { + ASSERT_EQ(FlutterEnginePostCallbackOnAllNativeThreads( + engine.get(), + [](FlutterNativeThreadType type, void* baton) { + auto captures = reinterpret_cast(baton); + { + std::scoped_lock lock(captures->captures_mutex); + switch (type) { + case kFlutterNativeThreadTypeRender: + captures->render_threads_count++; + break; + case kFlutterNativeThreadTypeWorker: + captures->worker_threads_count++; + break; + case kFlutterNativeThreadTypeUI: + captures->ui_threads_count++; + break; + case kFlutterNativeThreadTypePlatform: + captures->platform_threads_count++; + break; + } + captures->thread_ids.insert(std::this_thread::get_id()); + } + captures->latch.CountDown(); + }, + &captures), + kSuccess); + }); + + captures.latch.Wait(); + ASSERT_EQ(captures.thread_ids.size(), engine_threads_count); + ASSERT_EQ(captures.platform_threads_count, 1u); + ASSERT_EQ(captures.render_threads_count, 1u); + ASSERT_EQ(captures.ui_threads_count, 1u); + ASSERT_EQ(captures.worker_threads_count, worker_count + 1u /* for IO */); + EXPECT_GE(captures.worker_threads_count - 1, 2u); + EXPECT_LE(captures.worker_threads_count - 1, 4u); + + platform_task_runner->PostTask([&]() { + engine.reset(); + sync_latch.Signal(); + }); + sync_latch.Wait(); + + // The engine should have already been destroyed on the platform task runner. + ASSERT_FALSE(engine.is_valid()); +} + +TEST_F(EmbedderTest, InvalidAOTDataSourcesMustReturnError) { + if (!DartVM::IsRunningPrecompiledCode()) { + GTEST_SKIP(); + return; + } + FlutterEngineAOTDataSource data_in = {}; + FlutterEngineAOTData data_out = nullptr; + + // Null source specified. + ASSERT_EQ(FlutterEngineCreateAOTData(nullptr, &data_out), kInvalidArguments); + ASSERT_EQ(data_out, nullptr); + + // Null data_out specified. + ASSERT_EQ(FlutterEngineCreateAOTData(&data_in, nullptr), kInvalidArguments); + + // Invalid FlutterEngineAOTDataSourceType type specified. + // NOLINTNEXTLINE(clang-analyzer-optin.core.EnumCastOutOfRange) + data_in.type = static_cast(-1); + ASSERT_EQ(FlutterEngineCreateAOTData(&data_in, &data_out), kInvalidArguments); + ASSERT_EQ(data_out, nullptr); + + // Invalid ELF path specified. + data_in.type = kFlutterEngineAOTDataSourceTypeElfPath; + data_in.elf_path = nullptr; + ASSERT_EQ(FlutterEngineCreateAOTData(&data_in, &data_out), kInvalidArguments); + ASSERT_EQ(data_in.type, kFlutterEngineAOTDataSourceTypeElfPath); + ASSERT_EQ(data_in.elf_path, nullptr); + ASSERT_EQ(data_out, nullptr); + + // Invalid ELF path specified. + data_in.elf_path = ""; + ASSERT_EQ(FlutterEngineCreateAOTData(&data_in, &data_out), kInvalidArguments); + ASSERT_EQ(data_in.type, kFlutterEngineAOTDataSourceTypeElfPath); + ASSERT_EQ(data_in.elf_path, ""); + ASSERT_EQ(data_out, nullptr); + + // Could not find VM snapshot data. + data_in.elf_path = "/bin/true"; + ASSERT_EQ(FlutterEngineCreateAOTData(&data_in, &data_out), kInvalidArguments); + ASSERT_EQ(data_in.type, kFlutterEngineAOTDataSourceTypeElfPath); + ASSERT_EQ(data_in.elf_path, "/bin/true"); + ASSERT_EQ(data_out, nullptr); +} + +TEST_F(EmbedderTest, MustNotRunWithMultipleAOTSources) { + if (!DartVM::IsRunningPrecompiledCode()) { + GTEST_SKIP(); + return; + } + auto& context = GetEmbedderContext(); + + EmbedderConfigBuilder builder( + context, + EmbedderConfigBuilder::InitializationPreference::kMultiAOTInitialize); + + builder.SetSurface(SkISize::Make(1, 1)); + + auto engine = builder.LaunchEngine(); + ASSERT_FALSE(engine.is_valid()); +} + +TEST_F(EmbedderTest, CanCreateAndCollectAValidElfSource) { + if (!DartVM::IsRunningPrecompiledCode()) { + GTEST_SKIP(); + return; + } + FlutterEngineAOTDataSource data_in = {}; + FlutterEngineAOTData data_out = nullptr; + + // Collecting a null object should be allowed + ASSERT_EQ(FlutterEngineCollectAOTData(data_out), kSuccess); + + const auto elf_path = + fml::paths::JoinPaths({GetFixturesPath(), kDefaultAOTAppELFFileName}); + + data_in.type = kFlutterEngineAOTDataSourceTypeElfPath; + data_in.elf_path = elf_path.c_str(); + + ASSERT_EQ(FlutterEngineCreateAOTData(&data_in, &data_out), kSuccess); + ASSERT_EQ(data_in.type, kFlutterEngineAOTDataSourceTypeElfPath); + ASSERT_EQ(data_in.elf_path, elf_path.c_str()); + ASSERT_NE(data_out, nullptr); + + ASSERT_EQ(FlutterEngineCollectAOTData(data_out), kSuccess); +} + +TEST_F(EmbedderTest, CanLaunchAndShutdownWithAValidElfSource) { + if (!DartVM::IsRunningPrecompiledCode()) { + GTEST_SKIP(); + return; + } + auto& context = GetEmbedderContext(); + + fml::AutoResetWaitableEvent latch; + context.AddIsolateCreateCallback([&latch]() { latch.Signal(); }); + + EmbedderConfigBuilder builder( + context, + EmbedderConfigBuilder::InitializationPreference::kAOTDataInitialize); + + builder.SetSurface(SkISize::Make(1, 1)); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // Wait for the root isolate to launch. + latch.Wait(); + engine.reset(); +} + +#if defined(__clang_analyzer__) +#define TEST_VM_SNAPSHOT_DATA "vm_data" +#define TEST_VM_SNAPSHOT_INSTRUCTIONS "vm_instructions" +#define TEST_ISOLATE_SNAPSHOT_DATA "isolate_data" +#define TEST_ISOLATE_SNAPSHOT_INSTRUCTIONS "isolate_instructions" +#endif + +//------------------------------------------------------------------------------ +/// PopulateJITSnapshotMappingCallbacks should successfully change the callbacks +/// of the snapshots in the engine's settings when JIT snapshots are explicitly +/// defined. +/// +TEST_F(EmbedderTest, CanSuccessfullyPopulateSpecificJITSnapshotCallbacks) { +// TODO(#107263): Inconsistent snapshot paths in the Linux Fuchsia FEMU test. +#if defined(OS_FUCHSIA) + GTEST_SKIP() << "Inconsistent paths in Fuchsia."; +#else + + // This test is only relevant in JIT mode. + if (DartVM::IsRunningPrecompiledCode()) { + GTEST_SKIP(); + return; + } + + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + + // Construct the location of valid JIT snapshots. + const std::string src_path = GetSourcePath(); + const std::string vm_snapshot_data = + fml::paths::JoinPaths({src_path, TEST_VM_SNAPSHOT_DATA}); + const std::string vm_snapshot_instructions = + fml::paths::JoinPaths({src_path, TEST_VM_SNAPSHOT_INSTRUCTIONS}); + const std::string isolate_snapshot_data = + fml::paths::JoinPaths({src_path, TEST_ISOLATE_SNAPSHOT_DATA}); + const std::string isolate_snapshot_instructions = + fml::paths::JoinPaths({src_path, TEST_ISOLATE_SNAPSHOT_INSTRUCTIONS}); + + // Explicitly define the locations of the JIT snapshots + builder.GetProjectArgs().vm_snapshot_data = + reinterpret_cast(vm_snapshot_data.c_str()); + builder.GetProjectArgs().vm_snapshot_instructions = + reinterpret_cast(vm_snapshot_instructions.c_str()); + builder.GetProjectArgs().isolate_snapshot_data = + reinterpret_cast(isolate_snapshot_data.c_str()); + builder.GetProjectArgs().isolate_snapshot_instructions = + reinterpret_cast(isolate_snapshot_instructions.c_str()); + + auto engine = builder.LaunchEngine(); + + flutter::Shell& shell = ToEmbedderEngine(engine.get())->GetShell(); + const Settings settings = shell.GetSettings(); + + ASSERT_NE(settings.vm_snapshot_data(), nullptr); + ASSERT_NE(settings.vm_snapshot_instr(), nullptr); + ASSERT_NE(settings.isolate_snapshot_data(), nullptr); + ASSERT_NE(settings.isolate_snapshot_instr(), nullptr); + ASSERT_NE(settings.dart_library_sources_kernel(), nullptr); +#endif // OS_FUCHSIA +} + +//------------------------------------------------------------------------------ +/// PopulateJITSnapshotMappingCallbacks should still be able to successfully +/// change the callbacks of the snapshots in the engine's settings when JIT +/// snapshots are explicitly defined. However, if those snapshot locations are +/// invalid, the callbacks should return a nullptr. +/// +TEST_F(EmbedderTest, JITSnapshotCallbacksFailWithInvalidLocation) { +// TODO(#107263): Inconsistent snapshot paths in the Linux Fuchsia FEMU test. +#if defined(OS_FUCHSIA) + GTEST_SKIP() << "Inconsistent paths in Fuchsia."; +#else + + // This test is only relevant in JIT mode. + if (DartVM::IsRunningPrecompiledCode()) { + GTEST_SKIP(); + return; + } + + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + + // Explicitly define the locations of the invalid JIT snapshots + builder.GetProjectArgs().vm_snapshot_data = + reinterpret_cast("invalid_vm_data"); + builder.GetProjectArgs().vm_snapshot_instructions = + reinterpret_cast("invalid_vm_instructions"); + builder.GetProjectArgs().isolate_snapshot_data = + reinterpret_cast("invalid_snapshot_data"); + builder.GetProjectArgs().isolate_snapshot_instructions = + reinterpret_cast("invalid_snapshot_instructions"); + + auto engine = builder.LaunchEngine(); + + flutter::Shell& shell = ToEmbedderEngine(engine.get())->GetShell(); + const Settings settings = shell.GetSettings(); + + ASSERT_EQ(settings.vm_snapshot_data(), nullptr); + ASSERT_EQ(settings.vm_snapshot_instr(), nullptr); + ASSERT_EQ(settings.isolate_snapshot_data(), nullptr); + ASSERT_EQ(settings.isolate_snapshot_instr(), nullptr); +#endif // OS_FUCHSIA +} + +//------------------------------------------------------------------------------ +/// The embedder must be able to run explicitly specified snapshots in JIT mode +/// (i.e. when those are present in known locations). +/// +TEST_F(EmbedderTest, CanLaunchEngineWithSpecifiedJITSnapshots) { + // This test is only relevant in JIT mode. + if (DartVM::IsRunningPrecompiledCode()) { + GTEST_SKIP(); + return; + } + + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + + // Construct the location of valid JIT snapshots. + const std::string src_path = GetSourcePath(); + const std::string vm_snapshot_data = + fml::paths::JoinPaths({src_path, TEST_VM_SNAPSHOT_DATA}); + const std::string vm_snapshot_instructions = + fml::paths::JoinPaths({src_path, TEST_VM_SNAPSHOT_INSTRUCTIONS}); + const std::string isolate_snapshot_data = + fml::paths::JoinPaths({src_path, TEST_ISOLATE_SNAPSHOT_DATA}); + const std::string isolate_snapshot_instructions = + fml::paths::JoinPaths({src_path, TEST_ISOLATE_SNAPSHOT_INSTRUCTIONS}); + + // Explicitly define the locations of the JIT snapshots + builder.GetProjectArgs().vm_snapshot_data = + reinterpret_cast(vm_snapshot_data.c_str()); + builder.GetProjectArgs().vm_snapshot_instructions = + reinterpret_cast(vm_snapshot_instructions.c_str()); + builder.GetProjectArgs().isolate_snapshot_data = + reinterpret_cast(isolate_snapshot_data.c_str()); + builder.GetProjectArgs().isolate_snapshot_instructions = + reinterpret_cast(isolate_snapshot_instructions.c_str()); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); +} + +//------------------------------------------------------------------------------ +/// The embedder must be able to run in JIT mode when only some snapshots are +/// specified. +/// +TEST_F(EmbedderTest, CanLaunchEngineWithSomeSpecifiedJITSnapshots) { + // This test is only relevant in JIT mode. + if (DartVM::IsRunningPrecompiledCode()) { + GTEST_SKIP(); + return; + } + + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + + // Construct the location of valid JIT snapshots. + const std::string src_path = GetSourcePath(); + const std::string vm_snapshot_data = + fml::paths::JoinPaths({src_path, TEST_VM_SNAPSHOT_DATA}); + const std::string vm_snapshot_instructions = + fml::paths::JoinPaths({src_path, TEST_VM_SNAPSHOT_INSTRUCTIONS}); + + // Explicitly define the locations of the JIT snapshots + builder.GetProjectArgs().vm_snapshot_data = + reinterpret_cast(vm_snapshot_data.c_str()); + builder.GetProjectArgs().vm_snapshot_instructions = + reinterpret_cast(vm_snapshot_instructions.c_str()); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); +} + +//------------------------------------------------------------------------------ +/// The embedder must be able to run in JIT mode even when the specfied +/// snapshots are invalid. It should be able to resolve them as it would when +/// the snapshots are not specified. +/// +TEST_F(EmbedderTest, CanLaunchEngineWithInvalidJITSnapshots) { + // This test is only relevant in JIT mode. + if (DartVM::IsRunningPrecompiledCode()) { + GTEST_SKIP(); + return; + } + + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + + // Explicitly define the locations of the JIT snapshots + builder.GetProjectArgs().isolate_snapshot_data = + reinterpret_cast("invalid_snapshot_data"); + builder.GetProjectArgs().isolate_snapshot_instructions = + reinterpret_cast("invalid_snapshot_instructions"); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + ASSERT_EQ(FlutterEngineRunInitialized(engine.get()), kInvalidArguments); +} + +//------------------------------------------------------------------------------ +/// The embedder must be able to launch even when the snapshots are not +/// explicitly defined in JIT mode. It must be able to resolve those snapshots. +/// +TEST_F(EmbedderTest, CanLaunchEngineWithUnspecifiedJITSnapshots) { + // This test is only relevant in JIT mode. + if (DartVM::IsRunningPrecompiledCode()) { + GTEST_SKIP(); + return; + } + + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + + ASSERT_EQ(builder.GetProjectArgs().vm_snapshot_data, nullptr); + ASSERT_EQ(builder.GetProjectArgs().vm_snapshot_instructions, nullptr); + ASSERT_EQ(builder.GetProjectArgs().isolate_snapshot_data, nullptr); + ASSERT_EQ(builder.GetProjectArgs().isolate_snapshot_instructions, nullptr); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); +} + +TEST_F(EmbedderTest, InvalidFlutterWindowMetricsEvent) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + auto engine = builder.LaunchEngine(); + + ASSERT_TRUE(engine.is_valid()); + + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 0.0; + event.physical_view_inset_top = 0.0; + event.physical_view_inset_right = 0.0; + event.physical_view_inset_bottom = 0.0; + event.physical_view_inset_left = 0.0; + + // Pixel ratio must be positive. + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kInvalidArguments); + + event.pixel_ratio = 1.0; + event.physical_view_inset_top = -1.0; + event.physical_view_inset_right = -1.0; + event.physical_view_inset_bottom = -1.0; + event.physical_view_inset_left = -1.0; + + // Physical view insets must be non-negative. + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kInvalidArguments); + + event.physical_view_inset_top = 700; + event.physical_view_inset_right = 900; + event.physical_view_inset_bottom = 700; + event.physical_view_inset_left = 900; + + // Top/bottom insets cannot be greater than height. + // Left/right insets cannot be greater than width. + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kInvalidArguments); +} + +static void expectSoftwareRenderingOutputMatches( + EmbedderTest& test, + std::string entrypoint, + FlutterSoftwarePixelFormat pixfmt, + const std::vector& bytes) { + auto& context = test.GetEmbedderContext(); + + EmbedderConfigBuilder builder(context); + fml::AutoResetWaitableEvent latch; + bool matches = false; + + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetCompositor(); + builder.SetDartEntrypoint(std::move(entrypoint)); + builder.SetRenderTargetType( + EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer2, + pixfmt); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + context.GetCompositor().SetNextPresentCallback( + [&context, &matches, &bytes, &latch](FlutterViewId view_id, + const FlutterLayer** layers, + size_t layers_count) { + ASSERT_EQ(layers[0]->type, kFlutterLayerContentTypeBackingStore); + ASSERT_EQ(layers[0]->backing_store->type, + kFlutterBackingStoreTypeSoftware2); + sk_sp surface = + context.GetCompositor().GetSurface(layers[0]->backing_store); + matches = SurfacePixelDataMatchesBytes(surface.get(), bytes); + latch.Signal(); + }); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 1; + event.height = 1; + event.pixel_ratio = 1.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + + latch.Wait(); + ASSERT_TRUE(matches); + + engine.reset(); +} + +template +static void expectSoftwareRenderingOutputMatches( + EmbedderTest& test, + std::string entrypoint, + FlutterSoftwarePixelFormat pixfmt, + T pixelvalue) { + uint8_t* bytes = reinterpret_cast(&pixelvalue); + return expectSoftwareRenderingOutputMatches( + test, std::move(entrypoint), pixfmt, + std::vector(bytes, bytes + sizeof(T))); +} + +#define SW_PIXFMT_TEST_F(test_name, dart_entrypoint, pixfmt, matcher) \ + TEST_F(EmbedderTest, SoftwareRenderingPixelFormats##test_name) { \ + expectSoftwareRenderingOutputMatches(*this, #dart_entrypoint, pixfmt, \ + matcher); \ + } + +// Don't test the pixel formats that contain padding (so an X) and the +// kFlutterSoftwarePixelFormatNative32 pixel format here, so we don't add any +// flakiness. +SW_PIXFMT_TEST_F(RedRGBA565xF800, + draw_solid_red, + kFlutterSoftwarePixelFormatRGB565, + (uint16_t)0xF800); +SW_PIXFMT_TEST_F(RedRGBA4444xF00F, + draw_solid_red, + kFlutterSoftwarePixelFormatRGBA4444, + (uint16_t)0xF00F); +SW_PIXFMT_TEST_F(RedRGBA8888xFFx00x00xFF, + draw_solid_red, + kFlutterSoftwarePixelFormatRGBA8888, + (std::vector{0xFF, 0x00, 0x00, 0xFF})); +SW_PIXFMT_TEST_F(RedBGRA8888x00x00xFFxFF, + draw_solid_red, + kFlutterSoftwarePixelFormatBGRA8888, + (std::vector{0x00, 0x00, 0xFF, 0xFF})); +SW_PIXFMT_TEST_F(RedGray8x36, + draw_solid_red, + kFlutterSoftwarePixelFormatGray8, + (uint8_t)0x36); + +SW_PIXFMT_TEST_F(GreenRGB565x07E0, + draw_solid_green, + kFlutterSoftwarePixelFormatRGB565, + (uint16_t)0x07E0); +SW_PIXFMT_TEST_F(GreenRGBA4444x0F0F, + draw_solid_green, + kFlutterSoftwarePixelFormatRGBA4444, + (uint16_t)0x0F0F); +SW_PIXFMT_TEST_F(GreenRGBA8888x00xFFx00xFF, + draw_solid_green, + kFlutterSoftwarePixelFormatRGBA8888, + (std::vector{0x00, 0xFF, 0x00, 0xFF})); +SW_PIXFMT_TEST_F(GreenBGRA8888x00xFFx00xFF, + draw_solid_green, + kFlutterSoftwarePixelFormatBGRA8888, + (std::vector{0x00, 0xFF, 0x00, 0xFF})); +SW_PIXFMT_TEST_F(GreenGray8xB6, + draw_solid_green, + kFlutterSoftwarePixelFormatGray8, + (uint8_t)0xB6); + +SW_PIXFMT_TEST_F(BlueRGB565x001F, + draw_solid_blue, + kFlutterSoftwarePixelFormatRGB565, + (uint16_t)0x001F); +SW_PIXFMT_TEST_F(BlueRGBA4444x00FF, + draw_solid_blue, + kFlutterSoftwarePixelFormatRGBA4444, + (uint16_t)0x00FF); +SW_PIXFMT_TEST_F(BlueRGBA8888x00x00xFFxFF, + draw_solid_blue, + kFlutterSoftwarePixelFormatRGBA8888, + (std::vector{0x00, 0x00, 0xFF, 0xFF})); +SW_PIXFMT_TEST_F(BlueBGRA8888xFFx00x00xFF, + draw_solid_blue, + kFlutterSoftwarePixelFormatBGRA8888, + (std::vector{0xFF, 0x00, 0x00, 0xFF})); +SW_PIXFMT_TEST_F(BlueGray8x12, + draw_solid_blue, + kFlutterSoftwarePixelFormatGray8, + (uint8_t)0x12); + +//------------------------------------------------------------------------------ +// Key Data +//------------------------------------------------------------------------------ + +typedef struct { + std::shared_ptr latch; + bool returned; +} KeyEventUserData; + +// Convert `kind` in integer form to its enum form. +// +// It performs a revesed mapping from `_serializeKeyEventType` +// in shell/platform/embedder/fixtures/main.dart. +FlutterKeyEventType UnserializeKeyEventType(uint64_t kind) { + switch (kind) { + case 1: + return kFlutterKeyEventTypeUp; + case 2: + return kFlutterKeyEventTypeDown; + case 3: + return kFlutterKeyEventTypeRepeat; + default: + FML_UNREACHABLE(); + return kFlutterKeyEventTypeUp; + } +} + +// Convert `source` in integer form to its enum form. +// +// It performs a revesed mapping from `_serializeKeyEventDeviceType` +// in shell/platform/embedder/fixtures/main.dart. +FlutterKeyEventDeviceType UnserializeKeyEventDeviceType(uint64_t source) { + switch (source) { + case 1: + return kFlutterKeyEventDeviceTypeKeyboard; + case 2: + return kFlutterKeyEventDeviceTypeDirectionalPad; + case 3: + return kFlutterKeyEventDeviceTypeGamepad; + case 4: + return kFlutterKeyEventDeviceTypeJoystick; + case 5: + return kFlutterKeyEventDeviceTypeHdmi; + default: + FML_UNREACHABLE(); + return kFlutterKeyEventDeviceTypeKeyboard; + } +} + +// Checks the equality of two `FlutterKeyEvent` by each of their members except +// for `character`. The `character` must be checked separately. +void ExpectKeyEventEq(const FlutterKeyEvent& subject, + const FlutterKeyEvent& baseline) { + EXPECT_EQ(subject.timestamp, baseline.timestamp); + EXPECT_EQ(subject.type, baseline.type); + EXPECT_EQ(subject.physical, baseline.physical); + EXPECT_EQ(subject.logical, baseline.logical); + EXPECT_EQ(subject.synthesized, baseline.synthesized); + EXPECT_EQ(subject.device_type, baseline.device_type); +} + +TEST_F(EmbedderTest, KeyDataIsCorrectlySerialized) { + auto message_latch = std::make_shared(); + uint64_t echoed_char; + FlutterKeyEvent echoed_event; + echoed_event.struct_size = sizeof(FlutterKeyEvent); + + auto native_echo_event = [&](Dart_NativeArguments args) { + echoed_event.type = + UnserializeKeyEventType(tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0))); + echoed_event.timestamp = + static_cast(tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 1))); + echoed_event.physical = tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 2)); + echoed_event.logical = tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 3)); + echoed_char = tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 4)); + echoed_event.synthesized = + tonic::DartConverter::FromDart(Dart_GetNativeArgument(args, 5)); + echoed_event.device_type = + UnserializeKeyEventDeviceType(tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 6))); + + message_latch->Signal(); + }; + + auto platform_task_runner = CreateNewThread("platform_thread"); + + UniqueEngine engine; + fml::AutoResetWaitableEvent ready; + platform_task_runner->PostTask([&]() { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("key_data_echo"); + builder.SetPlatformMessageCallback( + [&](const FlutterPlatformMessage* message) { + FlutterEngineSendPlatformMessageResponse( + engine.get(), message->response_handle, nullptr, 0); + }); + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&ready](Dart_NativeArguments args) { ready.Signal(); })); + + context.AddNativeCallback("EchoKeyEvent", + CREATE_NATIVE_ENTRY(native_echo_event)); + + engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + }); + + ready.Wait(); + + // A normal down event + const FlutterKeyEvent down_event_upper_a{ + .struct_size = sizeof(FlutterKeyEvent), + .timestamp = 1, + .type = kFlutterKeyEventTypeDown, + .physical = 0x00070004, + .logical = 0x00000000061, + .character = "A", + .synthesized = false, + .device_type = kFlutterKeyEventDeviceTypeKeyboard, + }; + platform_task_runner->PostTask([&]() { + FlutterEngineSendKeyEvent(engine.get(), &down_event_upper_a, nullptr, + nullptr); + }); + message_latch->Wait(); + + ExpectKeyEventEq(echoed_event, down_event_upper_a); + EXPECT_EQ(echoed_char, 0x41llu); + + // A repeat event with multi-byte character + const FlutterKeyEvent repeat_event_wide_char{ + .struct_size = sizeof(FlutterKeyEvent), + .timestamp = 1000, + .type = kFlutterKeyEventTypeRepeat, + .physical = 0x00070005, + .logical = 0x00000000062, + .character = "∆", + .synthesized = false, + .device_type = kFlutterKeyEventDeviceTypeKeyboard, + }; + platform_task_runner->PostTask([&]() { + FlutterEngineSendKeyEvent(engine.get(), &repeat_event_wide_char, nullptr, + nullptr); + }); + message_latch->Wait(); + + ExpectKeyEventEq(echoed_event, repeat_event_wide_char); + EXPECT_EQ(echoed_char, 0x2206llu); + + // An up event with no character, synthesized + const FlutterKeyEvent up_event{ + .struct_size = sizeof(FlutterKeyEvent), + .timestamp = 1000000, + .type = kFlutterKeyEventTypeUp, + .physical = 0x00070006, + .logical = 0x00000000063, + .character = nullptr, + .synthesized = true, + .device_type = kFlutterKeyEventDeviceTypeKeyboard, + }; + platform_task_runner->PostTask([&]() { + FlutterEngineSendKeyEvent(engine.get(), &up_event, nullptr, nullptr); + }); + message_latch->Wait(); + + ExpectKeyEventEq(echoed_event, up_event); + EXPECT_EQ(echoed_char, 0llu); + + fml::AutoResetWaitableEvent shutdown_latch; + platform_task_runner->PostTask([&]() { + engine.reset(); + shutdown_latch.Signal(); + }); + shutdown_latch.Wait(); +} + +TEST_F(EmbedderTest, KeyDataAreBuffered) { + auto message_latch = std::make_shared(); + std::vector echoed_events; + + auto native_echo_event = [&](Dart_NativeArguments args) { + echoed_events.push_back(FlutterKeyEvent{ + .timestamp = + static_cast(tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 1))), + .type = + UnserializeKeyEventType(tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0))), + .physical = tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 2)), + .logical = tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 3)), + .synthesized = tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 5)), + .device_type = UnserializeKeyEventDeviceType( + tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 6))), + }); + + message_latch->Signal(); + }; + + auto platform_task_runner = CreateNewThread("platform_thread"); + + UniqueEngine engine; + fml::AutoResetWaitableEvent ready; + platform_task_runner->PostTask([&]() { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("key_data_late_echo"); + builder.SetPlatformMessageCallback( + [&](const FlutterPlatformMessage* message) { + FlutterEngineSendPlatformMessageResponse( + engine.get(), message->response_handle, nullptr, 0); + }); + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&ready](Dart_NativeArguments args) { ready.Signal(); })); + + context.AddNativeCallback("EchoKeyEvent", + CREATE_NATIVE_ENTRY(native_echo_event)); + + engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + }); + ready.Wait(); + + FlutterKeyEvent sample_event{ + .struct_size = sizeof(FlutterKeyEvent), + .type = kFlutterKeyEventTypeDown, + .physical = 0x00070004, + .logical = 0x00000000061, + .character = "A", + .synthesized = false, + .device_type = kFlutterKeyEventDeviceTypeKeyboard, + }; + + // Send an event. + sample_event.timestamp = 1.0l; + platform_task_runner->PostTask([&]() { + FlutterEngineSendKeyEvent(engine.get(), &sample_event, nullptr, nullptr); + message_latch->Signal(); + }); + message_latch->Wait(); + + // Should not receive echos because the callback is not set yet. + EXPECT_EQ(echoed_events.size(), 0u); + + // Send an empty message to 'test/starts_echo' to start echoing. + FlutterPlatformMessageResponseHandle* response_handle = nullptr; + FlutterPlatformMessageCreateResponseHandle( + engine.get(), [](const uint8_t* data, size_t size, void* user_data) {}, + nullptr, &response_handle); + + FlutterPlatformMessage message{ + .struct_size = sizeof(FlutterPlatformMessage), + .channel = "test/starts_echo", + .message = nullptr, + .message_size = 0, + .response_handle = response_handle, + }; + + platform_task_runner->PostTask([&]() { + FlutterEngineResult result = + FlutterEngineSendPlatformMessage(engine.get(), &message); + ASSERT_EQ(result, kSuccess); + + FlutterPlatformMessageReleaseResponseHandle(engine.get(), response_handle); + }); + + // message_latch->Wait(); + message_latch->Wait(); + // All previous events should be received now. + EXPECT_EQ(echoed_events.size(), 1u); + + // Send a second event. + sample_event.timestamp = 10.0l; + platform_task_runner->PostTask([&]() { + FlutterEngineSendKeyEvent(engine.get(), &sample_event, nullptr, nullptr); + }); + message_latch->Wait(); + + // The event should be echoed, too. + EXPECT_EQ(echoed_events.size(), 2u); + + fml::AutoResetWaitableEvent shutdown_latch; + platform_task_runner->PostTask([&]() { + engine.reset(); + shutdown_latch.Signal(); + }); + shutdown_latch.Wait(); +} + +TEST_F(EmbedderTest, KeyDataResponseIsCorrectlyInvoked) { + UniqueEngine engine; + fml::AutoResetWaitableEvent sync_latch; + fml::AutoResetWaitableEvent ready; + + // One of the threads that the key data callback will be posted to is the + // platform thread. So we cannot wait for assertions to complete on the + // platform thread. Create a new thread to manage the engine instance and wait + // for assertions on the test thread. + auto platform_task_runner = CreateNewThread("platform_thread"); + + platform_task_runner->PostTask([&]() { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("key_data_echo"); + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&ready](Dart_NativeArguments args) { ready.Signal(); })); + context.AddNativeCallback( + "EchoKeyEvent", CREATE_NATIVE_ENTRY([](Dart_NativeArguments args) {})); + + engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + sync_latch.Signal(); + }); + sync_latch.Wait(); + ready.Wait(); + + // Dispatch a single event + FlutterKeyEvent event{ + .struct_size = sizeof(FlutterKeyEvent), + .timestamp = 1000, + .type = kFlutterKeyEventTypeDown, + .physical = 0x00070005, + .logical = 0x00000000062, + .character = nullptr, + .device_type = kFlutterKeyEventDeviceTypeKeyboard, + }; + + KeyEventUserData user_data1{ + .latch = std::make_shared(), + }; + // Entrypoint `key_data_echo` returns `event.synthesized` as `handled`. + event.synthesized = true; + platform_task_runner->PostTask([&]() { + // Test when the response callback is empty. + // It should not cause a crash. + FlutterEngineSendKeyEvent(engine.get(), &event, nullptr, nullptr); + + // Test when the response callback is non-empty. + // It should be invoked (so that the latch can be unlocked.) + FlutterEngineSendKeyEvent( + engine.get(), &event, + [](bool handled, void* untyped_user_data) { + KeyEventUserData* user_data = + reinterpret_cast(untyped_user_data); + EXPECT_EQ(handled, true); + user_data->latch->Signal(); + }, + &user_data1); + }); + user_data1.latch->Wait(); + fml::AutoResetWaitableEvent shutdown_latch; + platform_task_runner->PostTask([&]() { + engine.reset(); + shutdown_latch.Signal(); + }); + shutdown_latch.Wait(); +} + +TEST_F(EmbedderTest, BackToBackKeyEventResponsesCorrectlyInvoked) { + UniqueEngine engine; + fml::AutoResetWaitableEvent sync_latch; + fml::AutoResetWaitableEvent ready; + + // One of the threads that the callback will be posted to is the platform + // thread. So we cannot wait for assertions to complete on the platform + // thread. Create a new thread to manage the engine instance and wait for + // assertions on the test thread. + auto platform_task_runner = CreateNewThread("platform_thread"); + + platform_task_runner->PostTask([&]() { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("key_data_echo"); + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&ready](Dart_NativeArguments args) { ready.Signal(); })); + + context.AddNativeCallback( + "EchoKeyEvent", CREATE_NATIVE_ENTRY([](Dart_NativeArguments args) {})); + + engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + sync_latch.Signal(); + }); + sync_latch.Wait(); + ready.Wait(); + + // Dispatch a single event + FlutterKeyEvent event{ + .struct_size = sizeof(FlutterKeyEvent), + .timestamp = 1000, + .type = kFlutterKeyEventTypeDown, + .physical = 0x00070005, + .logical = 0x00000000062, + .character = nullptr, + .synthesized = false, + .device_type = kFlutterKeyEventDeviceTypeKeyboard, + }; + + // Dispatch two events back to back, using the same callback on different + // user_data + KeyEventUserData user_data2{ + .latch = std::make_shared(), + .returned = false, + }; + KeyEventUserData user_data3{ + .latch = std::make_shared(), + .returned = false, + }; + auto callback23 = [](bool handled, void* untyped_user_data) { + KeyEventUserData* user_data = + reinterpret_cast(untyped_user_data); + EXPECT_EQ(handled, false); + user_data->returned = true; + user_data->latch->Signal(); + }; + platform_task_runner->PostTask([&]() { + FlutterEngineSendKeyEvent(engine.get(), &event, callback23, &user_data2); + FlutterEngineSendKeyEvent(engine.get(), &event, callback23, &user_data3); + }); + user_data2.latch->Wait(); + user_data3.latch->Wait(); + + EXPECT_TRUE(user_data2.returned); + EXPECT_TRUE(user_data3.returned); + + fml::AutoResetWaitableEvent shutdown_latch; + platform_task_runner->PostTask([&]() { + engine.reset(); + shutdown_latch.Signal(); + }); + shutdown_latch.Wait(); +} + +//------------------------------------------------------------------------------ +// Vsync waiter +//------------------------------------------------------------------------------ + +// This test schedules a frame for the future and asserts that vsync waiter +// posts the event at the right frame start time (which is in the future). +TEST_F(EmbedderTest, VsyncCallbackPostedIntoFuture) { + UniqueEngine engine; + fml::AutoResetWaitableEvent present_latch; + fml::AutoResetWaitableEvent vsync_latch; + + // One of the threads that the callback (FlutterEngineOnVsync) will be posted + // to is the platform thread. So we cannot wait for assertions to complete on + // the platform thread. Create a new thread to manage the engine instance and + // wait for assertions on the test thread. + auto platform_task_runner = CreateNewThread("platform_thread"); + + platform_task_runner->PostTask([&]() { + auto& context = GetEmbedderContext(); + context.SetVsyncCallback([&](intptr_t baton) { + platform_task_runner->PostTask([baton = baton, &engine, &vsync_latch]() { + FlutterEngineOnVsync(engine.get(), baton, NanosFromEpoch(16), + NanosFromEpoch(32)); + vsync_latch.Signal(); + }); + }); + context.AddNativeCallback( + "SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + present_latch.Signal(); + })); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetupVsyncCallback(); + builder.SetDartEntrypoint("empty_scene"); + engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + }); + + vsync_latch.Wait(); + present_latch.Wait(); + + fml::AutoResetWaitableEvent shutdown_latch; + platform_task_runner->PostTask([&]() { + engine.reset(); + shutdown_latch.Signal(); + }); + shutdown_latch.Wait(); +} + +TEST_F(EmbedderTest, CanScheduleFrame) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("can_schedule_frame"); + fml::AutoResetWaitableEvent latch; + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&latch](Dart_NativeArguments args) { latch.Signal(); })); + + fml::AutoResetWaitableEvent check_latch; + context.AddNativeCallback( + "SignalNativeCount", + CREATE_NATIVE_ENTRY( + [&check_latch](Dart_NativeArguments args) { check_latch.Signal(); })); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // Wait for the application to attach the listener. + latch.Wait(); + + ASSERT_EQ(FlutterEngineScheduleFrame(engine.get()), kSuccess); + + check_latch.Wait(); +} + +TEST_F(EmbedderTest, CanSetNextFrameCallback) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("draw_solid_red"); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + // Register the callback that is executed once the next frame is drawn. + fml::AutoResetWaitableEvent callback_latch; + VoidCallback callback = [](void* user_data) { + fml::AutoResetWaitableEvent* callback_latch = + static_cast(user_data); + + callback_latch->Signal(); + }; + + auto result = FlutterEngineSetNextFrameCallback(engine.get(), callback, + &callback_latch); + ASSERT_EQ(result, kSuccess); + + // Send a window metrics events so frames may be scheduled. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(event); + event.width = 800; + event.height = 600; + event.pixel_ratio = 1.0; + event.physical_view_inset_top = 0.0; + event.physical_view_inset_right = 0.0; + event.physical_view_inset_bottom = 0.0; + event.physical_view_inset_left = 0.0; + ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), + kSuccess); + + callback_latch.Wait(); +} + +#if defined(FML_OS_MACOSX) + +static void MockThreadConfigSetter(const fml::Thread::ThreadConfig& config) { + pthread_t tid = pthread_self(); + struct sched_param param; + int policy = SCHED_OTHER; + switch (config.priority) { + case fml::Thread::ThreadPriority::kDisplay: + param.sched_priority = 10; + break; + default: + param.sched_priority = 1; + } + pthread_setschedparam(tid, policy, ¶m); +} + +TEST_F(EmbedderTest, EmbedderThreadHostUseCustomThreadConfig) { + auto thread_host = + flutter::EmbedderThreadHost::CreateEmbedderOrEngineManagedThreadHost( + nullptr, MockThreadConfigSetter); + + fml::AutoResetWaitableEvent ui_latch; + int ui_policy; + struct sched_param ui_param; + + thread_host->GetTaskRunners().GetUITaskRunner()->PostTask([&] { + pthread_t current_thread = pthread_self(); + pthread_getschedparam(current_thread, &ui_policy, &ui_param); + ASSERT_EQ(ui_param.sched_priority, 10); + ui_latch.Signal(); + }); + + fml::AutoResetWaitableEvent io_latch; + int io_policy; + struct sched_param io_param; + thread_host->GetTaskRunners().GetIOTaskRunner()->PostTask([&] { + pthread_t current_thread = pthread_self(); + pthread_getschedparam(current_thread, &io_policy, &io_param); + ASSERT_EQ(io_param.sched_priority, 1); + io_latch.Signal(); + }); + + ui_latch.Wait(); + io_latch.Wait(); +} +#endif + +/// Send a pointer event to Dart and wait until the Dart code signals +/// it received the event. +TEST_F(EmbedderTest, CanSendPointer) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("pointer_data_packet"); + + fml::AutoResetWaitableEvent ready_latch, count_latch, message_latch; + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&ready_latch](Dart_NativeArguments args) { ready_latch.Signal(); })); + context.AddNativeCallback( + "SignalNativeCount", + CREATE_NATIVE_ENTRY([&count_latch](Dart_NativeArguments args) { + int count = tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + ASSERT_EQ(count, 1); + count_latch.Signal(); + })); + context.AddNativeCallback( + "SignalNativeMessage", + CREATE_NATIVE_ENTRY([&message_latch](Dart_NativeArguments args) { + auto message = tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + ASSERT_EQ("PointerData(viewId: 0, x: 123.0, y: 456.0)", message); + message_latch.Signal(); + })); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + ready_latch.Wait(); + + FlutterPointerEvent pointer_event = {}; + pointer_event.struct_size = sizeof(FlutterPointerEvent); + pointer_event.phase = FlutterPointerPhase::kAdd; + pointer_event.x = 123; + pointer_event.y = 456; + pointer_event.timestamp = static_cast(1234567890); + pointer_event.view_id = 0; + + FlutterEngineResult result = + FlutterEngineSendPointerEvent(engine.get(), &pointer_event, 1); + ASSERT_EQ(result, kSuccess); + + count_latch.Wait(); + message_latch.Wait(); +} + +/// Send a pointer event to Dart and wait until the Dart code echos with the +/// view ID. +TEST_F(EmbedderTest, CanSendPointerEventWithViewId) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("pointer_data_packet_view_id"); + + fml::AutoResetWaitableEvent ready_latch, add_view_latch, message_latch; + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&ready_latch](Dart_NativeArguments args) { ready_latch.Signal(); })); + context.AddNativeCallback( + "SignalNativeMessage", + CREATE_NATIVE_ENTRY([&message_latch](Dart_NativeArguments args) { + auto message = tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + ASSERT_EQ("ViewID: 2", message); + message_latch.Signal(); + })); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + ready_latch.Wait(); + + // Add view 2 + FlutterWindowMetricsEvent metrics = {}; + metrics.struct_size = sizeof(FlutterWindowMetricsEvent); + metrics.width = 800; + metrics.height = 600; + metrics.pixel_ratio = 1.0; + metrics.view_id = 2; + + FlutterAddViewInfo info = {}; + info.struct_size = sizeof(FlutterAddViewInfo); + info.view_id = 2; + info.view_metrics = &metrics; + info.add_view_callback = [](const FlutterAddViewResult* result) { + EXPECT_TRUE(result->added); + fml::AutoResetWaitableEvent* add_view_latch = + reinterpret_cast(result->user_data); + add_view_latch->Signal(); + }; + info.user_data = &add_view_latch; + ASSERT_EQ(FlutterEngineAddView(engine.get(), &info), kSuccess); + add_view_latch.Wait(); + + // Send a pointer event for view 2 + FlutterPointerEvent pointer_event = {}; + pointer_event.struct_size = sizeof(FlutterPointerEvent); + pointer_event.phase = FlutterPointerPhase::kAdd; + pointer_event.x = 123; + pointer_event.y = 456; + pointer_event.timestamp = static_cast(1234567890); + pointer_event.view_id = 2; + + FlutterEngineResult result = + FlutterEngineSendPointerEvent(engine.get(), &pointer_event, 1); + ASSERT_EQ(result, kSuccess); + + message_latch.Wait(); +} + +TEST_F(EmbedderTest, WindowMetricsEventDefaultsToImplicitView) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("window_metrics_event_view_id"); + + fml::AutoResetWaitableEvent ready_latch, message_latch; + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&ready_latch](Dart_NativeArguments args) { ready_latch.Signal(); })); + context.AddNativeCallback( + "SignalNativeMessage", + CREATE_NATIVE_ENTRY([&message_latch](Dart_NativeArguments args) { + auto message = tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + ASSERT_EQ("Changed: [0]", message); + message_latch.Signal(); + })); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + ready_latch.Wait(); + + FlutterWindowMetricsEvent event = {}; + // Simulate an event that comes from an old version of embedder.h that doesn't + // have the view_id field. + event.struct_size = offsetof(FlutterWindowMetricsEvent, view_id); + event.width = 200; + event.height = 300; + event.pixel_ratio = 1.5; + // Skip assigning event.view_id here to test the default behavior. + + FlutterEngineResult result = + FlutterEngineSendWindowMetricsEvent(engine.get(), &event); + ASSERT_EQ(result, kSuccess); + + message_latch.Wait(); +} + +TEST_F(EmbedderTest, IgnoresWindowMetricsEventForUnknownView) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("window_metrics_event_view_id"); + + fml::AutoResetWaitableEvent ready_latch, message_latch; + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&ready_latch](Dart_NativeArguments args) { ready_latch.Signal(); })); + + context.AddNativeCallback( + "SignalNativeMessage", + CREATE_NATIVE_ENTRY([&message_latch](Dart_NativeArguments args) { + auto message = tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + // Message latch should only be signaled once as the bad + // view metric should be dropped by the engine. + ASSERT_FALSE(message_latch.IsSignaledForTest()); + ASSERT_EQ("Changed: [0]", message); + message_latch.Signal(); + })); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + ready_latch.Wait(); + + // Send a window metric for a nonexistent view, which should be dropped by the + // engine. + FlutterWindowMetricsEvent bad_event = {}; + bad_event.struct_size = sizeof(FlutterWindowMetricsEvent); + bad_event.width = 200; + bad_event.height = 300; + bad_event.pixel_ratio = 1.5; + bad_event.view_id = 100; + + FlutterEngineResult result = + FlutterEngineSendWindowMetricsEvent(engine.get(), &bad_event); + ASSERT_EQ(result, kSuccess); + + // Send a window metric for a valid view. The engine notifies the Dart app. + FlutterWindowMetricsEvent event = {}; + event.struct_size = sizeof(FlutterWindowMetricsEvent); + event.width = 200; + event.height = 300; + event.pixel_ratio = 1.5; + event.view_id = 0; + + result = FlutterEngineSendWindowMetricsEvent(engine.get(), &event); + ASSERT_EQ(result, kSuccess); + + message_latch.Wait(); +} + +TEST_F(EmbedderTest, RegisterChannelListener) { + auto& context = GetEmbedderContext(); + + fml::AutoResetWaitableEvent latch; + fml::AutoResetWaitableEvent latch2; + bool listening = false; + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments) { latch.Signal(); })); + context.SetChannelUpdateCallback([&](const FlutterChannelUpdate* update) { + EXPECT_STREQ(update->channel, "test/listen"); + EXPECT_TRUE(update->listening); + listening = true; + latch2.Signal(); + }); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetDartEntrypoint("channel_listener_response"); + + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + latch.Wait(); + // Drain tasks posted to platform thread task runner. + fml::MessageLoop::GetCurrent().RunExpiredTasksNow(); + latch2.Wait(); + + ASSERT_TRUE(listening); +} + +TEST_F(EmbedderTest, PlatformThreadIsolatesWithCustomPlatformTaskRunner) { + auto& context = GetEmbedderContext(); + static fml::AutoResetWaitableEvent latch; + + static std::thread::id ffi_call_thread_id; + static void (*ffi_signal_native_test)() = []() -> void { + ffi_call_thread_id = std::this_thread::get_id(); + latch.Signal(); + }; + + Dart_FfiNativeResolver ffi_resolver = [](const char* name, + uintptr_t args_n) -> void* { + if (std::string_view(name) == "FFISignalNativeTest") { + return reinterpret_cast(ffi_signal_native_test); + } + return nullptr; + }; + + // The test's Dart code will call this native function which overrides the + // FFI resolver. After that, the Dart code will invoke the FFI function + // using runOnPlatformThread. + context.AddNativeCallback( + "SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + Dart_SetFfiNativeResolver(Dart_RootLibrary(), ffi_resolver); + })); + + auto platform_task_runner = CreateNewThread("test_platform_thread"); + + UniqueEngine engine; + + EmbedderTestTaskRunner test_task_runner( + platform_task_runner, [&](FlutterTask task) { + if (!engine.is_valid()) { + return; + } + FlutterEngineRunTask(engine.get(), &task); + }); + + std::thread::id platform_thread_id; + platform_task_runner->PostTask([&]() { + platform_thread_id = std::this_thread::get_id(); + + EmbedderConfigBuilder builder(context); + const auto task_runner_description = + test_task_runner.GetFlutterTaskRunnerDescription(); + builder.SetSurface(SkISize::Make(1, 1)); + builder.SetPlatformTaskRunner(&task_runner_description); + builder.SetDartEntrypoint("invokePlatformThreadIsolate"); + builder.AddCommandLineArgument("--enable-platform-isolates"); + engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + }); + + latch.Wait(); + + fml::AutoResetWaitableEvent kill_latch; + platform_task_runner->PostTask(fml::MakeCopyable([&]() mutable { + engine.reset(); + + platform_task_runner->PostTask([&kill_latch] { kill_latch.Signal(); }); + })); + kill_latch.Wait(); + + // Check that the FFI call was executed on the platform thread. + ASSERT_EQ(platform_thread_id, ffi_call_thread_id); +} + +} // namespace testing +} // namespace flutter + +// NOLINTEND(clang-analyzer-core.StackAddressEscape) diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_unittests_proctable.cc b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_unittests_proctable.cc new file mode 100644 index 0000000000000000000000000000000000000000..dd1462c8f3d26a4a969d6c9715cac45aeca46b13 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_unittests_proctable.cc @@ -0,0 +1,62 @@ +// 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/shell/platform/embedder/embedder.h" + +#include + +#include "flutter/testing/testing.h" + +#ifdef _WIN32 +// winbase.h defines GetCurrentTime as a macro. +#undef GetCurrentTime +#endif + +namespace flutter { +namespace testing { + +// Verifies that the proc table is fully populated. +TEST(EmbedderProcTable, AllPointersProvided) { + FlutterEngineProcTable procs = {}; + procs.struct_size = sizeof(FlutterEngineProcTable); + ASSERT_EQ(FlutterEngineGetProcAddresses(&procs), kSuccess); + + void (**proc)() = reinterpret_cast(&procs.CreateAOTData); + const uintptr_t end_address = + reinterpret_cast(&procs) + procs.struct_size; + while (reinterpret_cast(proc) < end_address) { + EXPECT_NE(*proc, nullptr); + ++proc; + } +} + +// Ensures that there are no duplicate pointers in the proc table, to catch +// copy/paste mistakes when adding a new entry to FlutterEngineGetProcAddresses. +TEST(EmbedderProcTable, NoDuplicatePointers) { + FlutterEngineProcTable procs = {}; + procs.struct_size = sizeof(FlutterEngineProcTable); + ASSERT_EQ(FlutterEngineGetProcAddresses(&procs), kSuccess); + + void (**proc)() = reinterpret_cast(&procs.CreateAOTData); + const uintptr_t end_address = + reinterpret_cast(&procs) + procs.struct_size; + std::set seen_procs; + while (reinterpret_cast(proc) < end_address) { + auto result = seen_procs.insert(*proc); + EXPECT_TRUE(result.second); + ++proc; + } +} + +// Spot-checks that calling one of the function pointers works. +TEST(EmbedderProcTable, CallProc) { + FlutterEngineProcTable procs = {}; + procs.struct_size = sizeof(FlutterEngineProcTable); + ASSERT_EQ(FlutterEngineGetProcAddresses(&procs), kSuccess); + + EXPECT_NE(procs.GetCurrentTime(), 0ULL); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_unittests_util.cc b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_unittests_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..a29bf166a3ae54a9b3b4a9b4f17165671beecd8c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_unittests_util.cc @@ -0,0 +1,311 @@ +// 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. + +#define FML_USED_ON_EMBEDDER + +#include +#include + +#include "flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer.h" +#include "flutter/shell/platform/embedder/tests/embedder_unittests_util.h" + +#include "third_party/skia/include/core/SkImage.h" +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/include/encode/SkPngEncoder.h" +#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" + +namespace flutter { +namespace testing { + +sk_sp CreateRenderSurface(const FlutterLayer& layer, + GrDirectContext* context) { + const auto image_info = + SkImageInfo::MakeN32Premul(layer.size.width, layer.size.height); + auto surface = context ? SkSurfaces::RenderTarget( + context, // context + skgpu::Budgeted::kNo, // budgeted + image_info, // image info + 1, // sample count + kTopLeft_GrSurfaceOrigin, // surface origin + nullptr, // surface properties + false // mipmaps + + ) + : SkSurfaces::Raster(image_info); + FML_CHECK(surface != nullptr); + return surface; +} + +// Normalizes the color-space, color-type and alpha-type for comparison. +static sk_sp NormalizeImage(const sk_sp& image) { + // To avoid clipping, convert to a very wide gamut, and a high bit depth. + sk_sp norm_colorspace = SkColorSpace::MakeRGB( + SkNamedTransferFn::kRec2020, SkNamedGamut::kRec2020); + SkImageInfo norm_image_info = + SkImageInfo::Make(image->width(), image->height(), + SkColorType::kR16G16B16A16_unorm_SkColorType, + SkAlphaType::kUnpremul_SkAlphaType, norm_colorspace); + size_t row_bytes = norm_image_info.minRowBytes(); + size_t size = norm_image_info.computeByteSize(row_bytes); + sk_sp data = SkData::MakeUninitialized(size); + if (!data) { + FML_CHECK(false) << "Unable to allocate data."; + } + + bool success = image->readPixels(norm_image_info, data->writable_data(), + row_bytes, 0, 0); + if (!success) { + FML_CHECK(false) << "Unable to read pixels."; + } + + return data; +} + +bool RasterImagesAreSame(const sk_sp& a, const sk_sp& b) { + if (!a || !b) { + return false; + } + + FML_CHECK(!a->isTextureBacked()); + FML_CHECK(!b->isTextureBacked()); + + sk_sp normalized_a = NormalizeImage(a); + sk_sp normalized_b = NormalizeImage(b); + + return normalized_a->equals(normalized_b.get()); +} + +std::string FixtureNameForBackend(EmbedderTestContextType backend, + const std::string& name) { + switch (backend) { + case EmbedderTestContextType::kVulkanContext: + return "vk_" + name; + default: + return name; + } +} + +EmbedderTestBackingStoreProducer::RenderTargetType GetRenderTargetFromBackend( + EmbedderTestContextType backend, + bool opengl_framebuffer) { + switch (backend) { + case EmbedderTestContextType::kVulkanContext: + return EmbedderTestBackingStoreProducer::RenderTargetType::kVulkanImage; + case EmbedderTestContextType::kOpenGLContext: + if (opengl_framebuffer) { + return EmbedderTestBackingStoreProducer::RenderTargetType:: + kOpenGLFramebuffer; + } + return EmbedderTestBackingStoreProducer::RenderTargetType::kOpenGLTexture; + case EmbedderTestContextType::kMetalContext: + return EmbedderTestBackingStoreProducer::RenderTargetType::kMetalTexture; + case EmbedderTestContextType::kSoftwareContext: + return EmbedderTestBackingStoreProducer::RenderTargetType:: + kSoftwareBuffer; + } +} + +void ConfigureBackingStore(FlutterBackingStore& backing_store, + EmbedderTestContextType backend, + bool opengl_framebuffer) { + switch (backend) { + case EmbedderTestContextType::kVulkanContext: + backing_store.type = kFlutterBackingStoreTypeVulkan; + break; + case EmbedderTestContextType::kOpenGLContext: + if (opengl_framebuffer) { + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; + } else { + backing_store.type = kFlutterBackingStoreTypeOpenGL; + backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; + } + break; + case EmbedderTestContextType::kMetalContext: + backing_store.type = kFlutterBackingStoreTypeMetal; + break; + case EmbedderTestContextType::kSoftwareContext: + backing_store.type = kFlutterBackingStoreTypeSoftware; + break; + } +} + +bool WriteImageToDisk(const fml::UniqueFD& directory, + const std::string& name, + const sk_sp& image) { + if (!image) { + return false; + } + + auto data = SkPngEncoder::Encode(nullptr, image.get(), {}); + + if (!data) { + return false; + } + + fml::NonOwnedMapping mapping(static_cast(data->data()), + data->size()); + return WriteAtomically(directory, name.c_str(), mapping); +} + +bool ImageMatchesFixture(const std::string& fixture_file_name, + const sk_sp& scene_image) { + fml::FileMapping fixture_image_mapping(OpenFixture(fixture_file_name)); + + FML_CHECK(fixture_image_mapping.GetSize() != 0u) + << "Could not find fixture: " << fixture_file_name; + + auto encoded_image = SkData::MakeWithoutCopy( + fixture_image_mapping.GetMapping(), fixture_image_mapping.GetSize()); + auto fixture_image = + SkImages::DeferredFromEncodedData(std::move(encoded_image)) + ->makeRasterImage(); + + FML_CHECK(fixture_image) << "Could not create image from fixture: " + << fixture_file_name; + + FML_CHECK(scene_image) << "Invalid scene image."; + + auto scene_image_subset = scene_image->makeSubset( + nullptr, + SkIRect::MakeWH(fixture_image->width(), fixture_image->height())); + + FML_CHECK(scene_image_subset) + << "Could not create image subset for fixture comparison: " + << scene_image_subset; + + const auto images_are_same = + RasterImagesAreSame(scene_image_subset, fixture_image); + + // If the images are not the same, this predicate is going to indicate test + // failure. Dump both the actual image and the expectation to disk to the + // test author can figure out what went wrong. + if (!images_are_same) { + const auto fixtures_path = GetFixturesPath(); + + const auto actual_file_name = "actual_" + fixture_file_name; + const auto expect_file_name = "expectation_" + fixture_file_name; + + auto fixtures_fd = OpenFixturesDirectory(); + + FML_CHECK( + WriteImageToDisk(fixtures_fd, actual_file_name, scene_image_subset)) + << "Could not write file to disk: " << actual_file_name; + + FML_CHECK(WriteImageToDisk(fixtures_fd, expect_file_name, fixture_image)) + << "Could not write file to disk: " << expect_file_name; + + FML_LOG(ERROR) << "Image did not match expectation." << std::endl + << "Expected:" + << fml::paths::JoinPaths({fixtures_path, expect_file_name}) + << std::endl + << "Got:" + << fml::paths::JoinPaths({fixtures_path, actual_file_name}) + << std::endl; + } + return images_are_same; +} + +bool ImageMatchesFixture(const std::string& fixture_file_name, + std::future>& scene_image) { + return ImageMatchesFixture(fixture_file_name, scene_image.get()); +} + +bool SurfacePixelDataMatchesBytes(SkSurface* surface, + const std::vector& bytes) { + SkPixmap pixmap; + auto ok = surface->peekPixels(&pixmap); + if (!ok) { + return false; + } + + auto matches = (pixmap.rowBytes() == bytes.size()) && + (memcmp(bytes.data(), pixmap.addr(), bytes.size()) == 0); + + if (!matches) { + FML_LOG(ERROR) << "SkImage pixel data didn't match bytes."; + + { + const uint8_t* addr = static_cast(pixmap.addr()); + std::stringstream stream; + for (size_t i = 0; i < pixmap.computeByteSize(); ++i) { + stream << "0x" << std::setfill('0') << std::setw(2) << std::uppercase + << std::hex << static_cast(addr[i]); + if (i != pixmap.computeByteSize() - 1) { + stream << ", "; + } + } + FML_LOG(ERROR) << " Actual: " << stream.str(); + } + { + std::stringstream stream; + for (auto b = bytes.begin(); b != bytes.end(); ++b) { + stream << "0x" << std::setfill('0') << std::setw(2) << std::uppercase + << std::hex << static_cast(*b); + if (b != bytes.end() - 1) { + stream << ", "; + } + } + FML_LOG(ERROR) << " Expected: " << stream.str(); + } + } + + return matches; +} + +bool SurfacePixelDataMatchesBytes(std::future& surface_future, + const std::vector& bytes) { + return SurfacePixelDataMatchesBytes(surface_future.get(), bytes); +} + +void FilterMutationsByType( + const FlutterPlatformViewMutation** mutations, + size_t count, + FlutterPlatformViewMutationType type, + const std::function& + handler) { + if (mutations == nullptr) { + return; + } + + for (size_t i = 0; i < count; ++i) { + const FlutterPlatformViewMutation* mutation = mutations[i]; + if (mutation->type != type) { + continue; + } + + handler(*mutation); + } +} + +void FilterMutationsByType( + const FlutterPlatformView* view, + FlutterPlatformViewMutationType type, + const std::function& + handler) { + return FilterMutationsByType(view->mutations, view->mutations_count, type, + handler); +} + +SkMatrix GetTotalMutationTransformationMatrix( + const FlutterPlatformViewMutation** mutations, + size_t count) { + SkMatrix collected; + + FilterMutationsByType( + mutations, count, kFlutterPlatformViewMutationTypeTransformation, + [&](const auto& mutation) { + collected.preConcat(SkMatrixMake(mutation.transformation)); + }); + + return collected; +} + +SkMatrix GetTotalMutationTransformationMatrix(const FlutterPlatformView* view) { + return GetTotalMutationTransformationMatrix(view->mutations, + view->mutations_count); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_unittests_util.h b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_unittests_util.h new file mode 100644 index 0000000000000000000000000000000000000000..1336b3ef34377b2d4f66ba849b62523d388cf0af --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_unittests_util.h @@ -0,0 +1,158 @@ +// 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_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_UNITTESTS_UTIL_H_ +#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_UNITTESTS_UTIL_H_ + +#define FML_USED_ON_EMBEDDER + +#include +#include + +#include "flutter/fml/mapping.h" +#include "flutter/fml/message_loop.h" +#include "flutter/fml/paths.h" +#include "flutter/shell/platform/embedder/tests/embedder_assertions.h" +#include "flutter/shell/platform/embedder/tests/embedder_config_builder.h" +#include "flutter/shell/platform/embedder/tests/embedder_test.h" +#include "third_party/skia/include/core/SkSurface.h" + +namespace flutter { +namespace testing { + +sk_sp CreateRenderSurface(const FlutterLayer& layer, + GrDirectContext* context); + +bool RasterImagesAreSame(const sk_sp& a, const sk_sp& b); + +/// @brief Prepends a prefix to the name which is unique to the test +/// context type. This is useful for tests that use +/// EmbedderTestMultiBackend and require different fixtures per +/// backend. For OpenGL, the name remains unchanged. +/// @param[in] backend The test context type used to determine the prepended +/// prefix (e.g. `vk_[name]` for Vulkan). +/// @param[in] name The name of the fixture without any special prefixes. +std::string FixtureNameForBackend(EmbedderTestContextType backend, + const std::string& name); + +/// @brief Resolves a render target type for a given backend description. +/// This is useful for tests that use EmbedderTestMultiBackend. +/// @param[in] backend The test context type to resolve the render +/// target for. +/// @param[in] opengl_framebuffer Ignored for all non-OpenGL backends. Flutter +/// supports rendering to both OpenGL textures +/// and framebuffers. When false, the OpenGL +/// texture render target type is returned. +EmbedderTestBackingStoreProducer::RenderTargetType GetRenderTargetFromBackend( + EmbedderTestContextType backend, + bool opengl_framebuffer); + +/// @brief Configures per-backend properties for a given backing store. +/// @param[in] backing_store The backing store to configure. +/// @param[in] backend The test context type used to decide which +/// backend the backing store will be used with. +/// @param[in] opengl_framebuffer Ignored for all non-OpenGL backends. Flutter +/// supports rendering to both OpenGL textures +/// and framebuffers. When false, the backing +/// store is configured to be an OpenGL texture. +void ConfigureBackingStore(FlutterBackingStore& backing_store, + EmbedderTestContextType backend, + bool opengl_framebuffer); + +bool WriteImageToDisk(const fml::UniqueFD& directory, + const std::string& name, + const sk_sp& image); + +bool ImageMatchesFixture(const std::string& fixture_file_name, + const sk_sp& scene_image); + +bool ImageMatchesFixture(const std::string& fixture_file_name, + std::future>& scene_image); + +bool SurfacePixelDataMatchesBytes(SkSurface* surface, + const std::vector& bytes); + +bool SurfacePixelDataMatchesBytes(std::future& surface_future, + const std::vector& bytes); + +void FilterMutationsByType( + const FlutterPlatformViewMutation** mutations, + size_t count, + FlutterPlatformViewMutationType type, + const std::function& + handler); + +void FilterMutationsByType( + const FlutterPlatformView* view, + FlutterPlatformViewMutationType type, + const std::function& + handler); + +SkMatrix GetTotalMutationTransformationMatrix( + const FlutterPlatformViewMutation** mutations, + size_t count); + +SkMatrix GetTotalMutationTransformationMatrix(const FlutterPlatformView* view); + +//------------------------------------------------------------------------------ +/// @brief A task runner that we expect the embedder to provide but whose +/// implementation is a real FML task runner. +/// +class EmbedderTestTaskRunner { + public: + using TaskExpiryCallback = std::function; + EmbedderTestTaskRunner(fml::RefPtr real_task_runner, + TaskExpiryCallback on_task_expired) + : identifier_(++sEmbedderTaskRunnerIdentifiers), + real_task_runner_(std::move(real_task_runner)), + on_task_expired_(std::move(on_task_expired)) { + FML_CHECK(real_task_runner_); + FML_CHECK(on_task_expired_); + + task_runner_description_.struct_size = sizeof(FlutterTaskRunnerDescription); + task_runner_description_.user_data = this; + task_runner_description_.runs_task_on_current_thread_callback = + [](void* user_data) -> bool { + return reinterpret_cast(user_data) + ->real_task_runner_->RunsTasksOnCurrentThread(); + }; + task_runner_description_.post_task_callback = [](FlutterTask task, + uint64_t target_time_nanos, + void* user_data) -> void { + auto thiz = reinterpret_cast(user_data); + + auto target_time = fml::TimePoint::FromEpochDelta( + fml::TimeDelta::FromNanoseconds(target_time_nanos)); + auto on_task_expired = thiz->on_task_expired_; + auto invoke_task = [task, on_task_expired]() { on_task_expired(task); }; + auto real_task_runner = thiz->real_task_runner_; + + real_task_runner->PostTaskForTime(invoke_task, target_time); + }; + task_runner_description_.destruction_callback = [](void* user_data) {}; + task_runner_description_.identifier = identifier_; + } + + void SetDestructionCallback(VoidCallback callback) { + task_runner_description_.destruction_callback = callback; + } + + const FlutterTaskRunnerDescription& GetFlutterTaskRunnerDescription() { + return task_runner_description_; + } + + private: + static std::atomic_size_t sEmbedderTaskRunnerIdentifiers; + const size_t identifier_; + fml::RefPtr real_task_runner_; + TaskExpiryCallback on_task_expired_; + FlutterTaskRunnerDescription task_runner_description_ = {}; + + FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestTaskRunner); +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_UNITTESTS_UTIL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_vk_unittests.cc b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_vk_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..6589830bbf1acc861532b45dc7d13e0db2d469c0 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/embedder/tests/embedder_vk_unittests.cc @@ -0,0 +1,135 @@ +// 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. + +#define FML_USED_ON_EMBEDDER + +#include +#include +#include +#include + +#include "embedder.h" +#include "embedder_engine.h" +#include "flutter/fml/synchronization/count_down_latch.h" +#include "flutter/shell/platform/embedder/tests/embedder_config_builder.h" +#include "flutter/shell/platform/embedder/tests/embedder_test.h" +#include "flutter/shell/platform/embedder/tests/embedder_test_context_vulkan.h" +#include "flutter/shell/platform/embedder/tests/embedder_unittests_util.h" +#include "flutter/testing/testing.h" + +// CREATE_NATIVE_ENTRY is leaky by design +// NOLINTBEGIN(clang-analyzer-core.StackAddressEscape) + +namespace flutter { +namespace testing { + +using EmbedderTest = testing::EmbedderTest; + +//////////////////////////////////////////////////////////////////////////////// +// Notice: Other Vulkan unit tests exist in embedder_gl_unittests.cc. +// See https://github.com/flutter/flutter/issues/134322 +//////////////////////////////////////////////////////////////////////////////// + +namespace { + +struct VulkanProcInfo { + decltype(vkGetInstanceProcAddr)* get_instance_proc_addr = nullptr; + decltype(vkGetDeviceProcAddr)* get_device_proc_addr = nullptr; + decltype(vkQueueSubmit)* queue_submit_proc_addr = nullptr; + bool did_call_queue_submit = false; +}; + +static_assert(std::is_trivially_destructible_v); + +VulkanProcInfo g_vulkan_proc_info; + +VkResult QueueSubmit(VkQueue queue, + uint32_t submitCount, + const VkSubmitInfo* pSubmits, + VkFence fence) { + FML_DCHECK(g_vulkan_proc_info.queue_submit_proc_addr != nullptr); + g_vulkan_proc_info.did_call_queue_submit = true; + return g_vulkan_proc_info.queue_submit_proc_addr(queue, submitCount, pSubmits, + fence); +} + +template +int StrcmpFixed(const char* str1, const char (&str2)[N]) { + return strncmp(str1, str2, N - 1); +} + +PFN_vkVoidFunction GetDeviceProcAddr(VkDevice device, const char* pName) { + FML_DCHECK(g_vulkan_proc_info.get_device_proc_addr != nullptr); + if (StrcmpFixed(pName, "vkQueueSubmit") == 0) { + g_vulkan_proc_info.queue_submit_proc_addr = + reinterpret_cast( + g_vulkan_proc_info.get_device_proc_addr(device, pName)); + return reinterpret_cast(QueueSubmit); + } + return g_vulkan_proc_info.get_device_proc_addr(device, pName); +} + +PFN_vkVoidFunction GetInstanceProcAddr(VkInstance instance, const char* pName) { + FML_DCHECK(g_vulkan_proc_info.get_instance_proc_addr != nullptr); + if (StrcmpFixed(pName, "vkGetDeviceProcAddr") == 0) { + g_vulkan_proc_info.get_device_proc_addr = + reinterpret_cast( + g_vulkan_proc_info.get_instance_proc_addr(instance, pName)); + return reinterpret_cast(GetDeviceProcAddr); + } + return g_vulkan_proc_info.get_instance_proc_addr(instance, pName); +} + +template +struct CheckSameSignature : std::false_type {}; + +template +struct CheckSameSignature : std::true_type {}; + +static_assert(CheckSameSignature::value); +static_assert(CheckSameSignature::value); +static_assert( + CheckSameSignature::value); +} // namespace + +TEST_F(EmbedderTest, CanGetVulkanEmbedderContext) { + auto& context = GetEmbedderContext(); + EmbedderConfigBuilder builder(context); +} + +TEST_F(EmbedderTest, CanSwapOutVulkanCalls) { + fml::AutoResetWaitableEvent latch; + + auto& context = GetEmbedderContext(); + context.AddIsolateCreateCallback([&latch]() { latch.Signal(); }); + context.SetVulkanInstanceProcAddressCallback( + [](void* user_data, FlutterVulkanInstanceHandle instance, + const char* name) -> void* { + if (StrcmpFixed(name, "vkGetInstanceProcAddr") == 0) { + g_vulkan_proc_info.get_instance_proc_addr = + reinterpret_cast( + EmbedderTestContextVulkan::InstanceProcAddr(user_data, + instance, name)); + return reinterpret_cast(GetInstanceProcAddr); + } + return EmbedderTestContextVulkan::InstanceProcAddr(user_data, instance, + name); + }); + + EmbedderConfigBuilder builder(context); + builder.SetSurface(SkISize::Make(1024, 1024)); + auto engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + // Wait for the root isolate to launch. + latch.Wait(); + engine.reset(); + EXPECT_TRUE(g_vulkan_proc_info.did_call_queue_submit); +} + +} // namespace testing +} // namespace flutter + +// NOLINTEND(clang-analyzer-core.StackAddressEscape) diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c04a41690e62ffd25a4db1fc44e61992861ac715 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/BUILD.gn @@ -0,0 +1,31 @@ +# 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. + +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") + +config("sdk_ext_config") { + include_dirs = [ "../.." ] +} + +group("fuchsia") { + public_deps = [ ":sdk_ext" ] +} + +source_set("sdk_ext") { + sources = [ + "sdk_ext/fuchsia.cc", + "sdk_ext/fuchsia.h", + ] + + deps = [ + "${fuchsia_sdk}/pkg/async-cpp", + "../zircon", + "//flutter/fml", + "//flutter/third_party/tonic", + ] + + public_deps = [ "${fuchsia_sdk}/pkg/zx" ] + + public_configs = [ ":sdk_ext_config" ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/README.md b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d22670fbde55aae7d5f6c0a6bc515701e635aa11 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/README.md @@ -0,0 +1,4 @@ +dart:fuchsia +=========== + +These are the Dart bindings for the Fuchsia application model. diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/lib/fuchsia.dart b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/lib/fuchsia.dart new file mode 100644 index 0000000000000000000000000000000000000000..78387f906795c2d8c7427eb7b1bcb17ea46ead0a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/lib/fuchsia.dart @@ -0,0 +1,85 @@ +// 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. + +library fuchsia; + +import 'dart:io'; +import 'dart:isolate'; +import 'dart:zircon'; + +// ignore_for_file: native_function_body_in_non_sdk_code +// ignore_for_file: public_member_api_docs + +// TODO: refactors this incomingServices instead +@pragma('vm:entry-point') +Handle? _environment; + +@pragma('vm:entry-point') +Handle? _outgoingServices; + +@pragma('vm:entry-point') +Handle? _viewRef; + +class MxStartupInfo { + // TODO: refactor Handle to a Channel + // https://github.com/flutter/flutter/issues/49439 + static Handle takeEnvironment() { + if (_environment == null && Platform.isFuchsia) { + throw Exception('Attempting to call takeEnvironment more than once per process'); + } + final handle = _environment; + _environment = null; + return handle!; + } + + // TODO: refactor Handle to a Channel + // https://github.com/flutter/flutter/issues/49439 + static Handle takeOutgoingServices() { + if (_outgoingServices == null && Platform.isFuchsia) { + throw Exception('Attempting to call takeOutgoingServices more than once per process'); + } + final handle = _outgoingServices; + _outgoingServices = null; + return handle!; + } + + // TODO: refactor Handle to a ViewRef + // https://github.com/flutter/flutter/issues/49439 + static Handle takeViewRef() { + if (_viewRef == null && Platform.isFuchsia) { + throw Exception('Attempting to call takeViewRef more than once per process'); + } + final handle = _viewRef; + _viewRef = null; + return handle!; + } +} + +@pragma('vm:external-name', 'SetReturnCode') +external void _setReturnCode(int returnCode); + +void exit(int returnCode) { + _setReturnCode(returnCode); + Isolate.current.kill(priority: Isolate.immediate); +} + +// ignore: always_declare_return_types, prefer_generic_function_type_aliases +typedef _ListStringArgFunction(List args); + +// This function is used as the entry point for code in the dart runner and is +// not meant to be called directly outside of that context. The code will invoke +// the given main entry point and pass the args if the function takes args. This +// function is needed because without it the snapshot compiler will tree shake +// the function away unless the user marks it as being an entry point. +// +// The code does not catch any exceptions since this is handled in the dart +// runner calling code. +@pragma('vm:entry-point') +void _runUserMainForDartRunner(Function userMainFunction, List args) { + if (userMainFunction is _ListStringArgFunction) { + (userMainFunction as dynamic)(args); + } else { + userMainFunction(); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/pubspec.yaml b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fdacaaf5bde03bcc9d9f7a0a44173762596a70ce --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/pubspec.yaml @@ -0,0 +1,6 @@ +# 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. + +environment: + sdk: ^3.7.0-0 diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/sdk_ext/fuchsia.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/sdk_ext/fuchsia.cc new file mode 100644 index 0000000000000000000000000000000000000000..40c380751fb609009fdb3d68dffb14743c1cc831 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/sdk_ext/fuchsia.cc @@ -0,0 +1,134 @@ +// 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 "dart-pkg/fuchsia/sdk_ext/fuchsia.h" + +#include + +#include +#include +#include +#include + +#include "dart-pkg/zircon/sdk_ext/handle.h" +#include "dart-pkg/zircon/sdk_ext/natives.h" +#include "dart-pkg/zircon/sdk_ext/system.h" +#include "third_party/dart/runtime/include/dart_api.h" +#include "third_party/tonic/dart_binding_macros.h" +#include "third_party/tonic/dart_class_library.h" +#include "third_party/tonic/dart_class_provider.h" +#include "third_party/tonic/dart_library_natives.h" +#include "third_party/tonic/dart_state.h" +#include "third_party/tonic/logging/dart_invoke.h" +#include "third_party/tonic/typed_data/typed_list.h" + +using tonic::ToDart; + +namespace fuchsia { +namespace dart { +namespace { + +static tonic::DartLibraryNatives* g_natives; + +tonic::DartLibraryNatives* InitNatives() { + tonic::DartLibraryNatives* natives = new tonic::DartLibraryNatives(); + + return natives; +} + +#define REGISTER_FUNCTION(name, count) {"" #name, name, count}, +#define DECLARE_FUNCTION(name, count) \ + extern void name(Dart_NativeArguments args); + +#define FIDL_NATIVE_LIST(V) V(SetReturnCode, 1) + +FIDL_NATIVE_LIST(DECLARE_FUNCTION); + +static struct NativeEntries { + const char* name; + Dart_NativeFunction function; + int argument_count; +} Entries[] = {FIDL_NATIVE_LIST(REGISTER_FUNCTION)}; + +Dart_NativeFunction NativeLookup(Dart_Handle name, + int argument_count, + bool* auto_setup_scope) { + const char* function_name = nullptr; + Dart_Handle result = Dart_StringToCString(name, &function_name); + if (Dart_IsError(result)) { + Dart_PropagateError(result); + } + FML_DCHECK(function_name != nullptr); + FML_DCHECK(auto_setup_scope != nullptr); + *auto_setup_scope = true; + size_t num_entries = std::size(Entries); + for (size_t i = 0; i < num_entries; ++i) { + const struct NativeEntries& entry = Entries[i]; + if (!strcmp(function_name, entry.name) && + (entry.argument_count == argument_count)) { + return entry.function; + } + } + if (!g_natives) + g_natives = InitNatives(); + return g_natives->GetNativeFunction(name, argument_count, auto_setup_scope); +} + +const uint8_t* NativeSymbol(Dart_NativeFunction native_function) { + size_t num_entries = std::size(Entries); + for (size_t i = 0; i < num_entries; ++i) { + const struct NativeEntries& entry = Entries[i]; + if (entry.function == native_function) { + return reinterpret_cast(entry.name); + } + } + if (!g_natives) + g_natives = InitNatives(); + return g_natives->GetSymbol(native_function); +} + +void SetReturnCode(Dart_NativeArguments arguments) { + int64_t return_code; + Dart_Handle status = + Dart_GetNativeIntegerArgument(arguments, 0, &return_code); + if (!tonic::CheckAndHandleError(status)) { + tonic::DartState::Current()->SetReturnCode(return_code); + } +} + +} // namespace + +void Initialize(zx::channel directory_request, + std::optional view_ref) { + zircon::dart::Initialize(); + + Dart_Handle library = Dart_LookupLibrary(ToDart("dart:fuchsia")); + FML_CHECK(!tonic::CheckAndHandleError(library)); + Dart_Handle result = Dart_SetNativeResolver( + library, fuchsia::dart::NativeLookup, fuchsia::dart::NativeSymbol); + FML_CHECK(!tonic::CheckAndHandleError(result)); + + auto dart_state = tonic::DartState::Current(); + std::unique_ptr fuchsia_class_provider( + new tonic::DartClassProvider(dart_state, "dart:fuchsia")); + dart_state->class_library().add_provider("fuchsia", + std::move(fuchsia_class_provider)); + + if (directory_request) { + result = Dart_SetField( + library, ToDart("_outgoingServices"), + ToDart(zircon::dart::Handle::Create(std::move(directory_request)))); + FML_CHECK(!tonic::CheckAndHandleError(result)); + } + + if (view_ref) { + result = Dart_SetField( + library, ToDart("_viewRef"), + ToDart(zircon::dart::Handle::Create((*view_ref).release()))); + FML_CHECK(!tonic::CheckAndHandleError(result)); + } +} + +} // namespace dart +} // namespace fuchsia diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/sdk_ext/fuchsia.h b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/sdk_ext/fuchsia.h new file mode 100644 index 0000000000000000000000000000000000000000..457528d99311cff9542938d943c99463feaada61 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/sdk_ext/fuchsia.h @@ -0,0 +1,23 @@ +// 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_SHELL_PLATFORM_FUCHSIA_DART_PKG_FUCHSIA_SDK_EXT_FUCHSIA_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_FUCHSIA_SDK_EXT_FUCHSIA_H_ + +#include +#include + +#include + +namespace fuchsia { +namespace dart { + +/// Initializes Dart bindings for the Fuchsia application model. +void Initialize(zx::channel directory_request, + std::optional view_ref); + +} // namespace dart +} // namespace fuchsia + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_FUCHSIA_SDK_EXT_FUCHSIA_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..0d13ea12c49faaa004612a94a4bc8ff763901507 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/BUILD.gn @@ -0,0 +1,92 @@ +# 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. + +import("//flutter/testing/testing.gni") +import("//flutter/tools/fuchsia/dart/dart_library.gni") +import("//flutter/tools/fuchsia/flutter/flutter_component.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/package.gni") + +config("zircon_config") { + include_dirs = [ "." ] +} + +source_set("zircon") { + public_configs = [ ":zircon_config" ] + + sources = [ + "sdk_ext/handle.cc", + "sdk_ext/handle.h", + "sdk_ext/handle_disposition.cc", + "sdk_ext/handle_disposition.h", + "sdk_ext/handle_waiter.cc", + "sdk_ext/handle_waiter.h", + "sdk_ext/natives.cc", + "sdk_ext/natives.h", + "sdk_ext/system.cc", + "sdk_ext/system.h", + ] + + deps = [ + "${fuchsia_sdk}/fidl/fuchsia.io", + "${fuchsia_sdk}/pkg/async-cpp", + "${fuchsia_sdk}/pkg/async-default", + "${fuchsia_sdk}/pkg/async-loop-cpp", + "${fuchsia_sdk}/pkg/fdio", + "${fuchsia_sdk}/pkg/zx", + "//flutter/fml", + "//flutter/third_party/tonic", + ] +} + +dart_library("zircon_lib") { + testonly = true + package_name = "zircon" + language_version = "2.12" + source_dir = "lib" + + sources = [ + "src/handle.dart", + "src/handle_disposition.dart", + "src/handle_waiter.dart", + "src/init.dart", + "src/system.dart", + "src/zd_channel.dart", + "src/zd_handle.dart", + "zircon.dart", + ] +} + +dart_library("zircon_tests_lib") { + testonly = true + package_name = "zircon_tests" + source_dir = "." + package_root = "test" + + sources = [ "zircon_tests.dart" ] + deps = [ "//flutter/shell/platform/fuchsia/dart:async_helper" ] +} + +flutter_component("zircon_tests_component") { + testonly = true + main_package = "zircon_tests" + component_name = "zircon_tests" + main_dart = "zircon_tests.dart" + manifest = rebase_path("test/meta/zircon_tests.cml") + + deps = [ ":zircon_tests_lib" ] +} + +fuchsia_package("zircon_tests_package") { + testonly = true + package_name = "zircon_tests" + deps = [ ":zircon_tests_component" ] +} + +if (enable_unittests) { + source_set("tests") { + testonly = true + deps = [ ":zircon_tests_package" ] + } +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/README.md b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c2a7fe7d57b29fd495e9da3b2a95ab9e3fe33f28 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/README.md @@ -0,0 +1,10 @@ +dart:zircon +=========== + +These are the Dart bindings for the Zircon [kernel +interface](https://fuchsia.googlesource.com/zircon/+/HEAD/docs/) + +This package exposes a `System` object with methods for may Zircon system +calls, a `Handle` type representing a Zircon handle and a `HandleWaiter` type +representing a wait on a handle. `Handle`s are returned by various methods on +`System` and `HandleWaiter`s are returned by `handle.asyncWait(...)`. diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/handle.dart b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/handle.dart new file mode 100644 index 0000000000000000000000000000000000000000..eea972780fbbfae9b5b439d1ca54f4c9d7ebe3a8 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/handle.dart @@ -0,0 +1,67 @@ +// 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. + +part of zircon; + +// ignore_for_file: native_function_body_in_non_sdk_code +// ignore_for_file: public_member_api_docs + +@pragma('vm:entry-point') +base class Handle extends NativeFieldWrapperClass1 { + // No public constructor - this can only be created from native code. + @pragma('vm:entry-point') + Handle._(); + + // Create an invalid handle object. + factory Handle.invalid() { + return _createInvalid(); + } + @pragma('vm:external-name', 'Handle_CreateInvalid') + external static Handle _createInvalid(); + + @pragma('vm:external-name', 'Handle_handle') + external int get handle; + + @pragma('vm:external-name', 'Handle_koid') + external int get koid; + + @override + String toString() => 'Handle($handle)'; + + @override + bool operator ==(Object other) { + return other is Handle && other.handle == handle; + } + + @override + int get hashCode => handle.hashCode; + + // Common handle operations. + @pragma('vm:external-name', 'Handle_is_valid') + external bool get isValid; + @pragma('vm:external-name', 'Handle_Close') + external int close(); + @pragma('vm:external-name', 'Handle_AsyncWait') + external HandleWaiter asyncWait(int signals, AsyncWaitCallback callback); + + @pragma('vm:external-name', 'Handle_Duplicate') + external Handle duplicate(int rights); + + @pragma('vm:external-name', 'Handle_Replace') + external Handle replace(int rights); +} + +@pragma('vm:entry-point') +class _OnWaitCompleteClosure { + // No public constructor - this can only be created from native code. + @pragma('vm:entry-point') + _OnWaitCompleteClosure(this._callback, this._arg1, this._arg2); + + Function _callback; + Object _arg1; + Object _arg2; + + @pragma('vm:entry-point') + Function get _closure => () => _callback(_arg1, _arg2); +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/handle_disposition.dart b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/handle_disposition.dart new file mode 100644 index 0000000000000000000000000000000000000000..a3ce43bbc6cd87bdf439c9ccbf57fa9639331a4f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/handle_disposition.dart @@ -0,0 +1,34 @@ +// 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. + +part of zircon; + +// ignore_for_file: native_function_body_in_non_sdk_code +// ignore_for_file: public_member_api_docs + +@pragma('vm:entry-point') +base class HandleDisposition extends NativeFieldWrapperClass1 { + @pragma('vm:entry-point') + HandleDisposition(int operation, Handle handle, int type, int rights) { + _constructor(operation, handle, type, rights); + } + + @pragma('vm:external-name', 'HandleDisposition_constructor') + external void _constructor(int operation, Handle handle, int type, int rights); + + @pragma('vm:external-name', 'HandleDisposition_operation') + external int get operation; + @pragma('vm:external-name', 'HandleDisposition_handle') + external Handle get handle; + @pragma('vm:external-name', 'HandleDisposition_type') + external int get type; + @pragma('vm:external-name', 'HandleDisposition_rights') + external int get rights; + @pragma('vm:external-name', 'HandleDisposition_result') + external int get result; + + @override + String toString() => + 'HandleDisposition(operation=$operation, handle=$handle, type=$type, rights=$rights, result=$result)'; +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/handle_waiter.dart b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/handle_waiter.dart new file mode 100644 index 0000000000000000000000000000000000000000..49bc437a5049f65cf912d59aa28489ae43e8d6ad --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/handle_waiter.dart @@ -0,0 +1,20 @@ +// 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. + +part of zircon; + +// ignore_for_file: native_function_body_in_non_sdk_code +// ignore_for_file: public_member_api_docs + +typedef AsyncWaitCallback = void Function(int status, int pending); + +@pragma('vm:entry-point') +base class HandleWaiter extends NativeFieldWrapperClass1 { + // Private constructor. + @pragma('vm:entry-point') + HandleWaiter._(); + + @pragma('vm:external-name', 'HandleWaiter_Cancel') + external void cancel(); +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/init.dart b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/init.dart new file mode 100644 index 0000000000000000000000000000000000000000..43274a718fe20b901b82f675812c8d8be5f4a547 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/init.dart @@ -0,0 +1,34 @@ +// 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. + +part of zircon; + +final _kZirconFFILibName = 'libzircon_ffi.so'; +final _kLibZirconDartPath = '/pkg/lib/$_kZirconFFILibName'; + +class _Bindings { + static ZirconFFIBindings? _bindings; + + @pragma('vm:entry-point') + static ZirconFFIBindings? get() { + // For soft-transition until libzircon_ffi.so rolls into GI. + if (!File(_kLibZirconDartPath).existsSync()) { + return null; + } + + if (_bindings == null) { + final _dylib = DynamicLibrary.open(_kZirconFFILibName); + _bindings = ZirconFFIBindings(_dylib); + } + + final initializer = _bindings!.zircon_dart_dl_initialize; + if (initializer(NativeApi.initializeApiDLData) != 1) { + throw UnsupportedError('Unable to initialize dart:zircon_ffi.'); + } + + return _bindings; + } +} + +final ZirconFFIBindings? zirconFFIBindings = _Bindings.get(); diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/system.dart b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/system.dart new file mode 100644 index 0000000000000000000000000000000000000000..c7e4b90f12961b543723c1470d033281e8d2815a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/system.dart @@ -0,0 +1,258 @@ +// 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. + +part of zircon; + +// ignore_for_file: native_function_body_in_non_sdk_code +// ignore_for_file: public_member_api_docs + +@pragma('vm:entry-point') +class _Namespace { + // No public constructor - this only has static methods. + _Namespace._(); + + // Library private variable set by the embedder used to cache the + // namespace (as an fdio_ns_t*). + @pragma('vm:entry-point') + static int? _namespace; +} + +/// An exception representing an error returned as an zx_status_t. +class ZxStatusException implements Exception { + final String? message; + final int status; + + ZxStatusException(this.status, [this.message]); + + @override + String toString() { + if (message == null) + return 'ZxStatusException: status = $status'; + else + return 'ZxStatusException: status = $status, "$message"'; + } +} + +/// Users of the [_Result] subclasses should check the status before +/// trying to read any data. Attempting to use a value stored in a result +/// when the status in not OK will result in an exception. +class _Result { + final int status; + const _Result(this.status); +} + +@pragma('vm:entry-point') +class HandleResult extends _Result { + final Handle? _handle; + Handle get handle => _handle!; + + @pragma('vm:entry-point') + const HandleResult(final int status, [this._handle]) : super(status); + @override + String toString() => 'HandleResult(status=$status, handle=$_handle)'; +} + +@pragma('vm:entry-point') +class HandlePairResult extends _Result { + final Handle? _first; + final Handle? _second; + + Handle get first => _first!; + Handle get second => _second!; + + @pragma('vm:entry-point') + const HandlePairResult(final int status, [this._first, this._second]) : super(status); + @override + String toString() => 'HandlePairResult(status=$status, first=$_first, second=$_second)'; +} + +@pragma('vm:entry-point') +class ReadResult extends _Result { + final ByteData? _bytes; + final int? _numBytes; + final List? _handles; + + ByteData get bytes => _bytes!; + int get numBytes => _numBytes!; + List get handles => _handles!; + + @pragma('vm:entry-point') + const ReadResult(final int status, [this._bytes, this._numBytes, this._handles]) : super(status); + + /// Returns the bytes as a Uint8List. If status != OK this will throw + /// an exception. + Uint8List bytesAsUint8List() { + final lbytes = bytes; + return lbytes.buffer.asUint8List(lbytes.offsetInBytes, _numBytes!); + } + + /// Returns the bytes as a String. If status != OK this will throw + /// an exception. + String bytesAsUTF8String() => utf8.decode(bytesAsUint8List()); + + @override + String toString() => + 'ReadResult(status=$status, bytes=$_bytes, numBytes=$_numBytes, handles=$_handles)'; +} + +@pragma('vm:entry-point') +class HandleInfo { + final Handle handle; + final int type; + final int rights; + + @pragma('vm:entry-point') + const HandleInfo(this.handle, this.type, this.rights); + + @override + String toString() => 'HandleInfo(handle=$handle, type=$type, rights=$rights)'; +} + +@pragma('vm:entry-point') +class ReadEtcResult extends _Result { + final ByteData? _bytes; + final int? _numBytes; + final List? _handleInfos; + + ByteData get bytes => _bytes!; + int get numBytes => _numBytes!; + List get handleInfos => _handleInfos!; + + @pragma('vm:entry-point') + const ReadEtcResult(final int status, [this._bytes, this._numBytes, this._handleInfos]) + : super(status); + + /// Returns the bytes as a Uint8List. If status != OK this will throw + /// an exception. + Uint8List bytesAsUint8List() { + final lbytes = bytes; + return lbytes.buffer.asUint8List(lbytes.offsetInBytes, _numBytes!); + } + + /// Returns the bytes as a String. If status != OK this will throw + /// an exception. + String bytesAsUTF8String() => utf8.decode(bytesAsUint8List()); + + @override + String toString() => + 'ReadEtcResult(status=$status, bytes=$_bytes, numBytes=$_numBytes, handleInfos=$_handleInfos)'; +} + +@pragma('vm:entry-point') +class WriteResult extends _Result { + final int? _numBytes; + int get numBytes => _numBytes!; + + @pragma('vm:entry-point') + const WriteResult(final int status, [this._numBytes]) : super(status); + @override + String toString() => 'WriteResult(status=$status, numBytes=$_numBytes)'; +} + +@pragma('vm:entry-point') +class GetSizeResult extends _Result { + final int? _size; + int get size => _size!; + + @pragma('vm:entry-point') + const GetSizeResult(final int status, [this._size]) : super(status); + @override + String toString() => 'GetSizeResult(status=$status, size=$_size)'; +} + +@pragma('vm:entry-point') +class FromFileResult extends _Result { + final Handle? _handle; + final int? _numBytes; + + Handle get handle => _handle!; + int get numBytes => _numBytes!; + + @pragma('vm:entry-point') + const FromFileResult(final int status, [this._handle, this._numBytes]) : super(status); + @override + String toString() => 'FromFileResult(status=$status, handle=$_handle, numBytes=$_numBytes)'; +} + +@pragma('vm:entry-point') +class MapResult extends _Result { + final Uint8List? _data; + Uint8List get data => _data!; + + @pragma('vm:entry-point') + const MapResult(final int status, [this._data]) : super(status); + @override + String toString() => 'MapResult(status=$status, data=$_data)'; +} + +@pragma('vm:entry-point') +base class System extends NativeFieldWrapperClass1 { + // No public constructor - this only has static methods. + System._(); + + // Channel operations. + @pragma('vm:external-name', 'System_ChannelCreate') + external static HandlePairResult channelCreate([int options = 0]); + @pragma('vm:external-name', 'System_ChannelFromFile') + external static HandleResult channelFromFile(String path); + @pragma('vm:external-name', 'System_ConnectToService') + external static int connectToService(String path, Handle channel); + @pragma('vm:external-name', 'System_ChannelWrite') + external static int channelWrite(Handle channel, ByteData data, List handles); + @pragma('vm:external-name', 'System_ChannelWriteEtc') + external static int channelWriteEtc( + Handle channel, + ByteData data, + List handleDispositions, + ); + @pragma('vm:external-name', 'System_ChannelQueryAndRead') + external static ReadResult channelQueryAndRead(Handle channel); + @pragma('vm:external-name', 'System_ChannelQueryAndReadEtc') + external static ReadEtcResult channelQueryAndReadEtc(Handle channel); + + // Eventpair operations. + @pragma('vm:external-name', 'System_EventpairCreate') + external static HandlePairResult eventpairCreate([int options = 0]); + + // Socket operations. + @pragma('vm:external-name', 'System_SocketCreate') + external static HandlePairResult socketCreate([int options = 0]); + @pragma('vm:external-name', 'System_SocketWrite') + external static WriteResult socketWrite(Handle socket, ByteData data, int options); + @pragma('vm:external-name', 'System_SocketRead') + external static ReadResult socketRead(Handle socket, int size); + + // Vmo operations. + @pragma('vm:external-name', 'System_VmoCreate') + external static HandleResult vmoCreate(int size, [int options = 0]); + @pragma('vm:external-name', 'System_VmoFromFile') + external static FromFileResult vmoFromFile(String path); + @pragma('vm:external-name', 'System_VmoGetSize') + external static GetSizeResult vmoGetSize(Handle vmo); + @pragma('vm:external-name', 'System_VmoSetSize') + external static int vmoSetSize(Handle vmo, int size); + @pragma('vm:external-name', 'System_VmoWrite') + external static int vmoWrite(Handle vmo, int offset, ByteData bytes); + @pragma('vm:external-name', 'System_VmoRead') + external static ReadResult vmoRead(Handle vmo, int offset, int size); + @pragma('vm:external-name', 'System_VmoMap') + external static MapResult vmoMap(Handle vmo); + + // Time operations. + static int clockGetMonotonic() { + if (zirconFFIBindings == null) { + return _nativeClockGetMonotonic(); + } else { + return zirconFFIBindings!.zircon_dart_clock_get_monotonic(); + } + } + + @pragma('vm:external-name', 'System_ClockGetMonotonic') + external static int _nativeClockGetMonotonic(); + + // TODO(edcoyne): Remove this, it is required to safely do an API transition across repos. + static int reboot() { + return -2; /*ZX_ERR_NOT_SUPPORTED*/ + } +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/zd_channel.dart b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/zd_channel.dart new file mode 100644 index 0000000000000000000000000000000000000000..884eb6e223c6b233bd36b65efaa94f94590157cf --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/zd_channel.dart @@ -0,0 +1,53 @@ +// 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. + +part of zircon; + +@pragma('vm:entry-point') +class ZDChannel { + static ZDChannel? create([int options = 0]) { + final Pointer? channelPtr = zirconFFIBindings + ?.zircon_dart_channel_create(options); + if (channelPtr == null || channelPtr.address == 0) { + throw Exception('Unable to create a channel'); + } + return ZDChannel._(ZDHandlePair._(channelPtr)); + } + + static int _write(ZDHandle channel, ByteData data, List handles) { + final Pointer handleList = + zirconFFIBindings!.zircon_dart_handle_list_create(); + handles.forEach((ZDHandle handle) { + zirconFFIBindings!.zircon_dart_handle_list_append(handleList, handle._ptr); + }); + + final Uint8List dataAsBytes = data.buffer.asUint8List(); + final Pointer byteArray = zirconFFIBindings! + .zircon_dart_byte_array_create(dataAsBytes.length); + for (int i = 0; i < dataAsBytes.length; i++) { + zirconFFIBindings!.zircon_dart_byte_array_set_value(byteArray, i, dataAsBytes.elementAt(i)); + } + int ret = zirconFFIBindings!.zircon_dart_channel_write(channel._ptr, byteArray, handleList); + + zirconFFIBindings!.zircon_dart_byte_array_free(byteArray); + zirconFFIBindings!.zircon_dart_handle_list_free(handleList); + return ret; + } + + int writeLeft(ByteData data, List handles) { + return _write(handlePair.left, data, handles); + } + + int writeRight(ByteData data, List handles) { + return _write(handlePair.right, data, handles); + } + + @pragma('vm:entry-point') + ZDChannel._(this.handlePair); + + final ZDHandlePair handlePair; + + @override + String toString() => 'Channel(handlePair=$handlePair)'; +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/zd_handle.dart b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/zd_handle.dart new file mode 100644 index 0000000000000000000000000000000000000000..24ae20c6d7c26bf4cac50fb46e04238399b7fb99 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/zd_handle.dart @@ -0,0 +1,77 @@ +// 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. + +part of zircon; + +@pragma('vm:entry-point') +class ZDHandle { + @pragma('vm:entry-point') + ZDHandle._(this._ptr) { + _attachFinalizer(); + } + + void _attachFinalizer() { + // TODO (kaushikiska): fix external allocation size. + final int? ret = zirconFFIBindings?.zircon_dart_handle_attach_finalizer(this, _ptr.cast(), 128); + if (ret != 1) { + throw Exception('Unable to attach finalizer to handle'); + } + } + + int get handle => _ptr.ref.handle; + + final Pointer _ptr; + + bool isValid() { + int? ret = zirconFFIBindings?.zircon_dart_handle_is_valid(_ptr); + return ret == 1; + } + + bool close() { + assert(isValid()); + if (isValid()) { + int? ret = zirconFFIBindings?.zircon_dart_handle_close(_ptr); + return ret == 1; + } + return false; + } + + @override + bool operator ==(Object other) { + return other is ZDHandle && other.handle == handle; + } + + @override + int get hashCode => handle.hashCode; + + @override + String toString() => 'ZDHandle(handle=$handle)'; +} + +@pragma('vm:entry-point') +class ZDHandlePair { + @pragma('vm:entry-point') + ZDHandlePair._(this._ptr) : left = ZDHandle._(_ptr.ref.left), right = ZDHandle._(_ptr.ref.right) { + _attachFinalizer(); + } + + void _attachFinalizer() { + // TODO (kaushikiska): fix external allocation size. + final int? ret = zirconFFIBindings?.zircon_dart_handle_pair_attach_finalizer( + this, + _ptr.cast(), + 128, + ); + if (ret != 1) { + throw Exception('Unable to attach finalizer to handle'); + } + } + + final Pointer _ptr; + final ZDHandle left; + final ZDHandle right; + + @override + String toString() => 'ZDHandlePair(left=$left, right=$right)'; +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/zircon.dart b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/zircon.dart new file mode 100644 index 0000000000000000000000000000000000000000..bf726e3ac94d94d79da4d4bb40a670760d0969af --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/zircon.dart @@ -0,0 +1,23 @@ +// 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. + +library zircon; + +// uncomment the next line for local testing. +// import 'package:zircon_ffi/zircon_ffi.dart'; + +import 'dart:convert' show utf8; +import 'dart:ffi'; +import 'dart:io'; +import 'dart:nativewrappers'; +import 'dart:typed_data'; +import 'dart:zircon_ffi'; + +part 'src/handle.dart'; +part 'src/handle_disposition.dart'; +part 'src/handle_waiter.dart'; +part 'src/init.dart'; +part 'src/system.dart'; +part 'src/zd_channel.dart'; +part 'src/zd_handle.dart'; diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/pubspec.yaml b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ac72505fe6e9246a77e49380b3d1b5c5e23e796e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/pubspec.yaml @@ -0,0 +1,20 @@ +# 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. + +name: zircon + +environment: + sdk: ^3.7.0-0 + + +# Uncomment block for local testing + +# dependencies: +# zircon_ffi: +# path: ../zircon_ffi + +# dev_dependencies: +# test: ^1.17.10 + +# block end diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle.cc new file mode 100644 index 0000000000000000000000000000000000000000..9208299e016776b130c7069c8b98681947705bca --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle.cc @@ -0,0 +1,138 @@ +// 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 "handle.h" + +#include + +#include "third_party/tonic/dart_binding_macros.h" +#include "third_party/tonic/dart_class_library.h" + +using tonic::ToDart; + +namespace zircon { +namespace dart { + +IMPLEMENT_WRAPPERTYPEINFO(zircon, Handle); + +Handle::Handle(zx_handle_t handle) : handle_(handle) {} + +Handle::~Handle() { + if (is_valid()) { + zx_status_t status = Close(); + FML_DCHECK(status == ZX_OK); + } +} + +fml::RefPtr Handle::Create(zx_handle_t handle) { + return fml::MakeRefCounted(handle); +} + +Dart_Handle Handle::CreateInvalid() { + return ToDart(Create(ZX_HANDLE_INVALID)); +} + +zx_handle_t Handle::ReleaseHandle() { + FML_DCHECK(is_valid()); + + zx_handle_t handle = handle_; + handle_ = ZX_HANDLE_INVALID; + cached_koid_ = std::nullopt; + while (waiters_.size()) { + // HandleWaiter::Cancel calls Handle::ReleaseWaiter which removes the + // HandleWaiter from waiters_. + FML_DCHECK(waiters_.back()->is_pending()); + waiters_.back()->Cancel(); + } + + FML_DCHECK(!is_valid()); + + return handle; +} + +zx_status_t Handle::Close() { + if (is_valid()) { + zx_handle_t handle = ReleaseHandle(); + return zx_handle_close(handle); + } + return ZX_ERR_BAD_HANDLE; +} + +fml::RefPtr Handle::AsyncWait(zx_signals_t signals, + Dart_Handle callback) { + if (!is_valid()) { + FML_LOG(WARNING) << "Attempt to wait on an invalid handle."; + return nullptr; + } + + fml::RefPtr waiter = + HandleWaiter::Create(this, signals, callback); + waiters_.push_back(waiter.get()); + + return waiter; +} + +void Handle::ReleaseWaiter(HandleWaiter* waiter) { + FML_DCHECK(waiter); + auto iter = std::find(waiters_.cbegin(), waiters_.cend(), waiter); + FML_DCHECK(iter != waiters_.cend()); + FML_DCHECK(*iter == waiter); + waiters_.erase(iter); +} + +Dart_Handle Handle::Duplicate(uint32_t rights) { + if (!is_valid()) { + return ToDart(Create(ZX_HANDLE_INVALID)); + } + + zx_handle_t out_handle; + zx_status_t status = zx_handle_duplicate(handle_, rights, &out_handle); + if (status != ZX_OK) { + return ToDart(Create(ZX_HANDLE_INVALID)); + } + return ToDart(Create(out_handle)); +} + +Dart_Handle Handle::Replace(uint32_t rights) { + if (!is_valid()) { + return ToDart(Create(ZX_HANDLE_INVALID)); + } + + zx_handle_t out_handle; + zx_status_t status = zx_handle_replace(ReleaseHandle(), rights, &out_handle); + if (status != ZX_OK) { + return ToDart(Create(ZX_HANDLE_INVALID)); + } + return ToDart(Create(out_handle)); +} + +// clang-format: off + +#define FOR_EACH_STATIC_BINDING(V) V(Handle, CreateInvalid) + +#define FOR_EACH_BINDING(V) \ + V(Handle, handle) \ + V(Handle, koid) \ + V(Handle, is_valid) \ + V(Handle, Close) \ + V(Handle, AsyncWait) \ + V(Handle, Duplicate) \ + V(Handle, Replace) + +// clang-format: on + +// Tonic is missing a comma. +#define DART_REGISTER_NATIVE_STATIC_(CLASS, METHOD) \ + DART_REGISTER_NATIVE_STATIC(CLASS, METHOD), + +FOR_EACH_STATIC_BINDING(DART_NATIVE_CALLBACK_STATIC) +FOR_EACH_BINDING(DART_NATIVE_NO_UI_CHECK_CALLBACK) + +void Handle::RegisterNatives(tonic::DartLibraryNatives* natives) { + natives->Register({FOR_EACH_STATIC_BINDING(DART_REGISTER_NATIVE_STATIC_) + FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); +} + +} // namespace dart +} // namespace zircon diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle.h b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle.h new file mode 100644 index 0000000000000000000000000000000000000000..a464d8c4896dc3de4e72218e89a9f51796a84de9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle.h @@ -0,0 +1,97 @@ +// 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_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_HANDLE_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_HANDLE_H_ + +#include + +#include +#include + +#include "flutter/fml/memory/ref_counted.h" +#include "handle_waiter.h" +#include "third_party/dart/runtime/include/dart_api.h" +#include "third_party/tonic/dart_library_natives.h" +#include "third_party/tonic/dart_wrappable.h" +#include "third_party/tonic/typed_data/dart_byte_data.h" + +namespace zircon { +namespace dart { +/** + * Handle is the native peer of a Dart object (Handle in dart:zircon) + * that holds an zx_handle_t. It tracks active waiters on handle too. + */ +class Handle : public fml::RefCountedThreadSafe, + public tonic::DartWrappable { + DEFINE_WRAPPERTYPEINFO(); + FML_FRIEND_REF_COUNTED_THREAD_SAFE(Handle); + FML_FRIEND_MAKE_REF_COUNTED(Handle); + + public: + ~Handle(); + + static void RegisterNatives(tonic::DartLibraryNatives* natives); + + static fml::RefPtr Create(zx_handle_t handle); + static fml::RefPtr Create(zx::handle handle) { + return Create(handle.release()); + } + + static fml::RefPtr Unwrap(Dart_Handle handle) { + return fml::RefPtr( + tonic::DartConverter::FromDart(handle)); + } + + static Dart_Handle CreateInvalid(); + + zx_handle_t ReleaseHandle(); + + bool is_valid() const { return handle_ != ZX_HANDLE_INVALID; } + + zx_handle_t handle() const { return handle_; } + + zx_koid_t koid() const { + if (!cached_koid_.has_value()) { + zx_info_handle_basic_t info; + zx_status_t status = zx_object_get_info( + handle_, ZX_INFO_HANDLE_BASIC, &info, sizeof(info), nullptr, nullptr); + cached_koid_ = std::optional( + status == ZX_OK ? info.koid : ZX_KOID_INVALID); + } + return cached_koid_.value(); + } + + zx_status_t Close(); + + fml::RefPtr AsyncWait(zx_signals_t signals, + Dart_Handle callback); + + void ReleaseWaiter(HandleWaiter* waiter); + + Dart_Handle Duplicate(uint32_t rights); + + Dart_Handle Replace(uint32_t rights); + + private: + explicit Handle(zx_handle_t handle); + + void RetainDartWrappableReference() const override { AddRef(); } + + void ReleaseDartWrappableReference() const override { Release(); } + + zx_handle_t handle_; + + std::vector waiters_; + + // Cache koid. To guarantee proper cache invalidation, only one `Handle` + // should own the `zx_handle_t` at a time and use of syscalls that invalidate + // the handle should use `ReleaseHandle()`. + mutable std::optional cached_koid_; +}; + +} // namespace dart +} // namespace zircon + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_HANDLE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_disposition.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_disposition.cc new file mode 100644 index 0000000000000000000000000000000000000000..c4e558fa16a153e9d387dcb23bafbbfad0f8989d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_disposition.cc @@ -0,0 +1,60 @@ +// 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 "handle_disposition.h" + +#include + +#include "third_party/tonic/dart_binding_macros.h" +#include "third_party/tonic/dart_class_library.h" + +using tonic::ToDart; + +namespace zircon { +namespace dart { + +IMPLEMENT_WRAPPERTYPEINFO(zircon, HandleDisposition); + +void HandleDisposition_constructor(Dart_NativeArguments args) { + DartCallConstructor(&HandleDisposition::create, args); +} + +fml::RefPtr HandleDisposition::create( + zx_handle_op_t operation, + fml::RefPtr handle, + zx_obj_type_t type, + zx_rights_t rights) { + return fml::MakeRefCounted(operation, handle, type, rights, + ZX_OK); +} + +// clang-format: off + +#define FOR_EACH_STATIC_BINDING(V) V(HandleDisposition, create) + +#define FOR_EACH_BINDING(V) \ + V(HandleDisposition, operation) \ + V(HandleDisposition, handle) \ + V(HandleDisposition, type) \ + V(HandleDisposition, rights) \ + V(HandleDisposition, result) + +// clang-format: on + +// Tonic is missing a comma. +#define DART_REGISTER_NATIVE_STATIC_(CLASS, METHOD) \ + DART_REGISTER_NATIVE_STATIC(CLASS, METHOD), + +FOR_EACH_STATIC_BINDING(DART_NATIVE_CALLBACK_STATIC) +FOR_EACH_BINDING(DART_NATIVE_NO_UI_CHECK_CALLBACK) + +void HandleDisposition::RegisterNatives(tonic::DartLibraryNatives* natives) { + natives->Register({{"HandleDisposition_constructor", + HandleDisposition_constructor, 5, true}, + FOR_EACH_STATIC_BINDING(DART_REGISTER_NATIVE_STATIC_) + FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); +} + +} // namespace dart +} // namespace zircon diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_disposition.h b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_disposition.h new file mode 100644 index 0000000000000000000000000000000000000000..752595545cb3961b5690da300863f5fe3b69b030 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_disposition.h @@ -0,0 +1,71 @@ +// 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_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_HANDLE_DISPOSITION_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_HANDLE_DISPOSITION_H_ + +#include + +#include + +#include "flutter/fml/memory/ref_counted.h" +#include "handle.h" +#include "third_party/dart/runtime/include/dart_api.h" +#include "third_party/tonic/dart_library_natives.h" +#include "third_party/tonic/dart_wrappable.h" + +namespace zircon { +namespace dart { +/** + * HandleDisposition is the native peer of a Dart object (HandleDisposition + * in dart:zircon) that holds a Handle and additional properties. + */ +class HandleDisposition : public fml::RefCountedThreadSafe, + public tonic::DartWrappable { + DEFINE_WRAPPERTYPEINFO(); + FML_FRIEND_REF_COUNTED_THREAD_SAFE(HandleDisposition); + FML_FRIEND_MAKE_REF_COUNTED(HandleDisposition); + + public: + static void RegisterNatives(tonic::DartLibraryNatives* natives); + + static fml::RefPtr create(zx_handle_op_t operation, + fml::RefPtr handle, + zx_obj_type_t type, + zx_rights_t rights); + + zx_handle_op_t operation() const { return operation_; } + fml::RefPtr handle() const { return handle_; } + zx_obj_type_t type() const { return type_; } + zx_rights_t rights() const { return rights_; } + zx_status_t result() const { return result_; } + void set_result(zx_status_t result) { result_ = result; } + + private: + explicit HandleDisposition(zx_handle_op_t operation, + fml::RefPtr handle, + zx_obj_type_t type, + zx_rights_t rights, + zx_status_t result) + : operation_(operation), + handle_(handle), + type_(type), + rights_(rights), + result_(result) {} + + void RetainDartWrappableReference() const override { AddRef(); } + + void ReleaseDartWrappableReference() const override { Release(); } + + const zx_handle_op_t operation_; + const fml::RefPtr handle_; + const zx_obj_type_t type_; + const zx_rights_t rights_; + zx_status_t result_; +}; + +} // namespace dart +} // namespace zircon + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_HANDLE_DISPOSITION_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_waiter.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_waiter.cc new file mode 100644 index 0000000000000000000000000000000000000000..4c502e4b70afe9316b22f5bea74633ba24586fbc --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_waiter.cc @@ -0,0 +1,121 @@ +// 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 "handle_waiter.h" + +#include + +#include "handle.h" +#include "third_party/tonic/converter/dart_converter.h" +#include "third_party/tonic/dart_args.h" +#include "third_party/tonic/dart_binding_macros.h" +#include "third_party/tonic/dart_library_natives.h" +#include "third_party/tonic/dart_message_handler.h" +#include "third_party/tonic/dart_microtask_queue.h" +#include "third_party/tonic/logging/dart_invoke.h" + +using tonic::DartInvokeField; +using tonic::DartState; +using tonic::ToDart; + +namespace zircon { +namespace dart { + +IMPLEMENT_WRAPPERTYPEINFO(zircon, HandleWaiter); + +#define FOR_EACH_BINDING(V) V(HandleWaiter, Cancel) + +FOR_EACH_BINDING(DART_NATIVE_NO_UI_CHECK_CALLBACK) + +void HandleWaiter::RegisterNatives(tonic::DartLibraryNatives* natives) { + natives->Register({FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); +} + +fml::RefPtr HandleWaiter::Create(Handle* handle, + zx_signals_t signals, + Dart_Handle callback) { + return fml::MakeRefCounted(handle, signals, callback); +} + +HandleWaiter::HandleWaiter(Handle* handle, + zx_signals_t signals, + Dart_Handle callback) + : wait_(this, handle->handle(), signals), + handle_(handle), + callback_(DartState::Current(), callback) { + FML_CHECK(handle_ != nullptr); + FML_CHECK(handle_->is_valid()); + + zx_status_t status = wait_.Begin(async_get_default_dispatcher()); + FML_DCHECK(status == ZX_OK); +} + +HandleWaiter::~HandleWaiter() { + Cancel(); +} + +void HandleWaiter::Cancel() { + FML_DCHECK(wait_.is_pending() == !!handle_); + if (handle_) { + // Cancel the wait. + wait_.Cancel(); + + // Release this object from the handle and clear handle_. + handle_->ReleaseWaiter(this); + handle_ = nullptr; + } + FML_DCHECK(!wait_.is_pending()); +} + +void HandleWaiter::OnWaitComplete(async_dispatcher_t* dispatcher, + async::WaitBase* wait, + zx_status_t status, + const zx_packet_signal_t* signal) { + FML_DCHECK(handle_); + + FML_DCHECK(!callback_.is_empty()); + + // Hold a reference to this object. + fml::RefPtr ref(this); + + // Remove this waiter from the handle. + handle_->ReleaseWaiter(this); + + // Clear handle_. + handle_ = nullptr; + + auto state = callback_.dart_state().lock(); + FML_DCHECK(state); + DartState::Scope scope(state); + + // Put the closure invocation on the microtask queue. + Dart_Handle zircon_lib = Dart_LookupLibrary(ToDart("dart:zircon")); + FML_DCHECK(!tonic::CheckAndHandleError(zircon_lib)); + + Dart_Handle owc_type = + Dart_GetClass(zircon_lib, ToDart("_OnWaitCompleteClosure")); + FML_DCHECK(!tonic::CheckAndHandleError(owc_type)); + + FML_DCHECK(!callback_.is_empty()); + std::vector owc_args{callback_.Release(), ToDart(status), + ToDart(signal->observed)}; + Dart_Handle owc = + Dart_New(owc_type, Dart_Null(), owc_args.size(), owc_args.data()); + FML_DCHECK(!tonic::CheckAndHandleError(owc)); + + Dart_Handle closure = Dart_GetField(owc, ToDart("_closure")); + FML_DCHECK(!tonic::CheckAndHandleError(closure)); + + // TODO(issue#tbd): Use tonic::DartMicrotaskQueue::ScheduleMicrotask() + // instead when tonic::DartState gets a microtask queue field. + Dart_Handle async_lib = Dart_LookupLibrary(ToDart("dart:async")); + FML_DCHECK(!tonic::CheckAndHandleError(async_lib)); + std::vector sm_args{closure}; + Dart_Handle sm_result = Dart_Invoke(async_lib, ToDart("scheduleMicrotask"), + sm_args.size(), sm_args.data()); + FML_DCHECK(!tonic::CheckAndHandleError(sm_result)); +} + +} // namespace dart +} // namespace zircon diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_waiter.h b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_waiter.h new file mode 100644 index 0000000000000000000000000000000000000000..fccd405b6473f45f15360e46e14a5026db7c4bd6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_waiter.h @@ -0,0 +1,63 @@ +// 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_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_HANDLE_WAITER_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_HANDLE_WAITER_H_ + +#include +#include + +#include "flutter/fml/memory/ref_counted.h" +#include "third_party/tonic/dart_wrappable.h" + +namespace tonic { +class DartLibraryNatives; +} // namespace tonic + +namespace zircon { +namespace dart { + +class Handle; + +class HandleWaiter : public fml::RefCountedThreadSafe, + public tonic::DartWrappable { + DEFINE_WRAPPERTYPEINFO(); + FML_FRIEND_REF_COUNTED_THREAD_SAFE(HandleWaiter); + FML_FRIEND_MAKE_REF_COUNTED(HandleWaiter); + + public: + static fml::RefPtr Create(Handle* handle, + zx_signals_t signals, + Dart_Handle callback); + + void Cancel(); + + bool is_pending() { return wait_.is_pending(); } + + static void RegisterNatives(tonic::DartLibraryNatives* natives); + + private: + explicit HandleWaiter(Handle* handle, + zx_signals_t signals, + Dart_Handle callback); + ~HandleWaiter(); + + void OnWaitComplete(async_dispatcher_t* dispatcher, + async::WaitBase* wait, + zx_status_t status, + const zx_packet_signal_t* signal); + + void RetainDartWrappableReference() const override { AddRef(); } + + void ReleaseDartWrappableReference() const override { Release(); } + + async::WaitMethod wait_; + Handle* handle_; + tonic::DartPersistentValue callback_; +}; + +} // namespace dart +} // namespace zircon + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_HANDLE_WAITER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/natives.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/natives.cc new file mode 100644 index 0000000000000000000000000000000000000000..b3558ad882ec8e520159b48787a92a9e9d05dfae --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/natives.cc @@ -0,0 +1,83 @@ +// 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 "natives.h" + +#include + +#include +#include +#include + +#include "handle.h" +#include "handle_disposition.h" +#include "handle_waiter.h" +#include "system.h" +#include "third_party/dart/runtime/include/dart_api.h" +#include "third_party/tonic/dart_binding_macros.h" +#include "third_party/tonic/dart_class_library.h" +#include "third_party/tonic/dart_class_provider.h" +#include "third_party/tonic/dart_library_natives.h" +#include "third_party/tonic/dart_state.h" +#include "third_party/tonic/logging/dart_invoke.h" +#include "third_party/tonic/typed_data/typed_list.h" + +using tonic::ToDart; + +namespace zircon { +namespace dart { +namespace { + +static tonic::DartLibraryNatives* g_natives; + +tonic::DartLibraryNatives* InitNatives() { + tonic::DartLibraryNatives* natives = new tonic::DartLibraryNatives(); + HandleDisposition::RegisterNatives(natives); + HandleWaiter::RegisterNatives(natives); + Handle::RegisterNatives(natives); + System::RegisterNatives(natives); + + return natives; +} + +Dart_NativeFunction NativeLookup(Dart_Handle name, + int argument_count, + bool* auto_setup_scope) { + const char* function_name = nullptr; + Dart_Handle result = Dart_StringToCString(name, &function_name); + if (Dart_IsError(result)) { + Dart_PropagateError(result); + } + FML_DCHECK(function_name != nullptr); + FML_DCHECK(auto_setup_scope != nullptr); + *auto_setup_scope = true; + if (!g_natives) + g_natives = InitNatives(); + return g_natives->GetNativeFunction(name, argument_count, auto_setup_scope); +} + +const uint8_t* NativeSymbol(Dart_NativeFunction native_function) { + if (!g_natives) + g_natives = InitNatives(); + return g_natives->GetSymbol(native_function); +} + +} // namespace + +void Initialize() { + Dart_Handle library = Dart_LookupLibrary(ToDart("dart:zircon")); + FML_CHECK(!tonic::CheckAndHandleError(library)); + Dart_Handle result = Dart_SetNativeResolver( + library, zircon::dart::NativeLookup, zircon::dart::NativeSymbol); + FML_CHECK(!tonic::CheckAndHandleError(result)); + + auto dart_state = tonic::DartState::Current(); + std::unique_ptr zircon_class_provider( + new tonic::DartClassProvider(dart_state, "dart:zircon")); + dart_state->class_library().add_provider("zircon", + std::move(zircon_class_provider)); +} + +} // namespace dart +} // namespace zircon diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/natives.h b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/natives.h new file mode 100644 index 0000000000000000000000000000000000000000..f124f672034e871df200fd43d7dfde8dbb7bc929 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/natives.h @@ -0,0 +1,16 @@ +// 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_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_NATIVES_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_NATIVES_H_ + +namespace zircon { +namespace dart { + +void Initialize(); + +} // namespace dart +} // namespace zircon + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_NATIVES_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/system.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/system.cc new file mode 100644 index 0000000000000000000000000000000000000000..7d79423e42c9db01139345dbed547e3c39cf4c7e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/system.cc @@ -0,0 +1,609 @@ +// 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 "system.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "flutter/fml/unique_fd.h" +#include "third_party/tonic/dart_binding_macros.h" +#include "third_party/tonic/dart_class_library.h" + +using tonic::ToDart; + +namespace zircon { +namespace dart { + +namespace { + +constexpr char kGetSizeResult[] = "GetSizeResult"; +constexpr char kHandlePairResult[] = "HandlePairResult"; +constexpr char kHandleResult[] = "HandleResult"; +constexpr char kReadResult[] = "ReadResult"; +constexpr char kHandleInfo[] = "HandleInfo"; +constexpr char kReadEtcResult[] = "ReadEtcResult"; +constexpr char kWriteResult[] = "WriteResult"; +constexpr char kFromFileResult[] = "FromFileResult"; +constexpr char kMapResult[] = "MapResult"; + +class ByteDataScope { + public: + explicit ByteDataScope(Dart_Handle dart_handle) : dart_handle_(dart_handle) { + Acquire(); + } + + explicit ByteDataScope(size_t size) { + dart_handle_ = Dart_NewTypedData(Dart_TypedData_kByteData, size); + FML_DCHECK(!tonic::CheckAndHandleError(dart_handle_)); + Acquire(); + FML_DCHECK(size == size_); + } + + ~ByteDataScope() { + if (is_valid_) { + Release(); + } + } + + void* data() const { return data_; } + size_t size() const { return size_; } + Dart_Handle dart_handle() const { return dart_handle_; } + bool is_valid() const { return is_valid_; } + + void Release() { + FML_DCHECK(is_valid_); + Dart_Handle result = Dart_TypedDataReleaseData(dart_handle_); + tonic::CheckAndHandleError(result); + is_valid_ = false; + data_ = nullptr; + size_ = 0; + } + + private: + void Acquire() { + FML_DCHECK(size_ == 0); + FML_DCHECK(data_ == nullptr); + FML_DCHECK(!is_valid_); + + Dart_TypedData_Type type; + intptr_t size; + Dart_Handle result = + Dart_TypedDataAcquireData(dart_handle_, &type, &data_, &size); + is_valid_ = !tonic::CheckAndHandleError(result) && + type == Dart_TypedData_kByteData && data_; + if (is_valid_) { + size_ = size; + } else { + size_ = 0; + } + } + + Dart_Handle dart_handle_; + bool is_valid_ = false; + size_t size_ = 0; + void* data_ = nullptr; +}; + +Dart_Handle MakeHandleList(const std::vector& in_handles) { + tonic::DartClassLibrary& class_library = + tonic::DartState::Current()->class_library(); + Dart_Handle handle_type = class_library.GetClass("zircon", "Handle"); + Dart_Handle list = Dart_NewListOfTypeFilled( + handle_type, Handle::CreateInvalid(), in_handles.size()); + if (Dart_IsError(list)) + return list; + for (size_t i = 0; i < in_handles.size(); i++) { + Dart_Handle result = + Dart_ListSetAt(list, i, ToDart(Handle::Create(in_handles[i]))); + if (Dart_IsError(result)) + return result; + } + return list; +} + +template +Dart_Handle ConstructDartObject(const char* class_name, Args&&... args) { + tonic::DartClassLibrary& class_library = + tonic::DartState::Current()->class_library(); + Dart_Handle type = + Dart_HandleFromPersistent(class_library.GetClass("zircon", class_name)); + FML_DCHECK(!tonic::CheckAndHandleError(type)); + + const char* cstr; + Dart_StringToCString(Dart_ToString(type), &cstr); + + std::array args_array{ + {std::forward(args)...}}; + Dart_Handle object = + Dart_New(type, Dart_EmptyString(), sizeof...(Args), args_array.data()); + FML_DCHECK(!tonic::CheckAndHandleError(object)); + return object; +} + +Dart_Handle MakeHandleInfoList( + const std::vector& in_handles) { + tonic::DartClassLibrary& class_library = + tonic::DartState::Current()->class_library(); + Dart_Handle handle_info_type = class_library.GetClass("zircon", kHandleInfo); + Dart_Handle empty_handle_info = ConstructDartObject( + kHandleInfo, ToDart(Handle::CreateInvalid()), ToDart(-1), ToDart(-1)); + Dart_Handle list = Dart_NewListOfTypeFilled( + handle_info_type, empty_handle_info, in_handles.size()); + if (Dart_IsError(list)) + return list; + for (size_t i = 0; i < in_handles.size(); i++) { + Dart_Handle handle = ToDart(Handle::Create(in_handles[i].handle)); + Dart_Handle result = Dart_ListSetAt( + list, i, + ConstructDartObject(kHandleInfo, handle, ToDart(in_handles[i].type), + ToDart(in_handles[i].rights))); + if (Dart_IsError(result)) + return result; + } + return list; +} + +fdio_ns_t* GetNamespace() { + // Grab the fdio_ns_t* out of the isolate. + Dart_Handle zircon_lib = Dart_LookupLibrary(ToDart("dart:zircon")); + FML_DCHECK(!tonic::CheckAndHandleError(zircon_lib)); + Dart_Handle namespace_type = + Dart_GetNonNullableType(zircon_lib, ToDart("_Namespace"), 0, nullptr); + FML_DCHECK(!tonic::CheckAndHandleError(namespace_type)); + Dart_Handle namespace_field = + Dart_GetField(namespace_type, ToDart("_namespace")); + FML_DCHECK(!tonic::CheckAndHandleError(namespace_field)); + uint64_t fdio_ns_ptr; + Dart_Handle result = Dart_IntegerToUint64(namespace_field, &fdio_ns_ptr); + FML_DCHECK(!tonic::CheckAndHandleError(result)); + + return reinterpret_cast(fdio_ns_ptr); +} + +zx_status_t FdFromPath(const char* path, fml::UniqueFD& fd) { + fml::UniqueFD dir_fd(fdio_ns_opendir(GetNamespace())); + if (!dir_fd.is_valid()) { + // TODO: can we return errno? + return ZX_ERR_IO; + } + if (path != nullptr && *path == '/') { + path++; + } + int raw_fd; + if (zx_status_t status = fdio_open3_fd_at( + dir_fd.get(), path, uint64_t{fuchsia::io::PERM_READABLE}, &raw_fd); + status != ZX_OK) { + return status; + } + fd.reset(raw_fd); + return ZX_OK; +} + +} // namespace + +IMPLEMENT_WRAPPERTYPEINFO(zircon, System); + +Dart_Handle System::ChannelCreate(uint32_t options) { + zx_handle_t out0 = 0, out1 = 0; + zx_status_t status = zx_channel_create(options, &out0, &out1); + if (status != ZX_OK) { + return ConstructDartObject(kHandlePairResult, ToDart(status)); + } else { + return ConstructDartObject(kHandlePairResult, ToDart(status), + ToDart(Handle::Create(out0)), + ToDart(Handle::Create(out1))); + } +} + +zx_status_t System::ConnectToService(std::string path, + fml::RefPtr channel) { + return fdio_ns_service_connect(GetNamespace(), path.c_str(), + channel->ReleaseHandle()); +} + +Dart_Handle System::ChannelFromFile(std::string path) { + fml::UniqueFD fd; + if (zx_status_t status = FdFromPath(path.c_str(), fd); status != ZX_OK) { + return ConstructDartObject(kHandleResult, ToDart(status)); + } + + zx::handle handle; + if (zx_status_t status = + fdio_fd_transfer(fd.release(), handle.reset_and_get_address()); + status != ZX_OK) { + return ConstructDartObject(kHandleResult, ToDart(status)); + } + zx_info_handle_basic_t info; + if (zx_status_t status = handle.get_info(ZX_INFO_HANDLE_BASIC, &info, + sizeof(info), nullptr, nullptr); + status != ZX_OK) { + return ConstructDartObject(kHandleResult, ToDart(status)); + } + if (info.type != ZX_OBJ_TYPE_CHANNEL) { + return ConstructDartObject(kHandleResult, ToDart(ZX_ERR_WRONG_TYPE)); + } + + return ConstructDartObject(kHandleResult, ToDart(ZX_OK), + ToDart(Handle::Create(handle.release()))); +} + +zx_status_t System::ChannelWrite(fml::RefPtr channel, + const tonic::DartByteData& data, + std::vector handles) { + if (!channel || !channel->is_valid()) { + data.Release(); + return ZX_ERR_BAD_HANDLE; + } + + std::vector zx_handles; + for (Handle* handle : handles) { + zx_handles.push_back(handle->handle()); + } + + zx_status_t status = zx_channel_write(channel->handle(), 0, data.data(), + data.length_in_bytes(), + zx_handles.data(), zx_handles.size()); + // Handles are always consumed. + for (Handle* handle : handles) { + handle->ReleaseHandle(); + } + + data.Release(); + return status; +} + +zx_status_t System::ChannelWriteEtc( + fml::RefPtr channel, + const tonic::DartByteData& data, + std::vector handle_dispositions) { + if (!channel || !channel->is_valid()) { + data.Release(); + return ZX_ERR_BAD_HANDLE; + } + + std::vector zx_handle_dispositions; + for (HandleDisposition* handle : handle_dispositions) { + FML_DCHECK(handle->result() == ZX_OK); + zx_handle_dispositions.push_back({.operation = handle->operation(), + .handle = handle->handle()->handle(), + .type = handle->type(), + .rights = handle->rights(), + .result = ZX_OK}); + } + + zx_status_t status = zx_channel_write_etc( + channel->handle(), 0, data.data(), data.length_in_bytes(), + zx_handle_dispositions.data(), zx_handle_dispositions.size()); + + for (size_t i = 0; i < handle_dispositions.size(); ++i) { + handle_dispositions[i]->set_result(zx_handle_dispositions[i].result); + + // Handles that are not copied (i.e. moved) are always consumed. + if (handle_dispositions[i]->operation() != ZX_HANDLE_OP_DUPLICATE) { + handle_dispositions[i]->handle()->ReleaseHandle(); + } + } + + data.Release(); + return status; +} + +Dart_Handle System::ChannelQueryAndRead(fml::RefPtr channel) { + if (!channel || !channel->is_valid()) { + return ConstructDartObject(kReadResult, ToDart(ZX_ERR_BAD_HANDLE)); + } + + uint32_t actual_bytes = 0; + uint32_t actual_handles = 0; + + // Query the size of the next message. + zx_status_t status = zx_channel_read(channel->handle(), 0, nullptr, nullptr, + 0, 0, &actual_bytes, &actual_handles); + if (status != ZX_ERR_BUFFER_TOO_SMALL) { + // An empty message or an error. + return ConstructDartObject(kReadResult, ToDart(status)); + } + + // Allocate space for the bytes and handles. + ByteDataScope bytes(actual_bytes); + FML_DCHECK(bytes.is_valid()); + std::vector handles(actual_handles); + + // Make the call to actually get the message. + status = zx_channel_read(channel->handle(), 0, bytes.data(), handles.data(), + bytes.size(), handles.size(), &actual_bytes, + &actual_handles); + FML_DCHECK(status != ZX_OK || bytes.size() == actual_bytes); + + bytes.Release(); + + if (status == ZX_OK) { + FML_DCHECK(handles.size() == actual_handles); + + // return a ReadResult object. + return ConstructDartObject(kReadResult, ToDart(status), bytes.dart_handle(), + ToDart(actual_bytes), MakeHandleList(handles)); + } else { + return ConstructDartObject(kReadResult, ToDart(status)); + } +} + +Dart_Handle System::ChannelQueryAndReadEtc(fml::RefPtr channel) { + if (!channel || !channel->is_valid()) { + return ConstructDartObject(kReadEtcResult, ToDart(ZX_ERR_BAD_HANDLE)); + } + + uint32_t actual_bytes = 0; + uint32_t actual_handles = 0; + + // Query the size of the next message. + zx_status_t status = zx_channel_read(channel->handle(), 0, nullptr, nullptr, + 0, 0, &actual_bytes, &actual_handles); + if (status != ZX_ERR_BUFFER_TOO_SMALL) { + // An empty message or an error. + return ConstructDartObject(kReadEtcResult, ToDart(status)); + } + + // Allocate space for the bytes and handles. + ByteDataScope bytes(actual_bytes); + FML_DCHECK(bytes.is_valid()); + std::vector handles(actual_handles); + + // Make the call to actually get the message. + status = zx_channel_read_etc(channel->handle(), 0, bytes.data(), + handles.data(), bytes.size(), handles.size(), + &actual_bytes, &actual_handles); + FML_DCHECK(status != ZX_OK || bytes.size() == actual_bytes); + + bytes.Release(); + + if (status == ZX_OK) { + FML_DCHECK(handles.size() == actual_handles); + + // return a ReadResult object. + return ConstructDartObject(kReadEtcResult, ToDart(status), + bytes.dart_handle(), ToDart(actual_bytes), + MakeHandleInfoList(handles)); + } else { + return ConstructDartObject(kReadEtcResult, ToDart(status)); + } +} + +Dart_Handle System::EventpairCreate(uint32_t options) { + zx_handle_t out0 = 0, out1 = 0; + zx_status_t status = zx_eventpair_create(0, &out0, &out1); + if (status != ZX_OK) { + return ConstructDartObject(kHandlePairResult, ToDart(status)); + } else { + return ConstructDartObject(kHandlePairResult, ToDart(status), + ToDart(Handle::Create(out0)), + ToDart(Handle::Create(out1))); + } +} + +Dart_Handle System::SocketCreate(uint32_t options) { + zx_handle_t out0 = 0, out1 = 0; + zx_status_t status = zx_socket_create(options, &out0, &out1); + if (status != ZX_OK) { + return ConstructDartObject(kHandlePairResult, ToDart(status)); + } else { + return ConstructDartObject(kHandlePairResult, ToDart(status), + ToDart(Handle::Create(out0)), + ToDart(Handle::Create(out1))); + } +} + +Dart_Handle System::SocketWrite(fml::RefPtr socket, + const tonic::DartByteData& data, + int options) { + if (!socket || !socket->is_valid()) { + data.Release(); + return ConstructDartObject(kWriteResult, ToDart(ZX_ERR_BAD_HANDLE)); + } + + size_t actual; + zx_status_t status = zx_socket_write(socket->handle(), options, data.data(), + data.length_in_bytes(), &actual); + data.Release(); + return ConstructDartObject(kWriteResult, ToDart(status), ToDart(actual)); +} + +Dart_Handle System::SocketRead(fml::RefPtr socket, size_t size) { + if (!socket || !socket->is_valid()) { + return ConstructDartObject(kReadResult, ToDart(ZX_ERR_BAD_HANDLE)); + } + + ByteDataScope bytes(size); + size_t actual; + zx_status_t status = + zx_socket_read(socket->handle(), 0, bytes.data(), size, &actual); + bytes.Release(); + if (status == ZX_OK) { + FML_DCHECK(actual <= size); + return ConstructDartObject(kReadResult, ToDart(status), bytes.dart_handle(), + ToDart(actual)); + } + + return ConstructDartObject(kReadResult, ToDart(status)); +} + +Dart_Handle System::VmoCreate(uint64_t size, uint32_t options) { + zx_handle_t vmo = ZX_HANDLE_INVALID; + zx_status_t status = zx_vmo_create(size, options, &vmo); + if (status != ZX_OK) { + return ConstructDartObject(kHandleResult, ToDart(status)); + } else { + return ConstructDartObject(kHandleResult, ToDart(status), + ToDart(Handle::Create(vmo))); + } +} + +Dart_Handle System::VmoFromFile(std::string path) { + fml::UniqueFD fd; + if (zx_status_t status = FdFromPath(path.c_str(), fd); status != ZX_OK) { + return ConstructDartObject(kHandleResult, ToDart(status)); + } + + struct stat stat_struct; + if (fstat(fd.get(), &stat_struct) != 0) { + // TODO: can we return errno? + return ConstructDartObject(kFromFileResult, ToDart(ZX_ERR_IO)); + } + zx::vmo vmo; + if (zx_status_t status = + fdio_get_vmo_clone(fd.get(), vmo.reset_and_get_address()); + status != ZX_OK) { + return ConstructDartObject(kFromFileResult, ToDart(status)); + } + + return ConstructDartObject(kFromFileResult, ToDart(ZX_OK), + ToDart(Handle::Create(vmo.release())), + ToDart(stat_struct.st_size)); +} + +Dart_Handle System::VmoGetSize(fml::RefPtr vmo) { + if (!vmo || !vmo->is_valid()) { + return ConstructDartObject(kGetSizeResult, ToDart(ZX_ERR_BAD_HANDLE)); + } + + uint64_t size; + zx_status_t status = zx_vmo_get_size(vmo->handle(), &size); + + return ConstructDartObject(kGetSizeResult, ToDart(status), ToDart(size)); +} + +zx_status_t System::VmoSetSize(fml::RefPtr vmo, uint64_t size) { + if (!vmo || !vmo->is_valid()) { + return ZX_ERR_BAD_HANDLE; + } + return zx_vmo_set_size(vmo->handle(), size); +} + +zx_status_t System::VmoWrite(fml::RefPtr vmo, + uint64_t offset, + const tonic::DartByteData& data) { + if (!vmo || !vmo->is_valid()) { + data.Release(); + return ZX_ERR_BAD_HANDLE; + } + + zx_status_t status = + zx_vmo_write(vmo->handle(), data.data(), offset, data.length_in_bytes()); + + data.Release(); + return status; +} + +Dart_Handle System::VmoRead(fml::RefPtr vmo, + uint64_t offset, + size_t size) { + if (!vmo || !vmo->is_valid()) { + return ConstructDartObject(kReadResult, ToDart(ZX_ERR_BAD_HANDLE)); + } + + // TODO: constrain size? + ByteDataScope bytes(size); + zx_status_t status = zx_vmo_read(vmo->handle(), bytes.data(), offset, size); + bytes.Release(); + if (status == ZX_OK) { + return ConstructDartObject(kReadResult, ToDart(status), bytes.dart_handle(), + ToDart(size)); + } + return ConstructDartObject(kReadResult, ToDart(status)); +} + +struct SizedRegion { + SizedRegion(void* r, size_t s) : region(r), size(s) {} + void* region; + size_t size; +}; + +void System::VmoMapFinalizer(void* isolate_callback_data, void* peer) { + SizedRegion* r = reinterpret_cast(peer); + zx_vmar_unmap(zx_vmar_root_self(), reinterpret_cast(r->region), + r->size); + delete r; +} + +Dart_Handle System::VmoMap(fml::RefPtr vmo) { + if (!vmo || !vmo->is_valid()) + return ConstructDartObject(kMapResult, ToDart(ZX_ERR_BAD_HANDLE)); + + uint64_t size; + zx_status_t status = zx_vmo_get_size(vmo->handle(), &size); + if (status != ZX_OK) + return ConstructDartObject(kMapResult, ToDart(status)); + + uintptr_t mapped_addr; + status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ, 0, vmo->handle(), + 0, size, &mapped_addr); + if (status != ZX_OK) + return ConstructDartObject(kMapResult, ToDart(status)); + + void* data = reinterpret_cast(mapped_addr); + Dart_Handle object = Dart_NewExternalTypedData(Dart_TypedData_kUint8, data, + static_cast(size)); + FML_DCHECK(!tonic::CheckAndHandleError(object)); + + SizedRegion* r = new SizedRegion(data, size); + Dart_NewFinalizableHandle(object, reinterpret_cast(r), + static_cast(size) + sizeof(*r), + System::VmoMapFinalizer); + + return ConstructDartObject(kMapResult, ToDart(ZX_OK), object); +} + +uint64_t System::ClockGetMonotonic() { + return zx_clock_get_monotonic(); +} + +// clang-format: off + +#define FOR_EACH_STATIC_BINDING(V) \ + V(System, ChannelCreate) \ + V(System, ChannelFromFile) \ + V(System, ChannelWrite) \ + V(System, ChannelWriteEtc) \ + V(System, ChannelQueryAndRead) \ + V(System, ChannelQueryAndReadEtc) \ + V(System, EventpairCreate) \ + V(System, ConnectToService) \ + V(System, SocketCreate) \ + V(System, SocketWrite) \ + V(System, SocketRead) \ + V(System, VmoCreate) \ + V(System, VmoFromFile) \ + V(System, VmoGetSize) \ + V(System, VmoSetSize) \ + V(System, VmoRead) \ + V(System, VmoWrite) \ + V(System, VmoMap) \ + V(System, ClockGetMonotonic) + +// clang-format: on + +// Tonic is missing a comma. +#define DART_REGISTER_NATIVE_STATIC_(CLASS, METHOD) \ + DART_REGISTER_NATIVE_STATIC(CLASS, METHOD), + +FOR_EACH_STATIC_BINDING(DART_NATIVE_CALLBACK_STATIC) + +void System::RegisterNatives(tonic::DartLibraryNatives* natives) { + natives->Register({FOR_EACH_STATIC_BINDING(DART_REGISTER_NATIVE_STATIC_)}); +} + +} // namespace dart +} // namespace zircon diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/system.h b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/system.h new file mode 100644 index 0000000000000000000000000000000000000000..c2dd01c799c4ca85912c1819bff38655db69a553 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/system.h @@ -0,0 +1,75 @@ +// 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_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_SYSTEM_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_SYSTEM_H_ + +#include + +#include "handle.h" +#include "handle_disposition.h" +#include "third_party/dart/runtime/include/dart_api.h" +#include "third_party/tonic/dart_library_natives.h" +#include "third_party/tonic/dart_wrappable.h" +#include "third_party/tonic/typed_data/dart_byte_data.h" + +namespace zircon { +namespace dart { + +class System : public fml::RefCountedThreadSafe, + public tonic::DartWrappable { + DEFINE_WRAPPERTYPEINFO(); + FML_FRIEND_REF_COUNTED_THREAD_SAFE(System); + FML_FRIEND_MAKE_REF_COUNTED(System); + + public: + static Dart_Handle ChannelCreate(uint32_t options); + static Dart_Handle ChannelFromFile(std::string path); + static zx_status_t ChannelWrite(fml::RefPtr channel, + const tonic::DartByteData& data, + std::vector handles); + static zx_status_t ChannelWriteEtc( + fml::RefPtr channel, + const tonic::DartByteData& data, + std::vector handle_dispositions); + // TODO(ianloic): Add ChannelRead + static Dart_Handle ChannelQueryAndRead(fml::RefPtr channel); + static Dart_Handle ChannelQueryAndReadEtc(fml::RefPtr channel); + + static Dart_Handle EventpairCreate(uint32_t options); + + static Dart_Handle SocketCreate(uint32_t options); + static Dart_Handle SocketWrite(fml::RefPtr socket, + const tonic::DartByteData& data, + int options); + static Dart_Handle SocketRead(fml::RefPtr socket, size_t size); + + static Dart_Handle VmoCreate(uint64_t size, uint32_t options); + static Dart_Handle VmoFromFile(std::string path); + static Dart_Handle VmoGetSize(fml::RefPtr vmo); + static zx_status_t VmoSetSize(fml::RefPtr vmo, uint64_t size); + static zx_status_t VmoWrite(fml::RefPtr vmo, + uint64_t offset, + const tonic::DartByteData& data); + static Dart_Handle VmoRead(fml::RefPtr vmo, + uint64_t offset, + size_t size); + + static Dart_Handle VmoMap(fml::RefPtr vmo); + + static uint64_t ClockGetMonotonic(); + + static void RegisterNatives(tonic::DartLibraryNatives* natives); + + static zx_status_t ConnectToService(std::string path, + fml::RefPtr channel); + + private: + static void VmoMapFinalizer(void* isolate_callback_data, void* peer); +}; + +} // namespace dart +} // namespace zircon + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_SYSTEM_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/test/meta/zircon_tests.cml b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/test/meta/zircon_tests.cml new file mode 100644 index 0000000000000000000000000000000000000000..e7faccaece4ed3297d4e67f1d911ef2ba7869355 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/test/meta/zircon_tests.cml @@ -0,0 +1,6 @@ +{ + program: { + data: "data/zircon_tests", + runner: "dart_jit_runner", + }, +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/test/zircon_tests.dart b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/test/zircon_tests.dart new file mode 100644 index 0000000000000000000000000000000000000000..7b2d5befa50b5754d4b1c42dc0cd3f05f9ec8554 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/test/zircon_tests.dart @@ -0,0 +1,607 @@ +// 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. + +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; +import 'dart:zircon'; + +import 'package:async_helper/async_minitest.dart'; + +/// Helper method to turn a [String] into a [ByteData] containing the +/// text of the string encoded as UTF-8. +ByteData utf8Bytes(final String text) { + return ByteData.sublistView(utf8.encode(text)); +} + +// Take from zircon constants in zircon/errors.h, zircon/rights.h, zircon/types.h +abstract class ZX { + ZX._(); + + static const int OK = 0; + static const int KOID_INVALID = 0; + static const int ERR_BAD_HANDLE = -11; + static const int ERR_SHOULD_WAIT = -22; + static const int ERR_PEER_CLOSED = -24; + static const int ERR_ACCESS_DENIED = -30; + static const int EVENTPAIR_PEER_CLOSED = __ZX_OBJECT_PEER_CLOSED; + static const int CHANNEL_READABLE = __ZX_OBJECT_READABLE; + static const int CHANNEL_PEER_CLOSED = __ZX_OBJECT_PEER_CLOSED; + static const int SOCKET_READABLE = __ZX_OBJECT_READABLE; + static const int SOCKET_PEER_CLOSED = __ZX_OBJECT_PEER_CLOSED; + static const int RIGHT_DUPLICATE = 1 << 0; + static const int RIGHT_TRANSFER = 1 << 1; + static const int RIGHT_READ = 1 << 2; + static const int RIGHT_WRITE = 1 << 3; + static const int RIGHT_GET_PROPERTY = 1 << 6; + static const int RIGHT_SET_PROPERTY = 1 << 7; + static const int RIGHT_MAP = 1 << 5; + static const int RIGHT_SIGNAL = 1 << 12; + static const int RIGHT_WAIT = 1 << 14; + static const int RIGHT_INSPECT = 1 << 15; + static const int RIGHT_SAME_RIGHTS = 1 << 31; + static const int RIGHTS_BASIC = RIGHT_TRANSFER | RIGHT_DUPLICATE | RIGHT_WAIT | RIGHT_INSPECT; + static const int RIGHTS_IO = RIGHT_READ | RIGHT_WRITE; + static const int RIGHTS_PROPERTY = RIGHT_GET_PROPERTY | RIGHT_SET_PROPERTY; + static const int DEFAULT_VMO_RIGHTS = + RIGHTS_BASIC | RIGHTS_IO | RIGHTS_PROPERTY | RIGHT_MAP | RIGHT_SIGNAL; + static const int OBJ_TYPE_VMO = 3; + static const int OBJ_TYPE_CHANNEL = 4; + static const int HANDLE_OP_MOVE = 0; + static const int HANDLE_OP_DUPLICATE = 1; + static const int __ZX_OBJECT_READABLE = 1 << 0; + static const int __ZX_OBJECT_PEER_CLOSED = 1 << 2; +} + +void main() { + group('handle', () { + test('create and duplicate handles', () { + final HandlePairResult pair = System.eventpairCreate(); + expect(pair.status, equals(ZX.OK)); + expect(pair.first.isValid, isTrue); + expect(pair.second.isValid, isTrue); + + final Handle duplicate = pair.first.duplicate(ZX.RIGHT_SAME_RIGHTS); + expect(duplicate.isValid, isTrue); + + final Handle failedDuplicate = pair.first.duplicate(-1); + expect(failedDuplicate.isValid, isFalse); + }); + + test('failure invalid rights', () { + final HandleResult vmo = System.vmoCreate(0); + expect(vmo.status, equals(ZX.OK)); + final Handle failedDuplicate = vmo.handle.duplicate(-1); + expect(failedDuplicate.isValid, isFalse); + expect(vmo.handle.isValid, isTrue); + }); + + test('failure invalid handle', () { + final Handle handle = Handle.invalid(); + final Handle duplicate = handle.duplicate(ZX.RIGHT_SAME_RIGHTS); + expect(duplicate.isValid, isFalse); + }); + + test('duplicated handle should have same koid', () { + final HandlePairResult pair = System.eventpairCreate(); + expect(pair.status, equals(ZX.OK)); + expect(pair.first.isValid, isTrue); + expect(pair.second.isValid, isTrue); + + final Handle duplicate = pair.first.duplicate(ZX.RIGHT_SAME_RIGHTS); + expect(duplicate.isValid, isTrue); + + expect(pair.first.koid, duplicate.koid); + }); + + // TODO(fxbug.dev/77599): Simplify once zx_object_get_info is available. + test('reduced rights', () { + // Set up handle. + final HandleResult vmo = System.vmoCreate(2); + expect(vmo.status, equals(ZX.OK)); + + // Duplicate the first handle. + final Handle duplicate = vmo.handle.duplicate(ZX.RIGHTS_BASIC); + expect(duplicate.isValid, isTrue); + + // Write bytes to the original handle. + final ByteData data1 = utf8Bytes('a'); + final int status1 = System.vmoWrite(vmo.handle, 0, data1); + expect(status1, equals(ZX.OK)); + + // Write bytes to the duplicated handle. + final ByteData data2 = utf8Bytes('b'); + final int status2 = System.vmoWrite(duplicate, 1, data2); + expect(status2, equals(ZX.ERR_ACCESS_DENIED)); + + // Read bytes. + final ReadResult readResult = System.vmoRead(vmo.handle, 0, 2); + expect(readResult.status, equals(ZX.OK)); + expect(readResult.numBytes, equals(2)); + expect(readResult.bytes.lengthInBytes, equals(2)); + expect(readResult.bytesAsUTF8String(), equals('a\x00')); + }); + + test('create and replace handles', () { + final HandlePairResult pair = System.eventpairCreate(); + expect(pair.status, equals(ZX.OK)); + expect(pair.first.isValid, isTrue); + expect(pair.second.isValid, isTrue); + + final Handle replaced = pair.first.replace(ZX.RIGHT_SAME_RIGHTS); + expect(replaced.isValid, isTrue); + expect(pair.first.isValid, isFalse); + }); + + test('failure invalid rights', () { + final HandleResult vmo = System.vmoCreate(0); + expect(vmo.status, equals(ZX.OK)); + final Handle failedDuplicate = vmo.handle.replace(-1); + expect(failedDuplicate.isValid, isFalse); + expect(vmo.handle.isValid, isFalse); + }); + + test('failure invalid handle', () { + final Handle handle = Handle.invalid(); + final Handle replaced = handle.replace(ZX.RIGHT_SAME_RIGHTS); + expect(handle.isValid, isFalse); + expect(replaced.isValid, isFalse); + }); + + test('transferred handle should have same koid', () { + final HandlePairResult pair = System.eventpairCreate(); + expect(pair.status, equals(ZX.OK)); + expect(pair.first.isValid, isTrue); + expect(pair.second.isValid, isTrue); + + final int koid = pair.first.koid; + final Handle replaced = pair.first.replace(ZX.RIGHT_SAME_RIGHTS); + expect(replaced.isValid, isTrue); + + expect(koid, replaced.koid); + }); + + // TODO(fxbug.dev/77599): Simplify once zx_object_get_info is available. + test('reduced rights', () { + // Set up handle. + final HandleResult vmo = System.vmoCreate(2); + expect(vmo.status, equals(ZX.OK)); + + // Replace the first handle. + final Handle duplicate = vmo.handle.replace(ZX.RIGHTS_BASIC | ZX.RIGHT_READ); + expect(duplicate.isValid, isTrue); + + // Write bytes to the original handle. + final ByteData data1 = utf8Bytes('a'); + final int status1 = System.vmoWrite(vmo.handle, 0, data1); + expect(status1, equals(ZX.ERR_BAD_HANDLE)); + + // Write bytes to the duplicated handle. + final ByteData data2 = utf8Bytes('b'); + final int status2 = System.vmoWrite(duplicate, 1, data2); + expect(status2, equals(ZX.ERR_ACCESS_DENIED)); + + // Read bytes. + final ReadResult readResult = System.vmoRead(duplicate, 0, 2); + expect(readResult.status, equals(ZX.OK)); + expect(readResult.numBytes, equals(2)); + expect(readResult.bytes.lengthInBytes, equals(2)); + expect(readResult.bytesAsUTF8String(), equals('\x00\x00')); + }); + + test('cache koid and invalidate', () { + final HandleResult vmo = System.vmoCreate(0); + expect(vmo.status, equals(ZX.OK)); + int originalKoid = vmo.handle.koid; + expect(originalKoid != ZX.KOID_INVALID, true); + // Cached koid should be same value. + expect(originalKoid, equals(vmo.handle.koid)); + vmo.handle.close(); + // koid should be invalidated. + expect(vmo.handle.koid, equals(ZX.KOID_INVALID)); + }); + + test('store the disposition arguments correctly', () { + final Handle handle = System.channelCreate().first; + final HandleDisposition disposition = HandleDisposition(1, handle, 2, 3); + expect(disposition.operation, equals(1)); + expect(disposition.handle, equals(handle)); + expect(disposition.type, equals(2)); + expect(disposition.rights, equals(3)); + expect(disposition.result, equals(ZX.OK)); + }); + }); + + group('channel', () { + test('create channel', () { + final HandlePairResult pair = System.channelCreate(); + expect(pair.status, equals(ZX.OK)); + expect(pair.first.isValid, isTrue); + expect(pair.second.isValid, isTrue); + }); + + test('close channel', () { + final HandlePairResult pair = System.channelCreate(); + expect(pair.first.close(), equals(0)); + expect(pair.first.isValid, isFalse); + expect(pair.second.isValid, isTrue); + expect(System.channelWrite(pair.first, ByteData(1), []), equals(ZX.ERR_BAD_HANDLE)); + expect(System.channelWrite(pair.second, ByteData(1), []), equals(ZX.ERR_PEER_CLOSED)); + }); + + test('channel bytes', () { + final HandlePairResult pair = System.channelCreate(); + + // When no data is available, ZX.ERR_SHOULD_WAIT is returned. + expect(System.channelQueryAndRead(pair.second).status, equals(ZX.ERR_SHOULD_WAIT)); + + // Write bytes. + final ByteData data = utf8Bytes('Hello, world'); + final int status = System.channelWrite(pair.first, data, []); + expect(status, equals(ZX.OK)); + + // Read bytes. + final ReadResult readResult = System.channelQueryAndRead(pair.second); + expect(readResult.status, equals(ZX.OK)); + expect(readResult.numBytes, equals(data.lengthInBytes)); + expect(readResult.bytes.lengthInBytes, equals(data.lengthInBytes)); + expect(readResult.bytesAsUTF8String(), equals('Hello, world')); + expect(readResult.handles.length, equals(0)); + }); + + test('channel handles', () { + final HandlePairResult pair = System.channelCreate(); + final ByteData data = utf8Bytes(''); + final HandlePairResult eventPair = System.eventpairCreate(); + final int status = System.channelWrite(pair.first, data, [eventPair.first]); + expect(status, equals(ZX.OK)); + expect(eventPair.first.isValid, isFalse); + + final ReadResult readResult = System.channelQueryAndRead(pair.second); + expect(readResult.status, equals(ZX.OK)); + expect(readResult.numBytes, equals(0)); + expect(readResult.bytes.lengthInBytes, equals(0)); + expect(readResult.bytesAsUTF8String(), equals('')); + expect(readResult.handles.length, equals(1)); + expect(readResult.handles[0].isValid, isTrue); + }); + + test('async wait channel read', () async { + final HandlePairResult pair = System.channelCreate(); + final Completer> completer = Completer>(); + pair.first.asyncWait(ZX.CHANNEL_READABLE, (int status, int pending) { + completer.complete([status, pending]); + }); + + expect(completer.isCompleted, isFalse); + + System.channelWrite(pair.second, utf8Bytes('Hi'), []); + + final List result = await completer.future; + expect(result[0], equals(ZX.OK)); // status + expect(result[1] & ZX.CHANNEL_READABLE, equals(ZX.CHANNEL_READABLE)); // pending + }); + + test('async wait channel closed', () async { + final HandlePairResult pair = System.channelCreate(); + final Completer completer = Completer(); + pair.first.asyncWait(ZX.CHANNEL_PEER_CLOSED, (int status, int pending) { + completer.complete(status); + }); + + expect(completer.isCompleted, isFalse); + + pair.second.close(); + + final int status = await completer.future; + expect(status, equals(ZX.OK)); + }); + }); + + group('channel etc functions', () { + test('moved handle', () { + final HandlePairResult pair = System.channelCreate(); + final ByteData data = utf8Bytes(''); + final HandlePairResult transferred = System.channelCreate(); + + final HandleDisposition disposition = HandleDisposition( + ZX.HANDLE_OP_MOVE, + transferred.first, + ZX.OBJ_TYPE_CHANNEL, + ZX.RIGHTS_IO, + ); + final int status = System.channelWriteEtc(pair.first, data, [disposition]); + expect(status, equals(ZX.OK)); + expect(disposition.result, equals(ZX.OK)); + expect(transferred.first.isValid, isFalse); + + final ReadEtcResult readResult = System.channelQueryAndReadEtc(pair.second); + expect(readResult.status, equals(ZX.OK)); + expect(readResult.numBytes, equals(0)); + expect(readResult.bytes.lengthInBytes, equals(0)); + expect(readResult.bytesAsUTF8String(), equals('')); + expect(readResult.handleInfos.length, equals(1)); + final HandleInfo handleInfo = readResult.handleInfos[0]; + expect(handleInfo.handle.isValid, isTrue); + expect(handleInfo.type, equals(ZX.OBJ_TYPE_CHANNEL)); + expect(handleInfo.rights, equals(ZX.RIGHTS_IO)); + }); + + test('copied handle', () { + final HandlePairResult pair = System.channelCreate(); + final ByteData data = utf8Bytes(''); + final HandleResult vmo = System.vmoCreate(0); + + final HandleDisposition disposition = HandleDisposition( + ZX.HANDLE_OP_DUPLICATE, + vmo.handle, + ZX.OBJ_TYPE_VMO, + ZX.RIGHT_SAME_RIGHTS, + ); + final int status = System.channelWriteEtc(pair.first, data, [disposition]); + expect(status, equals(ZX.OK)); + expect(disposition.result, equals(ZX.OK)); + expect(vmo.handle.isValid, isTrue); + + final ReadEtcResult readResult = System.channelQueryAndReadEtc(pair.second); + expect(readResult.status, equals(ZX.OK)); + expect(readResult.numBytes, equals(0)); + expect(readResult.bytes.lengthInBytes, equals(0)); + expect(readResult.bytesAsUTF8String(), equals('')); + expect(readResult.handleInfos.length, equals(1)); + final HandleInfo handleInfo = readResult.handleInfos[0]; + expect(handleInfo.handle.isValid, isTrue); + expect(handleInfo.type, equals(ZX.OBJ_TYPE_VMO)); + expect(handleInfo.rights, equals(ZX.DEFAULT_VMO_RIGHTS)); + }); + + test('closed handle should error', () { + final HandlePairResult pair = System.channelCreate(); + final ByteData data = utf8Bytes(''); + final HandlePairResult closed = System.channelCreate(); + + final HandleDisposition disposition = HandleDisposition( + ZX.HANDLE_OP_MOVE, + closed.first, + ZX.OBJ_TYPE_CHANNEL, + ZX.RIGHT_SAME_RIGHTS, + ); + closed.first.close(); + final int status = System.channelWriteEtc(pair.first, data, [disposition]); + expect(status, equals(ZX.ERR_BAD_HANDLE)); + expect(disposition.result, equals(ZX.ERR_BAD_HANDLE)); + expect(closed.first.isValid, isFalse); + + final ReadEtcResult readResult = System.channelQueryAndReadEtc(pair.second); + expect(readResult.status, equals(ZX.ERR_SHOULD_WAIT)); + }); + + test('multiple handles', () { + final HandlePairResult pair = System.channelCreate(); + final ByteData data = utf8Bytes(''); + final HandlePairResult transferred = System.channelCreate(); + final HandleResult vmo = System.vmoCreate(0); + + final List dispositions = [ + HandleDisposition(ZX.HANDLE_OP_MOVE, transferred.first, ZX.OBJ_TYPE_CHANNEL, ZX.RIGHTS_IO), + HandleDisposition( + ZX.HANDLE_OP_DUPLICATE, + vmo.handle, + ZX.OBJ_TYPE_VMO, + ZX.RIGHT_SAME_RIGHTS, + ), + ]; + final int status = System.channelWriteEtc(pair.first, data, dispositions); + expect(status, equals(ZX.OK)); + expect(dispositions[0].result, equals(ZX.OK)); + expect(dispositions[1].result, equals(ZX.OK)); + expect(transferred.first.isValid, isFalse); + expect(vmo.handle.isValid, isTrue); + + final ReadEtcResult readResult = System.channelQueryAndReadEtc(pair.second); + expect(readResult.status, equals(ZX.OK)); + expect(readResult.numBytes, equals(0)); + expect(readResult.bytes.lengthInBytes, equals(0)); + expect(readResult.bytesAsUTF8String(), equals('')); + + expect(readResult.handleInfos.length, equals(2)); + final HandleInfo handleInfo = readResult.handleInfos[0]; + expect(handleInfo.handle.isValid, isTrue); + expect(handleInfo.type, equals(ZX.OBJ_TYPE_CHANNEL)); + expect(handleInfo.rights, equals(ZX.RIGHTS_IO)); + final HandleInfo vmoInfo = readResult.handleInfos[1]; + expect(vmoInfo.handle.isValid, isTrue); + expect(vmoInfo.type, equals(ZX.OBJ_TYPE_VMO)); + expect(vmoInfo.rights, equals(ZX.DEFAULT_VMO_RIGHTS)); + }); + }); + + group('eventpair', () { + test('create', () { + final HandlePairResult pair = System.eventpairCreate(); + expect(pair.status, equals(ZX.OK)); + expect(pair.first.isValid, isTrue); + expect(pair.second.isValid, isTrue); + }); + + test('duplicate', () { + final HandlePairResult pair = System.eventpairCreate(); + expect(pair.status, equals(ZX.OK)); + expect(pair.first.isValid, isTrue); + expect(pair.second.isValid, isTrue); + + expect(pair.first.duplicate(ZX.RIGHT_SAME_RIGHTS).isValid, isTrue); + expect(pair.second.duplicate(ZX.RIGHT_SAME_RIGHTS).isValid, isTrue); + }); + + test('close', () { + final HandlePairResult pair = System.eventpairCreate(); + expect(pair.first.close(), equals(0)); + expect(pair.first.isValid, isFalse); + expect(pair.second.isValid, isTrue); + + expect(pair.second.close(), equals(0)); + expect(pair.second.isValid, isFalse); + }); + + test('async wait peer closed', () async { + final HandlePairResult pair = System.eventpairCreate(); + final Completer completer = Completer(); + pair.first.asyncWait(ZX.EVENTPAIR_PEER_CLOSED, (int status, int pending) { + completer.complete(status); + }); + + expect(completer.isCompleted, isFalse); + pair.second.close(); + + final int status = await completer.future; + expect(status, equals(ZX.OK)); + }); + }); + + // NOTE: This only tests stream sockets. + // We should add tests for datagram sockets. + group('socket', () { + test('create socket', () { + final HandlePairResult pair = System.socketCreate(); + expect(pair.status, equals(ZX.OK)); + expect(pair.first.isValid, isTrue); + expect(pair.second.isValid, isTrue); + }); + + test('close socket', () { + final HandlePairResult pair = System.socketCreate(); + expect(pair.first.close(), equals(0)); + expect(pair.first.isValid, isFalse); + expect(pair.second.isValid, isTrue); + final WriteResult firstResult = System.socketWrite(pair.first, ByteData(1), 0); + expect(firstResult.status, equals(ZX.ERR_BAD_HANDLE)); + final WriteResult secondResult = System.socketWrite(pair.second, ByteData(1), 0); + expect(secondResult.status, equals(ZX.ERR_PEER_CLOSED)); + }); + + test('read write socket', () { + final HandlePairResult pair = System.socketCreate(); + + // When no data is available, ZX.ERR_SHOULD_WAIT is returned. + expect(System.socketRead(pair.second, 1).status, equals(ZX.ERR_SHOULD_WAIT)); + + final ByteData data = utf8Bytes('Hello, world'); + final WriteResult writeResult = System.socketWrite(pair.first, data, 0); + expect(writeResult.status, equals(ZX.OK)); + + final ReadResult readResult = System.socketRead(pair.second, data.lengthInBytes); + expect(readResult.status, equals(ZX.OK)); + expect(readResult.numBytes, equals(data.lengthInBytes)); + expect(readResult.bytes.lengthInBytes, equals(data.lengthInBytes)); + expect(readResult.bytesAsUTF8String(), equals('Hello, world')); + }); + + test('partial read socket', () { + final HandlePairResult pair = System.socketCreate(); + final ByteData data = utf8Bytes('Hello, world'); + final WriteResult writeResult = System.socketWrite(pair.first, data, 0); + expect(writeResult.status, equals(ZX.OK)); + + const int shortLength = 'Hello'.length; + final ReadResult shortReadResult = System.socketRead(pair.second, shortLength); + expect(shortReadResult.status, equals(ZX.OK)); + expect(shortReadResult.numBytes, equals(shortLength)); + expect(shortReadResult.bytes.lengthInBytes, equals(shortLength)); + expect(shortReadResult.bytesAsUTF8String(), equals('Hello')); + + final int longLength = data.lengthInBytes * 2; + final ReadResult longReadResult = System.socketRead(pair.second, longLength); + expect(longReadResult.status, equals(ZX.OK)); + expect(longReadResult.numBytes, equals(data.lengthInBytes - shortLength)); + expect(longReadResult.bytes.lengthInBytes, equals(longLength)); + expect(longReadResult.bytesAsUTF8String(), equals(', world')); + }); + + test('partial write socket', () { + final HandlePairResult pair = System.socketCreate(); + final WriteResult writeResult1 = System.socketWrite(pair.first, utf8Bytes('Hello, '), 0); + expect(writeResult1.status, equals(ZX.OK)); + final WriteResult writeResult2 = System.socketWrite(pair.first, utf8Bytes('world'), 0); + expect(writeResult2.status, equals(ZX.OK)); + + final ReadResult readResult = System.socketRead(pair.second, 100); + expect(readResult.status, equals(ZX.OK)); + expect(readResult.numBytes, equals('Hello, world'.length)); + expect(readResult.bytes.lengthInBytes, equals(100)); + expect(readResult.bytesAsUTF8String(), equals('Hello, world')); + }); + + test('async wait socket read', () async { + final HandlePairResult pair = System.socketCreate(); + final Completer completer = Completer(); + pair.first.asyncWait(ZX.SOCKET_READABLE, (int status, int pending) { + completer.complete(status); + }); + + expect(completer.isCompleted, isFalse); + + System.socketWrite(pair.second, utf8Bytes('Hi'), 0); + + final int status = await completer.future; + expect(status, equals(ZX.OK)); + }); + + test('async wait socket closed', () async { + final HandlePairResult pair = System.socketCreate(); + final Completer completer = Completer(); + pair.first.asyncWait(ZX.SOCKET_PEER_CLOSED, (int status, int pending) { + completer.complete(status); + }); + + expect(completer.isCompleted, isFalse); + + pair.second.close(); + + final int status = await completer.future; + expect(status, equals(ZX.OK)); + }); + }); + + group('vmo', () { + test('fromFile', () { + const String fuchsia = 'Fuchsia'; + File f = + File('tmp/testdata') + ..createSync() + ..writeAsStringSync(fuchsia); + String readFuchsia = f.readAsStringSync(); + expect(readFuchsia, equals(fuchsia)); + + FromFileResult fileResult = System.vmoFromFile('tmp/testdata'); + expect(fileResult.status, equals(ZX.OK)); + MapResult mapResult = System.vmoMap(fileResult.handle); + expect(mapResult.status, equals(ZX.OK)); + Uint8List fileData = mapResult.data.asUnmodifiableView(); + String fileString = utf8.decode(fileData.sublist(0, fileResult.numBytes)); + expect(fileString, equals(fuchsia)); + }); + + test('duplicate', () { + const String fuchsia = 'Fuchsia'; + Uint8List data = Uint8List.fromList(fuchsia.codeUnits); + HandleResult createResult = System.vmoCreate(data.length); + expect(createResult.status, equals(ZX.OK)); + int writeResult = System.vmoWrite(createResult.handle, 0, data.buffer.asByteData()); + expect(writeResult, equals(ZX.OK)); + Handle duplicate = createResult.handle.duplicate( + ZX.RIGHTS_BASIC | ZX.RIGHT_READ | ZX.RIGHT_MAP, + ); + expect(duplicate.isValid, isTrue); + + // Read from the duplicate. + MapResult mapResult = System.vmoMap(duplicate); + expect(mapResult.status, equals(ZX.OK)); + Uint8List vmoData = mapResult.data.asUnmodifiableView(); + String vmoString = utf8.decode(vmoData.sublist(0, data.length)); + expect(vmoString, equals(fuchsia)); + }); + }); +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..b98973a1d022146eb074d2c884356eea04fe4d3b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/BUILD.gn @@ -0,0 +1,33 @@ +# 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. + +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") + +config("zircon_ffi_config") { + include_dirs = [ "." ] +} + +shared_library("zircon_ffi") { + public_configs = [ ":zircon_ffi_config" ] + + sources = [ + "basic_types.cc", + "basic_types.h", + "channel.cc", + "channel.h", + "clock.cc", + "clock.h", + "dart_dl.cc", + "dart_dl.h", + "handle.cc", + "handle.h", + "macros.h", + ] + + deps = [ + "$dart_src/runtime:dart_api", + "${fuchsia_sdk}/pkg/zx", + "//flutter/fml", + ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/basic_types.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/basic_types.cc new file mode 100644 index 0000000000000000000000000000000000000000..32848cf14b326c0b4dac61a43e99a82b9990df23 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/basic_types.cc @@ -0,0 +1,32 @@ +// 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 "basic_types.h" + +#include +#include + +#include "flutter/fml/logging.h" + +zircon_dart_byte_array_t* zircon_dart_byte_array_create(uint32_t size) { + zircon_dart_byte_array_t* arr = static_cast( + malloc(sizeof(zircon_dart_byte_array_t))); + arr->length = size; + arr->data = static_cast(malloc(size * sizeof(uint8_t))); + return arr; +} + +void zircon_dart_byte_array_set_value(zircon_dart_byte_array_t* arr, + uint32_t index, + uint8_t value) { + FML_CHECK(arr); + FML_CHECK(arr->length > index); + arr->data[index] = value; +} + +void zircon_dart_byte_array_free(zircon_dart_byte_array_t* arr) { + FML_CHECK(arr); + free(arr->data); + free(arr); +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/basic_types.h b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/basic_types.h new file mode 100644 index 0000000000000000000000000000000000000000..153e77e3519f8747a448e81b7184d1b71e6dfc74 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/basic_types.h @@ -0,0 +1,36 @@ +// 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_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_BASIC_TYPES_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_BASIC_TYPES_H_ + +#include "macros.h" + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct zircon_dart_byte_array_t { + uint8_t* data; + uint32_t length; +} zircon_dart_byte_array_t; + +ZIRCON_FFI_EXPORT zircon_dart_byte_array_t* zircon_dart_byte_array_create( + uint32_t size); + +ZIRCON_FFI_EXPORT void zircon_dart_byte_array_set_value( + zircon_dart_byte_array_t* arr, + uint32_t index, + uint8_t value); + +ZIRCON_FFI_EXPORT void zircon_dart_byte_array_free( + zircon_dart_byte_array_t* arr); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_BASIC_TYPES_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/channel.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/channel.cc new file mode 100644 index 0000000000000000000000000000000000000000..b7a157cdd81ce4db3b35bfca1fdbbf75ce37575c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/channel.cc @@ -0,0 +1,61 @@ +// 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 "channel.h" + +#include "flutter/fml/logging.h" +#include "flutter/fml/macros.h" + +#include +#include + +#include +#include + +static zircon_dart_handle_t* MakeHandle(zx_handle_t handle) { + zircon_dart_handle_t* result = + static_cast(malloc(sizeof(zircon_dart_handle_t))); + result->handle = handle; + return result; +} + +zircon_dart_handle_pair_t* zircon_dart_channel_create(uint32_t options) { + zx_handle_t out0 = 0, out1 = 0; + zx_status_t status = zx_channel_create(options, &out0, &out1); + if (status != ZX_OK) { + return nullptr; + } else { + zircon_dart_handle_pair_t* result = static_cast( + malloc(sizeof(zircon_dart_handle_pair_t))); + result->left = MakeHandle(out0); + result->right = MakeHandle(out1); + return result; + } +} + +int32_t zircon_dart_channel_write(zircon_dart_handle_t* handle, + zircon_dart_byte_array_t* bytes, + zircon_dart_handle_list_t* handles) { + if (!handle || (handle->handle == ZX_HANDLE_INVALID)) { + return ZX_ERR_BAD_HANDLE; + } + + std::vector zx_handles; + std::vector handle_data = + *reinterpret_cast*>(handles->data); + for (auto handle_ptr : handle_data) { + zx_handles.push_back(handle_ptr->handle); + } + + zx_status_t status = + zx_channel_write(handle->handle, 0, bytes->data, bytes->length, + zx_handles.data(), zx_handles.size()); + + // Handles are always consumed. + for (auto handle_ptr : handle_data) { + handle_ptr->handle = ZX_HANDLE_INVALID; + } + + return status; +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/channel.h b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/channel.h new file mode 100644 index 0000000000000000000000000000000000000000..a096d3bd444aa9609fa41498d2573b540f6f731b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/channel.h @@ -0,0 +1,30 @@ +// 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_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_CHANNEL_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_CHANNEL_H_ + +#include "basic_types.h" +#include "handle.h" +#include "macros.h" + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +ZIRCON_FFI_EXPORT zircon_dart_handle_pair_t* zircon_dart_channel_create( + uint32_t options); + +ZIRCON_FFI_EXPORT int32_t zircon_dart_channel_write( + zircon_dart_handle_t* handle, + zircon_dart_byte_array_t* bytes, + zircon_dart_handle_list_t* handles); + +#ifdef __cplusplus +} +#endif + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_CHANNEL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/clock.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/clock.cc new file mode 100644 index 0000000000000000000000000000000000000000..c396d7763de11cc132a683c51fc3d7fb1bda29f4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/clock.cc @@ -0,0 +1,11 @@ +// 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 "clock.h" + +#include + +uint64_t zircon_dart_clock_get_monotonic() { + return zx_clock_get_monotonic(); +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/clock.h b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/clock.h new file mode 100644 index 0000000000000000000000000000000000000000..f7df958f030845793d22990b614e7e6b094cb0cb --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/clock.h @@ -0,0 +1,22 @@ +// 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_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_CLOCK_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_CLOCK_H_ + +#include "macros.h" + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +ZIRCON_FFI_EXPORT uint64_t zircon_dart_clock_get_monotonic(); + +#ifdef __cplusplus +} +#endif + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_CLOCK_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/dart_dl.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/dart_dl.cc new file mode 100644 index 0000000000000000000000000000000000000000..c6a234cdb2c5f656661bf6f15a9e14895d5b667b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/dart_dl.cc @@ -0,0 +1,17 @@ +#include "dart_dl.h" + +#include "flutter/fml/logging.h" +#include "include/dart_api_dl.h" + +int zircon_dart_dl_initialize(void* initialize_api_dl_data) { + if (Dart_InitializeApiDL(initialize_api_dl_data) != 0) { + FML_LOG(ERROR) << "Failed to initialise Dart VM API"; + return -1; + } + // Check symbols used are present + if (Dart_NewFinalizableHandle_DL == NULL) { + FML_LOG(ERROR) << "Unable to find Dart API finalizer symbols."; + return -1; + } + return 1; +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/dart_dl.h b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/dart_dl.h new file mode 100644 index 0000000000000000000000000000000000000000..0bd1e06b7cc1c28a8c3e8712574bbfa2cb8c0ab5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/dart_dl.h @@ -0,0 +1,24 @@ +#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_DART_DL_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_DART_DL_H_ + +#include "macros.h" + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// Initialize Dart API with dynamic linking. +// +// Must be called with `NativeApi.initializeApiDLData` from `dart:ffi`, before +// using other functions. +// +// Returns 1 on success. +ZIRCON_FFI_EXPORT int zircon_dart_dl_initialize(void* initialize_api_dl_data); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_DART_DL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/handle.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/handle.cc new file mode 100644 index 0000000000000000000000000000000000000000..4f296340b50884461870cbec0d6ae28b5fa97128 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/handle.cc @@ -0,0 +1,109 @@ +// 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 "handle.h" + +#include "flutter/fml/logging.h" + +#include +#include + +#include + +static void HandleFree(void* isolate_callback_data, void* peer) { + FML_CHECK(peer); + zircon_dart_handle_t* handle = reinterpret_cast(peer); + zircon_dart_handle_free(handle); +} + +static void HandlePairFree(void* isolate_callback_data, void* peer) { + FML_CHECK(peer); + zircon_dart_handle_pair_t* handle_pair = + reinterpret_cast(peer); + free(handle_pair); +} + +void zircon_dart_handle_free(zircon_dart_handle_t* handle) { + FML_CHECK(handle); + if (handle->handle != ZX_HANDLE_INVALID) { + zircon_dart_handle_close(handle); + } + free(handle); +} + +int32_t zircon_dart_handle_close(zircon_dart_handle_t* handle) { + FML_CHECK(handle->handle != ZX_HANDLE_INVALID); + zx_status_t status = zx_handle_close(handle->handle); + handle->handle = ZX_HANDLE_INVALID; + if (status == ZX_OK) { + return 1; + } else { + return 0; + } +} + +int32_t zircon_dart_handle_is_valid(zircon_dart_handle_t* handle) { + if (!handle || (handle->handle == ZX_HANDLE_INVALID)) { + return 0; + } else { + return 1; + } +} + +int zircon_dart_handle_attach_finalizer(Dart_Handle object, + void* pointer, + intptr_t external_allocation_size) { + Dart_FinalizableHandle weak_handle = Dart_NewFinalizableHandle_DL( + object, pointer, external_allocation_size, HandleFree); + + if (weak_handle == nullptr) { + FML_LOG(ERROR) << "Unable to attach finalizer: " << std::hex << pointer; + return -1; + } + + return 1; +} + +int zircon_dart_handle_pair_attach_finalizer( + Dart_Handle object, + void* pointer, + intptr_t external_allocation_size) { + Dart_FinalizableHandle weak_handle = Dart_NewFinalizableHandle_DL( + object, pointer, external_allocation_size, HandlePairFree); + + if (weak_handle == nullptr) { + FML_LOG(ERROR) << "Unable to attach finalizer: " << std::hex << pointer; + return -1; + } + + return 1; +} + +// zircon handle list methods. +using HandleVector = std::vector; +using HandleVectorPtr = HandleVector*; + +zircon_dart_handle_list_t* zircon_dart_handle_list_create() { + zircon_dart_handle_list_t* result = static_cast( + malloc(sizeof(zircon_dart_handle_list_t))); + result->size = 0; + result->data = new HandleVector(); + return result; +} + +void zircon_dart_handle_list_append(zircon_dart_handle_list_t* list, + zircon_dart_handle_t* handle) { + FML_CHECK(list); + FML_CHECK(handle); + list->size++; + auto data = reinterpret_cast(list->data); + data->push_back(handle); +} + +void zircon_dart_handle_list_free(zircon_dart_handle_list_t* list) { + auto data = reinterpret_cast(list->data); + data->clear(); + delete data; + free(list); +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/handle.h b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/handle.h new file mode 100644 index 0000000000000000000000000000000000000000..ba0435f2864b7888f2d8a98a3f8219b0fd7fe78e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/handle.h @@ -0,0 +1,83 @@ +// 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_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_HANDLE_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_HANDLE_H_ + +#include "macros.h" + +#include "include/dart_api_dl.h" + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct zircon_dart_handle_t { + uint32_t handle; +} zircon_dart_handle_t; + +typedef struct zircon_dart_handle_pair_t { + zircon_dart_handle_t* left; + zircon_dart_handle_t* right; +} zircon_dart_handle_pair_t; + +typedef struct zircon_dart_handle_list_t { + // data is of type `std::vector*`. + void* data; + uint32_t size; +} zircon_dart_handle_list_t; + +// Creates a list. +ZIRCON_FFI_EXPORT zircon_dart_handle_list_t* zircon_dart_handle_list_create(); + +// Appends to the list. +ZIRCON_FFI_EXPORT void zircon_dart_handle_list_append( + zircon_dart_handle_list_t* list, + zircon_dart_handle_t* handle); + +// Frees the list, all the handles passed here must have been released. +ZIRCON_FFI_EXPORT void zircon_dart_handle_list_free( + zircon_dart_handle_list_t* list); + +// Returns 1 if the handle is valid. +ZIRCON_FFI_EXPORT int32_t zircon_dart_handle_is_valid( + zircon_dart_handle_t* handle); + +// Closes the handle, but doesn't release any ffi-associated memory. Returns 1 +// on success. +ZIRCON_FFI_EXPORT int32_t zircon_dart_handle_close( + zircon_dart_handle_t* handle); + +// Closes the zircon handle if valid and frees the memory. +ZIRCON_FFI_EXPORT void zircon_dart_handle_free(zircon_dart_handle_t* handle); + +// Attach a finalizer for pointer to object, such that `finalizer(pointer)` will +// be called when `object` is collected by the Dart garbage collector. +// +// The external_allocation_size is used by the Dart garbage collector as a hint +// about the size of the external allocation. +// +// Returns 1 on success. + +ZIRCON_FFI_EXPORT int zircon_dart_handle_pair_attach_finalizer( + Dart_Handle object, + void* pointer, + intptr_t external_allocation_size); + +ZIRCON_FFI_EXPORT int zircon_dart_handle_attach_finalizer( + Dart_Handle object, + void* pointer, + intptr_t external_allocation_size); + +// ZIRCON_FFI_EXPORT zircon_dart_handle_t* zircon_dart_duplicate_handle( +// zircon_dart_handle_t* handle, +// uint32_t rights); + +#ifdef __cplusplus +} +#endif + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_HANDLE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/lib/zircon_ffi.dart b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/lib/zircon_ffi.dart new file mode 100644 index 0000000000000000000000000000000000000000..cc4c86ade2629ff76e36e2143efb6f73af1a8cf2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/lib/zircon_ffi.dart @@ -0,0 +1,320 @@ +// AUTO GENERATED FILE, DO NOT EDIT. +// +// Generated by `package:ffigen`. +import 'dart:ffi' as ffi; + +/// Bindings for `dart:zircon_ffi`. +class ZirconFFIBindings { + /// Holds the symbol lookup function. + final ffi.Pointer Function(String symbolName) _lookup; + + /// The symbols are looked up in [dynamicLibrary]. + ZirconFFIBindings(ffi.DynamicLibrary dynamicLibrary) : _lookup = dynamicLibrary.lookup; + + /// The symbols are looked up with [lookup]. + ZirconFFIBindings.fromLookup( + ffi.Pointer Function(String symbolName) lookup, + ) : _lookup = lookup; + + ffi.Pointer zircon_dart_byte_array_create(int size) { + return _zircon_dart_byte_array_create(size); + } + + late final _zircon_dart_byte_array_create_ptr = + _lookup>( + 'zircon_dart_byte_array_create', + ); + late final _dart_zircon_dart_byte_array_create _zircon_dart_byte_array_create = + _zircon_dart_byte_array_create_ptr.asFunction<_dart_zircon_dart_byte_array_create>(); + + void zircon_dart_byte_array_set_value( + ffi.Pointer arr, + int index, + int value, + ) { + return _zircon_dart_byte_array_set_value(arr, index, value); + } + + late final _zircon_dart_byte_array_set_value_ptr = + _lookup>( + 'zircon_dart_byte_array_set_value', + ); + late final _dart_zircon_dart_byte_array_set_value _zircon_dart_byte_array_set_value = + _zircon_dart_byte_array_set_value_ptr.asFunction<_dart_zircon_dart_byte_array_set_value>(); + + void zircon_dart_byte_array_free(ffi.Pointer arr) { + return _zircon_dart_byte_array_free(arr); + } + + late final _zircon_dart_byte_array_free_ptr = + _lookup>('zircon_dart_byte_array_free'); + late final _dart_zircon_dart_byte_array_free _zircon_dart_byte_array_free = + _zircon_dart_byte_array_free_ptr.asFunction<_dart_zircon_dart_byte_array_free>(); + + ffi.Pointer zircon_dart_handle_list_create() { + return _zircon_dart_handle_list_create(); + } + + late final _zircon_dart_handle_list_create_ptr = + _lookup>( + 'zircon_dart_handle_list_create', + ); + late final _dart_zircon_dart_handle_list_create _zircon_dart_handle_list_create = + _zircon_dart_handle_list_create_ptr.asFunction<_dart_zircon_dart_handle_list_create>(); + + void zircon_dart_handle_list_append( + ffi.Pointer list, + ffi.Pointer handle, + ) { + return _zircon_dart_handle_list_append(list, handle); + } + + late final _zircon_dart_handle_list_append_ptr = + _lookup>( + 'zircon_dart_handle_list_append', + ); + late final _dart_zircon_dart_handle_list_append _zircon_dart_handle_list_append = + _zircon_dart_handle_list_append_ptr.asFunction<_dart_zircon_dart_handle_list_append>(); + + void zircon_dart_handle_list_free(ffi.Pointer list) { + return _zircon_dart_handle_list_free(list); + } + + late final _zircon_dart_handle_list_free_ptr = + _lookup>('zircon_dart_handle_list_free'); + late final _dart_zircon_dart_handle_list_free _zircon_dart_handle_list_free = + _zircon_dart_handle_list_free_ptr.asFunction<_dart_zircon_dart_handle_list_free>(); + + int zircon_dart_handle_is_valid(ffi.Pointer handle) { + return _zircon_dart_handle_is_valid(handle); + } + + late final _zircon_dart_handle_is_valid_ptr = + _lookup>('zircon_dart_handle_is_valid'); + late final _dart_zircon_dart_handle_is_valid _zircon_dart_handle_is_valid = + _zircon_dart_handle_is_valid_ptr.asFunction<_dart_zircon_dart_handle_is_valid>(); + + int zircon_dart_handle_close(ffi.Pointer handle) { + return _zircon_dart_handle_close(handle); + } + + late final _zircon_dart_handle_close_ptr = + _lookup>('zircon_dart_handle_close'); + late final _dart_zircon_dart_handle_close _zircon_dart_handle_close = + _zircon_dart_handle_close_ptr.asFunction<_dart_zircon_dart_handle_close>(); + + void zircon_dart_handle_free(ffi.Pointer handle) { + return _zircon_dart_handle_free(handle); + } + + late final _zircon_dart_handle_free_ptr = _lookup>( + 'zircon_dart_handle_free', + ); + late final _dart_zircon_dart_handle_free _zircon_dart_handle_free = + _zircon_dart_handle_free_ptr.asFunction<_dart_zircon_dart_handle_free>(); + + int zircon_dart_handle_pair_attach_finalizer( + Object object, + ffi.Pointer pointer, + int external_allocation_size, + ) { + return _zircon_dart_handle_pair_attach_finalizer(object, pointer, external_allocation_size); + } + + late final _zircon_dart_handle_pair_attach_finalizer_ptr = + _lookup>( + 'zircon_dart_handle_pair_attach_finalizer', + ); + late final _dart_zircon_dart_handle_pair_attach_finalizer + _zircon_dart_handle_pair_attach_finalizer = + _zircon_dart_handle_pair_attach_finalizer_ptr + .asFunction<_dart_zircon_dart_handle_pair_attach_finalizer>(); + + int zircon_dart_handle_attach_finalizer( + Object object, + ffi.Pointer pointer, + int external_allocation_size, + ) { + return _zircon_dart_handle_attach_finalizer(object, pointer, external_allocation_size); + } + + late final _zircon_dart_handle_attach_finalizer_ptr = + _lookup>( + 'zircon_dart_handle_attach_finalizer', + ); + late final _dart_zircon_dart_handle_attach_finalizer _zircon_dart_handle_attach_finalizer = + _zircon_dart_handle_attach_finalizer_ptr + .asFunction<_dart_zircon_dart_handle_attach_finalizer>(); + + ffi.Pointer zircon_dart_channel_create(int options) { + return _zircon_dart_channel_create(options); + } + + late final _zircon_dart_channel_create_ptr = + _lookup>('zircon_dart_channel_create'); + late final _dart_zircon_dart_channel_create _zircon_dart_channel_create = + _zircon_dart_channel_create_ptr.asFunction<_dart_zircon_dart_channel_create>(); + + int zircon_dart_channel_write( + ffi.Pointer handle, + ffi.Pointer bytes, + ffi.Pointer handles, + ) { + return _zircon_dart_channel_write(handle, bytes, handles); + } + + late final _zircon_dart_channel_write_ptr = + _lookup>('zircon_dart_channel_write'); + late final _dart_zircon_dart_channel_write _zircon_dart_channel_write = + _zircon_dart_channel_write_ptr.asFunction<_dart_zircon_dart_channel_write>(); + + int zircon_dart_clock_get_monotonic() { + return _zircon_dart_clock_get_monotonic(); + } + + late final _zircon_dart_clock_get_monotonic_ptr = + _lookup>( + 'zircon_dart_clock_get_monotonic', + ); + late final _dart_zircon_dart_clock_get_monotonic _zircon_dart_clock_get_monotonic = + _zircon_dart_clock_get_monotonic_ptr.asFunction<_dart_zircon_dart_clock_get_monotonic>(); + + int zircon_dart_dl_initialize(ffi.Pointer initialize_api_dl_data) { + return _zircon_dart_dl_initialize(initialize_api_dl_data); + } + + late final _zircon_dart_dl_initialize_ptr = + _lookup>('zircon_dart_dl_initialize'); + late final _dart_zircon_dart_dl_initialize _zircon_dart_dl_initialize = + _zircon_dart_dl_initialize_ptr.asFunction<_dart_zircon_dart_dl_initialize>(); +} + +final class zircon_dart_byte_array_t extends ffi.Struct { + external ffi.Pointer data; + + @ffi.Uint32() + external int length; +} + +final class zircon_dart_handle_t extends ffi.Struct { + @ffi.Uint32() + external int handle; +} + +final class zircon_dart_handle_pair_t extends ffi.Struct { + external ffi.Pointer left; + + external ffi.Pointer right; +} + +final class zircon_dart_handle_list_t extends ffi.Struct { + external ffi.Pointer data; + + @ffi.Uint32() + external int size; +} + +final class _Dart_Handle extends ffi.Opaque {} + +typedef _c_zircon_dart_byte_array_create = + ffi.Pointer Function(ffi.Uint32 size); + +typedef _dart_zircon_dart_byte_array_create = + ffi.Pointer Function(int size); + +typedef _c_zircon_dart_byte_array_set_value = + ffi.Void Function(ffi.Pointer arr, ffi.Uint32 index, ffi.Uint8 value); + +typedef _dart_zircon_dart_byte_array_set_value = + void Function(ffi.Pointer arr, int index, int value); + +typedef _c_zircon_dart_byte_array_free = + ffi.Void Function(ffi.Pointer arr); + +typedef _dart_zircon_dart_byte_array_free = + void Function(ffi.Pointer arr); + +typedef _c_zircon_dart_handle_list_create = ffi.Pointer Function(); + +typedef _dart_zircon_dart_handle_list_create = ffi.Pointer Function(); + +typedef _c_zircon_dart_handle_list_append = + ffi.Void Function( + ffi.Pointer list, + ffi.Pointer handle, + ); + +typedef _dart_zircon_dart_handle_list_append = + void Function( + ffi.Pointer list, + ffi.Pointer handle, + ); + +typedef _c_zircon_dart_handle_list_free = + ffi.Void Function(ffi.Pointer list); + +typedef _dart_zircon_dart_handle_list_free = + void Function(ffi.Pointer list); + +typedef _c_zircon_dart_handle_is_valid = + ffi.Int32 Function(ffi.Pointer handle); + +typedef _dart_zircon_dart_handle_is_valid = int Function(ffi.Pointer handle); + +typedef _c_zircon_dart_handle_close = ffi.Int32 Function(ffi.Pointer handle); + +typedef _dart_zircon_dart_handle_close = int Function(ffi.Pointer handle); + +typedef _c_zircon_dart_handle_free = ffi.Void Function(ffi.Pointer handle); + +typedef _dart_zircon_dart_handle_free = void Function(ffi.Pointer handle); + +typedef _c_zircon_dart_handle_pair_attach_finalizer = + ffi.Int32 Function( + ffi.Handle object, + ffi.Pointer pointer, + ffi.IntPtr external_allocation_size, + ); + +typedef _dart_zircon_dart_handle_pair_attach_finalizer = + int Function(Object object, ffi.Pointer pointer, int external_allocation_size); + +typedef _c_zircon_dart_handle_attach_finalizer = + ffi.Int32 Function( + ffi.Handle object, + ffi.Pointer pointer, + ffi.IntPtr external_allocation_size, + ); + +typedef _dart_zircon_dart_handle_attach_finalizer = + int Function(Object object, ffi.Pointer pointer, int external_allocation_size); + +typedef _c_zircon_dart_channel_create = + ffi.Pointer Function(ffi.Uint32 options); + +typedef _dart_zircon_dart_channel_create = + ffi.Pointer Function(int options); + +typedef _c_zircon_dart_channel_write = + ffi.Int32 Function( + ffi.Pointer handle, + ffi.Pointer bytes, + ffi.Pointer handles, + ); + +typedef _dart_zircon_dart_channel_write = + int Function( + ffi.Pointer handle, + ffi.Pointer bytes, + ffi.Pointer handles, + ); + +typedef _c_zircon_dart_clock_get_monotonic = ffi.Uint64 Function(); + +typedef _dart_zircon_dart_clock_get_monotonic = int Function(); + +typedef _c_zircon_dart_dl_initialize = + ffi.Int32 Function(ffi.Pointer initialize_api_dl_data); + +typedef _dart_zircon_dart_dl_initialize = + int Function(ffi.Pointer initialize_api_dl_data); diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/macros.h b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/macros.h new file mode 100644 index 0000000000000000000000000000000000000000..7c78e0d6e3d3d65350f8d06abc9e5ee25b695bd5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/macros.h @@ -0,0 +1,10 @@ +// 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_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_MACROS_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_MACROS_H_ + +#define ZIRCON_FFI_EXPORT __attribute__((visibility("default"))) + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_MACROS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/pubspec.yaml b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f1d8c199db0cd48f9b5702fc62576889c08d6989 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon_ffi/pubspec.yaml @@ -0,0 +1,44 @@ +name: zircon_ffi + +environment: + sdk: ^3.7.0-0 + +dependencies: + ffi: ^1.0.0 + +dev_dependencies: + ffigen: ^3.0.0 + lints: ^1.0.1 + +ffigen: + name: ZirconFFIBindings + description: Bindings for `dart:zircon_ffi`. + output: 'lib/zircon_ffi.dart' + headers: + entry-points: + - 'basic_types.h' + - 'channel.h' + - 'clock.h' + - 'dart_dl.h' + - 'handle.h' + functions: + include: + - 'zircon_dart_.*' + macros: + include: + - nothing + enums: + include: + - nothing + unnamed-enums: + include: + - nothing + globals: + include: + - nothing + structs: + include: + - 'zircon_dart_.*' + dependency-only: opaque + compiler-opts: + - '-I../../../../../../third_party/dart/runtime' diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/dart/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..00bd71527b8fb612f7658076fc47049f6ac6c32c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart/BUILD.gn @@ -0,0 +1,429 @@ +# 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. + +import("//flutter/build/dart/rules.gni") +import("//flutter/tools/fuchsia/dart/dart_library.gni") + +application_snapshot("kernel_compiler") { + main_dart = "compiler.dart" + + deps = [ "../flutter/kernel:kernel_platform_files($host_toolchain)" ] + + package_config = rebase_path("$dart_src/.dart_tool/package_config.json") + + training_args = [ + "--train", + rebase_path(main_dart), + ] + + kernel_compiler_files = exec_script("$dart_src/tools/list_dart_files.py", + [ + "absolute", + rebase_path("."), + ], + "list lines") + + kernel_compiler_files += exec_script("$dart_src/tools/list_dart_files.py", + [ + "absolute", + rebase_path("$dart_src/pkg"), + ], + "list lines") + + inputs = kernel_compiler_files +} + +application_snapshot("_list_libraries_kernel") { + visibility = [ ":*" ] + snapshot_kind = "kernel" + main_dart = "$dart_src/pkg/vm/bin/list_libraries.dart" + package_config = rebase_path("$dart_src/.dart_tool/package_config.json") + training_args = [] + output = "$target_gen_dir/list_libraries.dart.dill" +} + +application_snapshot("list_libraries") { + deps = [ ":_list_libraries_kernel" ] + main_dart = "$dart_src/pkg/vm/bin/list_libraries.dart" + package_config = rebase_path("$dart_src/.dart_tool/package_config.json") + training_args = [ + # train against the dill file which is generated for this snapshot. + rebase_path("$target_gen_dir/list_libraries.dart.dill"), + ] +} + +dart_library("async_helper") { + package_root = "$dart_src/pkg/async_helper" + package_name = "async_helper" + + pubspec = "$package_root/pubspec.yaml" + + deps = [ ":expect" ] + + sources = [ + "async_helper.dart", + "async_minitest.dart", + ] +} + +dart_library("expect") { + package_root = "$dart_src/pkg/expect" + package_name = "expect" + + pubspec = "$package_root/pubspec.yaml" + + deps = [] + + sources = [ + "async_helper.dart", + "config.dart", + "expect.dart", + "legacy/async_minitest.dart", + "legacy/minitest.dart", + "minitest.dart", + "static_type_helper.dart", + "variations.dart", + ] +} + +dart_library("meta") { + package_root = "$dart_src/pkg/meta" + package_name = "meta" + + pubspec = "$package_root/pubspec.yaml" + + deps = [] + + sources = [ + "dart2js.dart", + "meta.dart", + "meta_meta.dart", + ] +} + +dart_library("args") { + package_root = "$dart_src/third_party/pkg/core/pkgs/args" + package_name = "args" + + language_version = "3.7" + + deps = [] + + sources = [ + "args.dart", + "command_runner.dart", + "src/allow_anything_parser.dart", + "src/arg_parser.dart", + "src/arg_parser_exception.dart", + "src/arg_results.dart", + "src/help_command.dart", + "src/option.dart", + "src/parser.dart", + "src/usage.dart", + "src/usage_exception.dart", + "src/utils.dart", + ] +} + +dart_library("collection") { + package_root = "$dart_src/third_party/pkg/core/pkgs/collection" + package_name = "collection" + + pubspec = "$package_root/pubspec.yaml" + + deps = [] + + sources = [ + "algorithms.dart", + "collection.dart", + "equality.dart", + "iterable_zip.dart", + "priority_queue.dart", + "src/algorithms.dart", + "src/canonicalized_map.dart", + "src/combined_wrappers/combined_iterable.dart", + "src/combined_wrappers/combined_iterator.dart", + "src/combined_wrappers/combined_list.dart", + "src/combined_wrappers/combined_map.dart", + "src/comparators.dart", + "src/empty_unmodifiable_set.dart", + "src/equality.dart", + "src/equality_map.dart", + "src/equality_set.dart", + "src/functions.dart", + "src/iterable_extensions.dart", + "src/iterable_zip.dart", + "src/list_extensions.dart", + "src/priority_queue.dart", + "src/queue_list.dart", + "src/union_set.dart", + "src/union_set_controller.dart", + "src/unmodifiable_wrappers.dart", + "src/utils.dart", + "src/wrappers.dart", + "wrappers.dart", + ] +} + +dart_library("logging") { + package_root = "$dart_src/third_party/pkg/core/pkgs/logging" + package_name = "logging" + + pubspec = "$package_root/pubspec.yaml" + + deps = [] + + sources = [ + "logging.dart", + "src/level.dart", + "src/log_record.dart", + "src/logger.dart", + ] +} + +dart_library("path") { + package_root = "$dart_src/third_party/pkg/core/pkgs/path" + package_name = "path" + + pubspec = "$package_root/pubspec.yaml" + + deps = [] + + sources = [ + "path.dart", + "src/characters.dart", + "src/context.dart", + "src/internal_style.dart", + "src/parsed_path.dart", + "src/path_exception.dart", + "src/path_map.dart", + "src/path_set.dart", + "src/style.dart", + "src/style/posix.dart", + "src/style/url.dart", + "src/style/windows.dart", + "src/utils.dart", + ] +} + +dart_library("stack_trace") { + package_root = "$dart_src/third_party/pkg/stack_trace" + package_name = "stack_trace" + + pubspec = "$package_root/pubspec.yaml" + + deps = [ ":path" ] + + sources = [ + "src/chain.dart", + "src/frame.dart", + "src/lazy_chain.dart", + "src/lazy_trace.dart", + "src/stack_zone_specification.dart", + "src/trace.dart", + "src/unparsed_frame.dart", + "src/utils.dart", + "src/vm_trace.dart", + "stack_trace.dart", + ] +} + +dart_library("matcher") { + package_root = "$dart_src/third_party/pkg/test/pkgs/matcher" + package_name = "matcher" + + pubspec = "$package_root/pubspec.yaml" + + deps = [ ":stack_trace" ] + + sources = [ + "expect.dart", + "matcher.dart", + "mirror_matchers.dart", + "src/core_matchers.dart", + "src/custom_matcher.dart", + "src/description.dart", + "src/equals_matcher.dart", + "src/error_matchers.dart", + "src/expect/async_matcher.dart", + "src/expect/expect.dart", + "src/expect/expect_async.dart", + "src/expect/future_matchers.dart", + "src/expect/never_called.dart", + "src/expect/prints_matcher.dart", + "src/expect/stream_matcher.dart", + "src/expect/stream_matchers.dart", + "src/expect/throws_matcher.dart", + "src/expect/throws_matchers.dart", + "src/expect/util/placeholder.dart", + "src/expect/util/pretty_print.dart", + "src/feature_matcher.dart", + "src/having_matcher.dart", + "src/interfaces.dart", + "src/iterable_matchers.dart", + "src/map_matchers.dart", + "src/numeric_matchers.dart", + "src/operator_matchers.dart", + "src/order_matchers.dart", + "src/pretty_print.dart", + "src/string_matchers.dart", + "src/type_matcher.dart", + "src/util.dart", + ] +} + +dart_library("quiver") { + package_root = "//third_party/pkg/quiver" + package_name = "quiver" + + pubspec = "$package_root/pubspec.yaml" + + deps = [ + ":matcher", + ":meta", + ] + + sources = [ + "async.dart", + "cache.dart", + "check.dart", + "collection.dart", + "core.dart", + "iterables.dart", + "pattern.dart", + "src/async/collect.dart", + "src/async/concat.dart", + "src/async/countdown_timer.dart", + "src/async/enumerate.dart", + "src/async/future_stream.dart", + "src/async/metronome.dart", + "src/async/stream_buffer.dart", + "src/async/stream_router.dart", + "src/async/string.dart", + "src/cache/cache.dart", + "src/cache/map_cache.dart", + "src/collection/bimap.dart", + "src/collection/delegates/iterable.dart", + "src/collection/delegates/list.dart", + "src/collection/delegates/map.dart", + "src/collection/delegates/queue.dart", + "src/collection/delegates/set.dart", + "src/collection/lru_map.dart", + "src/collection/multimap.dart", + "src/collection/treeset.dart", + "src/collection/utils.dart", + "src/core/hash.dart", + "src/core/optional.dart", + "src/core/utils.dart", + "src/iterables/concat.dart", + "src/iterables/count.dart", + "src/iterables/cycle.dart", + "src/iterables/enumerate.dart", + "src/iterables/generating_iterable.dart", + "src/iterables/infinite_iterable.dart", + "src/iterables/merge.dart", + "src/iterables/min_max.dart", + "src/iterables/partition.dart", + "src/iterables/range.dart", + "src/iterables/zip.dart", + "src/time/clock.dart", + "src/time/duration_unit_constants.dart", + "src/time/util.dart", + "strings.dart", + "testing/async.dart", + "testing/equality.dart", + "testing/src/async/fake_async.dart", + "testing/src/equality/equality.dart", + "testing/src/time/time.dart", + "testing/time.dart", + "time.dart", + ] +} + +dart_library("vector_math") { + package_root = "//flutter/third_party/pkg/vector_math" + package_name = "vector_math" + + pubspec = "$package_root/pubspec.yaml" + + deps = [] + + sources = [ + "hash.dart", + "src/vector_math/aabb2.dart", + "src/vector_math/aabb3.dart", + "src/vector_math/colors.dart", + "src/vector_math/constants.dart", + "src/vector_math/error_helpers.dart", + "src/vector_math/frustum.dart", + "src/vector_math/intersection_result.dart", + "src/vector_math/matrix2.dart", + "src/vector_math/matrix3.dart", + "src/vector_math/matrix4.dart", + "src/vector_math/obb3.dart", + "src/vector_math/opengl.dart", + "src/vector_math/plane.dart", + "src/vector_math/quad.dart", + "src/vector_math/quaternion.dart", + "src/vector_math/ray.dart", + "src/vector_math/sphere.dart", + "src/vector_math/third_party/noise.dart", + "src/vector_math/triangle.dart", + "src/vector_math/utilities.dart", + "src/vector_math/vector.dart", + "src/vector_math/vector2.dart", + "src/vector_math/vector3.dart", + "src/vector_math/vector4.dart", + "src/vector_math_64/aabb2.dart", + "src/vector_math_64/aabb3.dart", + "src/vector_math_64/colors.dart", + "src/vector_math_64/constants.dart", + "src/vector_math_64/error_helpers.dart", + "src/vector_math_64/frustum.dart", + "src/vector_math_64/intersection_result.dart", + "src/vector_math_64/matrix2.dart", + "src/vector_math_64/matrix3.dart", + "src/vector_math_64/matrix4.dart", + "src/vector_math_64/obb3.dart", + "src/vector_math_64/opengl.dart", + "src/vector_math_64/plane.dart", + "src/vector_math_64/quad.dart", + "src/vector_math_64/quaternion.dart", + "src/vector_math_64/ray.dart", + "src/vector_math_64/sphere.dart", + "src/vector_math_64/third_party/noise.dart", + "src/vector_math_64/triangle.dart", + "src/vector_math_64/utilities.dart", + "src/vector_math_64/vector.dart", + "src/vector_math_64/vector2.dart", + "src/vector_math_64/vector3.dart", + "src/vector_math_64/vector4.dart", + "src/vector_math_geometry/filters/barycentric_filter.dart", + "src/vector_math_geometry/filters/color_filter.dart", + "src/vector_math_geometry/filters/flat_shade_filter.dart", + "src/vector_math_geometry/filters/geometry_filter.dart", + "src/vector_math_geometry/filters/invert_filter.dart", + "src/vector_math_geometry/filters/transform_filter.dart", + "src/vector_math_geometry/generators/attribute_generators.dart", + "src/vector_math_geometry/generators/circle_generator.dart", + "src/vector_math_geometry/generators/cube_generator.dart", + "src/vector_math_geometry/generators/cylinder_generator.dart", + "src/vector_math_geometry/generators/geometry_generator.dart", + "src/vector_math_geometry/generators/ring_generator.dart", + "src/vector_math_geometry/generators/sphere_generator.dart", + "src/vector_math_geometry/mesh_geometry.dart", + "src/vector_math_lists/scalar_list_view.dart", + "src/vector_math_lists/vector2_list.dart", + "src/vector_math_lists/vector3_list.dart", + "src/vector_math_lists/vector4_list.dart", + "src/vector_math_lists/vector_list.dart", + "src/vector_math_operations/matrix.dart", + "src/vector_math_operations/vector.dart", + "vector_math.dart", + "vector_math_64.dart", + "vector_math_geometry.dart", + "vector_math_lists.dart", + "vector_math_operations.dart", + ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart/compiler.dart b/flutter/engine/src/flutter/shell/platform/fuchsia/dart/compiler.dart new file mode 100644 index 0000000000000000000000000000000000000000..ffd755884c1fa481d06de819bf45d7766076196f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart/compiler.dart @@ -0,0 +1,60 @@ +// 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. + +import 'dart:async'; +import 'dart:io'; + +import 'package:args/args.dart'; +import 'package:crypto/crypto.dart'; + +import 'package:vm/kernel_front_end.dart' + show createCompilerArgParser, runCompiler, successExitCode; + +final ArgParser _argParser = + createCompilerArgParser()..addFlag( + 'train', + help: 'Run through sample command line to produce snapshot', + negatable: false, + ); + +String _usage = ''' +Usage: compiler [options] input.dart + +Options: +${_argParser.usage} +'''; + +Future main(List args) async { + ArgResults options; + try { + options = _argParser.parse(args); + + if (options['train']) { + final Directory temp = Directory.systemTemp.createTempSync('train_kernel_compiler'); + try { + options = _argParser.parse(['--manifest=flutter', '--data-dir=${temp.absolute}']); + + await runCompiler(options, _usage); + return; + } finally { + temp.deleteSync(recursive: true); + } + } + + if (!options.rest.isNotEmpty) { + throw Exception('Must specify input.dart'); + } + } on Exception catch (error) { + print('ERROR: $error\n'); + print(_usage); + exitCode = 1; + return; + } + + final compilerExitCode = await runCompiler(options, _usage); + if (compilerExitCode != successExitCode) { + exitCode = compilerExitCode; + return; + } +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c42682d0f541f4293d93f0883d1ad835f6c6e542 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/BUILD.gn @@ -0,0 +1,336 @@ +# 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. + +assert(is_fuchsia) + +import("//flutter/common/fuchsia_config.gni") +import("//flutter/testing/testing.gni") +import("//flutter/tools/fuchsia/dart.gni") +import("//flutter/tools/fuchsia/fuchsia_archive.gni") +import("//flutter/tools/fuchsia/fuchsia_libs.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") + +template("runner_sources") { + assert(defined(invoker.product), "runner_sources must define product") + source_set(target_name) { + forward_variables_from(invoker, [ "defines" ]) + sources = [ + "builtin_libraries.cc", + "builtin_libraries.h", + "dart_component_controller.cc", + "dart_component_controller.h", + "dart_runner.cc", + "dart_runner.h", + "dart_test_component_controller.cc", + "dart_test_component_controller.h", + "logging.h", + "service_isolate.cc", + "service_isolate.h", + ] + + dart_public_deps = [] + if (!invoker.product) { + dart_public_deps += [ + "$dart_src/runtime/bin:dart_io_api", + "//flutter/shell/platform/fuchsia/runtime/dart/utils:utils", + ] + } else { + dart_public_deps += [ + "$dart_src/runtime/bin:dart_io_api_product", + "//flutter/shell/platform/fuchsia/runtime/dart/utils:utils_product", + ] + } + + public_deps = [ + "${fuchsia_sdk}/fidl/fuchsia.component.runner", + "${fuchsia_sdk}/fidl/fuchsia.test", + "${fuchsia_sdk}/pkg/sys_cpp", + "//flutter/fml", + ] + dart_public_deps + + deps = [ + "${fuchsia_sdk}/fidl/fuchsia.logger", + "${fuchsia_sdk}/pkg/async", + "${fuchsia_sdk}/pkg/async-cpp", + "${fuchsia_sdk}/pkg/async-default", + "${fuchsia_sdk}/pkg/async-loop", + "${fuchsia_sdk}/pkg/async-loop-cpp", + "${fuchsia_sdk}/pkg/async-loop-default", + "${fuchsia_sdk}/pkg/fidl_cpp", + "${fuchsia_sdk}/pkg/inspect", + "${fuchsia_sdk}/pkg/inspect_component_cpp", + "${fuchsia_sdk}/pkg/sys_cpp", + "${fuchsia_sdk}/pkg/sys_cpp_testing", + "${fuchsia_sdk}/pkg/trace", + "${fuchsia_sdk}/pkg/vfs_cpp", + "${fuchsia_sdk}/pkg/zx", + "fidl:dart_test", + "//flutter/common", + "//flutter/shell/platform/fuchsia/dart-pkg/fuchsia", + "//flutter/shell/platform/fuchsia/dart-pkg/zircon", + "//flutter/third_party/tonic", + ] + } +} + +template("runner") { + assert(defined(invoker.product), "The parameter 'product' must be defined.") + assert(defined(invoker.output_name), + "The parameter 'output_name' must be defined") + + invoker_output_name = invoker.output_name + extra_defines = invoker.extra_defines + extra_deps = invoker.extra_deps + if (is_debug) { + extra_defines += [ "DEBUG" ] # Needed due to direct dart dependencies. + } + + runner_sources(target_name + "_runner_sources") { + product = invoker.product + defines = extra_defines + } + + executable(target_name) { + output_name = invoker_output_name + + sources = [ "main.cc" ] + + defines = extra_defines + + deps = [ + ":" + target_name + "_runner_sources", + "${fuchsia_sdk}/pkg/inspect_component_cpp", + "${fuchsia_sdk}/pkg/trace-provider-so", + ] + extra_deps + } +} + +runner("dart_jit_runner_bin") { + output_name = "dart_jit_runner" + product = false + extra_defines = [] + if (flutter_runtime_mode == "profile") { + extra_defines += [ "FLUTTER_PROFILE" ] + } + extra_deps = [ + "$dart_src/runtime:libdart_jit", + "$dart_src/runtime/platform:libdart_platform_jit", + ] +} + +runner("dart_jit_product_runner_bin") { + output_name = "dart_jit_product_runner" + product = true + extra_defines = [ "DART_PRODUCT" ] + extra_deps = [ + "$dart_src/runtime:libdart_jit", + "$dart_src/runtime/platform:libdart_platform_jit", + ] +} + +runner("dart_aot_runner_bin") { + output_name = "dart_aot_runner" + product = false + extra_defines = [ "AOT_RUNTIME" ] + if (flutter_runtime_mode == "profile") { + extra_defines += [ "FLUTTER_PROFILE" ] + } + extra_deps = [ + "$dart_src/runtime:libdart_aotruntime", + "$dart_src/runtime/platform:libdart_platform_aotruntime", + "embedder:dart_aot_snapshot_cc", + ] +} + +runner("dart_aot_product_runner_bin") { + output_name = "dart_aot_product_runner" + product = true + extra_defines = [ + "AOT_RUNTIME", + "DART_PRODUCT", + ] + extra_deps = [ + "$dart_src/runtime:libdart_aotruntime", + "$dart_src/runtime/platform:libdart_platform_aotruntime", + "embedder:dart_aot_product_snapshot_cc", + ] +} + +template("aot_runner_package") { + assert(defined(invoker.product), "The parameter 'product' must be defined") + product_suffix = "" + if (invoker.product) { + product_suffix = "_product" + } + fuchsia_archive(target_name) { + deps = [ ":dart_aot${product_suffix}_runner_bin" ] + if (!invoker.product) { + deps += [ + "vmservice:vmservice_snapshot", + "//flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols:dart_aot_runner", + + # TODO(kaushikiska): Figure out how to get the profiler symbols for `libdart_aotruntime` + # "$dart_src/runtime:libdart_aotruntime", + observatory_target, + ] + } + + binary = "dart_aot${product_suffix}_runner" + + libraries = common_libs + + resources = [] + if (!invoker.product) { + vmservice_snapshot = rebase_path( + get_label_info("vmservice:vmservice_snapshot", "target_gen_dir") + + "/vmservice_snapshot.so") + dart_profiler_symbols = rebase_path( + get_label_info( + "//flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols:dart_aot_runner", + "target_gen_dir") + "/dart_aot_runner.dartprofilersymbols") + + resources += [ + { + path = vmservice_snapshot + dest = "vmservice_snapshot.so" + }, + { + path = rebase_path(observatory_archive_file) + dest = "observatory.tar" + }, + { + path = dart_profiler_symbols + dest = "dart_aot_runner.dartprofilersymbols" + }, + ] + } + } +} + +template("jit_runner_package") { + assert(defined(invoker.product), "The parameter 'product' must be defined") + product_suffix = "" + if (invoker.product) { + product_suffix = "_product" + } + + fuchsia_archive(target_name) { + deps = [ + ":dart_jit${product_suffix}_runner_bin", + "kernel:kernel_core_snapshot${product_suffix}", + ] + + if (!invoker.product) { + deps += [ + "//flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols:dart_jit_runner", + observatory_target, + ] + } + + binary = "dart_jit${product_suffix}_runner" + + libraries = common_libs + + resources = [ + { + path = + rebase_path("$target_gen_dir/kernel/vm_data${product_suffix}.bin") + dest = "vm_snapshot_data.bin" + }, + { + path = rebase_path( + "$target_gen_dir/kernel/isolate_data${product_suffix}.bin") + dest = "isolate_core_snapshot_data.bin" + }, + ] + + if (!invoker.product) { + resources += [ + { + path = rebase_path(observatory_archive_file) + dest = "observatory.tar" + }, + { + path = rebase_path( + get_label_info( + "//flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols:dart_jit_runner", + "target_gen_dir") + "/dart_jit_runner.dartprofilersymbols") + dest = "dart_jit_runner.dartprofilersymbols" + }, + ] + } + } +} + +aot_runner_package("dart_aot_runner") { + product = false +} + +aot_runner_package("dart_aot_product_runner") { + product = true +} + +jit_runner_package("dart_jit_runner") { + product = false +} + +jit_runner_package("dart_jit_product_runner") { + product = true +} + +# "OOT" copy of the runner used by tests, to avoid conflicting with the runner +# in the base fuchsia image. +# TODO(fxbug.dev/106575): Fix this with subpackages. +aot_runner_package("oot_dart_aot_runner") { + product = false +} + +# "OOT" copy of the runner used by tests, to avoid conflicting with the runner +# in the base fuchsia image. +# TODO(fxbug.dev/106575): Fix this with subpackages. +jit_runner_package("oot_dart_jit_runner") { + product = false +} + +if (enable_unittests) { + runner_sources("jit_runner_sources_for_test") { + product = false + } + + executable("dart_test_runner_unittests") { + testonly = true + + output_name = "dart_runner_tests" + + sources = [ "tests/suite_impl_unittests.cc" ] + + # This is needed for //flutter/third_party/googletest for linking zircon + # symbols. + libs = [ "${fuchsia_arch_root}/sysroot/lib/libzircon.so" ] + + deps = [ + ":jit_runner_sources_for_test", + "$dart_src/runtime:libdart_jit", + "$dart_src/runtime/platform:libdart_platform_jit", + "//flutter/fml", + "//flutter/third_party/googletest:gtest_main", + ] + } + + fuchsia_test_archive("dart_runner_tests") { + deps = [ ":dart_test_runner_unittests" ] + gen_cml_file = true + } + + # When adding a new dep here, please also ensure the dep is added to + # testing/fuchsia/test_suites.yaml. + group("tests") { + testonly = true + + deps = [ + ":dart_runner_tests", + "tests/startup_integration_test", + ] + } +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/README.md b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ea68d8900137cc5f5917cd496b66feaebab9757a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/README.md @@ -0,0 +1,4 @@ +# Dart Application Runner + +Implements the `fuchsia::component::runner::ComponentRunner` FIDL interface to +launch and run Dart applications that don't use Flutter. \ No newline at end of file diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/builtin_libraries.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/builtin_libraries.cc new file mode 100644 index 0000000000000000000000000000000000000000..9207d4c2a337725e801556d0b757ad48d8d89d1c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/builtin_libraries.cc @@ -0,0 +1,241 @@ +// 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 "builtin_libraries.h" + +#include +#include + +#include + +#include "dart-pkg/fuchsia/sdk_ext/fuchsia.h" +#include "flutter/fml/logging.h" +#include "runtime/dart/utils/inlines.h" +#include "third_party/dart/runtime/bin/io_natives.h" +#include "third_party/dart/runtime/include/dart_api.h" +#include "third_party/tonic/converter/dart_converter.h" +#include "third_party/tonic/dart_microtask_queue.h" +#include "third_party/tonic/logging/dart_error.h" + +#include "logging.h" + +using tonic::ToDart; + +namespace dart_runner { +namespace { + +#define REGISTER_FUNCTION(name, count) {#name, name, count}, +#define DECLARE_FUNCTION(name, count) \ + extern void name(Dart_NativeArguments args); + +#define BUILTIN_NATIVE_LIST(V) \ + V(Logger_PrintString, 1) \ + V(ScheduleMicrotask, 1) + +BUILTIN_NATIVE_LIST(DECLARE_FUNCTION); + +const struct NativeEntry { + const char* name; + Dart_NativeFunction function; + int argument_count; +} kBuiltinEntries[] = {BUILTIN_NATIVE_LIST(REGISTER_FUNCTION)}; + +Dart_NativeFunction BuiltinNativeLookup(Dart_Handle name, + int argument_count, + bool* auto_setup_scope) { + const char* function_name = nullptr; + Dart_Handle result = Dart_StringToCString(name, &function_name); + if (Dart_IsError(result)) { + Dart_PropagateError(result); + } + FML_DCHECK(function_name != nullptr); + FML_DCHECK(auto_setup_scope != nullptr); + *auto_setup_scope = true; + size_t num_entries = dart_utils::ArraySize(kBuiltinEntries); + for (size_t i = 0; i < num_entries; i++) { + const NativeEntry& entry = kBuiltinEntries[i]; + if (!strcmp(function_name, entry.name) && + (entry.argument_count == argument_count)) { + return entry.function; + } + } + return nullptr; +} + +const uint8_t* BuiltinNativeSymbol(Dart_NativeFunction native_function) { + size_t num_entries = dart_utils::ArraySize(kBuiltinEntries); + for (size_t i = 0; i < num_entries; i++) { + const NativeEntry& entry = kBuiltinEntries[i]; + if (entry.function == native_function) + return reinterpret_cast(entry.name); + } + return nullptr; +} + +void Logger_PrintString(Dart_NativeArguments args) { + intptr_t length = 0; + uint8_t* chars = nullptr; + Dart_Handle str = Dart_GetNativeArgument(args, 0); + Dart_Handle result = Dart_StringToUTF8(str, &chars, &length); + if (Dart_IsError(result)) { + Dart_PropagateError(result); + } else { + fwrite(chars, 1, length, stdout); + fputc('\n', stdout); + fflush(stdout); + } +} + +void ScheduleMicrotask(Dart_NativeArguments args) { + Dart_Handle closure = Dart_GetNativeArgument(args, 0); + if (tonic::CheckAndHandleError(closure) || !Dart_IsClosure(closure)) + return; + tonic::DartMicrotaskQueue::GetForCurrentThread()->ScheduleMicrotask(closure); +} + +} // namespace + +void InitBuiltinLibrariesForIsolate(const std::string& script_uri, + fdio_ns_t* namespc, + int stdoutfd, + int stderrfd, + zx::channel directory_request, + bool service_isolate) { + // dart:fuchsia -------------------------------------------------------------- + // dart runner doesn't care about scenic view ref. + if (!service_isolate) { + fuchsia::dart::Initialize(std::move(directory_request), std::nullopt); + } + + // dart:fuchsia.builtin ------------------------------------------------------ + + Dart_Handle builtin_lib = Dart_LookupLibrary(ToDart("dart:fuchsia.builtin")); + FML_CHECK(!tonic::CheckAndHandleError(builtin_lib)); + Dart_Handle result = Dart_SetNativeResolver(builtin_lib, BuiltinNativeLookup, + BuiltinNativeSymbol); + FML_CHECK(!tonic::CheckAndHandleError(result)); + + // dart:io ------------------------------------------------------------------- + + Dart_Handle io_lib = Dart_LookupLibrary(ToDart("dart:io")); + FML_CHECK(!tonic::CheckAndHandleError(io_lib)); + result = Dart_SetNativeResolver(io_lib, dart::bin::IONativeLookup, + dart::bin::IONativeSymbol); + FML_CHECK(!tonic::CheckAndHandleError(result)); + + // dart:zircon --------------------------------------------------------------- + + Dart_Handle zircon_lib = Dart_LookupLibrary(ToDart("dart:zircon")); + FML_CHECK(!tonic::CheckAndHandleError(zircon_lib)); + // NativeResolver already set by fuchsia::dart::Initialize(). + + // Core libraries ------------------------------------------------------------ + + Dart_Handle async_lib = Dart_LookupLibrary(ToDart("dart:async")); + FML_CHECK(!tonic::CheckAndHandleError(async_lib)); + + Dart_Handle core_lib = Dart_LookupLibrary(ToDart("dart:core")); + FML_CHECK(!tonic::CheckAndHandleError(core_lib)); + + Dart_Handle internal_lib = Dart_LookupLibrary(ToDart("dart:_internal")); + FML_CHECK(!tonic::CheckAndHandleError(internal_lib)); + + Dart_Handle isolate_lib = Dart_LookupLibrary(ToDart("dart:isolate")); + FML_CHECK(!tonic::CheckAndHandleError(isolate_lib)); + +#if !defined(AOT_RUNTIME) + // AOT: These steps already happened at compile time in gen_snapshot. + + // We need to ensure that all the scripts loaded so far are finalized + // as we are about to invoke some Dart code below to set up closures. + result = Dart_FinalizeLoading(false); + FML_CHECK(!tonic::CheckAndHandleError(result)); +#endif + + // Setup the internal library's 'internalPrint' function. + Dart_Handle print = + Dart_Invoke(builtin_lib, ToDart("_getPrintClosure"), 0, nullptr); + FML_CHECK(!tonic::CheckAndHandleError(print)); + + result = Dart_SetField(internal_lib, ToDart("_printClosure"), print); + FML_CHECK(!tonic::CheckAndHandleError(result)); + + // Set up the 'scheduleImmediate' closure. + Dart_Handle schedule_immediate_closure; + if (service_isolate) { + // Running on dart::ThreadPool. + schedule_immediate_closure = Dart_Invoke( + isolate_lib, ToDart("_getIsolateScheduleImmediateClosure"), 0, nullptr); + } else { + // Running on async::Loop. + schedule_immediate_closure = Dart_Invoke( + builtin_lib, ToDart("_getScheduleMicrotaskClosure"), 0, nullptr); + } + FML_CHECK(!tonic::CheckAndHandleError(schedule_immediate_closure)); + + Dart_Handle schedule_args[1]; + schedule_args[0] = schedule_immediate_closure; + result = Dart_Invoke(async_lib, ToDart("_setScheduleImmediateClosure"), 1, + schedule_args); + FML_CHECK(!tonic::CheckAndHandleError(result)); + + // Set up the namespace in dart:io. + Dart_Handle namespace_type = + Dart_GetNonNullableType(io_lib, ToDart("_Namespace"), 0, nullptr); + FML_CHECK(!tonic::CheckAndHandleError(namespace_type)); + + Dart_Handle namespace_args[1]; + namespace_args[0] = ToDart(reinterpret_cast(namespc)); + result = + Dart_Invoke(namespace_type, ToDart("_setupNamespace"), 1, namespace_args); + FML_CHECK(!tonic::CheckAndHandleError(result)); + + // Set up the namespace in dart:zircon. + namespace_type = + Dart_GetNonNullableType(zircon_lib, ToDart("_Namespace"), 0, nullptr); + FML_CHECK(!tonic::CheckAndHandleError(namespace_type)); + + result = Dart_SetField(namespace_type, ToDart("_namespace"), + ToDart(reinterpret_cast(namespc))); + FML_CHECK(!tonic::CheckAndHandleError(result)); + + // Set up stdout and stderr. + Dart_Handle stdio_args[3]; + stdio_args[0] = Dart_NewInteger(0); + stdio_args[1] = Dart_NewInteger(stdoutfd); + stdio_args[2] = Dart_NewInteger(stderrfd); + result = Dart_Invoke(io_lib, ToDart("_setStdioFDs"), 3, stdio_args); + FML_CHECK(!tonic::CheckAndHandleError(result)); + + // Disable some dart:io operations. + Dart_Handle embedder_config_type = + Dart_GetNonNullableType(io_lib, ToDart("_EmbedderConfig"), 0, nullptr); + FML_CHECK(!tonic::CheckAndHandleError(embedder_config_type)); + + result = + Dart_SetField(embedder_config_type, ToDart("_mayExit"), Dart_False()); + FML_CHECK(!tonic::CheckAndHandleError(result)); + + // Set the script location. + result = Dart_SetField(builtin_lib, ToDart("_rawScript"), ToDart(script_uri)); + FML_CHECK(!tonic::CheckAndHandleError(result)); + + // Setup the uriBase with the base uri of the fidl app. + Dart_Handle uri_base = + Dart_Invoke(io_lib, ToDart("_getUriBaseClosure"), 0, nullptr); + FML_CHECK(!tonic::CheckAndHandleError(uri_base)); + + result = Dart_SetField(core_lib, ToDart("_uriBaseClosure"), uri_base); + FML_CHECK(!tonic::CheckAndHandleError(result)); + + Dart_Handle setup_hooks = ToDart("_setupHooks"); + result = Dart_Invoke(builtin_lib, setup_hooks, 0, nullptr); + FML_CHECK(!tonic::CheckAndHandleError(result)); + result = Dart_Invoke(io_lib, setup_hooks, 0, nullptr); + FML_CHECK(!tonic::CheckAndHandleError(result)); + result = Dart_Invoke(isolate_lib, setup_hooks, 0, nullptr); + FML_CHECK(!tonic::CheckAndHandleError(result)); +} + +} // namespace dart_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/builtin_libraries.h b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/builtin_libraries.h new file mode 100644 index 0000000000000000000000000000000000000000..b44dc0166c578b7703cbd13a8c786ec442a3fd1b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/builtin_libraries.h @@ -0,0 +1,25 @@ +// 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_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_BUILTIN_LIBRARIES_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_BUILTIN_LIBRARIES_H_ + +#include +#include + +#include +#include + +namespace dart_runner { + +void InitBuiltinLibrariesForIsolate(const std::string& script_uri, + fdio_ns_t* namespc, + int stdoutfd, + int stderrfd, + zx::channel directory_request, + bool service_isolate); + +} // namespace dart_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_BUILTIN_LIBRARIES_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/dart_component_controller.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/dart_component_controller.cc new file mode 100644 index 0000000000000000000000000000000000000000..80c007d8d4f9871ed80803fbbd7898fcb3e9536a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/dart_component_controller.cc @@ -0,0 +1,644 @@ +// 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 "dart_component_controller.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "dart_api.h" +#include "flutter/fml/logging.h" +#include "runtime/dart/utils/files.h" +#include "runtime/dart/utils/handle_exception.h" +#include "runtime/dart/utils/tempfs.h" +#include "third_party/dart/runtime/include/dart_tools_api.h" +#include "third_party/tonic/converter/dart_converter.h" +#include "third_party/tonic/dart_message_handler.h" +#include "third_party/tonic/dart_microtask_queue.h" +#include "third_party/tonic/dart_state.h" +#include "third_party/tonic/logging/dart_error.h" +#include "third_party/tonic/logging/dart_invoke.h" + +#include "builtin_libraries.h" + +using tonic::ToDart; + +namespace dart_runner { + +namespace { + +constexpr char kTmpPath[] = "/tmp"; + +constexpr zx::duration kIdleWaitDuration = zx::sec(2); +constexpr zx::duration kIdleNotifyDuration = zx::msec(500); +constexpr zx::duration kIdleSlack = zx::sec(1); + +void AfterTask(async_loop_t*, void*) { + tonic::DartMicrotaskQueue* queue = + tonic::DartMicrotaskQueue::GetForCurrentThread(); + // Verify that the queue exists, as this method could have been called back as + // part of the exit routine, after the destruction of the microtask queue. + if (queue) { + queue->RunMicrotasks(); + } +} + +constexpr async_loop_config_t kLoopConfig = { + .default_accessors = + { + .getter = async_get_default_dispatcher, + .setter = async_set_default_dispatcher, + }, + .make_default_for_current_thread = true, + .epilogue = &AfterTask, +}; + +// Find the last path of the component. +// fuchsia-pkg://fuchsia.com/hello_dart#meta/hello_dart.cmx -> hello_dart.cmx +std::string GetLabelFromUrl(const std::string& url) { + for (size_t i = url.length() - 1; i > 0; i--) { + if (url[i] == '/') { + return url.substr(i + 1, url.length() - 1); + } + } + return url; +} + +// Find the name of the component. +// fuchsia-pkg://fuchsia.com/hello_dart#meta/hello_dart.cm -> hello_dart +std::string GetComponentNameFromUrl(const std::string& url) { + const std::string label = GetLabelFromUrl(url); + for (size_t i = 0; i < label.length(); ++i) { + if (label[i] == '.') { + return label.substr(0, i); + } + } + return label; +} + +} // namespace + +DartComponentController::DartComponentController( + fuchsia::component::runner::ComponentStartInfo start_info, + std::shared_ptr runner_incoming_services, + fidl::InterfaceRequest + controller) + : loop_(new async::Loop(&kLoopConfig)), + label_(GetLabelFromUrl(start_info.resolved_url())), + url_(start_info.resolved_url()), + runner_incoming_services_(std::move(runner_incoming_services)), + dart_outgoing_dir_(new vfs::PseudoDir()), + start_info_(std::move(start_info)), + binding_(this, std::move(controller)) { + binding_.set_error_handler([this](zx_status_t status) { Kill(); }); + + // TODO(fxb/84537): This data path is configured based how we build Flutter + // applications in tree currently, but the way we build the Flutter + // application may change. We should avoid assuming the data path and let the + // CML file specify this data path instead. + const std::string component_name = GetComponentNameFromUrl(url_); + data_path_ = "pkg/data/" + component_name; + + zx_status_t idle_timer_status = + zx::timer::create(ZX_TIMER_SLACK_LATE, ZX_CLOCK_MONOTONIC, &idle_timer_); + if (idle_timer_status != ZX_OK) { + FML_LOG(INFO) << "Idle timer creation failed: " + << zx_status_get_string(idle_timer_status); + } else { + idle_wait_.set_object(idle_timer_.get()); + idle_wait_.set_trigger(ZX_TIMER_SIGNALED); + idle_wait_.Begin(async_get_default_dispatcher()); + } + + // Close the runtime_dir channel if we don't intend to serve it. Otherwise any + // access to the runtime_dir will hang forever. + start_info_.clear_runtime_dir(); +} + +DartComponentController::~DartComponentController() { + if (namespace_) { + fdio_ns_destroy(namespace_); + namespace_ = nullptr; + } + close(stdout_fd_); + close(stderr_fd_); +} + +bool DartComponentController::SetUp() { + // Name the thread after the url of the component being launched. + zx::thread::self()->set_property(ZX_PROP_NAME, label_.c_str(), label_.size()); + Dart_SetThreadName(label_.c_str()); + + if (!CreateAndBindNamespace()) { + return false; + } + + if (SetUpFromAppSnapshot()) { + FML_LOG(INFO) << url_ << " is running from an app snapshot"; + } else if (SetUpFromKernel()) { + FML_LOG(INFO) << url_ << " is running from kernel"; + } else { + FML_LOG(ERROR) << "Failed to set up component controller for " << url_; + return false; + } + + return true; +} + +bool DartComponentController::CreateAndBindNamespace() { + if (!start_info_.has_ns()) { + FML_LOG(ERROR) << "Component start info does not have a namespace."; + return false; + } + + const zx_status_t ns_create_status = fdio_ns_create(&namespace_); + if (ns_create_status != ZX_OK) { + FML_LOG(ERROR) << "Failed to create namespace: " + << zx_status_get_string(ns_create_status); + } + + dart_utils::BindTemp(namespace_); + + // Bind each directory in start_info's namespace to the controller's namespace + // instance. + for (auto& ns_entry : *start_info_.mutable_ns()) { + // TODO(akbiggs): Under what circumstances does a namespace entry not have a + // path or directory? Should we log an error for these? + if (!ns_entry.has_path() || !ns_entry.has_directory()) { + continue; + } + + if (ns_entry.path() == kTmpPath) { + // /tmp is covered by a locally served virtual filesystem. + continue; + } + + // We move ownership of the directory & path since RAII is used to keep + // the handle open. + fidl::InterfaceHandle<::fuchsia::io::Directory> dir = + std::move(*ns_entry.mutable_directory()); + const std::string path = std::move(*ns_entry.mutable_path()); + + const zx_status_t ns_bind_status = + fdio_ns_bind(namespace_, path.c_str(), dir.TakeChannel().release()); + if (ns_bind_status != ZX_OK) { + FML_LOG(ERROR) << "Failed to bind " << path << " to namespace: " + << zx_status_get_string(ns_bind_status); + return false; + } + } + + dart_outgoing_dir_request_ = dart_outgoing_dir_ptr_.NewRequest(); + + fuchsia::io::DirectoryHandle dart_public_dir; + { + auto request = dart_public_dir.NewRequest().TakeChannel(); + const zx_status_t status = + fdio_open3_at(dart_outgoing_dir_ptr_.channel().get(), "svc", + uint64_t{fuchsia::io::PERM_READABLE}, request.release()); + if (status != ZX_OK) { + FML_LOG(ERROR) << "Failed to open /svc in outgoing directory: " + << zx_status_get_string(status); + return false; + } + } + + auto composed_service_dir = std::make_unique(); + composed_service_dir->SetFallback( + fidl::ClientEnd(dart_public_dir.TakeChannel())); + + // Request an event from the directory to ensure it is servicing requests. + dart_outgoing_dir_ptr_->Open3( + ".", + fuchsia::io::Flags::PROTOCOL_NODE | + fuchsia::io::Flags::FLAG_SEND_REPRESENTATION, + {}, dart_outgoing_dir_ptr_to_check_on_open_.NewRequest().TakeChannel()); + + // Collect our standard set of directories. + std::vector other_dirs = {"debug", "ctrl"}; + + dart_outgoing_dir_ptr_to_check_on_open_.events().OnRepresentation = + [this, other_dirs](auto unused) { + dart_outgoing_dir_ptr_to_check_on_open_.Unbind(); + // add other directories as RemoteDirs. + for (auto& dir_str : other_dirs) { + fuchsia::io::DirectoryHandle dir; + auto request = dir.NewRequest().TakeChannel(); + const zx_status_t status = fdio_open3_at( + dart_outgoing_dir_ptr_.channel().get(), dir_str.c_str(), + uint64_t{fuchsia::io::Flags::PROTOCOL_DIRECTORY | + fuchsia::io::PERM_READABLE}, + request.release()); + if (status == ZX_OK) { + dart_outgoing_dir_->AddEntry( + dir_str.c_str(), + std::make_unique(dir.TakeChannel())); + } else { + FML_LOG(ERROR) << "could not add out directory entry(" << dir_str + << ") for flutter component(" << label_ + << "): " << zx_status_get_string(status); + } + } + }; + dart_outgoing_dir_ptr_to_check_on_open_.set_error_handler( + [this](zx_status_t status) { + dart_outgoing_dir_ptr_to_check_on_open_.Unbind(); + }); + + // Expose the "Echo" service here on behalf of the running dart program, so + // that integration tests can make use of it. + // + // The flutter/engine repository doesn't support connecting to FIDL from Dart, + // so for the tests sake we connect to the FIDL from C++ here and proxy the + // Echo to dart using native hooks. + composed_service_dir->AddService( + dart::test::Echo::Name_, + std::make_unique([this](zx::channel channel, + async_dispatcher_t* dispatcher) { + echo_binding_.AddBinding( + this, fidl::InterfaceRequest(std::move(channel))); + })); + dart_outgoing_dir_->AddEntry("svc", std::move(composed_service_dir)); + + if (start_info_.has_outgoing_dir()) { + fidl::ServerEnd server_end{ + start_info_.mutable_outgoing_dir()->TakeChannel()}; + dart_outgoing_dir_->Serve( + fuchsia_io::wire::kPermReadable | fuchsia_io::wire::kPermWritable, + std::move(server_end)); + } + + return true; +} + +bool DartComponentController::SetUpFromKernel() { + dart_utils::MappedResource manifest; + if (!dart_utils::MappedResource::LoadFromNamespace( + namespace_, data_path_ + "/app.dilplist", manifest)) { + return false; + } + + if (!dart_utils::MappedResource::LoadFromNamespace( + nullptr, "/pkg/data/isolate_core_snapshot_data.bin", + isolate_snapshot_data_)) { + return false; + } + + std::string str(reinterpret_cast(manifest.address()), + manifest.size()); + Dart_Handle library = Dart_Null(); + + for (size_t start = 0; start < manifest.size();) { + size_t end = str.find("\n", start); + if (end == std::string::npos) { + FML_LOG(ERROR) << "Malformed manifest"; + Dart_ExitScope(); + return false; + } + + std::string path = data_path_ + "/" + str.substr(start, end - start); + start = end + 1; + + dart_utils::MappedResource kernel; + if (!dart_utils::MappedResource::LoadFromNamespace(namespace_, path, + kernel)) { + FML_LOG(ERROR) << "Cannot load kernel from namespace: " << path; + Dart_ExitScope(); + return false; + } + kernel_peices_.emplace_back(std::move(kernel)); + } + + if (!CreateIsolate(isolate_snapshot_data_.address(), + /*isolate_snapshot_instructions=*/nullptr)) { + return false; + } + + Dart_EnterScope(); + + for (const auto& kernel : kernel_peices_) { + library = Dart_LoadLibraryFromKernel(kernel.address(), kernel.size()); + if (Dart_IsError(library)) { + FML_LOG(ERROR) << "Cannot load library from kernel: " + << Dart_GetError(library); + Dart_ExitScope(); + return false; + } + } + + Dart_SetRootLibrary(library); + + Dart_Handle result = Dart_FinalizeLoading(false); + if (Dart_IsError(result)) { + FML_LOG(ERROR) << "Failed to FinalizeLoading: " << Dart_GetError(result); + Dart_ExitScope(); + return false; + } + + return true; +} + +bool DartComponentController::SetUpFromAppSnapshot() { +#if !defined(AOT_RUNTIME) + return false; +#else + // Load the ELF snapshot as available, and fall back to a blobs snapshot + // otherwise. + const uint8_t *isolate_data, *isolate_instructions; + if (elf_snapshot_.Load(namespace_, data_path_ + "/app_aot_snapshot.so")) { + isolate_data = elf_snapshot_.IsolateData(); + isolate_instructions = elf_snapshot_.IsolateInstrs(); + if (isolate_data == nullptr || isolate_instructions == nullptr) { + return false; + } + } else { + if (!dart_utils::MappedResource::LoadFromNamespace( + namespace_, data_path_ + "/isolate_snapshot_data.bin", + isolate_snapshot_data_)) { + return false; + } + isolate_data = isolate_snapshot_data_.address(); + isolate_instructions = nullptr; + } + return CreateIsolate(isolate_data, isolate_instructions); +#endif // defined(AOT_RUNTIME) +} + +bool DartComponentController::CreateIsolate( + const uint8_t* isolate_snapshot_data, + const uint8_t* isolate_snapshot_instructions) { + // Create the isolate from the snapshot. + char* error = nullptr; + + // TODO(dart_runner): Pass if we start using tonic's loader. + intptr_t namespace_fd = -1; + + // Freed in IsolateShutdownCallback. + auto state = new std::shared_ptr(new tonic::DartState( + namespace_fd, [this](Dart_Handle result) { MessageEpilogue(result); })); + + Dart_IsolateFlags isolate_flags; + Dart_IsolateFlagsInitialize(&isolate_flags); + isolate_flags.null_safety = true; + + isolate_ = Dart_CreateIsolateGroup( + url_.c_str(), label_.c_str(), isolate_snapshot_data, + isolate_snapshot_instructions, &isolate_flags, state, state, &error); + if (!isolate_) { + FML_LOG(ERROR) << "Dart_CreateIsolateGroup failed: " << error; + return false; + } + + state->get()->SetIsolate(isolate_); + + tonic::DartMessageHandler::TaskDispatcher dispatcher = + [loop = loop_.get()](auto callback) { + async::PostTask(loop->dispatcher(), std::move(callback)); + }; + state->get()->message_handler().Initialize(dispatcher); + + state->get()->SetReturnCodeCallback( + [this](uint32_t return_code) { return_code_ = return_code; }); + + return true; +} + +void DartComponentController::Run() { + async::PostTask(loop_->dispatcher(), [loop = loop_.get(), app = this] { + if (!app->RunDartMain()) { + loop->Quit(); + } + }); + loop_->Run(); + + if (binding_.is_bound()) { + // From the documentation for ComponentController, ZX_OK should be sent when + // the ComponentController receives a termination request. However, if the + // component exited with a non-zero return code, we indicate this by sending + // an INTERNAL epitaph instead. + // + // TODO(fxb/86666): Communicate return code from the ComponentController + // once v2 has support. + if (return_code_ == 0) { + binding_.Close(ZX_OK); + } else { + FML_LOG(ERROR) << "Component exited with non-zero return code: " + << return_code_; + binding_.Close(zx_status_t(fuchsia::component::Error::INTERNAL)); + } + } +} + +bool DartComponentController::RunDartMain() { + FML_CHECK(namespace_ != nullptr); + Dart_EnterScope(); + + tonic::DartMicrotaskQueue::StartForCurrentThread(); + + // TODO(fxb/88384): Create a file descriptor for each component that is + // launched and listen for anything that is written to the component. When + // something is written to the component, forward that message along to the + // Fuchsia logger and decorate it with the tag that it came from the + // component. + stdout_fd_ = fileno(stdout); + stderr_fd_ = fileno(stderr); + + InitBuiltinLibrariesForIsolate(url_, namespace_, stdout_fd_, stderr_fd_, + dart_outgoing_dir_request_.TakeChannel(), + false /* service_isolate */); + + Dart_ExitScope(); + Dart_ExitIsolate(); + char* error = Dart_IsolateMakeRunnable(isolate_); + if (error != nullptr) { + Dart_EnterIsolate(isolate_); + Dart_ShutdownIsolate(); + FML_LOG(ERROR) << "Unable to make isolate runnable: " << error; + free(error); + return false; + } + Dart_EnterIsolate(isolate_); + Dart_EnterScope(); + + // TODO(fxb/88383): Support argument passing. + Dart_Handle corelib = Dart_LookupLibrary(ToDart("dart:core")); + Dart_Handle string_type = + Dart_GetNonNullableType(corelib, ToDart("String"), 0, NULL); + Dart_Handle dart_arguments = + Dart_NewListOfTypeFilled(string_type, Dart_EmptyString(), 0); + + if (Dart_IsError(dart_arguments)) { + FML_LOG(ERROR) << "Failed to allocate Dart arguments list: " + << Dart_GetError(dart_arguments); + Dart_ExitScope(); + return false; + } + + Dart_Handle user_main = Dart_GetField(Dart_RootLibrary(), ToDart("main")); + + if (Dart_IsError(user_main)) { + FML_LOG(ERROR) << "Failed to locate user_main in the root library: " + << Dart_GetError(user_main); + Dart_ExitScope(); + return false; + } + + Dart_Handle fuchsia_lib = Dart_LookupLibrary(tonic::ToDart("dart:fuchsia")); + + if (Dart_IsError(fuchsia_lib)) { + FML_LOG(ERROR) << "Failed to locate dart:fuchsia: " + << Dart_GetError(fuchsia_lib); + Dart_ExitScope(); + return false; + } + + Dart_Handle main_result = tonic::DartInvokeField( + fuchsia_lib, "_runUserMainForDartRunner", {user_main, dart_arguments}); + + if (Dart_IsError(main_result)) { + auto dart_state = tonic::DartState::Current(); + if (!dart_state->has_set_return_code()) { + // The program hasn't set a return code meaning this exit is unexpected. + FML_LOG(ERROR) << Dart_GetError(main_result); + return_code_ = tonic::GetErrorExitCode(main_result); + + dart_utils::HandleIfException(runner_incoming_services_, url_, + main_result); + } + Dart_ExitScope(); + return false; + } + + Dart_ExitScope(); + return true; +} + +void DartComponentController::EchoString(fidl::StringPtr value, + EchoStringCallback callback) { + Dart_EnterScope(); + + Dart_Handle builtin_lib = Dart_LookupLibrary(ToDart("dart:fuchsia.builtin")); + FML_CHECK(!tonic::CheckAndHandleError(builtin_lib)); + + Dart_Handle receive_echo_string = ToDart("_receiveEchoString"); + Dart_Handle string_to_echo = + value.has_value() ? tonic::ToDart(*value) : Dart_Null(); + Dart_Handle result = + Dart_Invoke(builtin_lib, receive_echo_string, 1, &string_to_echo); + FML_CHECK(!tonic::CheckAndHandleError(result)); + + fidl::StringPtr echo_string; + if (!Dart_IsNull(result)) { + echo_string = tonic::StdStringFromDart(result); + } + callback(std::move(echo_string)); + + Dart_ExitScope(); +} + +void DartComponentController::Kill() { + if (Dart_CurrentIsolate()) { + tonic::DartMicrotaskQueue* queue = + tonic::DartMicrotaskQueue::GetForCurrentThread(); + if (queue) { + queue->Destroy(); + } + + loop_->Quit(); + + // TODO(rosswang): The docs warn of threading issues if doing this again, + // but without this, attempting to shut down the isolate finalizes app + // contexts that can't tell a shutdown is in progress and so fatal. + Dart_SetMessageNotifyCallback(nullptr); + + Dart_ShutdownIsolate(); + } +} + +void DartComponentController::Stop() { + Kill(); +} + +void DartComponentController::MessageEpilogue(Dart_Handle result) { + auto dart_state = tonic::DartState::Current(); + // If the Dart program has set a return code, then it is intending to shut + // down by way of a fatal error, and so there is no need to override + // return_code_. + if (dart_state->has_set_return_code()) { + Dart_ShutdownIsolate(); + return; + } + + dart_utils::HandleIfException(runner_incoming_services_, url_, result); + + // Otherwise, see if there was any other error. + return_code_ = tonic::GetErrorExitCode(result); + if (return_code_ != 0) { + Dart_ShutdownIsolate(); + return; + } + + idle_start_ = zx::clock::get_monotonic(); + zx_status_t status = + idle_timer_.set(idle_start_ + kIdleWaitDuration, kIdleSlack); + if (status != ZX_OK) { + FML_LOG(INFO) << "Idle timer set failed: " << zx_status_get_string(status); + } +} + +void DartComponentController::OnIdleTimer(async_dispatcher_t* dispatcher, + async::WaitBase* wait, + zx_status_t status, + const zx_packet_signal* signal) { + if ((status != ZX_OK) || !(signal->observed & ZX_TIMER_SIGNALED) || + !Dart_CurrentIsolate()) { + // Timer closed or isolate shutdown. + return; + } + + zx::time deadline = idle_start_ + kIdleWaitDuration; + zx::time now = zx::clock::get_monotonic(); + if (now >= deadline) { + // No Dart message has been processed for kIdleWaitDuration: assume we'll + // stay idle for kIdleNotifyDuration. + Dart_NotifyIdle((now + kIdleNotifyDuration).get()); + idle_start_ = zx::time(0); + idle_timer_.cancel(); // De-assert signal. + } else { + // Early wakeup or message pushed idle time forward: reschedule. + zx_status_t status = idle_timer_.set(deadline, kIdleSlack); + if (status != ZX_OK) { + FML_LOG(INFO) << "Idle timer set failed: " + << zx_status_get_string(status); + } + } + wait->Begin(dispatcher); // ignore errors +} + +void DartComponentController::handle_unknown_method(uint64_t ordinal, + bool method_has_response) { + FML_LOG(ERROR) << "Unknown method called on DartComponentController. " + "Ordinal: " + << ordinal; +} + +} // namespace dart_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/dart_component_controller.h b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/dart_component_controller.h new file mode 100644 index 0000000000000000000000000000000000000000..1cb3fc53b20a0f2f6f1a6b591e400039d290a8a6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/dart_component_controller.h @@ -0,0 +1,126 @@ +// 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_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_COMPONENT_CONTROLLER_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_COMPONENT_CONTROLLER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "runtime/dart/utils/mapped_resource.h" +#include "third_party/dart/runtime/include/dart_api.h" + +namespace dart_runner { + +/// Starts a Dart component written in CFv2. +class DartComponentController + : public dart::test::Echo, + public fuchsia::component::runner::ComponentController { + public: + DartComponentController( + fuchsia::component::runner::ComponentStartInfo start_info, + std::shared_ptr runner_incoming_services, + fidl::InterfaceRequest + controller); + ~DartComponentController() override; + + /// Sets up the controller. + /// + /// This should be called before |Run|. + bool SetUp(); + + /// Runs the Dart component in a task, sending the return code back to + /// the Fuchsia component controller. + /// + /// This should be called after |SetUp|. + void Run(); + + void handle_unknown_method(uint64_t ordinal, + bool method_has_response) override; + + private: + /// Helper for actually running the Dart main. Returns true if successful, + /// false otherwise. + bool RunDartMain(); + + /// Creates and binds the namespace for this component. Returns true if + /// successful, false otherwise. + bool CreateAndBindNamespace(); + + bool SetUpFromKernel(); + bool SetUpFromAppSnapshot(); + + bool CreateIsolate(const uint8_t* isolate_snapshot_data, + const uint8_t* isolate_snapshot_instructions); + + // |Echo| + void EchoString(fidl::StringPtr value, EchoStringCallback callback) override; + + // |ComponentController| + void Kill() override; + void Stop() override; + + // Idle notification. + void MessageEpilogue(Dart_Handle result); + void OnIdleTimer(async_dispatcher_t* dispatcher, + async::WaitBase* wait, + zx_status_t status, + const zx_packet_signal* signal); + + // The loop must be the first declared member so that it gets destroyed after + // binding_ which expects the existence of a loop. + std::unique_ptr loop_; + + std::string label_; + std::string url_; + std::string data_path_; + std::shared_ptr runner_incoming_services_; + std::unique_ptr context_; + std::unique_ptr dart_outgoing_dir_; + fuchsia::io::DirectoryPtr dart_outgoing_dir_ptr_; + fidl::InterfaceRequest dart_outgoing_dir_request_; + fuchsia::io::NodePtr dart_outgoing_dir_ptr_to_check_on_open_; + + fuchsia::component::runner::ComponentStartInfo start_info_; + fidl::Binding binding_; + fidl::BindingSet echo_binding_; + + fdio_ns_t* namespace_ = nullptr; + int stdout_fd_ = -1; + int stderr_fd_ = -1; + + dart_utils::ElfSnapshot elf_snapshot_; // AOT snapshot + dart_utils::MappedResource isolate_snapshot_data_; // JIT snapshot + dart_utils::MappedResource isolate_snapshot_instructions_; // JIT snapshot + std::vector kernel_peices_; + + Dart_Isolate isolate_; + int32_t return_code_ = 0; + + zx::time idle_start_{0}; + zx::timer idle_timer_; + async::WaitMethod + idle_wait_{this}; + + // Disallow copy and assignment. + DartComponentController(const DartComponentController&) = delete; + DartComponentController& operator=(const DartComponentController&) = delete; +}; + +} // namespace dart_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_COMPONENT_CONTROLLER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/dart_runner.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/dart_runner.cc new file mode 100644 index 0000000000000000000000000000000000000000..1d140723eb6e6c7ccca1e0ee86a0b7b495f249e3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/dart_runner.cc @@ -0,0 +1,285 @@ +// 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 "dart_runner.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "dart_component_controller.h" +#include "flutter/fml/command_line.h" +#include "flutter/fml/logging.h" +#include "flutter/fml/trace_event.h" +#include "runtime/dart/utils/inlines.h" +#include "runtime/dart/utils/vmservice_object.h" +#include "service_isolate.h" +#include "third_party/dart/runtime/include/bin/dart_io_api.h" +#include "third_party/tonic/dart_microtask_queue.h" +#include "third_party/tonic/dart_state.h" + +#if defined(AOT_RUNTIME) +extern "C" uint8_t _kDartVmSnapshotData[]; +extern "C" uint8_t _kDartVmSnapshotInstructions[]; +#endif + +namespace dart_runner { + +namespace { + +const char* kDartVMArgs[] = { + // clang-format off + + "--timeline_recorder=systrace", + "--timeline_streams=Compiler,Dart,Debugger,Embedder,GC,Isolate,VM", + +#if defined(AOT_RUNTIME) + "--precompilation", +#else + "--enable_mirrors=false", +#endif + + // No asserts in debug or release product. + // No asserts in release with flutter_profile=true (non-product) + // Yes asserts in non-product debug. +#if !defined(DART_PRODUCT) && (!defined(FLUTTER_PROFILE) || !defined(NDEBUG)) + "--enable_asserts", +#endif +}; + +Dart_Isolate IsolateGroupCreateCallback(const char* uri, + const char* name, + const char* package_root, + const char* package_config, + Dart_IsolateFlags* flags, + void* callback_data, + char** error) { + if (std::string(uri) == DART_VM_SERVICE_ISOLATE_NAME) { +#if defined(DART_PRODUCT) + *error = strdup("The service isolate is not implemented in product mode"); + return NULL; +#else + return CreateServiceIsolate(uri, flags, error); +#endif + } + + *error = strdup("Isolate spawning is not implemented in dart_runner"); + return NULL; +} + +void IsolateShutdownCallback(void* isolate_group_data, void* isolate_data) { + // The service isolate (and maybe later the kernel isolate) doesn't have an + // async loop. + auto dispatcher = async_get_default_dispatcher(); + auto loop = async_loop_from_dispatcher(dispatcher); + if (loop) { + tonic::DartMicrotaskQueue* queue = + tonic::DartMicrotaskQueue::GetForCurrentThread(); + if (queue) { + queue->Destroy(); + } + + async_loop_quit(loop); + } + + auto state = + static_cast*>(isolate_group_data); + state->get()->SetIsShuttingDown(); +} + +void IsolateGroupCleanupCallback(void* isolate_group_data) { + delete static_cast*>(isolate_group_data); +} + +// Runs the application for a Dart component. +void RunApplication( + DartRunner* runner, + fuchsia::component::runner::ComponentStartInfo start_info, + std::shared_ptr runner_incoming_services, + fidl::InterfaceRequest + controller) { + const int64_t start = Dart_TimelineGetMicros(); + + DartComponentController app(std::move(start_info), runner_incoming_services, + std::move(controller)); + const bool success = app.SetUp(); + + const int64_t end = Dart_TimelineGetMicros(); + Dart_RecordTimelineEvent( + "DartComponentController::SetUp", start, end, 0, nullptr, + Dart_Timeline_Event_Duration, 0, NULL, NULL); + if (success) { + app.Run(); + } + + if (Dart_CurrentIsolate()) { + Dart_ShutdownIsolate(); + } +} + +void RunTestApplication( + DartRunner* runner, + fuchsia::component::runner::ComponentStartInfo start_info, + std::shared_ptr runner_incoming_services, + fidl::InterfaceRequest + controller, + fit::function)> + component_created_callback, + fit::function done_callback) { + const int64_t start = Dart_TimelineGetMicros(); + + auto test_component = std::make_shared( + std::move(start_info), runner_incoming_services, std::move(controller), + std::move(done_callback)); + + component_created_callback(test_component); + + // Start up the dart isolate and serve the suite protocol. + test_component->SetUp(); + + const int64_t end = Dart_TimelineGetMicros(); + Dart_RecordTimelineEvent( + "DartTestComponentController::SetUp", start, end, 0, nullptr, + Dart_Timeline_Event_Duration, 0, NULL, NULL); +} + +bool EntropySource(uint8_t* buffer, intptr_t count) { + zx_cprng_draw(buffer, count); + return true; +} + +} // namespace + +// "args" are how the component specifies arguments to the runner. +constexpr char kArgsKey[] = "args"; + +/// Parses the |args| field from the "program" field to determine +/// if a test component is being executed. +bool IsTestProgram(const fuchsia::data::Dictionary& program_metadata) { + for (const auto& entry : program_metadata.entries()) { + if (entry.key.compare(kArgsKey) != 0 || entry.value == nullptr) { + continue; + } + auto args = entry.value->str_vec(); + + // fml::CommandLine expects the first argument to be the name of the + // program, so we prepend a dummy argument so we can use fml::CommandLine to + // parse the arguments for us. + std::vector command_line_args = {""}; + command_line_args.insert(command_line_args.end(), args.begin(), args.end()); + fml::CommandLine parsed_args = fml::CommandLineFromIterators( + command_line_args.begin(), command_line_args.end()); + + std::string is_test_str; + return parsed_args.GetOptionValue("is_test", &is_test_str) && + is_test_str == "true"; + } + return false; +} + +DartRunner::DartRunner(sys::ComponentContext* context) : context_(context) { + context_->outgoing() + ->AddPublicService( + [this](fidl::InterfaceRequest< + fuchsia::component::runner::ComponentRunner> request) { + component_runner_bindings_.AddBinding(this, std::move(request)); + }); + +#if !defined(DART_PRODUCT) + // The VM service isolate uses the process-wide namespace. It writes the + // vm service protocol port under /tmp. The VMServiceObject exposes that + // port number to The Hub. + context_->outgoing()->debug_dir()->AddEntry( + dart_utils::VMServiceObject::kPortDirName, + std::make_unique()); + +#endif // !defined(DART_PRODUCT) + + dart::bin::BootstrapDartIo(); + + char* error = + Dart_SetVMFlags(dart_utils::ArraySize(kDartVMArgs), kDartVMArgs); + if (error) { + FML_LOG(FATAL) << "Dart_SetVMFlags failed: " << error; + } + + Dart_InitializeParams params = {}; + params.version = DART_INITIALIZE_PARAMS_CURRENT_VERSION; +#if defined(AOT_RUNTIME) + params.vm_snapshot_data = ::_kDartVmSnapshotData; + params.vm_snapshot_instructions = ::_kDartVmSnapshotInstructions; +#else + if (!dart_utils::MappedResource::LoadFromNamespace( + nullptr, "/pkg/data/vm_snapshot_data.bin", vm_snapshot_data_)) { + FML_LOG(FATAL) << "Failed to load vm snapshot data"; + } + params.vm_snapshot_data = vm_snapshot_data_.address(); +#endif + params.create_group = IsolateGroupCreateCallback; + params.shutdown_isolate = IsolateShutdownCallback; + params.cleanup_group = IsolateGroupCleanupCallback; + params.entropy_source = EntropySource; +#if !defined(DART_PRODUCT) + params.get_service_assets = GetVMServiceAssetsArchiveCallback; +#endif + error = Dart_Initialize(¶ms); + if (error) + FML_LOG(FATAL) << "Dart_Initialize failed: " << error; +} + +DartRunner::~DartRunner() { + char* error = Dart_Cleanup(); + if (error) + FML_LOG(FATAL) << "Dart_Cleanup failed: " << error; +} + +void DartRunner::Start( + fuchsia::component::runner::ComponentStartInfo start_info, + fidl::InterfaceRequest + controller) { + // Parse the program field of the component's cml and check if it is a test + // component. If so, serve the |fuchsia.test.Suite| protocol from the + // component's outgoing directory, via DartTestComponentController. + if (IsTestProgram(start_info.program())) { + std::string url_copy = start_info.resolved_url(); + TRACE_EVENT1("dart", "Start", "url", url_copy.c_str()); + std::thread thread( + RunTestApplication, this, std::move(start_info), context_->svc(), + std::move(controller), + // component_created_callback + [this](std::shared_ptr ptr) { + test_components_.emplace(ptr.get(), std::move(ptr)); + }, + // done_callback + [this](DartTestComponentController* ptr) { + auto it = test_components_.find(ptr); + if (it != test_components_.end()) { + test_components_.erase(it); + } + }); + thread.detach(); + } else { + std::string url_copy = start_info.resolved_url(); + TRACE_EVENT1("dart", "Start", "url", url_copy.c_str()); + std::thread thread(RunApplication, this, std::move(start_info), + context_->svc(), std::move(controller)); + thread.detach(); + } +} + +void DartRunner::handle_unknown_method(uint64_t ordinal, + bool method_has_response) { + FML_LOG(ERROR) << "Unknown method called on DartRunner. Ordinal: " + << ordinal; +} + +} // namespace dart_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/dart_runner.h b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/dart_runner.h new file mode 100644 index 0000000000000000000000000000000000000000..1c9adbb3b50ecc59c4846579a384d53d13da1419 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/dart_runner.h @@ -0,0 +1,55 @@ +// 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_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_RUNNER_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_RUNNER_H_ + +#include +#include +#include + +#include "dart_test_component_controller.h" +#include "runtime/dart/utils/mapped_resource.h" + +namespace dart_runner { + +class DartRunner : public fuchsia::component::runner::ComponentRunner { + public: + explicit DartRunner(sys::ComponentContext* context); + ~DartRunner() override; + + void handle_unknown_method(uint64_t ordinal, + bool method_has_response) override; + + private: + // |fuchsia::component::runner::ComponentRunner| implementation: + void Start( + fuchsia::component::runner::ComponentStartInfo start_info, + fidl::InterfaceRequest + controller) override; + + // Add test components to this map to ensure it is kept alive in memory for + // the duration of test execution and retrieval of exit code. + std::map> + test_components_; + + // Not owned by DartRunner. + sys::ComponentContext* context_; + fidl::BindingSet + component_runner_bindings_; + +#if !defined(AOT_RUNTIME) + dart_utils::MappedResource vm_snapshot_data_; + dart_utils::MappedResource vm_snapshot_instructions_; +#endif + + // Disallow copy and assignment. + DartRunner(const DartRunner&) = delete; + DartRunner& operator=(const DartRunner&) = delete; +}; + +} // namespace dart_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_RUNNER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/dart_test_component_controller.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/dart_test_component_controller.cc new file mode 100644 index 0000000000000000000000000000000000000000..22446e86b7da25a1dfa39fdab5ec5b247f4696d2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/dart_test_component_controller.cc @@ -0,0 +1,678 @@ +// 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 "dart_test_component_controller.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "flutter/fml/logging.h" +#include "runtime/dart/utils/files.h" +#include "runtime/dart/utils/handle_exception.h" +#include "runtime/dart/utils/inlines.h" +#include "runtime/dart/utils/tempfs.h" +#include "third_party/dart/runtime/include/dart_tools_api.h" +#include "third_party/tonic/converter/dart_converter.h" +#include "third_party/tonic/dart_message_handler.h" +#include "third_party/tonic/dart_microtask_queue.h" +#include "third_party/tonic/dart_state.h" +#include "third_party/tonic/logging/dart_error.h" +#include "third_party/tonic/logging/dart_invoke.h" + +#include "builtin_libraries.h" + +using tonic::ToDart; + +namespace dart_runner { + +namespace { + +constexpr char kTmpPath[] = "/tmp"; + +constexpr zx::duration kIdleWaitDuration = zx::sec(2); +constexpr zx::duration kIdleNotifyDuration = zx::msec(500); +constexpr zx::duration kIdleSlack = zx::sec(1); + +constexpr zx::duration kTestTimeout = zx::sec(60); + +void AfterTask(async_loop_t*, void*) { + tonic::DartMicrotaskQueue* queue = + tonic::DartMicrotaskQueue::GetForCurrentThread(); + // Verify that the queue exists, as this method could have been called back as + // part of the exit routine, after the destruction of the microtask queue. + if (queue) { + queue->RunMicrotasks(); + } +} + +constexpr async_loop_config_t kLoopConfig = { + .default_accessors = + { + .getter = async_get_default_dispatcher, + .setter = async_set_default_dispatcher, + }, + .make_default_for_current_thread = true, + .epilogue = &AfterTask, +}; + +// Find the last path of the component. +// fuchsia-pkg://fuchsia.com/hello_dart#meta/hello_dart.cmx -> hello_dart.cmx +std::string GetLabelFromUrl(const std::string& url) { + for (size_t i = url.length() - 1; i > 0; i--) { + if (url[i] == '/') { + return url.substr(i + 1, url.length() - 1); + } + } + return url; +} + +// Find the name of the component. +// fuchsia-pkg://fuchsia.com/hello_dart#meta/hello_dart.cm -> hello_dart +std::string GetComponentNameFromUrl(const std::string& url) { + const std::string label = GetLabelFromUrl(url); + for (size_t i = 0; i < label.length(); ++i) { + if (label[i] == '.') { + return label.substr(0, i); + } + } + return label; +} + +} // namespace + +DartTestComponentController::DartTestComponentController( + fuchsia::component::runner::ComponentStartInfo start_info, + std::shared_ptr runner_incoming_services, + fidl::InterfaceRequest + controller, + DoneCallback done_callback) + : loop_(new async::Loop(&kLoopConfig)), + executor_(loop_->dispatcher()), + label_(GetLabelFromUrl(start_info.resolved_url())), + url_(std::move(start_info.resolved_url())), + runner_incoming_services_(runner_incoming_services), + start_info_(std::move(start_info)), + binding_(this), + done_callback_(std::move(done_callback)) { + // TODO(fxb/84537): This data path is configured based how we build Flutter + // applications in tree currently, but the way we build the Flutter + // application may change. We should avoid assuming the data path and let the + // CML file specify this data path instead. + test_component_name_ = GetComponentNameFromUrl(url_); + data_path_ = "pkg/data/" + test_component_name_; + + if (controller.is_valid()) { + binding_.Bind(std::move(controller)); + binding_.set_error_handler([this](zx_status_t status) { Kill(); }); + } else { + FML_LOG(ERROR) << "Fuchsia component controller endpoint is not valid."; + } + + zx_status_t idle_timer_status = + zx::timer::create(ZX_TIMER_SLACK_LATE, ZX_CLOCK_MONOTONIC, &idle_timer_); + if (idle_timer_status != ZX_OK) { + FML_LOG(INFO) << "Idle timer creation failed: " + << zx_status_get_string(idle_timer_status); + } else { + idle_wait_.set_object(idle_timer_.get()); + idle_wait_.set_trigger(ZX_TIMER_SIGNALED); + idle_wait_.Begin(async_get_default_dispatcher()); + } + + // Close the runtime_dir channel if we don't intend to serve it. Otherwise any + // access to the runtime_dir will hang forever. + start_info_.clear_runtime_dir(); +} + +DartTestComponentController::~DartTestComponentController() { + if (namespace_) { + fdio_ns_destroy(namespace_); + namespace_ = nullptr; + } + close(stdout_fd_); + close(stderr_fd_); +} + +void DartTestComponentController::SetUp() { + // Name the thread after the url of the component being launched. + zx::thread::self()->set_property(ZX_PROP_NAME, label_.c_str(), label_.size()); + Dart_SetThreadName(label_.c_str()); + + if (!CreateAndBindNamespace()) { + return; + } + + if (SetUpFromAppSnapshot()) { + FML_LOG(INFO) << url_ << " is running from an app snapshot"; + } else if (SetUpFromKernel()) { + FML_LOG(INFO) << url_ << " is running from kernel"; + } else { + FML_LOG(ERROR) << "Failed to set up component controller for " << url_; + return; + } + + // Serve |fuchsia::test::Suite| on outgoing directory. + suite_context_ = sys::ComponentContext::Create(); + suite_context_->outgoing()->AddPublicService(this->GetHandler()); + suite_context_->outgoing()->Serve( + std::move(*start_info_.mutable_outgoing_dir()), loop_->dispatcher()); + + loop_->Run(); +} + +bool DartTestComponentController::CreateAndBindNamespace() { + if (!start_info_.has_ns()) { + FML_LOG(ERROR) << "Component start info does not have a namespace."; + return false; + } + + const zx_status_t ns_create_status = fdio_ns_create(&namespace_); + if (ns_create_status != ZX_OK) { + FML_LOG(ERROR) << "Failed to create namespace: " + << zx_status_get_string(ns_create_status); + } + + dart_utils::BindTemp(namespace_); + + // Bind each directory in start_info's namespace to the controller's namespace + // instance. + for (auto& ns_entry : *start_info_.mutable_ns()) { + // TODO(akbiggs): Under what circumstances does a namespace entry not + // have a path or directory? Should we log an error for these? + if (!ns_entry.has_path() || !ns_entry.has_directory()) { + continue; + } + + if (ns_entry.path() == kTmpPath) { + // /tmp is covered by a locally served virtual filesystem. + continue; + } + + // We move ownership of the directory & path since RAII is used to keep + // the handle open. + fidl::InterfaceHandle<::fuchsia::io::Directory> dir = + std::move(*ns_entry.mutable_directory()); + const std::string path = std::move(*ns_entry.mutable_path()); + + const zx_status_t ns_bind_status = + fdio_ns_bind(namespace_, path.c_str(), dir.TakeChannel().release()); + if (ns_bind_status != ZX_OK) { + FML_LOG(ERROR) << "Failed to bind " << path << " to namespace: " + << zx_status_get_string(ns_bind_status); + return false; + } + } + + return true; +} + +bool DartTestComponentController::SetUpFromKernel() { + dart_utils::MappedResource manifest; + if (!dart_utils::MappedResource::LoadFromNamespace( + namespace_, data_path_ + "/app.dilplist", manifest)) { + return false; + } + + if (!dart_utils::MappedResource::LoadFromNamespace( + nullptr, "/pkg/data/isolate_core_snapshot_data.bin", + isolate_snapshot_data_)) { + return false; + } + + std::string str(reinterpret_cast(manifest.address()), + manifest.size()); + Dart_Handle library = Dart_Null(); + + for (size_t start = 0; start < manifest.size();) { + size_t end = str.find("\n", start); + if (end == std::string::npos) { + FML_LOG(ERROR) << "Malformed manifest"; + return false; + } + + std::string path = data_path_ + "/" + str.substr(start, end - start); + start = end + 1; + + dart_utils::MappedResource kernel; + if (!dart_utils::MappedResource::LoadFromNamespace(namespace_, path, + kernel)) { + FML_LOG(ERROR) << "Cannot load kernel from namespace: " << path; + return false; + } + kernel_peices_.emplace_back(std::move(kernel)); + } + + if (!CreateIsolate(isolate_snapshot_data_.address(), + /*isolate_snapshot_instructions=*/nullptr)) { + return false; + } + + Dart_EnterScope(); + + for (const auto& kernel : kernel_peices_) { + library = Dart_LoadLibraryFromKernel(kernel.address(), kernel.size()); + if (Dart_IsError(library)) { + FML_LOG(ERROR) << "Cannot load library from kernel: " + << Dart_GetError(library); + Dart_ExitScope(); + return false; + } + } + Dart_SetRootLibrary(library); + + Dart_Handle result = Dart_FinalizeLoading(false); + if (Dart_IsError(result)) { + FML_LOG(ERROR) << "Failed to FinalizeLoading: " << Dart_GetError(result); + Dart_ExitScope(); + return false; + } + + return true; +} + +bool DartTestComponentController::SetUpFromAppSnapshot() { +#if !defined(AOT_RUNTIME) + return false; +#else + // Load the ELF snapshot as available, and fall back to a blobs snapshot + // otherwise. + const uint8_t *isolate_data, *isolate_instructions; + if (elf_snapshot_.Load(namespace_, data_path_ + "/app_aot_snapshot.so")) { + isolate_data = elf_snapshot_.IsolateData(); + isolate_instructions = elf_snapshot_.IsolateInstrs(); + if (isolate_data == nullptr || isolate_instructions == nullptr) { + return false; + } + } else { + if (!dart_utils::MappedResource::LoadFromNamespace( + namespace_, data_path_ + "/isolate_snapshot_data.bin", + isolate_snapshot_data_)) { + return false; + } + isolate_data = isolate_snapshot_data_.address(); + isolate_instructions = nullptr; + } + return CreateIsolate(isolate_data, isolate_instructions); +#endif // defined(AOT_RUNTIME) +} + +bool DartTestComponentController::CreateIsolate( + const uint8_t* isolate_snapshot_data, + const uint8_t* isolate_snapshot_instructions) { + // Create the isolate from the snapshot. + char* error = nullptr; + + // TODO(dart_runner): Pass if we start using tonic's loader. + intptr_t namespace_fd = -1; + + // Freed in IsolateShutdownCallback. + auto state = new std::shared_ptr(new tonic::DartState( + namespace_fd, [this](Dart_Handle result) { MessageEpilogue(result); })); + + Dart_IsolateFlags isolate_flags; + Dart_IsolateFlagsInitialize(&isolate_flags); + isolate_flags.null_safety = true; + + isolate_ = Dart_CreateIsolateGroup( + url_.c_str(), label_.c_str(), isolate_snapshot_data, + isolate_snapshot_instructions, &isolate_flags, state, state, &error); + if (!isolate_) { + FML_LOG(ERROR) << "Dart_CreateIsolateGroup failed: " << error; + return false; + } + + state->get()->SetIsolate(isolate_); + + tonic::DartMessageHandler::TaskDispatcher dispatcher = + [loop = loop_.get()](auto callback) { + async::PostTask(loop->dispatcher(), std::move(callback)); + }; + state->get()->message_handler().Initialize(dispatcher); + + state->get()->SetReturnCodeCallback([this](uint32_t return_code) { + return_code_ = return_code; + auto ret_status = return_code == 0 ? fuchsia::test::Status::PASSED + : fuchsia::test::Status::FAILED; + fuchsia::test::Result result; + result.set_status(ret_status); + case_listener_->Finished(std::move(result)); + }); + + return true; +} + +// |fuchsia::test::CaseIterator| +DartTestComponentController::CaseIterator::CaseIterator( + fidl::InterfaceRequest request, + async_dispatcher_t* dispatcher, + std::string test_component_name, + fit::function done_callback) + : binding_(this, std::move(request), dispatcher), + test_component_name_(test_component_name), + done_callback_(std::move(done_callback)) {} + +// |fuchsia::test::CaseIterator| +void DartTestComponentController::CaseIterator::GetNext( + GetNextCallback callback) { + // Dart test suites run as multiple tests behind one + // test case. Flip flag once the one test case has been retrieved. + if (first_case_) { + fuchsia::test::Case test_case; + test_case.set_name(test_component_name_); + test_case.set_enabled(true); + std::vector cases; + cases.push_back(std::move(test_case)); + callback(std::move(cases)); + first_case_ = false; + } else { + // Return an pass an empty vector to the callback to indicate there + // are no more tests to be executed. + std::vector cases; + callback(std::move(cases)); + done_callback_(this); + } +} + +// |fuchsia::test::CaseIterator| +std::unique_ptr +DartTestComponentController::RemoveCaseInterator(CaseIterator* case_iterator) { + auto it = case_iterators_.find(case_iterator); + std::unique_ptr case_iterator_ptr; + if (it != case_iterators_.end()) { + case_iterator_ptr = std::move(it->second); + case_iterators_.erase(it); + } + return case_iterator_ptr; +} + +// |fuchsia::test::Suite| +void DartTestComponentController::GetTests( + fidl::InterfaceRequest iterator) { + auto case_iterator = std::make_unique( + std::move(iterator), loop_->dispatcher(), test_component_name_, + [this](CaseIterator* case_iterator) { + RemoveCaseInterator(case_iterator); + }); + case_iterators_.emplace(case_iterator.get(), std::move(case_iterator)); +} + +// |fuchsia::test::Suite| +void DartTestComponentController::Run( + std::vector tests, + fuchsia::test::RunOptions options, + fidl::InterfaceHandle listener) { + std::vector args; + if (options.has_arguments()) { + args = std::move(*options.mutable_arguments()); + } + + auto listener_proxy = listener.Bind(); + + // We expect 1 test that will run all other tests in the test suite (i.e. a + // single main.dart that calls out to all of the dart tests). If the dart + // implementation in-tree changes, iterating over the invocations like so + // will be able to handle that. + for (auto it = tests.begin(); it != tests.end(); it++) { + auto invocation = std::move(*it); + std::string test_case_name; + if (invocation.has_name()) { + test_case_name = invocation.name(); + } + + // Create and out/err sockets and pass file descriptor for each to the + // dart process so that logging can be forwarded to the test_manager. + auto status = zx::socket::create(0, &out_, &out_client_); + if (status != ZX_OK) { + FML_LOG(FATAL) << "cannot create out socket: " + << zx_status_get_string(status); + } + + status = fdio_fd_create(out_.release(), &stdout_fd_); + if (status != ZX_OK) { + FML_LOG(FATAL) << "failed to extract output fd: " + << zx_status_get_string(status); + } + + status = zx::socket::create(0, &err_, &err_client_); + if (status != ZX_OK) { + FML_LOG(FATAL) << "cannot create error socket: " + << zx_status_get_string(status); + } + + status = fdio_fd_create(err_.release(), &stderr_fd_); + if (status != ZX_OK) { + FML_LOG(FATAL) << "failed to extract error fd: " + << zx_status_get_string(status); + } + + // Pass client end of out and err socket for test_manager to stream logs to + // current terminal, via |fuchsia::test::StdHandles|. + fuchsia::test::StdHandles std_handles; + std_handles.set_out(std::move(out_client_)); + std_handles.set_err(std::move(err_client_)); + + listener_proxy->OnTestCaseStarted(std::move(invocation), + std::move(std_handles), + case_listener_.NewRequest()); + + // Run dart main and wait until exit code has been set before notifying of + // test completion. + auto dart_main_promise = fpromise::make_promise([&] { RunDartMain(); }); + auto dart_state = tonic::DartState::Current(); + executor_.schedule_task(std::move(dart_main_promise)); + while (!dart_state->has_set_return_code()) { + loop_->Run(zx::deadline_after(kTestTimeout), true); + } + + // Notify the test_manager that the test has completed. + listener_proxy->OnFinished(); + } + + if (binding_.is_bound()) { + // From the documentation for ComponentController, ZX_OK should be sent when + // the ComponentController receives a termination request. However, if the + // component exited with a non-zero return code, we indicate this by sending + // an INTERNAL epitaph instead. + // + // TODO(fxb/86666): Communicate return code from the ComponentController + // once v2 has support. + if (return_code_ == 0) { + binding_.Close(ZX_OK); + } else { + binding_.Close(zx_status_t(fuchsia::component::Error::INTERNAL)); + } + } + + // Stop and kill the test component. + Stop(); +} + +fpromise::promise<> DartTestComponentController::RunDartMain() { + FML_CHECK(namespace_ != nullptr); + Dart_EnterScope(); + + tonic::DartMicrotaskQueue::StartForCurrentThread(); + + fidl::InterfaceRequest outgoing_dir = + std::move(*start_info_.mutable_outgoing_dir()); + InitBuiltinLibrariesForIsolate(url_, namespace_, stdout_fd_, stderr_fd_, + outgoing_dir.TakeChannel(), + false /* service_isolate */); + + Dart_ExitScope(); + Dart_ExitIsolate(); + char* error = Dart_IsolateMakeRunnable(isolate_); + if (error != nullptr) { + Dart_EnterIsolate(isolate_); + Dart_ShutdownIsolate(); + FML_LOG(ERROR) << "Unable to make isolate runnable: " << error; + free(error); + return fpromise::make_error_promise(); + } + Dart_EnterIsolate(isolate_); + Dart_EnterScope(); + + // TODO(fxb/88383): Support argument passing. + Dart_Handle corelib = Dart_LookupLibrary(ToDart("dart:core")); + Dart_Handle string_type = + Dart_GetNonNullableType(corelib, ToDart("String"), 0, NULL); + Dart_Handle dart_arguments = + Dart_NewListOfTypeFilled(string_type, Dart_EmptyString(), 0); + + if (Dart_IsError(dart_arguments)) { + FML_LOG(ERROR) << "Failed to allocate Dart arguments list: " + << Dart_GetError(dart_arguments); + Dart_ExitScope(); + return fpromise::make_error_promise(); + } + + Dart_Handle user_main = Dart_GetField(Dart_RootLibrary(), ToDart("main")); + + if (Dart_IsError(user_main)) { + FML_LOG(ERROR) << "Failed to locate user_main in the root library: " + << Dart_GetError(user_main); + Dart_ExitScope(); + return fpromise::make_error_promise(); + } + + Dart_Handle fuchsia_lib = Dart_LookupLibrary(tonic::ToDart("dart:fuchsia")); + + if (Dart_IsError(fuchsia_lib)) { + FML_LOG(ERROR) << "Failed to locate dart:fuchsia: " + << Dart_GetError(fuchsia_lib); + Dart_ExitScope(); + return fpromise::make_error_promise(); + } + + Dart_Handle main_result = tonic::DartInvokeField( + fuchsia_lib, "_runUserMainForDartRunner", {user_main, dart_arguments}); + + if (Dart_IsError(main_result)) { + auto dart_state = tonic::DartState::Current(); + if (!dart_state->has_set_return_code()) { + // The program hasn't set a return code meaning this exit is unexpected. + FML_LOG(ERROR) << Dart_GetError(main_result); + return_code_ = tonic::GetErrorExitCode(main_result); + + dart_utils::HandleIfException(runner_incoming_services_, url_, + main_result); + } + Dart_ExitScope(); + return fpromise::make_error_promise(); + } + + Dart_ExitScope(); + return fpromise::make_ok_promise(); +} + +void DartTestComponentController::Kill() { + done_callback_(this); + close(stdout_fd_); + close(stderr_fd_); + suite_bindings_.CloseAll(); + if (Dart_CurrentIsolate()) { + tonic::DartMicrotaskQueue* queue = + tonic::DartMicrotaskQueue::GetForCurrentThread(); + if (queue) { + queue->Destroy(); + } + + loop_->Quit(); + + // TODO(rosswang): The docs warn of threading issues if doing this again, + // but without this, attempting to shut down the isolate finalizes app + // contexts that can't tell a shutdown is in progress and so fatal. + Dart_SetMessageNotifyCallback(nullptr); + + Dart_ShutdownIsolate(); + } +} + +void DartTestComponentController::MessageEpilogue(Dart_Handle result) { + auto dart_state = tonic::DartState::Current(); + // If the Dart program has set a return code, then it is intending to shut + // down by way of a fatal error, and so there is no need to override + // return_code_. + if (dart_state->has_set_return_code()) { + Dart_ShutdownIsolate(); + return; + } + + dart_utils::HandleIfException(runner_incoming_services_, url_, result); + + // Otherwise, see if there was any other error. + return_code_ = tonic::GetErrorExitCode(result); + if (return_code_ != 0) { + Dart_ShutdownIsolate(); + return; + } + + idle_start_ = zx::clock::get_monotonic(); + zx_status_t status = + idle_timer_.set(idle_start_ + kIdleWaitDuration, kIdleSlack); + if (status != ZX_OK) { + FML_LOG(INFO) << "Idle timer set failed: " << zx_status_get_string(status); + } +} + +void DartTestComponentController::Stop() { + Kill(); +} + +void DartTestComponentController::OnIdleTimer(async_dispatcher_t* dispatcher, + async::WaitBase* wait, + zx_status_t status, + const zx_packet_signal* signal) { + if ((status != ZX_OK) || !(signal->observed & ZX_TIMER_SIGNALED) || + !Dart_CurrentIsolate()) { + // Timer closed or isolate shutdown. + return; + } + + zx::time deadline = idle_start_ + kIdleWaitDuration; + zx::time now = zx::clock::get_monotonic(); + if (now >= deadline) { + // No Dart message has been processed for kIdleWaitDuration: assume we'll + // stay idle for kIdleNotifyDuration. + Dart_NotifyIdle((now + kIdleNotifyDuration).get()); + idle_start_ = zx::time(0); + idle_timer_.cancel(); // De-assert signal. + } else { + // Early wakeup or message pushed idle time forward: reschedule. + zx_status_t status = idle_timer_.set(deadline, kIdleSlack); + if (status != ZX_OK) { + FML_LOG(INFO) << "Idle timer set failed: " + << zx_status_get_string(status); + } + } + wait->Begin(dispatcher); // ignore errors +} + +void DartTestComponentController::handle_unknown_method( + uint64_t ordinal, + bool method_has_response) { + FML_LOG(ERROR) << "Unknown method called on DartTestComponentController. " + "Ordinal: " + << ordinal; +} + +} // namespace dart_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/dart_test_component_controller.h b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/dart_test_component_controller.h new file mode 100644 index 0000000000000000000000000000000000000000..477a71384c6a5cf4a57f16742ca7f527e0594c3d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/dart_test_component_controller.h @@ -0,0 +1,170 @@ +// 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_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_TEST_COMPONENT_CONTROLLER_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_TEST_COMPONENT_CONTROLLER_H_ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include "lib/fidl/cpp/binding.h" +#include "runtime/dart/utils/mapped_resource.h" +#include "third_party/dart/runtime/include/dart_api.h" + +namespace dart_runner { + +/// Starts a Dart test component written in CFv2. It's different from +/// DartComponentController in that it must implement the +/// |fuchsia.test.Suite| protocol. It was forked to avoid a naming clash +/// between the two classes' methods as the Suite protocol requires a Run() +/// method for the test_manager to call on. This way, we avoid an extra layer +/// between the test_manager and actual test execution. +/// TODO(fxb/98369): Look into combining the two component classes once dart +/// testing is stable. +class DartTestComponentController + : public fuchsia::component::runner::ComponentController, + public fuchsia::test::Suite { + using DoneCallback = fit::function; + + public: + DartTestComponentController( + fuchsia::component::runner::ComponentStartInfo start_info, + std::shared_ptr runner_incoming_services, + fidl::InterfaceRequest + controller, + DoneCallback done_callback); + + ~DartTestComponentController() override; + + /// Sets up the controller. + /// + /// This should be called before |Run|. + void SetUp(); + + /// |Suite| protocol implementation. + void GetTests( + fidl::InterfaceRequest iterator) override; + + /// |Suite| protocol implementation. + void Run(std::vector tests, + fuchsia::test::RunOptions options, + fidl::InterfaceHandle listener) override; + + fidl::InterfaceRequestHandler GetHandler() { + return suite_bindings_.GetHandler(this, loop_->dispatcher()); + } + + void handle_unknown_method(uint64_t ordinal, + bool method_has_response) override; + + private: + /// Helper for actually running the Dart main. Returns a promise. + fpromise::promise<> RunDartMain(); + + /// Creates and binds the namespace for this component. Returns true if + /// successful, false otherwise. + bool CreateAndBindNamespace(); + + bool SetUpFromKernel(); + bool SetUpFromAppSnapshot(); + + bool CreateIsolate(const uint8_t* isolate_snapshot_data, + const uint8_t* isolate_snapshot_instructions); + + // |ComponentController| + void Kill() override; + void Stop() override; + + // Idle notification. + void MessageEpilogue(Dart_Handle result); + void OnIdleTimer(async_dispatcher_t* dispatcher, + async::WaitBase* wait, + zx_status_t status, + const zx_packet_signal* signal); + + // |CaseIterator| + class CaseIterator final : public fuchsia::test::CaseIterator { + public: + CaseIterator(fidl::InterfaceRequest request, + async_dispatcher_t* dispatcher, + std::string test_component_name, + fit::function done_callback); + + void GetNext(GetNextCallback callback) override; + + private: + bool first_case_ = true; + fidl::Binding binding_; + std::string test_component_name_; + fit::function done_callback_; + }; + + std::unique_ptr RemoveCaseInterator(CaseIterator*); + + // We only need one case_listener currently as dart tests are run as one + // large test file. In future iterations, case_listeners must be + // created per test case. + fidl::InterfacePtr case_listener_; + std::map> case_iterators_; + + // |Suite| + + /// Exposes suite protocol on behalf of test component. + std::string test_component_name_; + std::unique_ptr suite_context_; + fidl::BindingSet suite_bindings_; + + // The loop must be the first declared member so that it gets destroyed after + // binding_ which expects the existence of a loop. + std::unique_ptr loop_; + async::Executor executor_; + + std::string label_; + std::string url_; + std::shared_ptr runner_incoming_services_; + std::string data_path_; + std::unique_ptr context_; + + fuchsia::component::runner::ComponentStartInfo start_info_; + fidl::Binding binding_; + DoneCallback done_callback_; + + zx::socket out_, err_, out_client_, err_client_; + fdio_ns_t* namespace_ = nullptr; + int stdout_fd_ = -1; + int stderr_fd_ = -1; + + dart_utils::ElfSnapshot elf_snapshot_; // AOT snapshot + dart_utils::MappedResource isolate_snapshot_data_; // JIT snapshot + dart_utils::MappedResource isolate_snapshot_instructions_; // JIT snapshot + std::vector kernel_peices_; + + Dart_Isolate isolate_; + int32_t return_code_ = 0; + + zx::time idle_start_{0}; + zx::timer idle_timer_; + async::WaitMethod + idle_wait_{this}; + + // Disallow copy and assignment. + DartTestComponentController(const DartTestComponentController&) = delete; + DartTestComponentController& operator=(const DartTestComponentController&) = + delete; +}; + +} // namespace dart_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_TEST_COMPONENT_CONTROLLER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/embedder/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/embedder/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..eb7e0562fbd162927f69ea36afacf994e25609f5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/embedder/BUILD.gn @@ -0,0 +1,79 @@ +# 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. + +import("//build/compiled_action.gni") +import("//flutter/common/fuchsia_config.gni") +import("//flutter/tools/fuchsia/dart_kernel.gni") +import("$dart_src/build/dart/dart_action.gni") + +dart_kernel("shim_kernel") { + main_dart = "shim.dart" + kernel_platform_files = "../kernel:kernel_platform_files" + product = false + aot = true +} + +dart_kernel("shim_product_kernel") { + main_dart = "shim.dart" + kernel_platform_files = "../kernel:kernel_platform_files" + product = true + aot = true +} + +template("create_aot_snapshot") { + assert(defined(invoker.product), "The parameter 'product' must be defined") + product_suffix = "" + if (invoker.product) { + product_suffix = "_product" + } + compiled_action("${target_name}_assembly") { + snapshot_assembly = "$target_gen_dir/aot${product_suffix}_vm_snapshot.S" + + # gen_snapshot only needs this to go through the motions of setting up an isolate. + shim_target = ":shim${product_suffix}_kernel($host_toolchain)" + shim_kernel = get_label_info(shim_target, "target_gen_dir") + + "/shim${product_suffix}_kernel.dill" + + inputs = [ shim_kernel ] + outputs = [ snapshot_assembly ] + + deps = [ shim_target ] + if (invoker.product) { + tool = gen_snapshot_product + } else { + tool = gen_snapshot + } + + args = [ + "--deterministic", + "--snapshot_kind=vm-aot-assembly", + "--assembly=" + rebase_path(snapshot_assembly), + ] + + # No asserts in debug or release product. + # No asserts in release with flutter_profile=true (non-product) + # Yes asserts in non-product debug. + if (!invoker.product && (flutter_runtime_mode == "debug" || is_debug)) { + args += [ "--enable_asserts" ] + } + args += [ rebase_path(shim_kernel) ] + } + + source_set(target_name) { + deps = [ ":${target_name}_assembly" ] + + sources = [ + "$target_gen_dir/aot${product_suffix}_vm_snapshot.S", + "snapshot.h", + ] + } +} + +create_aot_snapshot("dart_aot_snapshot_cc") { + product = false +} + +create_aot_snapshot("dart_aot_product_snapshot_cc") { + product = true +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/embedder/builtin.dart b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/embedder/builtin.dart new file mode 100644 index 0000000000000000000000000000000000000000..8b03142e5deb7220d6340714d5fc25981668a113 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/embedder/builtin.dart @@ -0,0 +1,60 @@ +// 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. + +library fuchsia_builtin; + +import 'dart:async'; +import 'dart:io'; +import 'dart:_internal' show VMLibraryHooks; + +// Corelib 'print' implementation. +void _print(arg) { + _Logger._printString(arg.toString()); + try { + // If stdout is connected, print to it as well. + stdout.writeln(arg); + } on FileSystemException catch (_) { + // Some Fuchsia applications will not have stdout connected. + } +} + +class _Logger { + @pragma('vm:external-name', 'Logger_PrintString') + external static void _printString(String s); +} + +@pragma('vm:entry-point') +late String _rawScript; + +Uri _scriptUri() { + if (_rawScript.startsWith('http:') || + _rawScript.startsWith('https:') || + _rawScript.startsWith('file:')) { + return Uri.parse(_rawScript); + } else { + return Uri.base.resolveUri(Uri.file(_rawScript)); + } +} + +@pragma('vm:external-name', 'ScheduleMicrotask') +external void _scheduleMicrotask(void callback()); + +@pragma('vm:entry-point') +_getScheduleMicrotaskClosure() => _scheduleMicrotask; + +@pragma('vm:entry-point') +_setupHooks() { + VMLibraryHooks.platformScript = _scriptUri; +} + +@pragma('vm:entry-point') +_getPrintClosure() => _print; + +typedef EchoStringCallback = String? Function(String? str); +late EchoStringCallback? receiveEchoStringCallback; + +@pragma('vm:entry-point') +String? _receiveEchoString(String? str) { + return receiveEchoStringCallback?.call(str); +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/embedder/pubspec.yaml b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/embedder/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6ef1940491851722568c3ca096c4c5ca7b1192b7 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/embedder/pubspec.yaml @@ -0,0 +1,10 @@ +# 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. + +# The presence of this file is necessary in order to use the dart_library +# template in BUILD.gn. + +environment: + sdk: ^3.7.0-0 + diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/embedder/shim.dart b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/embedder/shim.dart new file mode 100644 index 0000000000000000000000000000000000000000..6fb4720184eaf5d43d105ad6dd4f1e572c3877f5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/embedder/shim.dart @@ -0,0 +1,5 @@ +// 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. + +main() {} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/embedder/snapshot.cc.tmpl b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/embedder/snapshot.cc.tmpl new file mode 100644 index 0000000000000000000000000000000000000000..29ce3993156a458828715eb818fe0fa3f7754edc --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/embedder/snapshot.cc.tmpl @@ -0,0 +1,25 @@ +// 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. + +// This file is linked into the dart executable when it has a snapshot +// linked into it. + +#include "embedder/snapshot.h" + +namespace dart_runner { + +// The string on the next line will be filled in with the contents of the +// generated snapshot binary file for the vm isolate. This string forms the +// content of the dart vm isolate snapshot which is loaded into the vm isolate. +static const uint8_t vm_isolate_snapshot_buffer_[] = { % s}; +uint8_t const* const vm_isolate_snapshot_buffer = vm_isolate_snapshot_buffer_; + +// The string on the next line will be filled in with the contents of the +// generated snapshot binary file for a regular dart isolate. +// This string forms the content of a regular dart isolate snapshot which +// is loaded into an isolate when it is created. +static const uint8_t isolate_snapshot_buffer_[] = { % s}; +uint8_t const* const isolate_snapshot_buffer = isolate_snapshot_buffer_; + +} // namespace dart_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/embedder/snapshot.dart b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/embedder/snapshot.dart new file mode 100644 index 0000000000000000000000000000000000000000..4bfa41edf0002f7b1884035c31067ba57a510d71 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/embedder/snapshot.dart @@ -0,0 +1,15 @@ +// 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. + +import 'dart:async'; +import 'dart:core'; +import 'dart:collection'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:isolate'; +import 'dart:math'; +import 'dart:fuchsia.builtin'; +import 'dart:zircon'; +import 'dart:fuchsia'; +import 'dart:typed_data'; diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/embedder/snapshot.h b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/embedder/snapshot.h new file mode 100644 index 0000000000000000000000000000000000000000..edd9c1eae59e9b32e1191c4c7e0d2360c52a1cbb --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/embedder/snapshot.h @@ -0,0 +1,17 @@ +// 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_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_EMBEDDER_SNAPSHOT_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_EMBEDDER_SNAPSHOT_H_ + +#include + +namespace dart_runner { + +extern uint8_t const* const vm_isolate_snapshot_buffer; +extern uint8_t const* const isolate_snapshot_buffer; + +} // namespace dart_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_EMBEDDER_SNAPSHOT_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/fidl/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/fidl/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..3923e527169adac30e80a1ca3f4dd8ed9c72d865 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/fidl/BUILD.gn @@ -0,0 +1,10 @@ +# 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. + +import("//flutter/tools/fuchsia/gn-sdk/src/fidl_library.gni") + +fidl_library("dart_test") { + library_name = "dart.test" + sources = [ "echo.fidl" ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/fidl/echo.fidl b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/fidl/echo.fidl new file mode 100644 index 0000000000000000000000000000000000000000..6c39ac59f7db28616c653f4db37d846efb25fc7f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/fidl/echo.fidl @@ -0,0 +1,17 @@ +// 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. + +library dart.test; + +const MAX_STRING_LENGTH uint64 = 32; + +@discoverable +closed protocol Echo { + /// Returns the input. + strict EchoString(struct { + value string:; + }) -> (struct { + response string:; + }); +}; diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/kernel/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/kernel/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..7e066a38b853e2a52cd336251547131d9a007e12 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/kernel/BUILD.gn @@ -0,0 +1,85 @@ +# 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. + +import("//build/compiled_action.gni") +import("//flutter/common/config.gni") +import("//flutter/tools/fuchsia/dart.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") +import("$dart_src/utils/compile_platform.gni") + +compile_platform("kernel_platform_files") { + single_root_scheme = "org-dartlang-sdk" + single_root_base = rebase_path("../../../../../../") + + libraries_specification_uri = "org-dartlang-sdk:///flutter/shell/platform/fuchsia/dart_runner/kernel/libraries.json" + + outputs = [ + "$root_out_dir/dart_runner_patched_sdk/platform_strong.dill", + "$root_out_dir/dart_runner_patched_sdk/vm_outline_strong.dill", + ] + + args = [ + "--nnbd-strong", + "--target=dart_runner", + "dart:core", + ] +} + +template("create_kernel_core_snapshot") { + assert(defined(invoker.product), "The parameter 'product' must be defined") + product_suffix = "" + if (invoker.product) { + product_suffix = "_product" + } + + compiled_action(target_name) { + deps = [ ":kernel_platform_files" ] + + platform_dill = "$root_out_dir/dart_runner_patched_sdk/platform_strong.dill" + inputs = [ platform_dill ] + + vm_snapshot_data = "$target_gen_dir/vm_data${product_suffix}.bin" + isolate_snapshot_data = "$target_gen_dir/isolate_data${product_suffix}.bin" + snapshot_profile = "$target_gen_dir/snapshot_profile${product_suffix}.json" + outputs = [ + vm_snapshot_data, + isolate_snapshot_data, + snapshot_profile, + ] + + gen_snapshot_to_use = gen_snapshot + if (invoker.product) { + gen_snapshot_to_use = gen_snapshot_product + } + + tool = gen_snapshot_to_use + + args = [ + "--enable_mirrors=false", + "--deterministic", + "--snapshot_kind=core", + "--vm_snapshot_data=" + rebase_path(vm_snapshot_data, root_build_dir), + "--isolate_snapshot_data=" + + rebase_path(isolate_snapshot_data, root_build_dir), + "--write_v8_snapshot_profile_to=" + + rebase_path(snapshot_profile, root_build_dir), + ] + + # No asserts in debug or release product. + # No asserts in release with flutter_profile=true (non-product) + # Yes asserts in non-product debug. + if (!invoker.product && (is_debug || flutter_runtime_mode == "debug")) { + args += [ "--enable_asserts" ] + } + args += [ rebase_path(platform_dill) ] + } +} + +create_kernel_core_snapshot("kernel_core_snapshot") { + product = false +} + +create_kernel_core_snapshot("kernel_core_snapshot_product") { + product = true +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/kernel/libraries.json b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/kernel/libraries.json new file mode 100644 index 0000000000000000000000000000000000000000..6161d1d2fa1d1ff95831ab5516ee6f951f0519fa --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/kernel/libraries.json @@ -0,0 +1,26 @@ +{ + "comment:0": "NOTE: THIS FILE IS GENERATED. DO NOT EDIT.", + "comment:1": "Instead modify 'flutter/shell/platform/fuchsia/dart_runner/kernel/libraries.yaml' and follow the instructions therein.", + "dart_runner": { + "include": [ + { + "path": "../../../../../third_party/dart/sdk/lib/libraries.json", + "target": "vm_common" + } + ], + "libraries": { + "fuchsia.builtin": { + "uri": "../embedder/builtin.dart" + }, + "zircon": { + "uri": "../../dart-pkg/zircon/lib/zircon.dart" + }, + "zircon_ffi": { + "uri": "../../dart-pkg/zircon_ffi/lib/zircon_ffi.dart" + }, + "fuchsia": { + "uri": "../../dart-pkg/fuchsia/lib/fuchsia.dart" + } + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/kernel/libraries.yaml b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/kernel/libraries.yaml new file mode 100644 index 0000000000000000000000000000000000000000..882104644d4a00a3d6e944b48f2bd99d95be1a3f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/kernel/libraries.yaml @@ -0,0 +1,30 @@ +# Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file +# for details. All rights reserved. Use of this source code is governed by a +# BSD-style license that can be found in the LICENSE file. + +# Note: if you edit this file, you must also generate libraries.json in this +# directory: +# +# dart third_party/dart/tools/yaml2json.dart flutter/shell/platform/fuchsia/dart_runner/kernel/libraries.yaml flutter/shell/platform/fuchsia/dart_runner/kernel/libraries.json +# +# We currently have several different files that needs to be updated when +# changing libraries, sources, and patch files. See +# https://github.com/dart-lang/sdk/issues/28836. + +dart_runner: + include: + - {path: "../../../../../../third_party/dart/sdk/lib/libraries.json", target: vm_common} + libraries: + fuchsia.builtin: + uri: "../embedder/builtin.dart" + + zircon: + uri: "../../dart-pkg/zircon/lib/zircon.dart" + + zircon_ffi: + uri: "../../dart-pkg/zircon_ffi/lib/zircon_ffi.dart" + + fuchsia: + uri: "../../dart-pkg/fuchsia/lib/fuchsia.dart" + + diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/logging.h b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/logging.h new file mode 100644 index 0000000000000000000000000000000000000000..2eb57d47d8cdd9ba2dba406a4c566d64c4b78e74 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/logging.h @@ -0,0 +1,15 @@ +// 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_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_LOGGING_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_LOGGING_H_ + +namespace dart_runner { + +// Use to mark logs published via the syslog API. +#define LOG_TAG "dart-runner" + +} // namespace dart_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_LOGGING_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/main.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/main.cc new file mode 100644 index 0000000000000000000000000000000000000000..1ab0648eaf3bca3ef407748a09c7cdc8271830e7 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/main.cc @@ -0,0 +1,79 @@ +// 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 +#include +#include +#include +#include + +#include "dart_runner.h" +#include "flutter/fml/logging.h" +#include "flutter/fml/platform/fuchsia/log_interest_listener.h" +#include "flutter/fml/platform/fuchsia/log_state.h" +#include "flutter/fml/trace_event.h" +#include "logging.h" +#include "platform/utils.h" +#include "runtime/dart/utils/build_info.h" +#include "runtime/dart/utils/files.h" +#include "runtime/dart/utils/root_inspect_node.h" +#include "runtime/dart/utils/tempfs.h" +#include "third_party/dart/runtime/include/dart_api.h" + +#if !defined(DART_PRODUCT) +// Register native symbol information for the Dart VM's profiler. +static void RegisterProfilerSymbols(const char* symbols_path, + const char* dso_name) { + std::string* symbols = new std::string(); + if (dart_utils::ReadFileToString(symbols_path, symbols)) { + Dart_AddSymbols(dso_name, symbols->data(), symbols->size()); + } else { + FML_LOG(ERROR) << "Failed to load " << symbols_path; + FML_CHECK(false); + } +} +#endif // !defined(DART_PRODUCT) + +int main(int argc, const char** argv) { + async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread); + + // Setup logging. + fml::LogState::Default().SetTags({LOG_TAG}); + fml::LogInterestListener listener(fml::LogState::Default().TakeClientEnd(), + loop.dispatcher()); + listener.AsyncWaitForInterestChanged(); + + // Create our component context which is served later. + auto context = sys::ComponentContext::Create(); + dart_utils::RootInspectNode::Initialize(context.get()); + auto build_info = dart_utils::RootInspectNode::CreateRootChild("build_info"); + dart_utils::BuildInfo::Dump(build_info); + + dart::SetDartVmNode(std::make_unique( + dart_utils::RootInspectNode::CreateRootChild("vm"))); + + std::unique_ptr provider; + { + bool already_started; + // Use CreateSynchronously to prevent loss of early events. + trace::TraceProviderWithFdio::CreateSynchronously( + loop.dispatcher(), "dart_runner", &provider, &already_started); + } + +#if !defined(DART_PRODUCT) +#if defined(AOT_RUNTIME) + RegisterProfilerSymbols("pkg/data/dart_aot_runner.dartprofilersymbols", ""); +#else + RegisterProfilerSymbols("pkg/data/dart_jit_runner.dartprofilersymbols", ""); +#endif // defined(AOT_RUNTIME) +#endif // !defined(DART_PRODUCT) + + dart_runner::DartRunner runner(context.get()); + + // Wait to serve until we have finished all of our setup. + context->outgoing()->ServeFromStartupInfo(); + + loop.Run(); + return 0; +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/meta/common.shard.cml b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/meta/common.shard.cml new file mode 100644 index 0000000000000000000000000000000000000000..bb473bfa635f4c2eb3d8edb85943537229942d94 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/meta/common.shard.cml @@ -0,0 +1,46 @@ +// 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. +{ + // TODO(https://fxbug.dev/404543928): Remove this shard usage when possible + // and replace with explicit routes. + include: [ "syslog/client.shard.cml" ], + use: [ + // This is used by the Dart VM to communicate from Dart code to C++ code. + { + storage: "tmp", + path: "/tmp", + }, + // This is used by the Dart VM to load i18n data. + { + directory: "config-data", + rights: [ "r*" ], + path: "/config/data", + }, + // The ICU time zone data, factored out of `config-data`. + // See: + // https://fuchsia.dev/fuchsia-src/concepts/process/namespaces?typical_directory_structure + { + directory: "tzdata-icu", + rights: [ "r*" ], + path: "/config/tzdata/icu", + }, + { + protocol: [ + "fuchsia.device.NameProvider", // For fdio uname() + "fuchsia.feedback.CrashReporter", + "fuchsia.intl.PropertyProvider", // For dartVM timezone support + "fuchsia.net.name.Lookup", // For fdio sockets + "fuchsia.posix.socket.Provider", // For fdio sockets + ], + from: "parent", + }, + { + protocol: [ + "fuchsia.tracing.provider.Registry", // For trace-provider + ], + from: "parent", + availability: "optional", + }, + ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/meta/dart_aot_product_runner.cml b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/meta/dart_aot_product_runner.cml new file mode 100644 index 0000000000000000000000000000000000000000..5f3e58cea8ff45ad8be2e99fb3ec5c21aa5fb45b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/meta/dart_aot_product_runner.cml @@ -0,0 +1,24 @@ +// 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: [ "common.shard.cml" ], + program: { + runner: "elf", + binary: "bin/app", + forward_stdout_to: "log", + forward_stderr_to: "log", + }, + capabilities: [ + { + runner: "dart_aot_product_runner", + path: "/svc/fuchsia.component.runner.ComponentRunner", + }, + ], + expose: [ + { + runner: "dart_aot_product_runner", + from: "self", + }, + ], +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/meta/dart_aot_runner.cml b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/meta/dart_aot_runner.cml new file mode 100644 index 0000000000000000000000000000000000000000..d884ba849fc38cc2cd06da742bd981ea7b3b16b9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/meta/dart_aot_runner.cml @@ -0,0 +1,24 @@ +// 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: [ "common.shard.cml" ], + program: { + runner: "elf", + binary: "bin/app", + forward_stdout_to: "log", + forward_stderr_to: "log", + }, + capabilities: [ + { + runner: "dart_aot_runner", + path: "/svc/fuchsia.component.runner.ComponentRunner", + }, + ], + expose: [ + { + runner: "dart_aot_runner", + from: "self", + }, + ], +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/meta/dart_jit_product_runner.cml b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/meta/dart_jit_product_runner.cml new file mode 100644 index 0000000000000000000000000000000000000000..3e547bef304578c08baca2d100756d6cb6322d73 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/meta/dart_jit_product_runner.cml @@ -0,0 +1,26 @@ +// 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: [ "common.shard.cml" ], + program: { + runner: "elf", + binary: "bin/app", + forward_stdout_to: "log", + forward_stderr_to: "log", + // Needed for JIT builds. + job_policy_ambient_mark_vmo_exec: "true", + }, + capabilities: [ + { + runner: "dart_jit_product_runner", + path: "/svc/fuchsia.component.runner.ComponentRunner", + }, + ], + expose: [ + { + runner: "dart_jit_product_runner", + from: "self", + }, + ], +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/meta/dart_jit_runner.cml b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/meta/dart_jit_runner.cml new file mode 100644 index 0000000000000000000000000000000000000000..2552f7ea676acd317ca67c1e573290b3e1085cb1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/meta/dart_jit_runner.cml @@ -0,0 +1,26 @@ +// 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: [ "common.shard.cml" ], + program: { + runner: "elf", + binary: "bin/app", + forward_stdout_to: "log", + forward_stderr_to: "log", + // Needed for JIT builds. + job_policy_ambient_mark_vmo_exec: "true", + }, + capabilities: [ + { + runner: "dart_jit_runner", + path: "/svc/fuchsia.component.runner.ComponentRunner", + }, + ], + expose: [ + { + runner: "dart_jit_runner", + from: "self", + }, + ], +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/service_isolate.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/service_isolate.cc new file mode 100644 index 0000000000000000000000000000000000000000..59d9cb8fbf99904c8a487464d15c5f67cb78b66a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/service_isolate.cc @@ -0,0 +1,214 @@ +// 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 "service_isolate.h" + +#include "flutter/fml/logging.h" +#include "third_party/dart/runtime/include/bin/dart_io_api.h" +#include "third_party/tonic/converter/dart_converter.h" +#include "third_party/tonic/dart_library_natives.h" +#include "third_party/tonic/dart_microtask_queue.h" +#include "third_party/tonic/dart_state.h" +#include "third_party/tonic/typed_data/typed_list.h" + +#include "builtin_libraries.h" +#include "dart_component_controller.h" + +namespace dart_runner { +namespace { + +dart_utils::ElfSnapshot elf_snapshot; // AOT snapshot +dart_utils::MappedResource mapped_isolate_snapshot_data; // JIT snapshot +dart_utils::MappedResource + mapped_isolate_snapshot_instructions; // JIT snapshot +tonic::DartLibraryNatives* service_natives = nullptr; + +Dart_NativeFunction GetNativeFunction(Dart_Handle name, + int argument_count, + bool* auto_setup_scope) { + FML_CHECK(service_natives); + return service_natives->GetNativeFunction(name, argument_count, + auto_setup_scope); +} + +const uint8_t* GetSymbol(Dart_NativeFunction native_function) { + FML_CHECK(service_natives); + return service_natives->GetSymbol(native_function); +} + +#define SHUTDOWN_ON_ERROR(handle) \ + if (Dart_IsError(handle)) { \ + *error = strdup(Dart_GetError(handle)); \ + FML_LOG(ERROR) << error; \ + Dart_ExitScope(); \ + Dart_ShutdownIsolate(); \ + return nullptr; \ + } + +void NotifyServerState(Dart_NativeArguments args) { + // NOP. +} + +void Shutdown(Dart_NativeArguments args) { + // NOP. +} + +void EmbedderInformationCallback(Dart_EmbedderInformation* info) { + info->version = DART_EMBEDDER_INFORMATION_CURRENT_VERSION; + info->name = "dart_runner"; + info->current_rss = -1; + info->max_rss = -1; + + zx_info_task_stats_t task_stats; + zx_handle_t process = zx_process_self(); + zx_status_t status = zx_object_get_info( + process, ZX_INFO_TASK_STATS, &task_stats, sizeof(task_stats), NULL, NULL); + if (status == ZX_OK) { + info->current_rss = + task_stats.mem_private_bytes + task_stats.mem_shared_bytes; + } +} + +} // namespace + +Dart_Isolate CreateServiceIsolate( + const char* uri, + Dart_IsolateFlags* flags_unused, // These flags are currently unused + char** error) { + Dart_SetEmbedderInformationCallback(EmbedderInformationCallback); + + const uint8_t *vmservice_data = nullptr, *vmservice_instructions = nullptr; + +#if defined(AOT_RUNTIME) + // The VM service was compiled as a separate app. + const char* snapshot_path = "/pkg/data/vmservice_snapshot.so"; + if (elf_snapshot.Load(nullptr, snapshot_path)) { + vmservice_data = elf_snapshot.IsolateData(); + vmservice_instructions = elf_snapshot.IsolateInstrs(); + if (vmservice_data == nullptr || vmservice_instructions == nullptr) { + return nullptr; + } + } else { + // The VM service was compiled as a separate app. + const char* snapshot_data_path = + "/pkg/data/vmservice_isolate_snapshot_data.bin"; + const char* snapshot_instructions_path = + "/pkg/data/vmservice_isolate_snapshot_instructions.bin"; +#else + // The VM service is embedded in the core snapshot. + const char* snapshot_data_path = "/pkg/data/isolate_core_snapshot_data.bin"; + const char* snapshot_instructions_path = + "/pkg/data/isolate_core_snapshot_instructions.bin"; +#endif + + if (!dart_utils::MappedResource::LoadFromNamespace( + nullptr, snapshot_data_path, mapped_isolate_snapshot_data)) { + *error = strdup("Failed to load snapshot for service isolate"); + FML_LOG(ERROR) << *error; + return nullptr; + } + if (!dart_utils::MappedResource::LoadFromNamespace( + nullptr, snapshot_instructions_path, + mapped_isolate_snapshot_instructions, true /* executable */)) { + *error = strdup("Failed to load snapshot for service isolate"); + FML_LOG(ERROR) << *error; + return nullptr; + } + + vmservice_data = mapped_isolate_snapshot_data.address(); + vmservice_instructions = mapped_isolate_snapshot_instructions.address(); +#if defined(AOT_RUNTIME) + } +#endif + + Dart_IsolateFlags flags; + Dart_IsolateFlagsInitialize(&flags); + flags.null_safety = true; + + auto state = new std::shared_ptr(new tonic::DartState()); + Dart_Isolate isolate = Dart_CreateIsolateGroup( + uri, DART_VM_SERVICE_ISOLATE_NAME, vmservice_data, vmservice_instructions, + &flags, state, state, error); + if (!isolate) { + FML_LOG(ERROR) << "Dart_CreateIsolateGroup failed: " << *error; + return nullptr; + } + + state->get()->SetIsolate(isolate); + + // Setup native entries. + service_natives = new tonic::DartLibraryNatives(); + service_natives->Register({ + {"VMServiceIO_NotifyServerState", NotifyServerState, 1, true}, + {"VMServiceIO_Shutdown", Shutdown, 0, true}, + }); + + Dart_EnterScope(); + + Dart_Handle library = + Dart_LookupLibrary(Dart_NewStringFromCString("dart:vmservice_io")); + SHUTDOWN_ON_ERROR(library); + Dart_Handle result = Dart_SetRootLibrary(library); + SHUTDOWN_ON_ERROR(result); + result = Dart_SetNativeResolver(library, GetNativeFunction, GetSymbol); + SHUTDOWN_ON_ERROR(result); + + // _ip = '127.0.0.1' + result = Dart_SetField(library, Dart_NewStringFromCString("_ip"), + Dart_NewStringFromCString("127.0.0.1")); + SHUTDOWN_ON_ERROR(result); + + // _port = 0 + result = Dart_SetField(library, Dart_NewStringFromCString("_port"), + Dart_NewInteger(0)); + SHUTDOWN_ON_ERROR(result); + + // _autoStart = true + result = Dart_SetField(library, Dart_NewStringFromCString("_autoStart"), + Dart_NewBoolean(true)); + SHUTDOWN_ON_ERROR(result); + + // _originCheckDisabled = false + result = + Dart_SetField(library, Dart_NewStringFromCString("_originCheckDisabled"), + Dart_NewBoolean(false)); + SHUTDOWN_ON_ERROR(result); + + // _authCodesDisabled = false + result = + Dart_SetField(library, Dart_NewStringFromCString("_authCodesDisabled"), + Dart_NewBoolean(false)); + SHUTDOWN_ON_ERROR(result); + + InitBuiltinLibrariesForIsolate(std::string(uri), nullptr, fileno(stdout), + fileno(stderr), zx::channel(), true); + + // Make runnable. + Dart_ExitScope(); + Dart_ExitIsolate(); + *error = Dart_IsolateMakeRunnable(isolate); + if (*error != nullptr) { + FML_LOG(ERROR) << *error; + Dart_EnterIsolate(isolate); + Dart_ShutdownIsolate(); + return nullptr; + } + return isolate; +} // namespace dart_runner + +Dart_Handle GetVMServiceAssetsArchiveCallback() { + dart_utils::MappedResource vm_service_tar; + if (!dart_utils::MappedResource::LoadFromNamespace( + nullptr, "/pkg/data/observatory.tar", vm_service_tar)) { + FML_LOG(ERROR) << "Failed to load Observatory assets"; + return nullptr; + } + // TODO(rmacnak): Should we avoid copying the tar? Or does the service + // library not hold onto it anyway? + return tonic::DartConverter::ToDart( + reinterpret_cast(vm_service_tar.address()), + vm_service_tar.size()); +} + +} // namespace dart_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/service_isolate.h b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/service_isolate.h new file mode 100644 index 0000000000000000000000000000000000000000..4e87f638769116c1fb88c76d2b188fc4bb477cbf --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/service_isolate.h @@ -0,0 +1,20 @@ +// 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_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_SERVICE_ISOLATE_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_SERVICE_ISOLATE_H_ + +#include "third_party/dart/runtime/include/dart_api.h" + +namespace dart_runner { + +Dart_Isolate CreateServiceIsolate(const char* uri, + Dart_IsolateFlags* flags, + char** error); + +Dart_Handle GetVMServiceAssetsArchiveCallback(); + +} // namespace dart_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_SERVICE_ISOLATE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/README.md b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2509a19baafb1aa9fc852b992d4a330fd08b11a5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/README.md @@ -0,0 +1,3 @@ +# Dart Runner Tests + +Contains tests for the Dart Runner and their corresponding utility code diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4580775e917c716a19c5bbd8e4ee47219e205f96 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/BUILD.gn @@ -0,0 +1,13 @@ +# 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. + +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") + +group("startup_integration_test") { + testonly = true + deps = [ + "dart_aot_runner:tests", + "dart_jit_runner:tests", + ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_aot_runner/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_aot_runner/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e1df73b8c230b0ef7f936ee9f39c9cd15fd93ed1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_aot_runner/BUILD.gn @@ -0,0 +1,43 @@ +# 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. + +import("//flutter/tools/fuchsia/dart/dart_component.gni") +import("//flutter/tools/fuchsia/fuchsia_archive.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/fidl_library.gni") + +group("tests") { + testonly = true + deps = [ ":dart-aot-runner-integration-test" ] +} + +executable("dart-aot-runner-integration-test-bin") { + testonly = true + + output_name = "dart-aot-runner-integration-test" + + sources = [ "dart-aot-runner-integration-test.cc" ] + + # This is needed for //flutter/third_party/googletest for linking zircon + # symbols. + libs = [ "${fuchsia_arch_root}/sysroot/lib/libzircon.so" ] + + deps = [ + "${fuchsia_sdk}/fidl/fuchsia.logger", + "${fuchsia_sdk}/fidl/fuchsia.tracing.provider", + "${fuchsia_sdk}/pkg/async", + "${fuchsia_sdk}/pkg/async-loop-testing", + "${fuchsia_sdk}/pkg/fidl_cpp", + "${fuchsia_sdk}/pkg/sys_component_cpp_testing", + "${fuchsia_sdk}/pkg/zx", + "../dart_echo_server:aot_echo_package", + "//flutter/fml", + "//flutter/shell/platform/fuchsia/dart_runner/fidl:dart_test", + "//flutter/third_party/googletest:gtest", + "//flutter/third_party/googletest:gtest_main", + ] +} + +fuchsia_test_archive("dart-aot-runner-integration-test") { + deps = [ ":dart-aot-runner-integration-test-bin" ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_aot_runner/README.md b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_aot_runner/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d9312738b0471bd526d56cc46279b1978b858da5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_aot_runner/README.md @@ -0,0 +1,36 @@ +# dart_aot_runner + +Contains the integration test for the Dart AOT runner. + +### Running Tests + +#### Setup emulator and PM serve +``` +fx set terminal.qemu-x64 +ffx emu start --headless + +fx serve +``` + +#### Prepare build files and build binary +``` +$ENGINE_DIR/flutter/tools/gn --fuchsia --no-lto --runtime-mode=profile +ninja -C $ENGINE_DIR/out/fuchsia_profile_x64 flutter/shell/platform/fuchsia fuchsia_tests +``` + +#### Publish files to PM +``` +$FUCHSIA_DIR/.jiri_root/bin/ffx repository publish $FUCHSIA_DIR/$(cat $FUCHSIA_DIR/.fx-build-dir)/amber-files --package-archive $ENGINE_DIR/out/fuchsia_profile_x64/dart-aot-runner-integration-test-0.far + +$FUCHSIA_DIR/.jiri_root/bin/ffx repository publish $FUCHSIA_DIR/$(cat $FUCHSIA_DIR/.fx-build-dir)/amber-files --package-archive $ENGINE_DIR/out/fuchsia_profile_x64/oot_dart_aot_runner-0.far + +$FUCHSIA_DIR/.jiri_root/bin/ffx repository publish $FUCHSIA_DIR/$(cat $FUCHSIA_DIR/.fx-build-dir)/amber-files --package-archive $ENGINE_DIR/out/fuchsia_profile_x64/gen/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/dart_aot_echo_server/dart_aot_echo_server.far +``` + +#### Run test +``` +ffx test run "fuchsia-pkg://fuchsia.com/dart-aot-runner-integration-test#meta/dart-aot-runner-integration-test.cm" +``` + +## Notes +The `profile` runtime should be used when running the `dart_aot_runner` integration test. Snapshots will fail to generate or generate incorrectly if the wrong runtime is used. diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_aot_runner/dart-aot-runner-integration-test.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_aot_runner/dart-aot-runner-integration-test.cc new file mode 100644 index 0000000000000000000000000000000000000000..b0e262fb63e0d4209d04b8b04c4d4dc3a508be73 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_aot_runner/dart-aot-runner-integration-test.cc @@ -0,0 +1,115 @@ +// 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 +#include +#include +#include +#include + +#include "flutter/fml/logging.h" +#include "gtest/gtest.h" + +namespace dart_aot_runner_testing::testing { +namespace { + +// Types imported for the realm_builder library +using component_testing::ChildOptions; +using component_testing::ChildRef; +using component_testing::Dictionary; +using component_testing::Directory; +using component_testing::ParentRef; +using component_testing::Protocol; +using component_testing::RealmBuilder; +using component_testing::RealmRoot; +using component_testing::Route; + +constexpr auto kDartRunnerEnvironment = "dart_runner_env"; + +constexpr auto kDartAotRunner = "dart_aot_runner"; +constexpr auto kDartAotRunnerRef = ChildRef{kDartAotRunner}; +constexpr auto kDartAotRunnerUrl = + "fuchsia-pkg://fuchsia.com/oot_dart_aot_runner#meta/" + "dart_aot_runner.cm"; + +constexpr auto kDartAotEchoServer = "dart_aot_echo_server"; +constexpr auto kDartAotEchoServerRef = ChildRef{kDartAotEchoServer}; +constexpr auto kDartAotEchoServerUrl = + "fuchsia-pkg://fuchsia.com/dart_aot_echo_server#meta/" + "dart_aot_echo_server.cm"; + +class RealmBuilderTest : public ::loop_fixture::RealLoop, + public ::testing::Test { + public: + RealmBuilderTest() = default; +}; + +TEST_F(RealmBuilderTest, DartRunnerStartsUp) { + auto realm_builder = RealmBuilder::Create(); + // Add Dart AOT runner as a child of RealmBuilder + realm_builder.AddChild(kDartAotRunner, kDartAotRunnerUrl); + + // Add environment providing the Dart AOT runner + fuchsia::component::decl::Environment dart_runner_environment; + dart_runner_environment.set_name(kDartRunnerEnvironment); + dart_runner_environment.set_extends( + fuchsia::component::decl::EnvironmentExtends::REALM); + dart_runner_environment.set_runners({}); + auto environment_runners = dart_runner_environment.mutable_runners(); + + fuchsia::component::decl::RunnerRegistration dart_aot_runner_reg; + dart_aot_runner_reg.set_source(fuchsia::component::decl::Ref::WithChild( + fuchsia::component::decl::ChildRef{.name = kDartAotRunner})); + dart_aot_runner_reg.set_source_name(kDartAotRunner); + dart_aot_runner_reg.set_target_name(kDartAotRunner); + environment_runners->push_back(std::move(dart_aot_runner_reg)); + + auto realm_decl = realm_builder.GetRealmDecl(); + if (!realm_decl.has_environments()) { + realm_decl.set_environments({}); + } + auto realm_environments = realm_decl.mutable_environments(); + realm_environments->push_back(std::move(dart_runner_environment)); + realm_builder.ReplaceRealmDecl(std::move(realm_decl)); + + // Add Dart server component as a child of Realm Builder + realm_builder.AddChild(kDartAotEchoServer, kDartAotEchoServerUrl, + ChildOptions{.environment = kDartRunnerEnvironment}); + + // Route base capabilities to the Dart AOT runner + realm_builder.AddRoute( + Route{.capabilities = {Protocol{"fuchsia.logger.LogSink"}, + Protocol{"fuchsia.tracing.provider.Registry"}, + Protocol{"fuchsia.posix.socket.Provider"}, + Protocol{"fuchsia.intl.PropertyProvider"}, + Protocol{"fuchsia.vulkan.loader.Loader"}, + Protocol{"fuchsia.inspect.InspectSink"}, + Directory{"config-data"}}, + .source = ParentRef(), + .targets = {kDartAotRunnerRef, kDartAotEchoServerRef}}); + + realm_builder.AddRoute( + Route{.capabilities = {Dictionary{"diagnostics"}}, + .source = ParentRef(), + .targets = {kDartAotRunnerRef, kDartAotEchoServerRef}}); + + // Route the Echo FIDL protocol, this allows the Dart echo server to + // communicate with the Realm Builder + realm_builder.AddRoute(Route{.capabilities = {Protocol{"dart.test.Echo"}}, + .source = kDartAotEchoServerRef, + .targets = {ParentRef()}}); + + // Build the Realm with the provided child and protocols + auto realm = realm_builder.Build(dispatcher()); + FML_LOG(INFO) << "Realm built: " << realm.component().GetChildName(); + // Connect to the Dart echo server + auto echo = realm.component().ConnectSync(); + fidl::StringPtr response; + // Attempt to ping the Dart echo server for a response + echo->EchoString("hello", &response); + ASSERT_EQ(response, "hello"); +} + +} // namespace +} // namespace dart_aot_runner_testing::testing diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_aot_runner/meta/dart-aot-runner-integration-test.cml b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_aot_runner/meta/dart-aot-runner-integration-test.cml new file mode 100644 index 0000000000000000000000000000000000000000..3733d9277330f1c6bf62b06f1486f289fdf63b46 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_aot_runner/meta/dart-aot-runner-integration-test.cml @@ -0,0 +1,52 @@ +// 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: [ + "sys/testing/gtest_runner.shard.cml", + "sys/component/realm_builder_absolute.shard.cml", + + // This test needs both the vulkan facet and the hermetic-tier-2 facet, + // so we are forced to make it a system test. + "sys/testing/system-test.shard.cml", + "syslog/client.shard.cml", + "inspect/client.shard.cml", + ], + program: { + binary: "bin/app", + }, + offer: [ + { + // Offer capabilities needed by components in this test realm. + // Keep it minimal, describe only what's actually needed. + protocol: [ + "fuchsia.sysmem.Allocator", + "fuchsia.sysmem2.Allocator", + "fuchsia.tracing.provider.Registry", + "fuchsia.vulkan.loader.Loader", + "fuchsia.posix.socket.Provider", + "fuchsia.intl.PropertyProvider", + ], + from: "parent", + to: "#realm_builder", + }, + { + directory: "pkg", + subdir: "config", + as: "config-data", + from: "framework", + to: "#realm_builder", + }, + ], + // TODO(https://fxbug.dev/114584): Figure out how to bring these in as deps (if possible oot). + facets: { + "fuchsia.test": { + "deprecated-allowed-packages": [ + "dart_aot_echo_server", + "test_manager", + "oot_dart_aot_runner" + ], + }, + }, +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..245bdb7ae92c9f731098ac5a360eaf6674fd6d09 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/BUILD.gn @@ -0,0 +1,67 @@ +# 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. + +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") + +import("//flutter/tools/fuchsia/dart/dart_component.gni") +import("//flutter/tools/fuchsia/dart/dart_library.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/package.gni") + +dart_library("lib") { + testonly = true + package_name = "dart_echo_server" + + source_dir = "." + sources = [ "main.dart" ] +} + +# Dart component that serves the test Echo FIDL protocol, built using the Dart AOT runner +dart_component("aot_component") { + testonly = true + + main_package = "dart_echo_server" + manifest = "meta/dart-aot-echo-server.cml" + component_name = "dart_aot_echo_server" + + deps = [ ":lib" ] +} + +# Dart component that serves the test Echo FIDL protocol, built using the Dart AOT runner +dart_component("jit_component") { + testonly = true + + main_package = "dart_echo_server" + manifest = "meta/dart-jit-echo-server.cml" + component_name = "dart_jit_echo_server" + + deps = [ ":lib" ] +} + +fuchsia_package("aot_echo_package") { + testonly = true + + package_name = "dart_aot_echo_server" + deps = [ + ":aot_component", + + # "OOT" copy of the runner used by tests, to avoid conflicting with the + # runners in the base fuchsia image. + # TODO(fxbug.dev/106575): Fix this with subpackages. + "//flutter/shell/platform/fuchsia/dart_runner:oot_dart_aot_runner", + ] +} + +fuchsia_package("jit_echo_package") { + testonly = true + + package_name = "dart_jit_echo_server" + deps = [ + ":jit_component", + + # "OOT" copy of the runner used by tests, to avoid conflicting with the + # runners in the base fuchsia image. + # TODO(fxbug.dev/106575): Fix this with subpackages. + "//flutter/shell/platform/fuchsia/dart_runner:oot_dart_jit_runner", + ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/README.md b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7e91d785abf376c14af3e06e7469e5ae8f31d0ce --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/README.md @@ -0,0 +1,7 @@ +# dart_echo_server + +Contains the Echo servers for the integration tests. There are currently two outputs: +- `dart-aot-echo-server` +- `dart-jit-echo-server` + +The outputs run with their respective Dart runners and are consumed by their respective integration test. diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/main.dart b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/main.dart new file mode 100644 index 0000000000000000000000000000000000000000..3741dcc6a7b9f31adee7c519fd9d71b49c217359 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/main.dart @@ -0,0 +1,14 @@ +// 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. + +import 'dart:fuchsia.builtin'; + +String? OnEchoString(String? str) { + print('Got echo string: $str'); + return str; +} + +void main(List args) { + receiveEchoStringCallback = OnEchoString; +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/meta/dart-aot-echo-server.cml b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/meta/dart-aot-echo-server.cml new file mode 100644 index 0000000000000000000000000000000000000000..b0c0971e47a6eb1bc7754a5846cbe72875f24007 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/meta/dart-aot-echo-server.cml @@ -0,0 +1,21 @@ +// 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: [ "syslog/client.shard.cml", "inspect/client.shard.cml" ], + program: { + data: "data/dart-aot-echo-server", + runner: "dart_aot_runner", + }, + // Capabilities provided by this component. + capabilities: [ + { protocol: "dart.test.Echo" }, + ], + expose: [ + { + protocol: "dart.test.Echo", + from: "self", + }, + ], +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/meta/dart-jit-echo-server.cml b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/meta/dart-jit-echo-server.cml new file mode 100644 index 0000000000000000000000000000000000000000..f4d3ca6072d0787027c36f19774dfd813eacf511 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/meta/dart-jit-echo-server.cml @@ -0,0 +1,21 @@ +// 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: [ "syslog/client.shard.cml" ], + program: { + data: "data/dart-jit-echo-server", + runner: "dart_jit_runner", + }, + // Capabilities provided by this component. + capabilities: [ + { protocol: "dart.test.Echo" }, + ], + expose: [ + { + protocol: "dart.test.Echo", + from: "self", + }, + ], +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_jit_runner/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_jit_runner/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..675753ee8ae5d7ac527ed93c97d99a6187f1e698 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_jit_runner/BUILD.gn @@ -0,0 +1,43 @@ +# 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. + +import("//flutter/tools/fuchsia/dart/dart_component.gni") +import("//flutter/tools/fuchsia/fuchsia_archive.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") + +group("tests") { + testonly = true + deps = [ ":dart-jit-runner-integration-test" ] +} + +executable("dart-jit-runner-integration-test-bin") { + testonly = true + + output_name = "dart-jit-runner-integration-test" + + sources = [ "dart-jit-runner-integration-test.cc" ] + + # This is needed for //flutter/third_party/googletest for linking zircon + # symbols. + libs = [ "${fuchsia_arch_root}/sysroot/lib/libzircon.so" ] + + deps = [ + "${fuchsia_sdk}/fidl/fuchsia.logger", + "${fuchsia_sdk}/fidl/fuchsia.tracing.provider", + "${fuchsia_sdk}/pkg/async", + "${fuchsia_sdk}/pkg/async-loop-testing", + "${fuchsia_sdk}/pkg/fidl_cpp", + "${fuchsia_sdk}/pkg/sys_component_cpp_testing", + "${fuchsia_sdk}/pkg/zx", + "../dart_echo_server:jit_echo_package", + "//flutter/fml", + "//flutter/shell/platform/fuchsia/dart_runner/fidl:dart_test", + "//flutter/third_party/googletest:gtest", + "//flutter/third_party/googletest:gtest_main", + ] +} + +fuchsia_test_archive("dart-jit-runner-integration-test") { + deps = [ ":dart-jit-runner-integration-test-bin" ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_jit_runner/README.md b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_jit_runner/README.md new file mode 100644 index 0000000000000000000000000000000000000000..08789dabe8ec68b780c4f87571bef68e5880c8d1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_jit_runner/README.md @@ -0,0 +1,36 @@ +# dart_jit_runner + +Contains the integration test for the Dart JIT runner. + +### Running Tests + +#### Setup emulator and PM serve +``` +fx set terminal.qemu-x64 +ffx emu start --headless + +fx serve +``` + +#### Prepare build files and build binary +``` +$ENGINE_DIR/flutter/tools/gn --fuchsia --no-lto +ninja -C $ENGINE_DIR/out/fuchsia_debug_x64 flutter/shell/platform/fuchsia fuchsia_tests +``` + +#### Publish files to PM +``` +$FUCHSIA_DIR/.jiri_root/bin/ffx repository publish $FUCHSIA_DIR/$(cat $FUCHSIA_DIR/.fx-build-dir)/amber-files --package-archive $ENGINE_DIR/out/fuchsia_debug_x64/dart-jit-runner-integration-test-0.far + +$FUCHSIA_DIR/.jiri_root/bin/ffx repository publish $FUCHSIA_DIR/$(cat $FUCHSIA_DIR/.fx-build-dir)/amber-files --package-archive $ENGINE_DIR/out/fuchsia_debug_x64/oot_dart_jit_runner-0.far + +$FUCHSIA_DIR/.jiri_root/bin/ffx repository publish $FUCHSIA_DIR/$(cat $FUCHSIA_DIR/.fx-build-dir)/amber-files --package-archive $ENGINE_DIR/out/fuchsia_debug_x64/gen/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/dart_jit_echo_server/dart_jit_echo_server.far +``` + +#### Run test +``` +ffx test run "fuchsia-pkg://fuchsia.com/dart-jit-runner-integration-test#meta/dart-jit-runner-integration-test.cm" +``` + +## Notes +The `debug` runtime should be used when running the `dart_jit_runner` integration test. Snapshots will fail to generate or generate incorrectly if the wrong runtime is used. diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_jit_runner/dart-jit-runner-integration-test.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_jit_runner/dart-jit-runner-integration-test.cc new file mode 100644 index 0000000000000000000000000000000000000000..ca078d44284298401a2fe756b53102b05b116fca --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_jit_runner/dart-jit-runner-integration-test.cc @@ -0,0 +1,113 @@ +// 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 +#include +#include +#include +#include + +#include "flutter/fml/logging.h" +#include "gtest/gtest.h" + +namespace dart_jit_runner_testing::testing { +namespace { + +// Types imported for the realm_builder library +using component_testing::ChildOptions; +using component_testing::ChildRef; +using component_testing::Dictionary; +using component_testing::Directory; +using component_testing::ParentRef; +using component_testing::Protocol; +using component_testing::RealmBuilder; +using component_testing::RealmRoot; +using component_testing::Route; + +constexpr auto kDartRunnerEnvironment = "dart_runner_env"; + +constexpr auto kDartJitRunner = "dart_jit_runner"; +constexpr auto kDartJitRunnerRef = ChildRef{kDartJitRunner}; +constexpr auto kDartJitRunnerUrl = + "fuchsia-pkg://fuchsia.com/oot_dart_jit_runner#meta/" + "dart_jit_runner.cm"; + +constexpr auto kDartJitEchoServer = "dart_jit_echo_server"; +constexpr auto kDartJitEchoServerRef = ChildRef{kDartJitEchoServer}; +constexpr auto kDartJitEchoServerUrl = + "fuchsia-pkg://fuchsia.com/dart_jit_echo_server#meta/" + "dart_jit_echo_server.cm"; + +class RealmBuilderTest : public ::loop_fixture::RealLoop, + public ::testing::Test { + public: + RealmBuilderTest() = default; +}; + +TEST_F(RealmBuilderTest, DartRunnerStartsUp) { + auto realm_builder = RealmBuilder::Create(); + // Add Dart JIT runner as a child of RealmBuilder + realm_builder.AddChild(kDartJitRunner, kDartJitRunnerUrl); + + // Add environment providing the Dart JIT runner + fuchsia::component::decl::Environment dart_runner_environment; + dart_runner_environment.set_name(kDartRunnerEnvironment); + dart_runner_environment.set_extends( + fuchsia::component::decl::EnvironmentExtends::REALM); + dart_runner_environment.set_runners({}); + auto environment_runners = dart_runner_environment.mutable_runners(); + + fuchsia::component::decl::RunnerRegistration dart_jit_runner_reg; + dart_jit_runner_reg.set_source(fuchsia::component::decl::Ref::WithChild( + fuchsia::component::decl::ChildRef{.name = kDartJitRunner})); + dart_jit_runner_reg.set_source_name(kDartJitRunner); + dart_jit_runner_reg.set_target_name(kDartJitRunner); + environment_runners->push_back(std::move(dart_jit_runner_reg)); + auto realm_decl = realm_builder.GetRealmDecl(); + if (!realm_decl.has_environments()) { + realm_decl.set_environments({}); + } + auto realm_environments = realm_decl.mutable_environments(); + realm_environments->push_back(std::move(dart_runner_environment)); + realm_builder.ReplaceRealmDecl(std::move(realm_decl)); + + // Add Dart server component as a child of Realm Builder + realm_builder.AddChild(kDartJitEchoServer, kDartJitEchoServerUrl, + ChildOptions{.environment = kDartRunnerEnvironment}); + + // Route base capabilities to the Dart JIT runner + realm_builder.AddRoute( + Route{.capabilities = {Protocol{"fuchsia.logger.LogSink"}, + Protocol{"fuchsia.tracing.provider.Registry"}, + Protocol{"fuchsia.posix.socket.Provider"}, + Protocol{"fuchsia.intl.PropertyProvider"}, + Protocol{"fuchsia.inspect.InspectSink"}, + Directory{"config-data"}}, + .source = ParentRef(), + .targets = {kDartJitRunnerRef, kDartJitEchoServerRef}}); + + realm_builder.AddRoute( + Route{.capabilities = {Dictionary{"diagnostics"}}, + .source = ParentRef(), + .targets = {kDartJitRunnerRef, kDartJitEchoServerRef}}); + + // Route the Echo FIDL protocol, this allows the Dart echo server to + // communicate with the Realm Builder + realm_builder.AddRoute(Route{.capabilities = {Protocol{"dart.test.Echo"}}, + .source = kDartJitEchoServerRef, + .targets = {ParentRef()}}); + + // Build the Realm with the provided child and protocols + auto realm = realm_builder.Build(dispatcher()); + FML_LOG(INFO) << "Realm built: " << realm.component().GetChildName(); + // Connect to the Dart echo server + auto echo = realm.component().ConnectSync(); + fidl::StringPtr response; + // Attempt to ping the Dart echo server for a response + echo->EchoString("hello", &response); + ASSERT_EQ(response, "hello"); +} + +} // namespace +} // namespace dart_jit_runner_testing::testing diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_jit_runner/meta/dart-jit-runner-integration-test.cml b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_jit_runner/meta/dart-jit-runner-integration-test.cml new file mode 100644 index 0000000000000000000000000000000000000000..4564ab7b2477e6bb887c6fca09ff65677fdd9c29 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_jit_runner/meta/dart-jit-runner-integration-test.cml @@ -0,0 +1,56 @@ +// 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: [ + "sys/testing/gtest_runner.shard.cml", + "sys/component/realm_builder_absolute.shard.cml", + + // This test needs both the vulkan facet and the hermetic-tier-2 facet, + // so we are forced to make it a system test. + "sys/testing/system-test.shard.cml", + ], + program: { + binary: "bin/app", + }, + offer: [ + { + // Offer capabilities needed by components in this test realm. + // Keep it minimal, describe only what's actually needed. + protocol: [ + "fuchsia.sysmem.Allocator", + "fuchsia.sysmem2.Allocator", + "fuchsia.tracing.provider.Registry", + "fuchsia.vulkan.loader.Loader", + "fuchsia.posix.socket.Provider", + "fuchsia.intl.PropertyProvider", + ], + from: "parent", + to: "#realm_builder", + }, + { + directory: "pkg", + subdir: "config", + as: "config-data", + from: "framework", + to: "#realm_builder", + }, + // See common.shard.cml. + { + directory: "tzdata-icu", + from: "framework", + to: "#realm_builder", + }, + ], + // TODO(https://fxbug.dev/114584): Figure out how to bring these in as deps (if possible oot). + facets: { + "fuchsia.test": { + "deprecated-allowed-packages": [ + "dart_jit_echo_server", + "test_manager", + "oot_dart_jit_runner" + ], + }, + }, +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/suite_impl_unittests.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/suite_impl_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..d63a5fd3b72c73f206eeaab8e2de4c7293bb65b2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/tests/suite_impl_unittests.cc @@ -0,0 +1,23 @@ +// Copyright 2022 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 "dart_runner/dart_test_component_controller.h" + +#include "gtest/gtest.h" + +namespace dart_runner::testing { +namespace { + +std::string GetCurrentTestName() { + return ::testing::UnitTest::GetInstance()->current_test_info()->name(); +} + +} // namespace + +// TODO(naudzghebre): Add unit tests for the dart_test_runner. +TEST(SuiteImplTest, EQUALITY) { + EXPECT_EQ(1, 1) << GetCurrentTestName(); +} + +} // namespace dart_runner::testing diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/vmservice/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/vmservice/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..0c87cc9c27384949cbdfc1c75ee7c2affac287eb --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/vmservice/BUILD.gn @@ -0,0 +1,79 @@ +# 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. + +import("//build/compiled_action.gni") +import("//flutter/common/config.gni") +import("//flutter/tools/fuchsia/dart.gni") +import("//flutter/tools/fuchsia/dart_kernel.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") +import("$dart_src/utils/compile_platform.gni") + +dart_kernel("vmservice_product_aot_kernel") { + kernel_platform_files = "../kernel:kernel_platform_files" + main_dart = "empty.dart" + product = true + aot = true +} + +dart_kernel("vmservice_aot_kernel") { + kernel_platform_files = "../kernel:kernel_platform_files" + main_dart = "empty.dart" + product = false + aot = true +} + +template("aot_snapshot") { + compiled_action(target_name) { + kernel_name = target_name + + if (defined(invoker.kernel_name)) { + kernel_name = invoker.kernel_name + } + + product = defined(invoker.product) && invoker.product + + product_suffix = "" + if (product) { + product_suffix = "_product" + } + + shim_target = ":vmservice${product_suffix}_aot_kernel($host_toolchain)" + shim_kernel = get_label_info(shim_target, "target_gen_dir") + + "/vmservice${product_suffix}_aot_kernel.dill" + + deps = [ shim_target ] + + snapshot_path = "$target_gen_dir/${kernel_name}_snapshot.so" + + inputs = [ shim_kernel ] + + outputs = [ snapshot_path ] + + if (product) { + tool = gen_snapshot_product + } else { + tool = gen_snapshot + } + + args = [ + "--deterministic", + "--snapshot_kind=app-aot-elf", + "--elf=" + rebase_path(snapshot_path), + ] + + # No asserts in debug or release product. + # No asserts in release with flutter_profile=true (non-product) + # Yes asserts in non-product debug. + if (!product && (flutter_runtime_mode == "debug" || is_debug)) { + args += [ "--enable_asserts" ] + } + + args += [ rebase_path(shim_kernel) ] + } +} + +aot_snapshot("vmservice_snapshot") { + kernel_name = "vmservice" + product = false +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/vmservice/empty.dart b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/vmservice/empty.dart new file mode 100644 index 0000000000000000000000000000000000000000..0d7f6a4b8b52d6b8ef75ffd3c83980eb71d8b7bd --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/vmservice/empty.dart @@ -0,0 +1,7 @@ +// 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. + +// This entry point is never invoked. Its purpose is to allow the vmservice's +// Dart code to built with dart_aot_app. +void main(List args) {} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/vmservice/pubspec.yaml b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/vmservice/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dfe2136345352e74526f2c49836b0f979e604276 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/dart_runner/vmservice/pubspec.yaml @@ -0,0 +1,7 @@ +# 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. + +environment: + sdk: ^3.7.0-0 + diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a7408d7ee5f0d706646b5b0afb2ccc797126a781 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/BUILD.gn @@ -0,0 +1,1066 @@ +# 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. + +assert(is_fuchsia) + +import("//flutter/common/config.gni") +import("//flutter/shell/config.gni") +import("//flutter/shell/gpu/gpu.gni") +import("//flutter/testing/testing.gni") +import("//flutter/tools/fuchsia/dart.gni") +import("//flutter/tools/fuchsia/fuchsia_archive.gni") +import("//flutter/tools/fuchsia/fuchsia_libs.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") +import("//flutter/vulkan/config.gni") + +# Fuchsia uses its own custom Surface implementation. +shell_gpu_configuration("fuchsia_gpu_configuration") { + enable_software = false + enable_gl = false + + # TODO(dworsham): Enable once Fuchsia supports Vulkan through the embedder. + enable_vulkan = false + enable_metal = false +} + +config("runner_base_config") { + defines = [ "FML_USED_ON_EMBEDDER" ] +} + +config("runner_debug_config") { + defines = [ "DEBUG" ] # Needed due to direct dart dependencies. +} + +config("runner_flutter_profile_config") { + defines = [ "FLUTTER_PROFILE" ] +} + +config("runner_product_config") { + defines = [ "DART_PRODUCT" ] +} + +template("runner_sources") { + assert(defined(invoker.product), "runner_sources must define product") + + runner_configs = [ ":runner_base_config" ] + if (is_debug) { + runner_configs += [ ":runner_debug_config" ] + } + if (flutter_runtime_mode == "profile") { + runner_configs += [ ":runner_flutter_profile_config" ] + } + if (invoker.product) { + runner_configs += [ ":runner_product_config" ] + } + + source_set(target_name) { + sources = [ + "accessibility_bridge.cc", + "accessibility_bridge.h", + "canvas_spy.cc", + "canvas_spy.h", + "component_v2.cc", + "component_v2.h", + "engine.cc", + "engine.h", + "external_view_embedder.cc", + "external_view_embedder.h", + "file_in_namespace_buffer.cc", + "file_in_namespace_buffer.h", + "flatland_connection.cc", + "flatland_connection.h", + "flutter_runner_product_configuration.cc", + "flutter_runner_product_configuration.h", + "focus_delegate.cc", + "focus_delegate.h", + "fuchsia_intl.cc", + "fuchsia_intl.h", + "isolate_configurator.cc", + "isolate_configurator.h", + "keyboard.cc", + "keyboard.h", + "logging.h", + "platform_view.cc", + "platform_view.h", + "pointer_delegate.cc", + "pointer_delegate.h", + "pointer_injector_delegate.cc", + "pointer_injector_delegate.h", + "program_metadata.h", + "rtree.cc", + "rtree.h", + "runner.cc", + "runner.h", + "software_surface.cc", + "software_surface.h", + "software_surface_producer.cc", + "software_surface_producer.h", + "surface.cc", + "surface.h", + "surface_producer.h", + "task_runner_adapter.cc", + "task_runner_adapter.h", + "text_delegate.cc", + "text_delegate.h", + "unique_fdio_ns.h", + "vsync_waiter.cc", + "vsync_waiter.h", + "vulkan_surface.cc", + "vulkan_surface.h", + "vulkan_surface_pool.cc", + "vulkan_surface_pool.h", + "vulkan_surface_producer.cc", + "vulkan_surface_producer.h", + ] + + public_configs = runner_configs + + # The use of these dependencies is temporary and will be moved behind the + # embedder API. + flutter_public_deps = [ + "//flutter/common/graphics", + "//flutter/flow", + "//flutter/lib/ui", + "//flutter/runtime", + "//flutter/shell/common", + "//flutter/shell/platform/common/client_wrapper:client_wrapper", + ] + + flutter_deps = [ + ":fuchsia_gpu_configuration", + "//flutter/assets", + "//flutter/common", + "//flutter/flutter_vma:flutter_skia_vma", + "//flutter/fml", + "//flutter/shell/platform/common/client_wrapper:client_wrapper_library_stubs", + "//flutter/vulkan", + "//flutter/vulkan/procs", + ] + + # TODO(zijiehe): Considering which deps should belong to the public_deps, + # multiple dependencies of this target use the following deps without + # explicitly claiming the dependencies. + public_deps = [ + "${fuchsia_sdk}/fidl/fuchsia.accessibility.semantics", + "${fuchsia_sdk}/fidl/fuchsia.component.runner", + "${fuchsia_sdk}/fidl/fuchsia.fonts", + "${fuchsia_sdk}/fidl/fuchsia.images", + "${fuchsia_sdk}/fidl/fuchsia.intl", + "${fuchsia_sdk}/fidl/fuchsia.io", + "${fuchsia_sdk}/fidl/fuchsia.media", + "${fuchsia_sdk}/fidl/fuchsia.memorypressure", + "${fuchsia_sdk}/fidl/fuchsia.ui.app", + "${fuchsia_sdk}/fidl/fuchsia.ui.composition", + "${fuchsia_sdk}/fidl/fuchsia.ui.input", + "${fuchsia_sdk}/fidl/fuchsia.ui.input3", + "${fuchsia_sdk}/fidl/fuchsia.ui.pointer", + "${fuchsia_sdk}/fidl/fuchsia.ui.pointerinjector", + "${fuchsia_sdk}/fidl/fuchsia.ui.test.input", + "${fuchsia_sdk}/fidl/fuchsia.ui.views", + "${fuchsia_sdk}/pkg/inspect", + "${fuchsia_sdk}/pkg/inspect_component_cpp", + "${fuchsia_sdk}/pkg/sys_cpp", + "//flutter/shell/platform/fuchsia/runtime/dart/utils", + ] + flutter_public_deps + + deps = [ + "${fuchsia_sdk}/pkg/async-cpp", + "${fuchsia_sdk}/pkg/async-default", + "${fuchsia_sdk}/pkg/async-loop", + "${fuchsia_sdk}/pkg/async-loop-cpp", + "${fuchsia_sdk}/pkg/fdio", + "${fuchsia_sdk}/pkg/fidl_cpp", + "${fuchsia_sdk}/pkg/trace", + "${fuchsia_sdk}/pkg/trace-engine", + "${fuchsia_sdk}/pkg/trace-provider-so", + "${fuchsia_sdk}/pkg/vfs_cpp", + "${fuchsia_sdk}/pkg/zx", + "//flutter/shell/platform/fuchsia/dart-pkg/fuchsia", + "//flutter/shell/platform/fuchsia/dart-pkg/zircon", + ] + flutter_deps + } +} + +runner_sources("flutter_runner_sources") { + product = false +} + +runner_sources("flutter_runner_sources_product") { + product = true +} + +# Things that explicitly being excluded: +# 1. Kernel snapshot framework mode. +# 2. Profiler symbols. + +# Builds a flutter_runner +# +# Parameters: +# +# output_name (required): +# The name of the resulting binary. +# +# extra_deps (required): +# Any additional dependencies. +# +# product (required): +# Whether to link against a Product mode Dart VM. +# +# extra_defines (optional): +# Any additional preprocessor defines. +template("flutter_runner") { + assert(defined(invoker.output_name), "flutter_runner must define output_name") + assert(defined(invoker.extra_deps), "flutter_runner must define extra_deps") + assert(defined(invoker.product), "flutter_runner must define product") + + invoker_output_name = invoker.output_name + extra_deps = invoker.extra_deps + + product_suffix = "" + if (invoker.product) { + product_suffix = "_product" + } + + executable(target_name) { + output_name = invoker_output_name + + sources = [ "main.cc" ] + + deps = [ + ":flutter_runner_sources${product_suffix}", + "${fuchsia_sdk}/pkg/async-loop-cpp", + "${fuchsia_sdk}/pkg/trace", + "${fuchsia_sdk}/pkg/trace-provider-so", + ] + extra_deps + + # The flags below are needed so that Dart's CPU profiler can walk the + # C++ stack. + cflags = [ "-fno-omit-frame-pointer" ] + + if (invoker.product) { + # Fuchsia's default stack size was resulting in test failures in a + # downstream project. Provide some extra room. + ldflags = [ "-Wl,-z,stack-size=0x100000" ] + } else { + # This flag is needed so that the call to dladdr() in Dart's native symbol + # resolver can report good symbol information for the CPU profiler. + ldflags = [ + "-Wl,-z,stack-size=0x100000", + "-rdynamic", + ] + } + } +} + +flutter_runner("jit") { + output_name = "flutter_jit_runner" + product = false + + extra_deps = [ + "$dart_src/runtime:libdart_jit", + "$dart_src/runtime/platform:libdart_platform_jit", + ] +} + +flutter_runner("jit_product") { + output_name = "flutter_jit_product_runner" + product = true + + extra_deps = [ + "$dart_src/runtime:libdart_jit", + "$dart_src/runtime/platform:libdart_platform_jit", + ] +} + +flutter_runner("aot") { + output_name = "flutter_aot_runner" + product = false + + extra_deps = [ + "$dart_src/runtime:libdart_aotruntime", + "$dart_src/runtime/platform:libdart_platform_aotruntime", + ] +} + +flutter_runner("aot_product") { + output_name = "flutter_aot_product_runner" + product = true + + extra_deps = [ + "$dart_src/runtime:libdart_aotruntime", + "$dart_src/runtime/platform:libdart_platform_aotruntime", + ] +} + +template("jit_runner") { + product = defined(invoker.product) && invoker.product + + product_suffix = "" + + if (product) { + product_suffix = "_product" + } + + fuchsia_archive(target_name) { + snapshot_label = "kernel:kernel_core_snapshot${product_suffix}" + snapshot_gen_dir = get_label_info(snapshot_label, "target_gen_dir") + + deps = [ + ":jit${product_suffix}", + snapshot_label, + ] + + if (!product) { + deps += [ + "//flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols:flutter_jit_runner", + observatory_target, + ] + } + + binary = "flutter_jit${product_suffix}_runner" + + resources = [ + { + path = rebase_path("//flutter/third_party/icu/common/icudtl.dat") + dest = "icudtl.dat" + }, + ] + + if (!product) { + resources += [ + { + path = rebase_path(observatory_archive_file) + dest = "observatory.tar" + }, + { + path = rebase_path( + get_label_info( + "//flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols:flutter_jit_runner", + "target_gen_dir") + + "/flutter_jit_runner.dartprofilersymbols") + dest = "flutter_jit_runner.dartprofilersymbols" + }, + ] + } + + resources += [ + { + path = rebase_path( + "$snapshot_gen_dir/vm_isolate_snapshot${product_suffix}.bin") + dest = "vm_snapshot_data.bin" + }, + { + path = rebase_path( + "$snapshot_gen_dir/isolate_snapshot${product_suffix}.bin") + dest = "isolate_core_snapshot_data.bin" + }, + ] + + _vulkan_icds = [] + _libs = common_libs + if (enable_vulkan_validation_layers) { + _libs += vulkan_validation_libs + _vulkan_icds += vulkan_icds + } + + resources += _vulkan_icds + + libraries = _libs + } +} + +template("aot_runner") { + product = defined(invoker.product) && invoker.product + product_suffix = "" + if (product) { + product_suffix = "_product" + } + + fuchsia_archive(target_name) { + deps = [ ":aot${product_suffix}" ] + + if (!product) { + deps += [ + "//flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols:flutter_aot_runner", + observatory_target, + ] + } + + binary = "flutter_aot${product_suffix}_runner" + + resources = [ + { + path = rebase_path("//flutter/third_party/icu/common/icudtl.dat") + dest = "icudtl.dat" + }, + ] + + if (!product) { + resources += [ + { + path = rebase_path(observatory_archive_file) + dest = "observatory.tar" + }, + { + path = rebase_path( + get_label_info( + "//flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols:flutter_aot_runner", + "target_gen_dir") + + "/flutter_aot_runner.dartprofilersymbols") + dest = "flutter_aot_runner.dartprofilersymbols" + }, + ] + } + + _vulkan_icds = [] + _libs = common_libs + if (enable_vulkan_validation_layers) { + _libs += vulkan_validation_libs + _vulkan_icds += vulkan_icds + } + + resources += _vulkan_icds + + libraries = _libs + } +} + +aot_runner("flutter_aot_runner") { + product = false +} + +aot_runner("flutter_aot_product_runner") { + product = true +} + +jit_runner("flutter_jit_runner") { + product = false +} + +jit_runner("flutter_jit_product_runner") { + product = true +} + +# "OOT" copy of the runner used by tests, to avoid conflicting with the runner +# in the base fuchsia image. +# TODO(fxbug.dev/106575): Fix this with subpackages. +aot_runner("oot_flutter_aot_runner") { + product = false +} + +# "OOT" copy of the runner used by tests, to avoid conflicting with the runner +# in the base fuchsia image. +# TODO(fxbug.dev/106575): Fix this with subpackages. +aot_runner("oot_flutter_aot_product_runner") { + product = true +} + +# "OOT" copy of the runner used by tests, to avoid conflicting with the runner +# in the base fuchsia image. +# TODO(fxbug.dev/106575): Fix this with subpackages. +jit_runner("oot_flutter_jit_runner") { + product = false +} + +# "OOT" copy of the runner used by tests, to avoid conflicting with the runner +# in the base fuchsia image. +# TODO(fxbug.dev/106575): Fix this with subpackages. +jit_runner("oot_flutter_jit_product_runner") { + product = true +} + +test_fixtures("flutter_runner_fixtures") { + fixtures = [] +} + +if (enable_unittests) { + executable("flutter_runner_unittests") { + testonly = true + + output_name = "flutter_runner_tests" + + sources = [ + "accessibility_bridge_unittest.cc", + "canvas_spy_unittests.cc", + "component_v2_unittest.cc", + "flutter_runner_fakes.h", + "focus_delegate_unittests.cc", + "fuchsia_intl_unittest.cc", + "keyboard_unittest.cc", + "pointer_delegate_unittests.cc", + "pointer_injector_delegate_unittest.cc", + "rtree_unittests.cc", + "tests/engine_unittests.cc", + "tests/external_view_embedder_unittests.cc", + "tests/fake_flatland_unittests.cc", + "tests/flatland_connection_unittests.cc", + "tests/flutter_runner_product_configuration_unittests.cc", + "tests/platform_view_unittest.cc", + "tests/pointer_event_utility.cc", + "tests/pointer_event_utility.h", + "text_delegate_unittests.cc", + "vsync_waiter_unittest.cc", + ] + + # This is needed for //flutter/third_party/googletest for linking zircon + # symbols. + libs = [ "${fuchsia_arch_root}/sysroot/lib/libzircon.so" ] + + # The use of these dependencies is temporary and will be moved behind the + # embedder API. + flutter_deps = [ + "$dart_src/runtime:libdart_jit", + "$dart_src/runtime/platform:libdart_platform_jit", + "//flutter/assets:assets", + "//flutter/common/graphics", + "//flutter/flow", + "//flutter/lib/ui", + "//flutter/shell/common", + ] + + deps = [ + ":flutter_runner_fixtures", + ":flutter_runner_sources", + "${fuchsia_sdk}/pkg/async-testing", + "${fuchsia_sdk}/pkg/sys_cpp_testing", + "tests/fakes", + "//flutter/shell/platform/common/client_wrapper:client_wrapper_library_stubs", + "//flutter/testing", + ] + flutter_deps + } + + executable("flutter_runner_tzdata_unittests") { + testonly = true + + output_name = "flutter_runner_tzdata_tests" + + sources = [ "runner_tzdata_unittest.cc" ] + + # This is needed for //flutter/third_party/googletest for linking zircon + # symbols. + libs = [ "${fuchsia_arch_root}/sysroot/lib/libzircon.so" ] + + # The use of these dependencies is temporary and will be moved behind the + # embedder API. + flutter_deps = [ + "$dart_src/runtime:libdart_jit", + "$dart_src/runtime/platform:libdart_platform_jit", + "//flutter/lib/ui", + "//flutter/shell/platform/common/client_wrapper:client_wrapper_library_stubs", + ] + + deps = [ + ":flutter_runner_fixtures", + ":flutter_runner_sources", + "//flutter/testing", + ] + flutter_deps + } + + executable("flutter_runner_tzdata_missing_unittests") { + testonly = true + + output_name = "flutter_runner_tzdata_missing_tests" + + sources = [ "runner_tzdata_missing_unittest.cc" ] + + # This is needed for //flutter/third_party/googletest for linking zircon + # symbols. + libs = [ "${fuchsia_arch_root}/sysroot/lib/libzircon.so" ] + + # The use of these dependencies is temporary and will be moved behind the + # embedder API. + flutter_deps = [ + "$dart_src/runtime:libdart_jit", + "$dart_src/runtime/platform:libdart_platform_jit", + "//flutter/lib/ui", + "//flutter/shell/platform/common/client_wrapper:client_wrapper_library_stubs", + ] + + deps = [ + ":flutter_runner_fixtures", + ":flutter_runner_sources", + "//flutter/testing", + ] + flutter_deps + } + + fuchsia_test_archive("flutter_runner_tests") { + deps = [ ":flutter_runner_unittests" ] + gen_cml_file = true + resources = [ + { + path = rebase_path("//flutter/third_party/icu/common/icudtl.dat") + dest = "icudtl.dat" + }, + ] + } + + fuchsia_test_archive("flutter_runner_tzdata_tests") { + deps = [ ":flutter_runner_tzdata_unittests" ] + gen_cml_file = true + resources = [ + { + path = rebase_path("//flutter/third_party/icu/common/icudtl.dat") + dest = "icudtl.dat" + }, + { + path = rebase_path( + "//flutter/shell/platform/fuchsia/flutter/tests/tzdata/2019a/44/le/metaZones.res") + dest = "tzdata/metaZones.res" + }, + { + path = rebase_path( + "//flutter/shell/platform/fuchsia/flutter/tests/tzdata/2019a/44/le/timezoneTypes.res") + dest = "tzdata/timezoneTypes.res" + }, + { + path = rebase_path( + "//flutter/shell/platform/fuchsia/flutter/tests/tzdata/2019a/44/le/zoneinfo64.res") + dest = "tzdata/zoneinfo64.res" + }, + ] + } + + fuchsia_test_archive("flutter_runner_tzdata_missing_tests") { + deps = [ ":flutter_runner_tzdata_missing_unittests" ] + gen_cml_file = true + resources = [ + { + path = rebase_path("//flutter/third_party/icu/common/icudtl.dat") + dest = "icudtl.dat" + }, + ] + } + + fuchsia_test_archive("fml_tests") { + deps = [ "//flutter/fml:fml_unittests" ] + gen_cml_file = true + binary = "fml_unittests" + } + + fuchsia_test_archive("display_list_tests") { + deps = [ "//flutter/display_list:display_list_unittests" ] + gen_cml_file = true + binary = "display_list_unittests" + resources = [ + { + path = rebase_path("//flutter/txt/third_party/fonts/Roboto-Regular.ttf") + dest = "assets/Roboto-Regular.ttf" + }, + ] + } + + fuchsia_test_archive("display_list_render_tests") { + deps = [ "//flutter/display_list:display_list_rendertests" ] + gen_cml_file = true + binary = "display_list_rendertests" + resources = [ + { + path = rebase_path("//flutter/txt/third_party/fonts/Roboto-Regular.ttf") + dest = "assets/Roboto-Regular.ttf" + }, + ] + } + + fuchsia_test_archive("flow_tests") { + deps = [ "//flutter/flow:flow_unittests" ] + gen_cml_file = true + binary = "flow_unittests" + resources = [ + { + path = rebase_path( + "//flutter/testing/resources/performance_overlay_gold_60fps.png") + dest = "flutter/testing/resources/performance_overlay_gold_60fps.png" + }, + { + path = rebase_path( + "//flutter/testing/resources/performance_overlay_gold_90fps.png") + dest = "flutter/testing/resources/performance_overlay_gold_90fps.png" + }, + { + path = rebase_path( + "//flutter/testing/resources/performance_overlay_gold_120fps.png") + dest = "flutter/testing/resources/performance_overlay_gold_120fps.png" + }, + { + path = rebase_path("//flutter/txt/third_party/fonts/Roboto-Regular.ttf") + dest = "assets/Roboto-Regular.ttf" + }, + ] + } + + fuchsia_test_archive("runtime_tests") { + deps = [ + "//flutter/runtime:runtime_fixtures", + "//flutter/runtime:runtime_unittests", + ] + gen_cml_file = true + binary = "runtime_unittests" + + # TODO(gw280): https://github.com/flutter/flutter/issues/50294 + # Right now we need to manually specify all the fixtures that are + # declared in the test_fixtures() call above. + resources = [ + { + path = "$root_gen_dir/flutter/runtime/assets/kernel_blob.bin" + dest = "assets/kernel_blob.bin" + }, + ] + } + + fuchsia_test_archive("shell_tests") { + deps = [ + "//flutter/shell/common:shell_unittests", + "//flutter/shell/common:shell_unittests_fixtures", + ] + gen_cml_file = true + binary = "shell_unittests" + + # TODO(gw280): https://github.com/flutter/flutter/issues/50294 + # Right now we need to manually specify all the fixtures that are + # declared in the test_fixtures() call above. + resources = [ + { + path = "$root_gen_dir/flutter/shell/common/assets/kernel_blob.bin" + dest = "assets/kernel_blob.bin" + }, + { + path = + "$root_gen_dir/flutter/shell/common/assets/shelltest_screenshot.png" + dest = "assets/shelltest_screenshot.png" + }, + { + path = rebase_path("//flutter/txt/third_party/fonts/Roboto-Regular.ttf") + dest = "assets/Roboto-Regular.ttf" + }, + ] + + libraries = vulkan_validation_libs + resources += vulkan_icds + } + + fuchsia_test_archive("txt_tests") { + deps = [ "//flutter/txt:txt_unittests" ] + gen_cml_file = true + binary = "txt_unittests" + + resources = [ + { + path = rebase_path("//flutter/third_party/icu/common/icudtl.dat") + dest = "icudtl.dat" + }, + { + path = rebase_path("//flutter/third_party/icu/common/icudtl.dat") + dest = "icudtl2.dat" + }, + ] + } + + fuchsia_test_archive("ui_tests") { + deps = [ + "//flutter/lib/ui:ui_unittests", + "//flutter/lib/ui:ui_unittests_fixtures", + ] + gen_cml_file = true + binary = "ui_unittests" + + # TODO(gw280): https://github.com/flutter/flutter/issues/50294 + # Right now we need to manually specify all the fixtures that are + # declared in the test_fixtures() call above. + resources = [ + { + path = "$root_gen_dir/flutter/lib/ui/assets/kernel_blob.bin" + dest = "assets/kernel_blob.bin" + }, + { + path = "$root_gen_dir/flutter/lib/ui/assets/DashInNooglerHat.jpg" + dest = "assets/DashInNooglerHat.jpg" + }, + { + path = "$root_gen_dir/flutter/lib/ui/assets/Horizontal.jpg" + dest = "assets/Horizontal.jpg" + }, + { + path = "$root_gen_dir/flutter/lib/ui/assets/Horizontal.png" + dest = "assets/Horizontal.png" + }, + { + path = "$root_gen_dir/flutter/lib/ui/assets/hello_loop_2.gif" + dest = "assets/hello_loop_2.gif" + }, + { + path = "$root_gen_dir/flutter/lib/ui/assets/hello_loop_2.webp" + dest = "assets/hello_loop_2.webp" + }, + ] + + libraries = vulkan_validation_libs + resources += vulkan_icds + } + + fuchsia_test_archive("embedder_tests") { + deps = [ + "//flutter/shell/platform/embedder:embedder_unittests", + "//flutter/shell/platform/embedder:fixtures", + ] + gen_cml_file = true + binary = "embedder_unittests" + + # TODO(gw280): https://github.com/flutter/flutter/issues/50294 + # Right now we need to manually specify all the fixtures that are + # declared in the test_fixtures() call above. + resources = [ + { + path = "$root_gen_dir/flutter/shell/platform/embedder/assets/kernel_blob.bin" + dest = "assets/kernel_blob.bin" + }, + { + path = "$root_gen_dir/flutter/shell/platform/embedder/assets/arc_end_caps.png" + dest = "assets/arc_end_caps.png" + }, + { + path = "$root_gen_dir/flutter/shell/platform/embedder/assets/compositor.png" + dest = "assets/compositor.png" + }, + { + path = "$root_gen_dir/flutter/shell/platform/embedder/assets/compositor_root_surface_xformation.png" + dest = "assets/compositor_root_surface_xformation.png" + }, + { + path = "$root_gen_dir/flutter/shell/platform/embedder/assets/compositor_software.png" + dest = "assets/compositor_software.png" + }, + { + path = "$root_gen_dir/flutter/shell/platform/embedder/assets/compositor_with_platform_layer_on_bottom.png" + dest = "assets/compositor_with_platform_layer_on_bottom.png" + }, + { + path = "$root_gen_dir/flutter/shell/platform/embedder/assets/compositor_with_root_layer_only.png" + dest = "assets/compositor_with_root_layer_only.png" + }, + { + path = "$root_gen_dir/flutter/shell/platform/embedder/assets/dpr_noxform.png" + dest = "assets/dpr_noxform.png" + }, + { + path = + "$root_gen_dir/flutter/shell/platform/embedder/assets/dpr_xform.png" + dest = "assets/dpr_xform.png" + }, + { + path = + "$root_gen_dir/flutter/shell/platform/embedder/assets/gradient.png" + dest = "assets/gradient.png" + }, + { + path = "$root_gen_dir/flutter/shell/platform/embedder/assets/gradient_xform.png" + dest = "assets/gradient_xform.png" + }, + { + path = "$root_gen_dir/flutter/shell/platform/embedder/assets/scene_without_custom_compositor.png" + dest = "assets/scene_without_custom_compositor.png" + }, + { + path = "$root_gen_dir/flutter/shell/platform/embedder/assets/scene_without_custom_compositor_with_xform.png" + dest = "assets/scene_without_custom_compositor_with_xform.png" + }, + { + path = "$root_gen_dir/flutter/shell/platform/embedder/assets/snapshot_large_scene.png" + dest = "assets/snapshot_large_scene.png" + }, + { + path = "$root_gen_dir/flutter/shell/platform/embedder/assets/verifyb143464703.png" + dest = "assets/verifyb143464703.png" + }, + { + path = "$root_gen_dir/flutter/shell/platform/embedder/assets/verifyb143464703_soft_noxform.png" + dest = "assets/verifyb143464703_soft_noxform.png" + }, + ] + } + + fuchsia_test_archive("dart_utils_tests") { + deps = [ "//flutter/shell/platform/fuchsia/runtime/dart/utils:dart_utils_unittests" ] + gen_cml_file = true + binary = "dart_utils_unittests" + } + + fuchsia_test_archive("assets_unittests") { + deps = [ "//flutter/assets:assets_unittests" ] + gen_cml_file = true + binary = "assets_unittests" + } + + fuchsia_test_archive("client_wrapper_unittests") { + deps = [ + "//flutter/shell/platform/common/client_wrapper:client_wrapper_unittests", + ] + gen_cml_file = true + binary = "client_wrapper_unittests" + } + + fuchsia_test_archive("common_cpp_core_unittests") { + deps = [ "//flutter/shell/platform/common:common_cpp_core_unittests" ] + gen_cml_file = true + binary = "common_cpp_core_unittests" + } + + fuchsia_test_archive("common_cpp_unittests") { + deps = [ "//flutter/shell/platform/common:common_cpp_unittests" ] + gen_cml_file = true + binary = "common_cpp_unittests" + } + + fuchsia_test_archive("dart_plugin_registrant_unittests") { + deps = [ + "//flutter/runtime:dart_plugin_registrant_unittests", + "//flutter/runtime:plugin_registrant", + ] + gen_cml_file = true + binary = "dart_plugin_registrant_unittests" + + # TODO(gw280): https://github.com/flutter/flutter/issues/50294 + # Right now we need to manually specify all the fixtures that are + # declared in the test_fixtures() call above. + resources = [ + { + path = "$root_gen_dir/flutter/runtime/assets/plugin_registrant_kernel_blob.bin" + dest = "assets/plugin_registrant_kernel_blob.bin" + }, + ] + if (is_aot_test) { + resources += [ + { + path = "$root_gen_dir/flutter/runtime/assets/plugin_registrant_app_elf_snapshot.so" + dest = "assets/plugin_registrant_app_elf_snapshot.so" + }, + ] + } + } + + fuchsia_test_archive("no_dart_plugin_registrant_unittests") { + deps = [ + "//flutter/runtime:no_dart_plugin_registrant_unittests", + "//flutter/runtime:no_plugin_registrant", + ] + gen_cml_file = true + binary = "no_dart_plugin_registrant_unittests" + + # TODO(gw280): https://github.com/flutter/flutter/issues/50294 + # Right now we need to manually specify all the fixtures that are + # declared in the test_fixtures() call above. + resources = [ + { + path = "$root_gen_dir/flutter/runtime/assets/no_plugin_registrant_kernel_blob.bin" + dest = "assets/no_plugin_registrant_kernel_blob.bin" + }, + ] + if (is_aot_test) { + resources += [ + { + path = "$root_gen_dir/flutter/runtime/assets/no_plugin_registrant_app_elf_snapshot.so" + dest = "assets/no_plugin_registrant_app_elf_snapshot.so" + }, + ] + } + } + + fuchsia_test_archive("embedder_a11y_unittests") { + deps = [ + "//flutter/shell/platform/embedder:embedder_a11y_unittests", + "//flutter/shell/platform/embedder:fixtures", + ] + gen_cml_file = true + binary = "embedder_a11y_unittests" + + # TODO(gw280): https://github.com/flutter/flutter/issues/50294 + # Right now we need to manually specify all the fixtures that are + # declared in the test_fixtures() call above. + resources = [ + { + path = "$root_gen_dir/flutter/shell/platform/embedder/assets/kernel_blob.bin" + dest = "assets/kernel_blob.bin" + }, + ] + if (is_aot_test) { + resources += [ + { + path = "$root_gen_dir/flutter/shell/platform/embedder/assets/app_elf_snapshot.so" + dest = "assets/app_elf_snapshot.so" + }, + ] + } + } + + fuchsia_test_archive("embedder_proctable_unittests") { + deps = [ "//flutter/shell/platform/embedder:embedder_proctable_unittests" ] + gen_cml_file = true + binary = "embedder_proctable_unittests" + } + + fuchsia_test_archive("testing_unittests") { + deps = [ "//flutter/testing:testing_unittests" ] + gen_cml_file = true + binary = "testing_unittests" + } + + fuchsia_test_archive("tonic_unittests") { + deps = [ + "//flutter/third_party/tonic/tests:tonic_fixtures", + "//flutter/third_party/tonic/tests:tonic_unittests", + ] + gen_cml_file = true + binary = "tonic_unittests" + + # TODO(gw280): https://github.com/flutter/flutter/issues/50294 + # Right now we need to manually specify all the fixtures that are + # declared in the test_fixtures() call above. + resources = [ + { + path = "$root_gen_dir/flutter/third_party/tonic/tests/assets/kernel_blob.bin" + dest = "assets/kernel_blob.bin" + }, + ] + if (is_aot_test) { + resources += [ + { + path = "$root_gen_dir/flutter/third_party/tonic/tests/assets/app_elf_snapshot.so" + dest = "assets/app_elf_snapshot.so" + }, + ] + } + } + + # When adding a new dep here, please also ensure the dep is added to + # testing/fuchsia/test_suites.yaml. + group("tests") { + testonly = true + + deps = [ + ":assets_unittests", + ":client_wrapper_unittests", + ":common_cpp_core_unittests", + ":common_cpp_unittests", + ":dart_plugin_registrant_unittests", + ":dart_utils_tests", + ":display_list_render_tests", + ":display_list_tests", + ":embedder_a11y_unittests", + ":embedder_proctable_unittests", + ":embedder_tests", + ":flow_tests", + ":flutter_runner_tests", + ":flutter_runner_tzdata_missing_tests", + ":flutter_runner_tzdata_tests", + ":fml_tests", + ":no_dart_plugin_registrant_unittests", + ":runtime_tests", + ":shell_tests", + ":testing_unittests", + ":tonic_unittests", + ":txt_tests", + ":ui_tests", + "tests/integration", + ] + } +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/README.md b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8ff726b1c6b77cbc7b241f50c21f210d40d2ea8a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/README.md @@ -0,0 +1,5 @@ +Flutter Application Runner +========================== + +Implements the `fuchsia::component::runner::ComponentRunner` FIDL interface to +launch and run multiple Flutter applications within the same process in Fuchsia. diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/accessibility_bridge.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/accessibility_bridge.cc new file mode 100644 index 0000000000000000000000000000000000000000..987b9303bace10f42dc01b953ef5c1424b62af23 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/accessibility_bridge.cc @@ -0,0 +1,972 @@ +// 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/shell/platform/fuchsia/flutter/accessibility_bridge.h" + +#include +#include +#include +#include + +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/lib/ui/semantics/semantics_node.h" + +#include "../runtime/dart/utils/root_inspect_node.h" + +namespace flutter_runner { +namespace { + +#if !FLUTTER_RELEASE +static constexpr char kTreeDumpInspectRootName[] = "semantic_tree_root"; + +// Converts flutter semantic node flags to a string representation. +std::string NodeFlagsToString(const flutter::SemanticsNode& node) { + std::string output; + if (node.HasFlag(flutter::SemanticsFlags::kHasCheckedState)) { + output += "kHasCheckedState|"; + } + if (node.HasFlag(flutter::SemanticsFlags::kHasEnabledState)) { + output += "kHasEnabledState|"; + } + if (node.HasFlag(flutter::SemanticsFlags::kHasImplicitScrolling)) { + output += "kHasImplicitScrolling|"; + } + if (node.HasFlag(flutter::SemanticsFlags::kHasToggledState)) { + output += "kHasToggledState|"; + } + if (node.HasFlag(flutter::SemanticsFlags::kIsButton)) { + output += "kIsButton|"; + } + if (node.HasFlag(flutter::SemanticsFlags::kIsChecked)) { + output += "kIsChecked|"; + } + if (node.HasFlag(flutter::SemanticsFlags::kIsEnabled)) { + output += "kIsEnabled|"; + } + if (node.HasFlag(flutter::SemanticsFlags::kIsFocusable)) { + output += "kIsFocusable|"; + } + if (node.HasFlag(flutter::SemanticsFlags::kIsFocused)) { + output += "kIsFocused|"; + } + if (node.HasFlag(flutter::SemanticsFlags::kIsHeader)) { + output += "kIsHeader|"; + } + if (node.HasFlag(flutter::SemanticsFlags::kIsHidden)) { + output += "kIsHidden|"; + } + if (node.HasFlag(flutter::SemanticsFlags::kIsImage)) { + output += "kIsImage|"; + } + if (node.HasFlag(flutter::SemanticsFlags::kIsInMutuallyExclusiveGroup)) { + output += "kIsInMutuallyExclusiveGroup|"; + } + if (node.HasFlag(flutter::SemanticsFlags::kIsKeyboardKey)) { + output += "kIsKeyboardKey|"; + } + if (node.HasFlag(flutter::SemanticsFlags::kIsLink)) { + output += "kIsLink|"; + } + if (node.HasFlag(flutter::SemanticsFlags::kIsLiveRegion)) { + output += "kIsLiveRegion|"; + } + if (node.HasFlag(flutter::SemanticsFlags::kIsObscured)) { + output += "kIsObscured|"; + } + if (node.HasFlag(flutter::SemanticsFlags::kIsReadOnly)) { + output += "kIsReadOnly|"; + } + if (node.HasFlag(flutter::SemanticsFlags::kIsSelected)) { + output += "kIsSelected|"; + } + if (node.HasFlag(flutter::SemanticsFlags::kIsSlider)) { + output += "kIsSlider|"; + } + if (node.HasFlag(flutter::SemanticsFlags::kIsTextField)) { + output += "kIsTextField|"; + } + if (node.HasFlag(flutter::SemanticsFlags::kIsToggled)) { + output += "kIsToggled|"; + } + if (node.HasFlag(flutter::SemanticsFlags::kNamesRoute)) { + output += "kNamesRoute|"; + } + if (node.HasFlag(flutter::SemanticsFlags::kScopesRoute)) { + output += "kScopesRoute|"; + } + + return output; +} + +// Converts flutter semantic node actions to a string representation. +std::string NodeActionsToString(const flutter::SemanticsNode& node) { + std::string output; + + if (node.HasAction(flutter::SemanticsAction::kCopy)) { + output += "kCopy|"; + } + if (node.HasAction(flutter::SemanticsAction::kCustomAction)) { + output += "kCustomAction|"; + } + if (node.HasAction(flutter::SemanticsAction::kCut)) { + output += "kCut|"; + } + if (node.HasAction(flutter::SemanticsAction::kDecrease)) { + output += "kDecrease|"; + } + if (node.HasAction(flutter::SemanticsAction::kDidGainAccessibilityFocus)) { + output += "kDidGainAccessibilityFocus|"; + } + if (node.HasAction(flutter::SemanticsAction::kDidLoseAccessibilityFocus)) { + output += "kDidLoseAccessibilityFocus|"; + } + if (node.HasAction(flutter::SemanticsAction::kDismiss)) { + output += "kDismiss|"; + } + if (node.HasAction(flutter::SemanticsAction::kIncrease)) { + output += "kIncrease|"; + } + if (node.HasAction(flutter::SemanticsAction::kLongPress)) { + output += "kLongPress|"; + } + if (node.HasAction( + flutter::SemanticsAction::kMoveCursorBackwardByCharacter)) { + output += "kMoveCursorBackwardByCharacter|"; + } + if (node.HasAction(flutter::SemanticsAction::kMoveCursorBackwardByWord)) { + output += "kMoveCursorBackwardByWord|"; + } + if (node.HasAction(flutter::SemanticsAction::kMoveCursorForwardByCharacter)) { + output += "kMoveCursorForwardByCharacter|"; + } + if (node.HasAction(flutter::SemanticsAction::kMoveCursorForwardByWord)) { + output += "kMoveCursorForwardByWord|"; + } + if (node.HasAction(flutter::SemanticsAction::kPaste)) { + output += "kPaste|"; + } + if (node.HasAction(flutter::SemanticsAction::kScrollDown)) { + output += "kScrollDown|"; + } + if (node.HasAction(flutter::SemanticsAction::kScrollLeft)) { + output += "kScrollLeft|"; + } + if (node.HasAction(flutter::SemanticsAction::kScrollRight)) { + output += "kScrollRight|"; + } + if (node.HasAction(flutter::SemanticsAction::kScrollUp)) { + output += "kScrollUp|"; + } + if (node.HasAction(flutter::SemanticsAction::kScrollToOffset)) { + output += "kScrollToOffset|"; + } + if (node.HasAction(flutter::SemanticsAction::kSetSelection)) { + output += "kSetSelection|"; + } + if (node.HasAction(flutter::SemanticsAction::kSetText)) { + output += "kSetText|"; + } + if (node.HasAction(flutter::SemanticsAction::kShowOnScreen)) { + output += "kShowOnScreen|"; + } + if (node.HasAction(flutter::SemanticsAction::kTap)) { + output += "kTap|"; + } + if (node.HasAction(flutter::SemanticsAction::kFocus)) { + output += "kFocus|"; + } + + return output; +} + +// Returns a string representation of the flutter semantic node absolut +// location. +std::string NodeLocationToString(const SkRect& rect) { + auto min_x = rect.fLeft; + auto min_y = rect.fTop; + auto max_x = rect.fRight; + auto max_y = rect.fBottom; + std::string location = + "min(" + std::to_string(min_x) + ", " + std::to_string(min_y) + ") max(" + + std::to_string(max_x) + ", " + std::to_string(max_y) + ")"; + + return location; +} + +// Returns a string representation of the node's different types of children. +std::string NodeChildrenToString(const flutter::SemanticsNode& node) { + std::stringstream output; + if (!node.childrenInTraversalOrder.empty()) { + output << "children in traversal order:["; + for (const auto child_id : node.childrenInTraversalOrder) { + output << child_id << ", "; + } + output << "]\n"; + } + if (!node.childrenInHitTestOrder.empty()) { + output << "children in hit test order:["; + for (const auto child_id : node.childrenInHitTestOrder) { + output << child_id << ", "; + } + output << ']'; + } + + return output.str(); +} +#endif // !FLUTTER_RELEASE + +} // namespace + +AccessibilityBridge::AccessibilityBridge( + SetSemanticsEnabledCallback set_semantics_enabled_callback, + DispatchSemanticsActionCallback dispatch_semantics_action_callback, + fuchsia::accessibility::semantics::SemanticsManagerHandle semantics_manager, + fuchsia::ui::views::ViewRef view_ref, + inspect::Node inspect_node) + : set_semantics_enabled_callback_( + std::move(set_semantics_enabled_callback)), + dispatch_semantics_action_callback_( + std::move(dispatch_semantics_action_callback)), + binding_(this), + fuchsia_semantics_manager_(semantics_manager.Bind()), + atomic_updates_(std::make_shared>()), + inspect_node_(std::move(inspect_node)) { + fuchsia_semantics_manager_.set_error_handler([](zx_status_t status) { + FML_LOG(ERROR) << "Flutter cannot connect to SemanticsManager with status: " + << zx_status_get_string(status) << "."; + }); + fuchsia_semantics_manager_->RegisterViewForSemantics( + std::move(view_ref), binding_.NewBinding(), tree_ptr_.NewRequest()); + +#if !FLUTTER_RELEASE + // The first argument to |CreateLazyValues| is the name of the lazy node, and + // will only be displayed if the callback used to generate the node's content + // fails. Therefore, we use an error message for this node name. + inspect_node_tree_dump_ = + inspect_node_.CreateLazyValues("dump_fail", [this]() { + inspect::Inspector inspector; + if (auto it = nodes_.find(kRootNodeId); it == nodes_.end()) { + inspector.GetRoot().CreateString( + "empty_tree", "this semantic tree is empty", &inspector); + } else { + FillInspectTree( + kRootNodeId, /*current_level=*/1, + inspector.GetRoot().CreateChild(kTreeDumpInspectRootName), + &inspector); + } + return fpromise::make_ok_promise(std::move(inspector)); + }); +#endif // !FLUTTER_RELEASE +} + +bool AccessibilityBridge::GetSemanticsEnabled() const { + return semantics_enabled_; +} + +void AccessibilityBridge::SetSemanticsEnabled(bool enabled) { + semantics_enabled_ = enabled; + if (!enabled) { + nodes_.clear(); + } +} + +fuchsia::ui::gfx::BoundingBox AccessibilityBridge::GetNodeLocation( + const flutter::SemanticsNode& node) const { + fuchsia::ui::gfx::BoundingBox box; + box.min.x = node.rect.fLeft; + box.min.y = node.rect.fTop; + box.min.z = static_cast(node.elevation); + box.max.x = node.rect.fRight; + box.max.y = node.rect.fBottom; + box.max.z = static_cast(node.thickness); + return box; +} + +fuchsia::ui::gfx::mat4 AccessibilityBridge::GetNodeTransform( + const flutter::SemanticsNode& node) const { + return ConvertSkiaTransformToMat4(node.transform); +} + +fuchsia::ui::gfx::mat4 AccessibilityBridge::ConvertSkiaTransformToMat4( + const SkM44 transform) const { + fuchsia::ui::gfx::mat4 value; + float* m = value.matrix.data(); + transform.getColMajor(m); + return value; +} + +fuchsia::accessibility::semantics::Attributes +AccessibilityBridge::GetNodeAttributes(const flutter::SemanticsNode& node, + size_t* added_size) const { + fuchsia::accessibility::semantics::Attributes attributes; + // TODO(MI4-2531): Don't truncate. + if (node.label.size() > fuchsia::accessibility::semantics::MAX_LABEL_SIZE) { + attributes.set_label(node.label.substr( + 0, fuchsia::accessibility::semantics::MAX_LABEL_SIZE)); + *added_size += fuchsia::accessibility::semantics::MAX_LABEL_SIZE; + } else { + attributes.set_label(node.label); + *added_size += node.label.size(); + } + + if (node.tooltip.size() > fuchsia::accessibility::semantics::MAX_LABEL_SIZE) { + attributes.set_secondary_label(node.tooltip.substr( + 0, fuchsia::accessibility::semantics::MAX_LABEL_SIZE)); + *added_size += fuchsia::accessibility::semantics::MAX_LABEL_SIZE; + } else { + attributes.set_secondary_label(node.tooltip); + *added_size += node.tooltip.size(); + } + + if (node.HasFlag(flutter::SemanticsFlags::kIsKeyboardKey)) { + attributes.set_is_keyboard_key(true); + } + + return attributes; +} + +fuchsia::accessibility::semantics::States AccessibilityBridge::GetNodeStates( + const flutter::SemanticsNode& node, + size_t* additional_size) const { + fuchsia::accessibility::semantics::States states; + (*additional_size) += sizeof(fuchsia::accessibility::semantics::States); + + // Set checked state. + if (!node.HasFlag(flutter::SemanticsFlags::kHasCheckedState)) { + states.set_checked_state( + fuchsia::accessibility::semantics::CheckedState::NONE); + } else { + states.set_checked_state( + node.HasFlag(flutter::SemanticsFlags::kIsChecked) + ? fuchsia::accessibility::semantics::CheckedState::CHECKED + : fuchsia::accessibility::semantics::CheckedState::UNCHECKED); + } + + // Set enabled state. + if (node.HasFlag(flutter::SemanticsFlags::kHasEnabledState)) { + states.set_enabled_state( + node.HasFlag(flutter::SemanticsFlags::kIsEnabled) + ? fuchsia::accessibility::semantics::EnabledState::ENABLED + : fuchsia::accessibility::semantics::EnabledState::DISABLED); + } + + // Set selected state. + states.set_selected(node.HasFlag(flutter::SemanticsFlags::kIsSelected)); + + // Flutter's definition of a hidden node is different from Fuchsia, so it must + // not be set here. + + // Set value. + if (node.value.size() > fuchsia::accessibility::semantics::MAX_VALUE_SIZE) { + states.set_value(node.value.substr( + 0, fuchsia::accessibility::semantics::MAX_VALUE_SIZE)); + (*additional_size) += fuchsia::accessibility::semantics::MAX_VALUE_SIZE; + } else { + states.set_value(node.value); + (*additional_size) += node.value.size(); + } + + // Set toggled state. + if (node.HasFlag(flutter::SemanticsFlags::kHasToggledState)) { + states.set_toggled_state( + node.HasFlag(flutter::SemanticsFlags::kIsToggled) + ? fuchsia::accessibility::semantics::ToggledState::ON + : fuchsia::accessibility::semantics::ToggledState::OFF); + } + + return states; +} + +std::vector +AccessibilityBridge::GetNodeActions(const flutter::SemanticsNode& node, + size_t* additional_size) const { + std::vector node_actions; + + if (node.HasAction(flutter::SemanticsAction::kTap)) { + node_actions.push_back(fuchsia::accessibility::semantics::Action::DEFAULT); + } + if (node.HasAction(flutter::SemanticsAction::kLongPress)) { + node_actions.push_back( + fuchsia::accessibility::semantics::Action::SECONDARY); + } + if (node.HasAction(flutter::SemanticsAction::kShowOnScreen)) { + node_actions.push_back( + fuchsia::accessibility::semantics::Action::SHOW_ON_SCREEN); + } + if (node.HasAction(flutter::SemanticsAction::kIncrease)) { + node_actions.push_back( + fuchsia::accessibility::semantics::Action::INCREMENT); + } + if (node.HasAction(flutter::SemanticsAction::kDecrease)) { + node_actions.push_back( + fuchsia::accessibility::semantics::Action::DECREMENT); + } + + *additional_size += + node_actions.size() * sizeof(fuchsia::accessibility::semantics::Action); + return node_actions; +} + +fuchsia::accessibility::semantics::Role AccessibilityBridge::GetNodeRole( + const flutter::SemanticsNode& node) const { + if (node.HasFlag(flutter::SemanticsFlags::kIsButton)) { + return fuchsia::accessibility::semantics::Role::BUTTON; + } + + if (node.HasFlag(flutter::SemanticsFlags::kIsTextField)) { + return fuchsia::accessibility::semantics::Role::TEXT_FIELD; + } + + if (node.HasFlag(flutter::SemanticsFlags::kIsLink)) { + return fuchsia::accessibility::semantics::Role::LINK; + } + + if (node.HasFlag(flutter::SemanticsFlags::kIsSlider)) { + return fuchsia::accessibility::semantics::Role::SLIDER; + } + + if (node.HasFlag(flutter::SemanticsFlags::kIsHeader)) { + return fuchsia::accessibility::semantics::Role::HEADER; + } + if (node.HasFlag(flutter::SemanticsFlags::kIsImage)) { + return fuchsia::accessibility::semantics::Role::IMAGE; + } + + // If a flutter node supports the kIncrease or kDecrease actions, it can be + // treated as a slider control by assistive technology. This is important + // because users have special gestures to deal with sliders, and Fuchsia API + // requires nodes that can receive this kind of action to be a slider control. + if (node.HasAction(flutter::SemanticsAction::kIncrease) || + node.HasAction(flutter::SemanticsAction::kDecrease)) { + return fuchsia::accessibility::semantics::Role::SLIDER; + } + + // If a flutter node has a checked state, then we assume it is either a + // checkbox or a radio button. We distinguish between checkboxes and + // radio buttons based on membership in a mutually exclusive group. + if (node.HasFlag(flutter::SemanticsFlags::kHasCheckedState)) { + if (node.HasFlag(flutter::SemanticsFlags::kIsInMutuallyExclusiveGroup)) { + return fuchsia::accessibility::semantics::Role::RADIO_BUTTON; + } else { + return fuchsia::accessibility::semantics::Role::CHECK_BOX; + } + } + + if (node.HasFlag(flutter::SemanticsFlags::kHasToggledState)) { + return fuchsia::accessibility::semantics::Role::TOGGLE_SWITCH; + } + return fuchsia::accessibility::semantics::Role::UNKNOWN; +} + +std::unordered_set AccessibilityBridge::GetDescendants( + int32_t node_id) const { + std::unordered_set descendents; + std::deque to_process = {node_id}; + while (!to_process.empty()) { + int32_t id = to_process.front(); + to_process.pop_front(); + descendents.emplace(id); + + auto it = nodes_.find(id); + if (it != nodes_.end()) { + const auto& node = it->second.data; + for (const auto& child : node.childrenInHitTestOrder) { + if (descendents.find(child) == descendents.end()) { + to_process.push_back(child); + } else { + // This indicates either a cycle or a child with multiple parents. + // Flutter should never let this happen, but the engine API does not + // explicitly forbid it right now. + // TODO(http://fxbug.dev/75905): Crash flutter accessibility bridge + // when a cycle in the tree is found. + FML_LOG(ERROR) << "Semantics Node " << child + << " has already been listed as a child of another " + "node, ignoring for parent " + << id << "."; + } + } + } + } + return descendents; +} + +// The only known usage of a negative number for a node ID is in the embedder +// API as a sentinel value, which is not expected here. No valid producer of +// nodes should give us a negative ID. +static uint32_t FlutterIdToFuchsiaId(int32_t flutter_node_id) { + FML_DCHECK(flutter_node_id >= 0) + << "Unexpectedly received a negative semantics node ID."; + return static_cast(flutter_node_id); +} + +void AccessibilityBridge::PruneUnreachableNodes( + FuchsiaAtomicUpdate* atomic_update) { + const auto& reachable_nodes = GetDescendants(kRootNodeId); + auto iter = nodes_.begin(); + while (iter != nodes_.end()) { + int32_t id = iter->first; + if (reachable_nodes.find(id) == reachable_nodes.end()) { + atomic_update->AddNodeDeletion(FlutterIdToFuchsiaId(id)); + iter = nodes_.erase(iter); + } else { + iter++; + } + } +} + +// TODO(FIDL-718) - remove this, handle the error instead in something like +// set_error_handler. +static void PrintNodeSizeError(uint32_t node_id) { + FML_LOG(ERROR) << "Semantics node with ID " << node_id + << " exceeded the maximum FIDL message size and may not " + "be delivered to the accessibility manager service."; +} + +void AccessibilityBridge::AddSemanticsNodeUpdate( + const flutter::SemanticsNodeUpdates update, + float view_pixel_ratio) { + if (update.empty()) { + return; + } + FML_DCHECK(nodes_.find(kRootNodeId) != nodes_.end() || + update.find(kRootNodeId) != update.end()) + << "AccessibilityBridge received an update with out ever getting a root " + "node."; + + FuchsiaAtomicUpdate atomic_update; + bool has_root_node_update = false; + // TODO(MI4-2498): Actions, Roles, hit test children, additional + // flags/states/attr + + // TODO(MI4-1478): Support for partial updates for nodes > 64kb + // e.g. if a node has a long label or more than 64k children. + for (const auto& [flutter_node_id, flutter_node] : update) { + size_t this_node_size = sizeof(fuchsia::accessibility::semantics::Node); + // We handle root update separately in GetRootNodeUpdate. + // TODO(chunhtai): remove this special case after we remove the inverse + // view pixel ratio transformation in scenic view. + // TODO(http://fxbug.dev/75908): Investigate flutter a11y bridge refactor + // after removal of the inverse view pixel ratio transformation in scenic + // view). + if (flutter_node.id == kRootNodeId) { + root_flutter_semantics_node_ = flutter_node; + has_root_node_update = true; + continue; + } + // Store the nodes for later hit testing and logging. + nodes_[flutter_node.id].data = flutter_node; + + fuchsia::accessibility::semantics::Node fuchsia_node; + std::vector child_ids; + // Send the nodes in traversal order, so the manager can figure out + // traversal. + for (int32_t flutter_child_id : flutter_node.childrenInTraversalOrder) { + child_ids.push_back(FlutterIdToFuchsiaId(flutter_child_id)); + } + // TODO(http://fxbug.dev/75910): check the usage of FlutterIdToFuchsiaId in + // the flutter accessibility bridge. + fuchsia_node.set_node_id(flutter_node.id) + .set_role(GetNodeRole(flutter_node)) + .set_location(GetNodeLocation(flutter_node)) + .set_transform(GetNodeTransform(flutter_node)) + .set_attributes(GetNodeAttributes(flutter_node, &this_node_size)) + .set_states(GetNodeStates(flutter_node, &this_node_size)) + .set_actions(GetNodeActions(flutter_node, &this_node_size)) + .set_child_ids(child_ids); + this_node_size += + kNodeIdSize * flutter_node.childrenInTraversalOrder.size(); + + atomic_update.AddNodeUpdate(std::move(fuchsia_node), this_node_size); + } + + // Handles root node update. + if (has_root_node_update || last_seen_view_pixel_ratio_ != view_pixel_ratio) { + last_seen_view_pixel_ratio_ = view_pixel_ratio; + size_t root_node_size; + fuchsia::accessibility::semantics::Node root_update = + GetRootNodeUpdate(root_node_size); + atomic_update.AddNodeUpdate(std::move(root_update), root_node_size); + } + + PruneUnreachableNodes(&atomic_update); + UpdateScreenRects(); + + atomic_updates_->push(std::move(atomic_update)); + if (atomic_updates_->size() == 1) { + // There were no commits in the queue, so send this one. + Apply(&atomic_updates_->front()); + } +} + +fuchsia::accessibility::semantics::Node AccessibilityBridge::GetRootNodeUpdate( + size_t& node_size) { + fuchsia::accessibility::semantics::Node root_fuchsia_node; + std::vector child_ids; + node_size = sizeof(fuchsia::accessibility::semantics::Node); + for (int32_t flutter_child_id : + root_flutter_semantics_node_.childrenInTraversalOrder) { + child_ids.push_back(FlutterIdToFuchsiaId(flutter_child_id)); + } + // Applies the inverse view pixel ratio transformation to the root node. + float inverse_view_pixel_ratio = 1.f / last_seen_view_pixel_ratio_; + SkM44 inverse_view_pixel_ratio_transform; + inverse_view_pixel_ratio_transform.setScale(inverse_view_pixel_ratio, + inverse_view_pixel_ratio, 1.f); + + SkM44 result = root_flutter_semantics_node_.transform * + inverse_view_pixel_ratio_transform; + nodes_[root_flutter_semantics_node_.id].data = root_flutter_semantics_node_; + + // TODO(http://fxbug.dev/75910): check the usage of FlutterIdToFuchsiaId in + // the flutter accessibility bridge. + root_fuchsia_node.set_node_id(root_flutter_semantics_node_.id) + .set_role(GetNodeRole(root_flutter_semantics_node_)) + .set_location(GetNodeLocation(root_flutter_semantics_node_)) + .set_transform(ConvertSkiaTransformToMat4(result)) + .set_attributes( + GetNodeAttributes(root_flutter_semantics_node_, &node_size)) + .set_states(GetNodeStates(root_flutter_semantics_node_, &node_size)) + .set_actions(GetNodeActions(root_flutter_semantics_node_, &node_size)) + .set_child_ids(child_ids); + node_size += kNodeIdSize * + root_flutter_semantics_node_.childrenInTraversalOrder.size(); + return root_fuchsia_node; +} + +void AccessibilityBridge::RequestAnnounce(const std::string message) { + fuchsia::accessibility::semantics::SemanticEvent semantic_event; + fuchsia::accessibility::semantics::AnnounceEvent announce_event; + announce_event.set_message(message); + semantic_event.set_announce(std::move(announce_event)); + + tree_ptr_->SendSemanticEvent(std::move(semantic_event), []() {}); +} + +void AccessibilityBridge::UpdateScreenRects() { + std::unordered_set visited_nodes; + + // The embedder applies a special pixel ratio transform to the root of the + // view, and the accessibility bridge applies the inverse of this transform + // to the root node. However, this transform is not persisted in the flutter + // representation of the root node, so we need to account for it explicitly + // here. + float inverse_view_pixel_ratio = 1.f / last_seen_view_pixel_ratio_; + SkM44 inverse_view_pixel_ratio_transform; + inverse_view_pixel_ratio_transform.setScale(inverse_view_pixel_ratio, + inverse_view_pixel_ratio, 1.f); + + UpdateScreenRects(kRootNodeId, inverse_view_pixel_ratio_transform, + &visited_nodes); +} + +void AccessibilityBridge::UpdateScreenRects( + int32_t node_id, + SkM44 parent_transform, + std::unordered_set* visited_nodes) { + auto it = nodes_.find(node_id); + if (it == nodes_.end()) { + FML_LOG(ERROR) << "UpdateScreenRects called on unknown node"; + return; + } + auto& node = it->second; + const auto& current_transform = parent_transform * node.data.transform; + + const auto& rect = node.data.rect; + SkV4 dst[2] = { + current_transform.map(rect.left(), rect.top(), 0, 1), + current_transform.map(rect.right(), rect.bottom(), 0, 1), + }; + node.screen_rect.setLTRB(dst[0].x, dst[0].y, dst[1].x, dst[1].y); + node.screen_rect.sort(); + + visited_nodes->emplace(node_id); + + for (uint32_t child_id : node.data.childrenInHitTestOrder) { + if (visited_nodes->find(child_id) == visited_nodes->end()) { + UpdateScreenRects(child_id, current_transform, visited_nodes); + } + } +} + +std::optional +AccessibilityBridge::GetFlutterSemanticsAction( + fuchsia::accessibility::semantics::Action fuchsia_action, + uint32_t node_id) { + switch (fuchsia_action) { + // The default action associated with the element. + case fuchsia::accessibility::semantics::Action::DEFAULT: + return flutter::SemanticsAction::kTap; + // The secondary action associated with the element. This may correspond to + // a long press (touchscreens) or right click (mouse). + case fuchsia::accessibility::semantics::Action::SECONDARY: + return flutter::SemanticsAction::kLongPress; + // Set (input/non-accessibility) focus on this element. + case fuchsia::accessibility::semantics::Action::SET_FOCUS: + FML_LOG(WARNING) + << "Unsupported action SET_FOCUS sent for accessibility node " + << node_id; + return {}; + // Set the element's value. + case fuchsia::accessibility::semantics::Action::SET_VALUE: + FML_LOG(WARNING) + << "Unsupported action SET_VALUE sent for accessibility node " + << node_id; + return {}; + // Scroll node to make it visible. + case fuchsia::accessibility::semantics::Action::SHOW_ON_SCREEN: + return flutter::SemanticsAction::kShowOnScreen; + case fuchsia::accessibility::semantics::Action::INCREMENT: + return flutter::SemanticsAction::kIncrease; + case fuchsia::accessibility::semantics::Action::DECREMENT: + return flutter::SemanticsAction::kDecrease; + default: + FML_LOG(WARNING) << "Unexpected action " + << static_cast(fuchsia_action) + << " sent for accessibility node " << node_id; + return {}; + } +} + +// |fuchsia::accessibility::semantics::SemanticListener| +void AccessibilityBridge::OnAccessibilityActionRequested( + uint32_t node_id, + fuchsia::accessibility::semantics::Action action, + fuchsia::accessibility::semantics::SemanticListener:: + OnAccessibilityActionRequestedCallback callback) { + // TODO(http://fxbug.dev/75910): check the usage of FlutterIdToFuchsiaId in + // the flutter accessibility bridge. + if (nodes_.find(node_id) == nodes_.end()) { + FML_LOG(ERROR) << "Attempted to send accessibility action " + << static_cast(action) + << " to unknown node id: " << node_id; + callback(false); + return; + } + + std::optional flutter_action = + GetFlutterSemanticsAction(action, node_id); + if (!flutter_action.has_value()) { + callback(false); + return; + } + dispatch_semantics_action_callback_(static_cast(node_id), + flutter_action.value()); + callback(true); +} + +// |fuchsia::accessibility::semantics::SemanticListener| +void AccessibilityBridge::HitTest( + fuchsia::math::PointF local_point, + fuchsia::accessibility::semantics::SemanticListener::HitTestCallback + callback) { + auto hit_node_id = GetHitNode(kRootNodeId, local_point.x, local_point.y); + FML_DCHECK(hit_node_id.has_value()); + fuchsia::accessibility::semantics::Hit hit; + // TODO(http://fxbug.dev/75910): check the usage of FlutterIdToFuchsiaId in + // the flutter accessibility bridge. + hit.set_node_id(hit_node_id.value_or(kRootNodeId)); + callback(std::move(hit)); +} + +std::optional AccessibilityBridge::GetHitNode(int32_t node_id, + float x, + float y) { + auto it = nodes_.find(node_id); + if (it == nodes_.end()) { + FML_LOG(ERROR) << "Attempted to hit test unknown node id: " << node_id; + return {}; + } + auto const& node = it->second; + if (node.data.flags & + static_cast(flutter::SemanticsFlags::kIsHidden) || // + !node.screen_rect.contains(x, y)) { + return {}; + } + for (int32_t child_id : node.data.childrenInHitTestOrder) { + auto candidate = GetHitNode(child_id, x, y); + if (candidate) { + return candidate; + } + } + + if (IsFocusable(node.data)) { + return node_id; + } + + return {}; +} + +bool AccessibilityBridge::IsFocusable( + const flutter::SemanticsNode& node) const { + if (node.HasFlag(flutter::SemanticsFlags::kScopesRoute)) { + return false; + } + + if (node.HasFlag(flutter::SemanticsFlags::kIsFocusable)) { + return true; + } + + // Always consider platform views focusable. + if (node.IsPlatformViewNode()) { + return true; + } + + // Always consider actionable nodes focusable. + if (node.actions != 0) { + return true; + } + + // Consider text nodes focusable. + return !node.label.empty() || !node.value.empty() || !node.hint.empty(); +} + +// |fuchsia::accessibility::semantics::SemanticListener| +void AccessibilityBridge::OnSemanticsModeChanged( + bool enabled, + OnSemanticsModeChangedCallback callback) { + set_semantics_enabled_callback_(enabled); +} + +#if !FLUTTER_RELEASE +void AccessibilityBridge::FillInspectTree(int32_t flutter_node_id, + int32_t current_level, + inspect::Node inspect_node, + inspect::Inspector* inspector) const { + const auto it = nodes_.find(flutter_node_id); + if (it == nodes_.end()) { + inspect_node.CreateString( + "missing_child", + "This node has a parent in the semantic tree but has no value", + inspector); + inspector->emplace(std::move(inspect_node)); + return; + } + const auto& semantic_node = it->second; + const auto& data = semantic_node.data; + + inspect_node.CreateInt("id", data.id, inspector); + + // Even with an empty label, we still want to create the property to + // explicetly show that it is empty. + inspect_node.CreateString("label", data.label, inspector); + if (!data.hint.empty()) { + inspect_node.CreateString("hint", data.hint, inspector); + } + if (!data.value.empty()) { + inspect_node.CreateString("value", data.value, inspector); + } + if (!data.increasedValue.empty()) { + inspect_node.CreateString("increased_value", data.increasedValue, + inspector); + } + if (!data.decreasedValue.empty()) { + inspect_node.CreateString("decreased_value", data.decreasedValue, + inspector); + } + + if (data.textDirection) { + inspect_node.CreateString( + "text_direction", data.textDirection == 1 ? "RTL" : "LTR", inspector); + } + + if (data.flags) { + inspect_node.CreateString("flags", NodeFlagsToString(data), inspector); + } + if (data.actions) { + inspect_node.CreateString("actions", NodeActionsToString(data), inspector); + } + + inspect_node.CreateString( + "location", NodeLocationToString(semantic_node.screen_rect), inspector); + if (!data.childrenInTraversalOrder.empty() || + !data.childrenInHitTestOrder.empty()) { + inspect_node.CreateString("children", NodeChildrenToString(data), + inspector); + } + + inspect_node.CreateInt("current_level", current_level, inspector); + + for (int32_t flutter_child_id : semantic_node.data.childrenInTraversalOrder) { + const auto inspect_name = "node_" + std::to_string(flutter_child_id); + FillInspectTree(flutter_child_id, current_level + 1, + inspect_node.CreateChild(inspect_name), inspector); + } + + inspector->emplace(std::move(inspect_node)); +} +#endif // !FLUTTER_RELEASE + +void AccessibilityBridge::Apply(FuchsiaAtomicUpdate* atomic_update) { + size_t begin = 0; + auto it = atomic_update->deletions.begin(); + + // Process up to kMaxDeletionsPerUpdate deletions at a time. + while (it != atomic_update->deletions.end()) { + std::vector to_delete; + size_t end = std::min(atomic_update->deletions.size() - begin, + kMaxDeletionsPerUpdate); + std::copy(std::make_move_iterator(it), std::make_move_iterator(it + end), + std::back_inserter(to_delete)); + tree_ptr_->DeleteSemanticNodes(std::move(to_delete)); + begin = end; + it += end; + } + + std::vector to_update; + size_t current_size = 0; + for (auto& node_and_size : atomic_update->updates) { + if (current_size + node_and_size.second > kMaxMessageSize) { + tree_ptr_->UpdateSemanticNodes(std::move(to_update)); + current_size = 0; + to_update.clear(); + } + current_size += node_and_size.second; + to_update.push_back(std::move(node_and_size.first)); + } + if (!to_update.empty()) { + tree_ptr_->UpdateSemanticNodes(std::move(to_update)); + } + + // Commit this update and subsequent ones; for flow control wait for a + // response between each commit. + tree_ptr_->CommitUpdates( + [this, atomic_updates = std::weak_ptr>( + atomic_updates_)]() { + auto atomic_updates_ptr = atomic_updates.lock(); + if (!atomic_updates_ptr) { + // The queue no longer exists, which means that is no longer + // necessary. + return; + } + // Removes the update that just went through. + atomic_updates_ptr->pop(); + if (!atomic_updates_ptr->empty()) { + Apply(&atomic_updates_ptr->front()); + } + }); + + atomic_update->deletions.clear(); + atomic_update->updates.clear(); +} + +void AccessibilityBridge::FuchsiaAtomicUpdate::AddNodeUpdate( + fuchsia::accessibility::semantics::Node node, + size_t size) { + if (size > kMaxMessageSize) { + // TODO(MI4-2531, FIDL-718): Remove this + // This is defensive. If, despite our best efforts, we ended up with a node + // that is larger than the max fidl size, we send no updates. + PrintNodeSizeError(node.node_id()); + return; + } + updates.emplace_back(std::move(node), size); +} + +void AccessibilityBridge::FuchsiaAtomicUpdate::AddNodeDeletion(uint32_t id) { + deletions.push_back(id); +} +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/accessibility_bridge.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/accessibility_bridge.h new file mode 100644 index 0000000000000000000000000000000000000000..b4bc5948d28f5908bad861d657b96f49416a9684 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/accessibility_bridge.h @@ -0,0 +1,275 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_ACCESSIBILITY_BRIDGE_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_ACCESSIBILITY_BRIDGE_H_ + +// Work around symbol conflicts with ICU. +#undef TRUE +#undef FALSE + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "flutter/fml/macros.h" +#include "flutter/lib/ui/semantics/semantics_node.h" + +namespace flutter_runner { + +// Accessibility bridge. +// +// This class intermediates accessibility-related calls between Fuchsia and +// Flutter. It serves to resolve the impedance mismatch between Flutter's +// platform-agnostic accessibility APIs and Fuchsia's APIs and behaviour. +// +// This bridge performs the following functions, among others: +// +// * Translates Flutter's semantics node updates to events Fuchsia requires +// (e.g. Flutter only sends updates for changed nodes, but Fuchsia requires +// the entire flattened subtree to be sent when a node changes. +class AccessibilityBridge + : public fuchsia::accessibility::semantics::SemanticListener { + public: + using SetSemanticsEnabledCallback = std::function; + using DispatchSemanticsActionCallback = + std::function; + + // TODO(MI4-2531, FIDL-718): Remove this. We shouldn't be worried about + // batching messages at this level. + // FIDL may encode a C++ struct as larger than the sizeof the C++ struct. + // This is to make sure we don't send updates that are too large. + static constexpr uint32_t kMaxMessageSize = ZX_CHANNEL_MAX_MSG_BYTES / 2; + + static_assert(fuchsia::accessibility::semantics::MAX_LABEL_SIZE < + kMaxMessageSize - 1); + + // Flutter uses signed 32 bit integers for node IDs, while Fuchsia uses + // unsigned 32 bit integers. A change in the size on either one would break + // casts and size tracking logic in the implementation. + static constexpr size_t kNodeIdSize = sizeof(flutter::SemanticsNode::id); + static_assert( + kNodeIdSize == + sizeof(fuchsia::accessibility::semantics::Node().node_id()), + "flutter::SemanticsNode::id and " + "fuchsia::accessibility::semantics::Node::node_id differ in size."); + + // Maximum number of node ids to be deleted through the Semantics API. + static constexpr size_t kMaxDeletionsPerUpdate = + kMaxMessageSize / kNodeIdSize; + + AccessibilityBridge( + SetSemanticsEnabledCallback set_semantics_enabled_callback, + DispatchSemanticsActionCallback dispatch_semantics_action_callback, + fuchsia::accessibility::semantics::SemanticsManagerHandle + semantics_manager, + fuchsia::ui::views::ViewRef view_ref, + inspect::Node inspect_node); + + // Returns true if accessible navigation is enabled. + bool GetSemanticsEnabled() const; + + // Enables Flutter accessibility navigation features. + // + // Once enabled, any semantics updates in the Flutter application will + // trigger |FuchsiaAccessibility::DispatchAccessibilityEvent| callbacks + // to send events back to the Fuchsia SemanticsManager. + void SetSemanticsEnabled(bool enabled); + + // Adds a semantics node update to the buffer of node updates to apply. + void AddSemanticsNodeUpdate(const flutter::SemanticsNodeUpdates update, + float view_pixel_ratio); + + // Requests a message announcement from the accessibility TTS system. + void RequestAnnounce(const std::string message); + + // Notifies the bridge of a 'hover move' touch exploration event. + zx_status_t OnHoverMove(double x, double y); + + // |fuchsia::accessibility::semantics::SemanticListener| + void HitTest( + fuchsia::math::PointF local_point, + fuchsia::accessibility::semantics::SemanticListener::HitTestCallback + callback) override; + + // |fuchsia::accessibility::semantics::SemanticListener| + void OnAccessibilityActionRequested( + uint32_t node_id, + fuchsia::accessibility::semantics::Action action, + fuchsia::accessibility::semantics::SemanticListener:: + OnAccessibilityActionRequestedCallback callback) override; + + private: + // Fuchsia's default root semantic node id. + static constexpr int32_t kRootNodeId = 0; + + // Represents an atomic semantic update to Fuchsia, which can contain deletes + // and updates of semantic nodes. + // + // An atomic update is a set of operations that take a semantic tree in a + // valid state to another valid state. Please check the semantics FIDL + // documentation for details. + struct FuchsiaAtomicUpdate { + FuchsiaAtomicUpdate() = default; + ~FuchsiaAtomicUpdate() = default; + FuchsiaAtomicUpdate(FuchsiaAtomicUpdate&&) = default; + + // Adds a node to be updated. |size| contains the + // size in bytes of the node to be updated. + void AddNodeUpdate(fuchsia::accessibility::semantics::Node node, + size_t size); + + // Adds a node to be deleted. + void AddNodeDeletion(uint32_t id); + + std::vector> + updates; + std::vector deletions; + }; + + // Holds a flutter semantic node and some extra info. + // In particular, it adds a screen_rect field to flutter::SemanticsNode. + struct SemanticsNode { + flutter::SemanticsNode data; + SkRect screen_rect; + }; + + fuchsia::accessibility::semantics::Node GetRootNodeUpdate(size_t& node_size); + + // Derives the BoundingBox of a Flutter semantics node from its + // rect and elevation. + fuchsia::ui::gfx::BoundingBox GetNodeLocation( + const flutter::SemanticsNode& node) const; + + // Gets mat4 transformation from a Flutter semantics node. + fuchsia::ui::gfx::mat4 GetNodeTransform( + const flutter::SemanticsNode& node) const; + + // Converts a Flutter semantics node's transformation to a mat4. + fuchsia::ui::gfx::mat4 ConvertSkiaTransformToMat4( + const SkM44 transform) const; + + // Derives the attributes for a Fuchsia semantics node from a Flutter + // semantics node. + fuchsia::accessibility::semantics::Attributes GetNodeAttributes( + const flutter::SemanticsNode& node, + size_t* added_size) const; + + // Derives the states for a Fuchsia semantics node from a Flutter semantics + // node. + fuchsia::accessibility::semantics::States GetNodeStates( + const flutter::SemanticsNode& node, + size_t* additional_size) const; + + // Derives the set of supported actions for a Fuchsia semantics node from + // a Flutter semantics node. + std::vector GetNodeActions( + const flutter::SemanticsNode& node, + size_t* additional_size) const; + + // Derives the role for a Fuchsia semantics node from a Flutter + // semantics node. + fuchsia::accessibility::semantics::Role GetNodeRole( + const flutter::SemanticsNode& node) const; + + // Gets the set of reachable descendants from the given node id. + std::unordered_set GetDescendants(int32_t node_id) const; + + // Removes internal references to any dangling nodes from previous + // updates, and adds the nodes to be deleted to the current |atomic_update|. + // + // The node ids to be deleted are only collected at this point, and will be + // committed in the next call to |Apply()|. + void PruneUnreachableNodes(FuchsiaAtomicUpdate* atomic_update); + + // Updates the on-screen positions of accessibility elements, + // starting from the root element with an identity matrix. + // + // This should be called from Update. + void UpdateScreenRects(); + + // Updates the on-screen positions of accessibility elements, starting + // from node_id and using the specified transform. + // + // Update calls this via UpdateScreenRects(). + void UpdateScreenRects(int32_t node_id, + SkM44 parent_transform, + std::unordered_set* visited_nodes); + + // Traverses the semantics tree to find the node_id hit by the given x,y + // point. + // + // Assumes that SemanticsNode::screen_rect is up to date. + std::optional GetHitNode(int32_t node_id, float x, float y); + + // Returns whether the node is considered focusable. + bool IsFocusable(const flutter::SemanticsNode& node) const; + + // Converts a fuchsia::accessibility::semantics::Action to a + // flutter::SemanticsAction. + // + // The node_id parameter is used for printing warnings about unsupported + // action types. + std::optional GetFlutterSemanticsAction( + fuchsia::accessibility::semantics::Action fuchsia_action, + uint32_t node_id); + + // Applies the updates and deletions in |atomic_update|, sending them via + // |tree_ptr|. + void Apply(FuchsiaAtomicUpdate* atomic_update); + + // |fuchsia::accessibility::semantics::SemanticListener| + void OnSemanticsModeChanged(bool enabled, + OnSemanticsModeChangedCallback callback) override; + +#if !FLUTTER_RELEASE + // Fills the inspect tree with debug information about the semantic tree. + void FillInspectTree(int32_t flutter_node_id, + int32_t current_level, + inspect::Node inspect_node, + inspect::Inspector* inspector) const; +#endif // !FLUTTER_RELEASE + + SetSemanticsEnabledCallback set_semantics_enabled_callback_; + DispatchSemanticsActionCallback dispatch_semantics_action_callback_; + flutter::SemanticsNode root_flutter_semantics_node_; + float last_seen_view_pixel_ratio_ = 1.f; + + fidl::Binding binding_; + fuchsia::accessibility::semantics::SemanticsManagerPtr + fuchsia_semantics_manager_; + fuchsia::accessibility::semantics::SemanticTreePtr tree_ptr_; + + // This is the cache of all nodes we've sent to Fuchsia's SemanticsManager. + // Assists with pruning unreachable nodes and hit testing. + std::unordered_map nodes_; + bool semantics_enabled_; + + // Queue of atomic updates to be sent to Fuchsia. + std::shared_ptr> atomic_updates_; + + // Node to publish inspect data. + inspect::Node inspect_node_; + +#if !FLUTTER_RELEASE + // Inspect node to store a dump of the semantic tree. Note that this only gets + // computed if requested, so it does not use memory to store the dump unless + // an explicit request is made. + inspect::LazyNode inspect_node_tree_dump_; +#endif // !FLUTTER_RELEASE + + FML_DISALLOW_COPY_AND_ASSIGN(AccessibilityBridge); +}; +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_ACCESSIBILITY_BRIDGE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/accessibility_bridge_unittest.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/accessibility_bridge_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..fc4d0809e7633f473f0f9a91ff2bc32561afba7f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/accessibility_bridge_unittest.cc @@ -0,0 +1,1185 @@ +// 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 "accessibility_bridge.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "flutter/lib/ui/semantics/semantics_node.h" +#include "gtest/gtest.h" + +#include "flutter_runner_fakes.h" + +namespace flutter_runner_test { + +namespace { + +void ExpectNodeHasRole( + const fuchsia::accessibility::semantics::Node& node, + const std::unordered_map + roles_by_node_id) { + ASSERT_TRUE(node.has_node_id()); + ASSERT_NE(roles_by_node_id.find(node.node_id()), roles_by_node_id.end()); + EXPECT_TRUE(node.has_role()); + EXPECT_EQ(node.role(), roles_by_node_id.at(node.node_id())); +} + +} // namespace + +class AccessibilityBridgeTestDelegate { + public: + void SetSemanticsEnabled(bool enabled) { enabled_ = enabled; } + void DispatchSemanticsAction(int32_t node_id, + flutter::SemanticsAction action) { + actions.push_back(std::make_pair(node_id, action)); + } + + bool enabled() { return enabled_; } + std::vector> actions; + + private: + bool enabled_; +}; + +class AccessibilityBridgeTest : public testing::Test { + public: + AccessibilityBridgeTest() + : loop_(&kAsyncLoopConfigAttachToCurrentThread), + services_provider_(loop_.dispatcher()), + executor_(loop_.dispatcher()) { + services_provider_.AddService( + semantics_manager_.GetHandler(loop_.dispatcher()), + SemanticsManager::Name_); + } + + void RunLoopUntilIdle() { + loop_.RunUntilIdle(); + loop_.ResetQuit(); + } + + void RunPromiseToCompletion(fpromise::promise<> promise) { + bool done = false; + executor_.schedule_task( + std::move(promise).and_then([&done]() { done = true; })); + while (loop_.GetState() == ASYNC_LOOP_RUNNABLE) { + if (done) { + loop_.ResetQuit(); + return; + } + + loop_.Run(zx::deadline_after(zx::duration::infinite()), true); + } + loop_.ResetQuit(); + } + + protected: + void SetUp() override { + // Connect to SemanticsManager service. + fuchsia::accessibility::semantics::SemanticsManagerHandle semantics_manager; + zx_status_t semantics_status = + services_provider_.service_directory() + ->Connect( + semantics_manager.NewRequest()); + if (semantics_status != ZX_OK) { + FML_LOG(WARNING) + << "fuchsia::accessibility::semantics::SemanticsManager connection " + "failed: " + << zx_status_get_string(semantics_status); + } + + accessibility_delegate_.actions.clear(); + inspector_ = std::make_unique(); + flutter_runner::AccessibilityBridge::SetSemanticsEnabledCallback + set_semantics_enabled_callback = [this](bool enabled) { + accessibility_delegate_.SetSemanticsEnabled(enabled); + }; + flutter_runner::AccessibilityBridge::DispatchSemanticsActionCallback + dispatch_semantics_action_callback = + [this](int32_t node_id, flutter::SemanticsAction action) { + accessibility_delegate_.DispatchSemanticsAction(node_id, action); + }; + + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ASSERT_EQ(status, ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + accessibility_bridge_ = + std::make_unique( + std::move(set_semantics_enabled_callback), + std::move(dispatch_semantics_action_callback), + std::move(semantics_manager), std::move(view_ref), + inspector_->GetRoot().CreateChild("test_node")); + + RunLoopUntilIdle(); + } + + void TearDown() override { semantics_manager_.ResetTree(); } + + MockSemanticsManager semantics_manager_; + AccessibilityBridgeTestDelegate accessibility_delegate_; + std::unique_ptr accessibility_bridge_; + // Required to verify inspect metrics. + std::unique_ptr inspector_; + + private: + async::Loop loop_; + sys::testing::ServiceDirectoryProvider services_provider_; + // Required to retrieve inspect metrics. + async::Executor executor_; +}; + +TEST_F(AccessibilityBridgeTest, RegistersViewRef) { + EXPECT_TRUE(semantics_manager_.RegisterViewCalled()); +} + +TEST_F(AccessibilityBridgeTest, EnableDisable) { + EXPECT_FALSE(accessibility_delegate_.enabled()); + std::unique_ptr listener( + accessibility_bridge_.release()); + listener->OnSemanticsModeChanged(true, nullptr); + EXPECT_TRUE(accessibility_delegate_.enabled()); +} + +TEST_F(AccessibilityBridgeTest, RequestAnnounce) { + accessibility_bridge_->RequestAnnounce("message"); + RunLoopUntilIdle(); + + auto& last_events = semantics_manager_.GetLastEvents(); + ASSERT_EQ(last_events.size(), 1u); + ASSERT_TRUE(last_events[0].is_announce()); + EXPECT_EQ(last_events[0].announce().message(), "message"); +} + +TEST_F(AccessibilityBridgeTest, PopulatesIsKeyboardKeyAttribute) { + flutter::SemanticsNode node0; + node0.id = 0; + node0.flags = static_cast(flutter::SemanticsFlags::kIsKeyboardKey); + + accessibility_bridge_->AddSemanticsNodeUpdate({{0, node0}}, 1.f); + RunLoopUntilIdle(); + + EXPECT_EQ(1U, semantics_manager_.LastUpdatedNodes().size()); + const auto& fuchsia_node = semantics_manager_.LastUpdatedNodes().at(0u); + EXPECT_EQ(fuchsia_node.node_id(), static_cast(node0.id)); + EXPECT_TRUE(fuchsia_node.has_attributes()); + EXPECT_TRUE(fuchsia_node.attributes().is_keyboard_key()); +} + +TEST_F(AccessibilityBridgeTest, UpdatesNodeRoles) { + flutter::SemanticsNodeUpdates updates; + + flutter::SemanticsNode node0; + node0.id = 0; + node0.flags |= static_cast(flutter::SemanticsFlags::kIsButton); + node0.childrenInTraversalOrder = {1, 2, 3, 4, 5, 6, 7, 8}; + node0.childrenInHitTestOrder = {1, 2, 3, 4, 5, 6, 7, 8}; + updates.emplace(0, node0); + + flutter::SemanticsNode node1; + node1.id = 1; + node1.flags |= static_cast(flutter::SemanticsFlags::kIsHeader); + node1.childrenInTraversalOrder = {}; + node1.childrenInHitTestOrder = {}; + updates.emplace(1, node1); + + flutter::SemanticsNode node2; + node2.id = 2; + node2.flags |= static_cast(flutter::SemanticsFlags::kIsImage); + node2.childrenInTraversalOrder = {}; + node2.childrenInHitTestOrder = {}; + updates.emplace(2, node2); + + flutter::SemanticsNode node3; + node3.id = 3; + node3.flags |= static_cast(flutter::SemanticsFlags::kIsTextField); + node3.childrenInTraversalOrder = {}; + node3.childrenInHitTestOrder = {}; + updates.emplace(3, node3); + + flutter::SemanticsNode node4; + node4.childrenInTraversalOrder = {}; + node4.childrenInHitTestOrder = {}; + node4.id = 4; + node4.flags |= static_cast(flutter::SemanticsFlags::kIsSlider); + updates.emplace(4, node4); + + flutter::SemanticsNode node5; + node5.childrenInTraversalOrder = {}; + node5.childrenInHitTestOrder = {}; + node5.id = 5; + node5.flags |= static_cast(flutter::SemanticsFlags::kIsLink); + updates.emplace(5, node5); + + flutter::SemanticsNode node6; + node6.childrenInTraversalOrder = {}; + node6.childrenInHitTestOrder = {}; + node6.id = 6; + node6.flags |= static_cast(flutter::SemanticsFlags::kHasCheckedState); + node6.flags |= + static_cast(flutter::SemanticsFlags::kIsInMutuallyExclusiveGroup); + updates.emplace(6, node6); + + flutter::SemanticsNode node7; + node7.childrenInTraversalOrder = {}; + node7.childrenInHitTestOrder = {}; + node7.id = 7; + node7.flags |= static_cast(flutter::SemanticsFlags::kHasCheckedState); + updates.emplace(7, node7); + + flutter::SemanticsNode node8; + node8.childrenInTraversalOrder = {}; + node8.childrenInHitTestOrder = {}; + node8.id = 8; + node8.flags |= static_cast(flutter::SemanticsFlags::kHasToggledState); + updates.emplace(7, node8); + + accessibility_bridge_->AddSemanticsNodeUpdate(std::move(updates), 1.f); + RunLoopUntilIdle(); + + std::unordered_map + roles_by_node_id = { + {0u, fuchsia::accessibility::semantics::Role::BUTTON}, + {1u, fuchsia::accessibility::semantics::Role::HEADER}, + {2u, fuchsia::accessibility::semantics::Role::IMAGE}, + {3u, fuchsia::accessibility::semantics::Role::TEXT_FIELD}, + {4u, fuchsia::accessibility::semantics::Role::SLIDER}, + {5u, fuchsia::accessibility::semantics::Role::LINK}, + {6u, fuchsia::accessibility::semantics::Role::RADIO_BUTTON}, + {7u, fuchsia::accessibility::semantics::Role::CHECK_BOX}, + {8u, fuchsia::accessibility::semantics::Role::TOGGLE_SWITCH}}; + + EXPECT_EQ(0, semantics_manager_.DeleteCount()); + EXPECT_EQ(1, semantics_manager_.UpdateCount()); + EXPECT_EQ(1, semantics_manager_.CommitCount()); + EXPECT_EQ(8u, semantics_manager_.LastUpdatedNodes().size()); + for (const auto& node : semantics_manager_.LastUpdatedNodes()) { + ExpectNodeHasRole(node, roles_by_node_id); + } + + EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); + EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); +} + +TEST_F(AccessibilityBridgeTest, DeletesChildrenTransitively) { + // Test that when a node is deleted, so are its transitive children. + flutter::SemanticsNode node2; + node2.id = 2; + + flutter::SemanticsNode node1; + node1.id = 1; + node1.childrenInTraversalOrder = {2}; + node1.childrenInHitTestOrder = {2}; + + flutter::SemanticsNode node0; + node0.id = 0; + node0.childrenInTraversalOrder = {1}; + node0.childrenInHitTestOrder = {1}; + + accessibility_bridge_->AddSemanticsNodeUpdate( + { + {0, node0}, + {1, node1}, + {2, node2}, + }, + 1.f); + RunLoopUntilIdle(); + + EXPECT_EQ(0, semantics_manager_.DeleteCount()); + EXPECT_EQ(1, semantics_manager_.UpdateCount()); + EXPECT_EQ(1, semantics_manager_.CommitCount()); + EXPECT_EQ(3U, semantics_manager_.LastUpdatedNodes().size()); + EXPECT_EQ(0U, semantics_manager_.LastDeletedNodeIds().size()); + EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); + EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); + + // Remove the children + node0.childrenInTraversalOrder.clear(); + node0.childrenInHitTestOrder.clear(); + accessibility_bridge_->AddSemanticsNodeUpdate( + { + {0, node0}, + }, + 1.f); + RunLoopUntilIdle(); + + EXPECT_EQ(1, semantics_manager_.DeleteCount()); + EXPECT_EQ(2, semantics_manager_.UpdateCount()); + EXPECT_EQ(2, semantics_manager_.CommitCount()); + EXPECT_EQ(1U, semantics_manager_.LastUpdatedNodes().size()); + ASSERT_EQ(std::vector({1, 2}), + semantics_manager_.LastDeletedNodeIds()); + EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); + EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); +} + +TEST_F(AccessibilityBridgeTest, PopulatesRoleButton) { + flutter::SemanticsNode node0; + node0.id = 0; + node0.flags = static_cast(flutter::SemanticsFlags::kIsButton); + + accessibility_bridge_->AddSemanticsNodeUpdate({{0, node0}}, 1.f); + RunLoopUntilIdle(); + + EXPECT_EQ(1U, semantics_manager_.LastUpdatedNodes().size()); + const auto& fuchsia_node = semantics_manager_.LastUpdatedNodes().at(0u); + EXPECT_EQ(fuchsia_node.node_id(), static_cast(node0.id)); + EXPECT_TRUE(fuchsia_node.has_role()); + EXPECT_EQ(fuchsia_node.role(), + fuchsia::accessibility::semantics::Role::BUTTON); +} + +TEST_F(AccessibilityBridgeTest, PopulatesRoleImage) { + flutter::SemanticsNode node0; + node0.id = 0; + node0.flags = static_cast(flutter::SemanticsFlags::kIsImage); + + accessibility_bridge_->AddSemanticsNodeUpdate({{0, node0}}, 1.f); + RunLoopUntilIdle(); + + EXPECT_EQ(1U, semantics_manager_.LastUpdatedNodes().size()); + const auto& fuchsia_node = semantics_manager_.LastUpdatedNodes().at(0u); + EXPECT_EQ(fuchsia_node.node_id(), static_cast(node0.id)); + EXPECT_TRUE(fuchsia_node.has_role()); + EXPECT_EQ(fuchsia_node.role(), + fuchsia::accessibility::semantics::Role::IMAGE); +} + +TEST_F(AccessibilityBridgeTest, PopulatesRoleSlider) { + flutter::SemanticsNode node0; + node0.id = 0; + node0.actions |= static_cast(flutter::SemanticsAction::kIncrease); + + accessibility_bridge_->AddSemanticsNodeUpdate({{0, node0}}, 1.f); + RunLoopUntilIdle(); + + EXPECT_EQ(1U, semantics_manager_.LastUpdatedNodes().size()); + const auto& fuchsia_node = semantics_manager_.LastUpdatedNodes().at(0u); + EXPECT_EQ(fuchsia_node.node_id(), static_cast(node0.id)); + EXPECT_TRUE(fuchsia_node.has_role()); + EXPECT_EQ(fuchsia_node.role(), + fuchsia::accessibility::semantics::Role::SLIDER); +} + +TEST_F(AccessibilityBridgeTest, PopulatesRoleHeader) { + flutter::SemanticsNode node0; + node0.id = 0; + node0.flags = static_cast(flutter::SemanticsFlags::kIsHeader); + + accessibility_bridge_->AddSemanticsNodeUpdate({{0, node0}}, 1.f); + RunLoopUntilIdle(); + + EXPECT_EQ(1U, semantics_manager_.LastUpdatedNodes().size()); + const auto& fuchsia_node = semantics_manager_.LastUpdatedNodes().at(0u); + EXPECT_EQ(fuchsia_node.node_id(), static_cast(node0.id)); + EXPECT_TRUE(fuchsia_node.has_role()); + EXPECT_EQ(fuchsia_node.role(), + fuchsia::accessibility::semantics::Role::HEADER); +} + +TEST_F(AccessibilityBridgeTest, PopulatesCheckedState) { + flutter::SemanticsNode node0; + node0.id = 0; + // HasCheckedState = true + // IsChecked = true + // IsSelected = false + node0.flags |= static_cast(flutter::SemanticsFlags::kHasCheckedState); + node0.flags |= static_cast(flutter::SemanticsFlags::kIsChecked); + node0.value = "value"; + + accessibility_bridge_->AddSemanticsNodeUpdate({{0, node0}}, 1.f); + RunLoopUntilIdle(); + + EXPECT_EQ(0, semantics_manager_.DeleteCount()); + EXPECT_EQ(1, semantics_manager_.UpdateCount()); + EXPECT_EQ(1, semantics_manager_.CommitCount()); + EXPECT_EQ(1U, semantics_manager_.LastUpdatedNodes().size()); + const auto& fuchsia_node = semantics_manager_.LastUpdatedNodes().at(0u); + EXPECT_EQ(fuchsia_node.node_id(), static_cast(node0.id)); + EXPECT_TRUE(fuchsia_node.has_states()); + const auto& states = fuchsia_node.states(); + EXPECT_TRUE(states.has_checked_state()); + EXPECT_EQ(states.checked_state(), + fuchsia::accessibility::semantics::CheckedState::CHECKED); + EXPECT_TRUE(states.has_selected()); + EXPECT_FALSE(states.selected()); + EXPECT_TRUE(states.has_value()); + EXPECT_EQ(states.value(), node0.value); + + EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); + EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); +} + +TEST_F(AccessibilityBridgeTest, PopulatesSelectedState) { + flutter::SemanticsNode node0; + node0.id = 0; + // HasCheckedState = false + // IsChecked = false + // IsSelected = true + node0.flags = static_cast(flutter::SemanticsFlags::kIsSelected); + + accessibility_bridge_->AddSemanticsNodeUpdate({{0, node0}}, 1.f); + RunLoopUntilIdle(); + + EXPECT_EQ(0, semantics_manager_.DeleteCount()); + EXPECT_EQ(1, semantics_manager_.UpdateCount()); + EXPECT_EQ(1, semantics_manager_.CommitCount()); + EXPECT_EQ(1U, semantics_manager_.LastUpdatedNodes().size()); + const auto& fuchsia_node = semantics_manager_.LastUpdatedNodes().at(0u); + EXPECT_EQ(fuchsia_node.node_id(), static_cast(node0.id)); + EXPECT_TRUE(fuchsia_node.has_states()); + const auto& states = fuchsia_node.states(); + EXPECT_TRUE(states.has_checked_state()); + EXPECT_EQ(states.checked_state(), + fuchsia::accessibility::semantics::CheckedState::NONE); + EXPECT_TRUE(states.has_selected()); + EXPECT_TRUE(states.selected()); + + EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); + EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); +} + +TEST_F(AccessibilityBridgeTest, PopulatesToggledState) { + flutter::SemanticsNode node0; + node0.id = 0; + node0.flags |= static_cast(flutter::SemanticsFlags::kHasToggledState); + node0.flags |= static_cast(flutter::SemanticsFlags::kIsToggled); + + accessibility_bridge_->AddSemanticsNodeUpdate({{0, node0}}, 1.f); + RunLoopUntilIdle(); + + EXPECT_EQ(0, semantics_manager_.DeleteCount()); + EXPECT_EQ(1, semantics_manager_.UpdateCount()); + EXPECT_EQ(1, semantics_manager_.CommitCount()); + EXPECT_EQ(1U, semantics_manager_.LastUpdatedNodes().size()); + const auto& fuchsia_node = semantics_manager_.LastUpdatedNodes().at(0u); + EXPECT_EQ(fuchsia_node.node_id(), static_cast(node0.id)); + EXPECT_TRUE(fuchsia_node.has_states()); + const auto& states = fuchsia_node.states(); + EXPECT_TRUE(states.has_toggled_state()); + EXPECT_EQ(states.toggled_state(), + fuchsia::accessibility::semantics::ToggledState::ON); + + EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); + EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); +} + +TEST_F(AccessibilityBridgeTest, PopulatesEnabledState) { + flutter::SemanticsNode node0; + node0.id = 0; + // HasEnabledState = true + // IsEnabled = true + node0.flags |= static_cast(flutter::SemanticsFlags::kHasEnabledState); + node0.flags |= static_cast(flutter::SemanticsFlags::kIsEnabled); + node0.value = "value"; + + accessibility_bridge_->AddSemanticsNodeUpdate({{0, node0}}, 1.f); + RunLoopUntilIdle(); + + EXPECT_EQ(0, semantics_manager_.DeleteCount()); + EXPECT_EQ(1, semantics_manager_.UpdateCount()); + EXPECT_EQ(1, semantics_manager_.CommitCount()); + EXPECT_EQ(1U, semantics_manager_.LastUpdatedNodes().size()); + const auto& fuchsia_node = semantics_manager_.LastUpdatedNodes().at(0u); + EXPECT_EQ(fuchsia_node.node_id(), static_cast(node0.id)); + EXPECT_TRUE(fuchsia_node.has_states()); + const auto& states = fuchsia_node.states(); + EXPECT_TRUE(states.has_enabled_state()); + EXPECT_EQ(states.enabled_state(), + fuchsia::accessibility::semantics::EnabledState::ENABLED); + EXPECT_TRUE(states.has_value()); + EXPECT_EQ(states.value(), node0.value); + + EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); + EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); +} + +TEST_F(AccessibilityBridgeTest, ApplyViewPixelRatioToRoot) { + flutter::SemanticsNode node0; + node0.id = 0; + node0.flags = static_cast(flutter::SemanticsFlags::kIsSelected); + + accessibility_bridge_->AddSemanticsNodeUpdate({{0, node0}}, 1.25f); + RunLoopUntilIdle(); + const auto& fuchsia_node = semantics_manager_.LastUpdatedNodes().at(0u); + EXPECT_EQ(fuchsia_node.node_id(), static_cast(node0.id)); + EXPECT_EQ(fuchsia_node.transform().matrix[0], 0.8f); + EXPECT_EQ(fuchsia_node.transform().matrix[5], 0.8f); + EXPECT_EQ(fuchsia_node.transform().matrix[10], 1.f); +} + +TEST_F(AccessibilityBridgeTest, DoesNotPopulatesHiddenState) { + // Flutter's notion of a hidden node is different from Fuchsia's hidden node. + // This test make sures that this state does not get sent. + flutter::SemanticsNode node0; + node0.id = 0; + // HasCheckedState = false + // IsChecked = false + // IsSelected = false + // IsHidden = true + node0.flags = static_cast(flutter::SemanticsFlags::kIsHidden); + + accessibility_bridge_->AddSemanticsNodeUpdate({{0, node0}}, 1.f); + RunLoopUntilIdle(); + + EXPECT_EQ(0, semantics_manager_.DeleteCount()); + EXPECT_EQ(1, semantics_manager_.UpdateCount()); + EXPECT_EQ(1, semantics_manager_.CommitCount()); + EXPECT_EQ(1u, semantics_manager_.LastUpdatedNodes().size()); + const auto& fuchsia_node = semantics_manager_.LastUpdatedNodes().at(0u); + EXPECT_EQ(fuchsia_node.node_id(), static_cast(node0.id)); + EXPECT_TRUE(fuchsia_node.has_states()); + const auto& states = fuchsia_node.states(); + EXPECT_TRUE(states.has_checked_state()); + EXPECT_EQ(states.checked_state(), + fuchsia::accessibility::semantics::CheckedState::NONE); + EXPECT_TRUE(states.has_selected()); + EXPECT_FALSE(states.selected()); + EXPECT_FALSE(states.has_hidden()); + + EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); + EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); +} + +TEST_F(AccessibilityBridgeTest, PopulatesActions) { + flutter::SemanticsNode node0; + node0.id = 0; + node0.actions |= static_cast(flutter::SemanticsAction::kTap); + node0.actions |= static_cast(flutter::SemanticsAction::kLongPress); + node0.actions |= static_cast(flutter::SemanticsAction::kShowOnScreen); + node0.actions |= static_cast(flutter::SemanticsAction::kIncrease); + node0.actions |= static_cast(flutter::SemanticsAction::kDecrease); + + accessibility_bridge_->AddSemanticsNodeUpdate({{0, node0}}, 1.f); + RunLoopUntilIdle(); + + EXPECT_EQ(0, semantics_manager_.DeleteCount()); + EXPECT_EQ(1, semantics_manager_.UpdateCount()); + EXPECT_EQ(1, semantics_manager_.CommitCount()); + EXPECT_EQ(1u, semantics_manager_.LastUpdatedNodes().size()); + const auto& fuchsia_node = semantics_manager_.LastUpdatedNodes().at(0u); + EXPECT_EQ(fuchsia_node.actions().size(), 5u); + EXPECT_EQ(fuchsia_node.actions().at(0u), + fuchsia::accessibility::semantics::Action::DEFAULT); + EXPECT_EQ(fuchsia_node.actions().at(1u), + fuchsia::accessibility::semantics::Action::SECONDARY); + EXPECT_EQ(fuchsia_node.actions().at(2u), + fuchsia::accessibility::semantics::Action::SHOW_ON_SCREEN); + EXPECT_EQ(fuchsia_node.actions().at(3u), + fuchsia::accessibility::semantics::Action::INCREMENT); + EXPECT_EQ(fuchsia_node.actions().at(4u), + fuchsia::accessibility::semantics::Action::DECREMENT); +} + +TEST_F(AccessibilityBridgeTest, TruncatesLargeLabel) { + // Test that labels which are too long are truncated. + flutter::SemanticsNode node0; + node0.id = 0; + + flutter::SemanticsNode node1; + node1.id = 1; + + flutter::SemanticsNode bad_node; + bad_node.id = 2; + bad_node.label = + std::string(fuchsia::accessibility::semantics::MAX_LABEL_SIZE + 1, '2'); + + node0.childrenInTraversalOrder = {1, 2}; + node0.childrenInHitTestOrder = {1, 2}; + + accessibility_bridge_->AddSemanticsNodeUpdate( + { + {0, node0}, + {1, node1}, + {2, bad_node}, + }, + 1.f); + RunLoopUntilIdle(); + + // Nothing to delete, but we should have broken + EXPECT_EQ(0, semantics_manager_.DeleteCount()); + EXPECT_EQ(1, semantics_manager_.UpdateCount()); + EXPECT_EQ(1, semantics_manager_.CommitCount()); + EXPECT_EQ(3U, semantics_manager_.LastUpdatedNodes().size()); + auto trimmed_node = + std::find_if(semantics_manager_.LastUpdatedNodes().begin(), + semantics_manager_.LastUpdatedNodes().end(), + [id = static_cast(bad_node.id)]( + fuchsia::accessibility::semantics::Node const& node) { + return node.node_id() == id; + }); + ASSERT_NE(trimmed_node, semantics_manager_.LastUpdatedNodes().end()); + ASSERT_TRUE(trimmed_node->has_attributes()); + EXPECT_EQ( + trimmed_node->attributes().label(), + std::string(fuchsia::accessibility::semantics::MAX_LABEL_SIZE, '2')); + EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); + EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); +} + +TEST_F(AccessibilityBridgeTest, TruncatesLargeToolTip) { + // Test that tooltips which are too long are truncated. + flutter::SemanticsNode node0; + node0.id = 0; + + flutter::SemanticsNode node1; + node1.id = 1; + + flutter::SemanticsNode bad_node; + bad_node.id = 2; + bad_node.tooltip = + std::string(fuchsia::accessibility::semantics::MAX_LABEL_SIZE + 1, '2'); + + node0.childrenInTraversalOrder = {1, 2}; + node0.childrenInHitTestOrder = {1, 2}; + + accessibility_bridge_->AddSemanticsNodeUpdate( + { + {0, node0}, + {1, node1}, + {2, bad_node}, + }, + 1.f); + RunLoopUntilIdle(); + + // Nothing to delete, but we should have broken + EXPECT_EQ(0, semantics_manager_.DeleteCount()); + EXPECT_EQ(1, semantics_manager_.UpdateCount()); + EXPECT_EQ(1, semantics_manager_.CommitCount()); + EXPECT_EQ(3U, semantics_manager_.LastUpdatedNodes().size()); + auto trimmed_node = + std::find_if(semantics_manager_.LastUpdatedNodes().begin(), + semantics_manager_.LastUpdatedNodes().end(), + [id = static_cast(bad_node.id)]( + fuchsia::accessibility::semantics::Node const& node) { + return node.node_id() == id; + }); + ASSERT_NE(trimmed_node, semantics_manager_.LastUpdatedNodes().end()); + ASSERT_TRUE(trimmed_node->has_attributes()); + EXPECT_EQ( + trimmed_node->attributes().secondary_label(), + std::string(fuchsia::accessibility::semantics::MAX_LABEL_SIZE, '2')); + EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); + EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); +} + +TEST_F(AccessibilityBridgeTest, TruncatesLargeValue) { + // Test that values which are too long are truncated. + flutter::SemanticsNode node0; + node0.id = 0; + + flutter::SemanticsNode node1; + node1.id = 1; + + flutter::SemanticsNode bad_node; + bad_node.id = 2; + bad_node.value = + std::string(fuchsia::accessibility::semantics::MAX_VALUE_SIZE + 1, '2'); + + node0.childrenInTraversalOrder = {1, 2}; + node0.childrenInHitTestOrder = {1, 2}; + + accessibility_bridge_->AddSemanticsNodeUpdate( + { + {0, node0}, + {1, node1}, + {2, bad_node}, + }, + 1.f); + RunLoopUntilIdle(); + + EXPECT_EQ(0, semantics_manager_.DeleteCount()); + EXPECT_EQ(1, semantics_manager_.UpdateCount()); + EXPECT_EQ(1, semantics_manager_.CommitCount()); + EXPECT_EQ(3U, semantics_manager_.LastUpdatedNodes().size()); + auto trimmed_node = + std::find_if(semantics_manager_.LastUpdatedNodes().begin(), + semantics_manager_.LastUpdatedNodes().end(), + [id = static_cast(bad_node.id)]( + fuchsia::accessibility::semantics::Node const& node) { + return node.node_id() == id; + }); + ASSERT_NE(trimmed_node, semantics_manager_.LastUpdatedNodes().end()); + ASSERT_TRUE(trimmed_node->has_states()); + EXPECT_EQ( + trimmed_node->states().value(), + std::string(fuchsia::accessibility::semantics::MAX_VALUE_SIZE, '2')); + EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); + EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); +} + +TEST_F(AccessibilityBridgeTest, SplitsLargeUpdates) { + // Test that labels which are too long are truncated. + flutter::SemanticsNode node0; + node0.id = 0; + + flutter::SemanticsNode node1; + node1.id = 1; + node1.label = + std::string(fuchsia::accessibility::semantics::MAX_LABEL_SIZE, '1'); + + flutter::SemanticsNode node2; + node2.id = 2; + node2.label = "2"; + + flutter::SemanticsNode node3; + node3.id = 3; + node3.label = "3"; + + flutter::SemanticsNode node4; + node4.id = 4; + node4.value = + std::string(fuchsia::accessibility::semantics::MAX_VALUE_SIZE, '4'); + + node0.childrenInTraversalOrder = {1, 2}; + node0.childrenInHitTestOrder = {1, 2}; + node1.childrenInTraversalOrder = {3, 4}; + node1.childrenInHitTestOrder = {3, 4}; + + accessibility_bridge_->AddSemanticsNodeUpdate( + { + {0, node0}, + {1, node1}, + {2, node2}, + {3, node3}, + {4, node4}, + }, + 1.f); + RunLoopUntilIdle(); + + // Nothing to delete, but we should have broken into groups (4, 3, 2), (1, 0) + EXPECT_EQ(0, semantics_manager_.DeleteCount()); + EXPECT_EQ(2, semantics_manager_.UpdateCount()); + EXPECT_EQ(1, semantics_manager_.CommitCount()); + EXPECT_EQ(2U, semantics_manager_.LastUpdatedNodes().size()); + EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); + EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); +} + +TEST_F(AccessibilityBridgeTest, HandlesCycles) { + // Test that cycles don't cause fatal error. + flutter::SemanticsNode node0; + node0.id = 0; + node0.childrenInTraversalOrder.push_back(0); + node0.childrenInHitTestOrder.push_back(0); + accessibility_bridge_->AddSemanticsNodeUpdate( + { + {0, node0}, + }, + 1.f); + RunLoopUntilIdle(); + + EXPECT_EQ(0, semantics_manager_.DeleteCount()); + EXPECT_EQ(1, semantics_manager_.UpdateCount()); + EXPECT_EQ(1, semantics_manager_.CommitCount()); + EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); + EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); + + node0.childrenInTraversalOrder = {0, 1}; + node0.childrenInHitTestOrder = {0, 1}; + flutter::SemanticsNode node1; + node1.id = 1; + node1.childrenInTraversalOrder = {0}; + node1.childrenInHitTestOrder = {0}; + accessibility_bridge_->AddSemanticsNodeUpdate( + { + {0, node0}, + {1, node1}, + }, + 1.f); + RunLoopUntilIdle(); + + EXPECT_EQ(0, semantics_manager_.DeleteCount()); + EXPECT_EQ(2, semantics_manager_.UpdateCount()); + EXPECT_EQ(2, semantics_manager_.CommitCount()); + EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); + EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); +} + +TEST_F(AccessibilityBridgeTest, BatchesLargeMessages) { + // Tests that messages get batched appropriately. + flutter::SemanticsNode node0; + node0.id = 0; + + flutter::SemanticsNodeUpdates update; + + const int32_t child_nodes = 100; + const int32_t leaf_nodes = 100; + for (int32_t i = 1; i < child_nodes + 1; i++) { + flutter::SemanticsNode node; + node.id = i; + node0.childrenInTraversalOrder.push_back(i); + node0.childrenInHitTestOrder.push_back(i); + for (int32_t j = 0; j < leaf_nodes; j++) { + flutter::SemanticsNode leaf_node; + int id = (i * child_nodes) + ((j + 1) * leaf_nodes); + leaf_node.id = id; + leaf_node.label = "A relatively simple label"; + node.childrenInTraversalOrder.push_back(id); + node.childrenInHitTestOrder.push_back(id); + update.insert(std::make_pair(id, std::move(leaf_node))); + } + update.insert(std::make_pair(i, std::move(node))); + } + + update.insert(std::make_pair(0, std::move(node0))); + + // Make the semantics manager hold answering to this commit to test the flow + // control. This means the second update will not be pushed until the first + // one has processed. + semantics_manager_.SetShouldHoldCommitResponse(true); + accessibility_bridge_->AddSemanticsNodeUpdate(update, 1.f); + RunLoopUntilIdle(); + + EXPECT_EQ(0, semantics_manager_.DeleteCount()); + + EXPECT_TRUE(6 <= semantics_manager_.UpdateCount() && + semantics_manager_.UpdateCount() <= 12); + EXPECT_EQ(1, semantics_manager_.CommitCount()); + EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); + EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); + + int next_update_count = semantics_manager_.UpdateCount() + 1; + // Remove the children + node0.childrenInTraversalOrder.clear(); + node0.childrenInHitTestOrder.clear(); + accessibility_bridge_->AddSemanticsNodeUpdate( + { + {0, node0}, + }, + 1.f); + RunLoopUntilIdle(); + + // Should still be 0, because the commit was not answered yet. + EXPECT_EQ(0, semantics_manager_.DeleteCount()); + + semantics_manager_.InvokeCommitCallback(); + RunLoopUntilIdle(); + + EXPECT_EQ(1, semantics_manager_.DeleteCount()); + EXPECT_EQ(next_update_count, semantics_manager_.UpdateCount()); + EXPECT_EQ(2, semantics_manager_.CommitCount()); + EXPECT_FALSE(semantics_manager_.DeleteOverflowed()); + EXPECT_FALSE(semantics_manager_.UpdateOverflowed()); +} + +TEST_F(AccessibilityBridgeTest, HitTest) { + flutter::SemanticsNode node0; + node0.id = 0; + node0.rect.setLTRB(0, 0, 100, 100); + node0.flags |= static_cast(flutter::SemanticsFlags::kIsFocusable); + + flutter::SemanticsNode node1; + node1.id = 1; + node1.rect.setLTRB(10, 10, 20, 20); + // Setting platform view id ensures this node is considered focusable. + node1.platformViewId = 1u; + + flutter::SemanticsNode node2; + node2.id = 2; + node2.rect.setLTRB(25, 10, 45, 20); + // Setting label ensures this node is considered focusable. + node2.label = "label"; + + flutter::SemanticsNode node3; + node3.id = 3; + node3.rect.setLTRB(10, 25, 20, 45); + // Setting actions to a nonzero value ensures this node is considered + // focusable. + node3.actions = 1u; + + flutter::SemanticsNode node4; + node4.id = 4; + node4.rect.setLTRB(10, 10, 20, 20); + node4.transform.setTranslate(20, 20, 0); + node4.flags |= static_cast(flutter::SemanticsFlags::kIsFocusable); + + node0.childrenInTraversalOrder = {1, 2, 3, 4}; + node0.childrenInHitTestOrder = {1, 2, 3, 4}; + + accessibility_bridge_->AddSemanticsNodeUpdate( + { + {0, node0}, + {1, node1}, + {2, node2}, + {3, node3}, + {4, node4}, + }, + 1.f); + RunLoopUntilIdle(); + + uint32_t hit_node_id; + auto callback = [&hit_node_id](fuchsia::accessibility::semantics::Hit hit) { + EXPECT_TRUE(hit.has_node_id()); + hit_node_id = hit.node_id(); + }; + + // Nodes are: + // ---------- + // | 1 2 | + // | 3 4 | + // ---------- + + accessibility_bridge_->HitTest({1, 1}, callback); + EXPECT_EQ(hit_node_id, 0u); + accessibility_bridge_->HitTest({15, 15}, callback); + EXPECT_EQ(hit_node_id, 1u); + accessibility_bridge_->HitTest({30, 15}, callback); + EXPECT_EQ(hit_node_id, 2u); + accessibility_bridge_->HitTest({15, 30}, callback); + EXPECT_EQ(hit_node_id, 3u); + accessibility_bridge_->HitTest({30, 30}, callback); + EXPECT_EQ(hit_node_id, 4u); +} + +TEST_F(AccessibilityBridgeTest, HitTestWithPixelRatio) { + flutter::SemanticsNode node0; + node0.id = 0; + node0.rect.setLTRB(0, 0, 100, 100); + node0.flags |= static_cast(flutter::SemanticsFlags::kIsFocusable); + + flutter::SemanticsNode node1; + node1.id = 1; + node1.rect.setLTRB(10, 10, 20, 20); + // Setting platform view id ensures this node is considered focusable. + node1.platformViewId = 1u; + + node0.childrenInTraversalOrder = {1}; + node0.childrenInHitTestOrder = {1}; + + accessibility_bridge_->AddSemanticsNodeUpdate( + { + {0, node0}, + {1, node1}, + }, + // Pick a very small pixel ratio so that a point within the bounds of + // the node's root-space coordinates will be well outside the "screen" + // bounds of the node. + .1f); + RunLoopUntilIdle(); + + uint32_t hit_node_id; + auto callback = [&hit_node_id](fuchsia::accessibility::semantics::Hit hit) { + EXPECT_TRUE(hit.has_node_id()); + hit_node_id = hit.node_id(); + }; + accessibility_bridge_->HitTest({15, 15}, callback); + EXPECT_EQ(hit_node_id, 0u); +} + +TEST_F(AccessibilityBridgeTest, HitTestUnfocusableChild) { + flutter::SemanticsNode node0; + node0.id = 0; + node0.rect.setLTRB(0, 0, 100, 100); + + flutter::SemanticsNode node1; + node1.id = 1; + node1.rect.setLTRB(10, 10, 60, 60); + + flutter::SemanticsNode node2; + node2.id = 2; + node2.rect.setLTRB(50, 50, 100, 100); + node2.flags |= static_cast(flutter::SemanticsFlags::kIsFocusable); + + node0.childrenInTraversalOrder = {1, 2}; + node0.childrenInHitTestOrder = {1, 2}; + + accessibility_bridge_->AddSemanticsNodeUpdate( + { + {0, node0}, + {1, node1}, + {2, node2}, + }, + 1.f); + RunLoopUntilIdle(); + + uint32_t hit_node_id; + auto callback = [&hit_node_id](fuchsia::accessibility::semantics::Hit hit) { + EXPECT_TRUE(hit.has_node_id()); + hit_node_id = hit.node_id(); + }; + + accessibility_bridge_->HitTest({55, 55}, callback); + EXPECT_EQ(hit_node_id, 2u); +} + +TEST_F(AccessibilityBridgeTest, HitTestOverlapping) { + // Tests that the first node in hit test order wins, even if a later node + // would be able to receive the hit. + flutter::SemanticsNode node0; + node0.id = 0; + node0.rect.setLTRB(0, 0, 100, 100); + node0.flags |= static_cast(flutter::SemanticsFlags::kIsFocusable); + + flutter::SemanticsNode node1; + node1.id = 1; + node1.rect.setLTRB(0, 0, 100, 100); + node1.flags |= static_cast(flutter::SemanticsFlags::kIsFocusable); + + flutter::SemanticsNode node2; + node2.id = 2; + node2.rect.setLTRB(25, 10, 45, 20); + node2.flags |= static_cast(flutter::SemanticsFlags::kIsFocusable); + + node0.childrenInTraversalOrder = {1, 2}; + node0.childrenInHitTestOrder = {2, 1}; + + accessibility_bridge_->AddSemanticsNodeUpdate( + { + {0, node0}, + {1, node1}, + {2, node2}, + }, + 1.f); + RunLoopUntilIdle(); + + uint32_t hit_node_id; + auto callback = [&hit_node_id](fuchsia::accessibility::semantics::Hit hit) { + EXPECT_TRUE(hit.has_node_id()); + hit_node_id = hit.node_id(); + }; + + accessibility_bridge_->HitTest({30, 15}, callback); + EXPECT_EQ(hit_node_id, 2u); +} + +TEST_F(AccessibilityBridgeTest, Actions) { + flutter::SemanticsNode node0; + node0.id = 0; + + flutter::SemanticsNode node1; + node1.id = 1; + + node0.childrenInTraversalOrder = {1}; + node0.childrenInHitTestOrder = {1}; + + accessibility_bridge_->AddSemanticsNodeUpdate( + { + {0, node0}, + {1, node1}, + }, + 1.f); + RunLoopUntilIdle(); + + auto handled_callback = [](bool handled) { EXPECT_TRUE(handled); }; + auto unhandled_callback = [](bool handled) { EXPECT_FALSE(handled); }; + + accessibility_bridge_->OnAccessibilityActionRequested( + 0u, fuchsia::accessibility::semantics::Action::DEFAULT, handled_callback); + EXPECT_EQ(accessibility_delegate_.actions.size(), 1u); + EXPECT_EQ(accessibility_delegate_.actions.back(), + std::make_pair(0, flutter::SemanticsAction::kTap)); + + accessibility_bridge_->OnAccessibilityActionRequested( + 0u, fuchsia::accessibility::semantics::Action::SECONDARY, + handled_callback); + EXPECT_EQ(accessibility_delegate_.actions.size(), 2u); + EXPECT_EQ(accessibility_delegate_.actions.back(), + std::make_pair(0, flutter::SemanticsAction::kLongPress)); + + accessibility_bridge_->OnAccessibilityActionRequested( + 0u, fuchsia::accessibility::semantics::Action::SET_FOCUS, + unhandled_callback); + EXPECT_EQ(accessibility_delegate_.actions.size(), 2u); + + accessibility_bridge_->OnAccessibilityActionRequested( + 0u, fuchsia::accessibility::semantics::Action::SET_VALUE, + unhandled_callback); + EXPECT_EQ(accessibility_delegate_.actions.size(), 2u); + + accessibility_bridge_->OnAccessibilityActionRequested( + 0u, fuchsia::accessibility::semantics::Action::SHOW_ON_SCREEN, + handled_callback); + EXPECT_EQ(accessibility_delegate_.actions.size(), 3u); + EXPECT_EQ(accessibility_delegate_.actions.back(), + std::make_pair(0, flutter::SemanticsAction::kShowOnScreen)); + + accessibility_bridge_->OnAccessibilityActionRequested( + 2u, fuchsia::accessibility::semantics::Action::DEFAULT, + unhandled_callback); + EXPECT_EQ(accessibility_delegate_.actions.size(), 3u); + + accessibility_bridge_->OnAccessibilityActionRequested( + 0u, fuchsia::accessibility::semantics::Action::INCREMENT, + handled_callback); + EXPECT_EQ(accessibility_delegate_.actions.size(), 4u); + EXPECT_EQ(accessibility_delegate_.actions.back(), + std::make_pair(0, flutter::SemanticsAction::kIncrease)); + + accessibility_bridge_->OnAccessibilityActionRequested( + 0u, fuchsia::accessibility::semantics::Action::DECREMENT, + handled_callback); + EXPECT_EQ(accessibility_delegate_.actions.size(), 5u); + EXPECT_EQ(accessibility_delegate_.actions.back(), + std::make_pair(0, flutter::SemanticsAction::kDecrease)); +} + +#if !FLUTTER_RELEASE +TEST_F(AccessibilityBridgeTest, InspectData) { + flutter::SemanticsNodeUpdates updates; + flutter::SemanticsNode node0; + node0.id = 0; + node0.label = "node0"; + node0.hint = "node0_hint"; + node0.value = "value"; + node0.flags |= static_cast(flutter::SemanticsFlags::kIsButton); + node0.childrenInTraversalOrder = {1}; + node0.childrenInHitTestOrder = {1}; + node0.rect.setLTRB(0, 0, 100, 100); + updates.emplace(0, node0); + + flutter::SemanticsNode node1; + node1.id = 1; + node1.flags |= static_cast(flutter::SemanticsFlags::kIsHeader); + node1.childrenInTraversalOrder = {}; + node1.childrenInHitTestOrder = {}; + updates.emplace(1, node1); + + accessibility_bridge_->AddSemanticsNodeUpdate(std::move(updates), 1.f); + RunLoopUntilIdle(); + + fpromise::result hierarchy; + ASSERT_FALSE(hierarchy.is_ok()); + RunPromiseToCompletion( + inspect::ReadFromInspector(*inspector_) + .then([&hierarchy](fpromise::result& result) { + hierarchy = std::move(result); + })); + ASSERT_TRUE(hierarchy.is_ok()); + + auto tree_inspect_hierarchy = hierarchy.value().GetByPath({"test_node"}); + ASSERT_NE(tree_inspect_hierarchy, nullptr); + // TODO(http://fxbug.dev/75841): Rewrite flutter engine accessibility bridge + // tests using inspect matchers. The checks bellow verify that the tree was + // built, and that it matches the format of the input tree. This will be + // updated in the future when test matchers are available to verify individual + // property values. + const auto& root = tree_inspect_hierarchy->children(); + ASSERT_EQ(root.size(), 1u); + EXPECT_EQ(root[0].name(), "semantic_tree_root"); + const auto& child = root[0].children(); + ASSERT_EQ(child.size(), 1u); + EXPECT_EQ(child[0].name(), "node_1"); +} +#endif // !FLUTTER_RELEASE + +} // namespace flutter_runner_test diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/build/asset_package.py b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/build/asset_package.py new file mode 100644 index 0000000000000000000000000000000000000000..12e1c37db2073079b1c3e18eeb5d661bc809d891 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/build/asset_package.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +# +# 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. + +import argparse +import subprocess +import os +import sys + + +def main(): + parser = argparse.ArgumentParser(description='Package a Flutter application') + + parser.add_argument('--flutter-root', type=str, required=True, help='The root of the Flutter SDK') + parser.add_argument( + '--flutter-tools', type=str, required=True, help='The executable for the Flutter tool' + ) + parser.add_argument( + '--asset-dir', type=str, required=True, help='The directory where to put intermediate files' + ) + parser.add_argument('--app-dir', type=str, required=True, help='The root of the app') + parser.add_argument('--packages', type=str, required=True, help='The package map to use') + parser.add_argument('--manifest', type=str, help='The application manifest') + parser.add_argument('--component-name', type=str, help='The name of the component') + parser.add_argument( + '--asset-manifest-out', + type=str, + help='Output path for the asset manifest used by the fuchsia packaging tool' + ) + + args = parser.parse_args() + + env = os.environ.copy() + env['FLUTTER_ROOT'] = args.flutter_root + + call_args = [ + args.flutter_tools, + '--asset-dir=%s' % args.asset_dir, + '--packages=%s' % args.packages, + ] + if 'manifest' in args: + call_args.append('--manifest=%s' % args.manifest) + + if args.asset_manifest_out: + call_args.append('--asset-manifest-out=%s' % args.asset_manifest_out) + + if args.component_name: + call_args.append('--component-name=%s' % args.component_name) + + result = subprocess.call(call_args, env=env, cwd=args.app_dir) + + return result + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/build/gen_debug_wrapper_main.py b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/build/gen_debug_wrapper_main.py new file mode 100644 index 0000000000000000000000000000000000000000..11b48b82254d3ded3792fa00679eb639a702c35f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/build/gen_debug_wrapper_main.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +# +# 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. +import argparse +import os +import re +import sys + + +def main(): + parser = argparse.ArgumentParser( + sys.argv[0], description="Generate main file for Fuchsia dart test" + ) + parser.add_argument("--out", help="Path to .dart file to generate", required=True) + parser.add_argument("--main-dart", help="Path to main.dart file to import", required=True) + args = parser.parse_args() + out_dir = os.path.dirname(args.out) + assert os.path.isfile(os.path.join(os.path.dirname(args.out), args.main_dart)) + outfile = open(args.out, 'w') + + # Ignores relative lib imports due to a few modules that complain about + # this. It is also possible that a future may be unawaited given that main + # may not always be synchronous across all functions. + outfile.write('''// Generated by ''') + outfile.write(os.path.basename(__file__)) + outfile.write( + ''' + + +// ignore_for_file: avoid_relative_lib_imports +import 'dart:async'; + +import 'package:flutter_driver/driver_extension.dart'; +''' + ) + outfile.write("import '%s' as flutter_app_main;\n" % args.main_dart) + outfile.write( + ''' +void main() async { + assert(await (() async { + // TODO(awdavies): Use the logger instead. + print('Overriding app main method because flutter_driver_extendable ' + 'is enabled in the build file'); + + try { + // Enables Flutter Driver VM service extension + // + // This extension is required for tests that use package:flutter_driver + // to drive applications from a separate process. + enableFlutterDriverExtension(); + + // TODO(awdavies): Use the logger instead. + print('flutter driver extensions enabled.'); + //ignore: avoid_catches_without_on_clauses + } catch (e) { + // TODO(awdavies): Use the logger instead. + // Noop. + print('flutter driver extensions not enabled. $e'); + } + // Always return true so that the assert succeeds. + return true; + }())); + // Execute the main method of the app under test + var res = (flutter_app_main.main as dynamic)(); + if (res != null && res is Future) { + await res; + } +} +''' + ) + outfile.close() + + +if __name__ == '__main__': + main() diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/canvas_spy.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/canvas_spy.cc new file mode 100644 index 0000000000000000000000000000000000000000..75df63a9069eba114011ae1693ddec38e93966c3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/canvas_spy.cc @@ -0,0 +1,270 @@ +// 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/shell/platform/fuchsia/flutter/canvas_spy.h" + +namespace flutter { + +CanvasSpy::CanvasSpy(SkCanvas* target_canvas) { + SkISize canvas_size = target_canvas->getBaseLayerSize(); + n_way_canvas_ = + std::make_unique(canvas_size.width(), canvas_size.height()); + did_draw_canvas_ = std::make_unique(canvas_size.width(), + canvas_size.height()); + n_way_canvas_->addCanvas(target_canvas); + n_way_canvas_->addCanvas(did_draw_canvas_.get()); + adapter_.set_canvas(n_way_canvas_.get()); +} + +DlCanvas* CanvasSpy::GetSpyingCanvas() { + return &adapter_; +} + +SkCanvas* CanvasSpy::GetRawSpyingCanvas() { + return n_way_canvas_.get(); +}; + +DidDrawCanvas::DidDrawCanvas(int width, int height) + : SkCanvasVirtualEnforcer(width, height) {} + +DidDrawCanvas::~DidDrawCanvas() {} + +void DidDrawCanvas::MarkDrawIfNonTransparentPaint(const SkPaint& paint) { + bool isTransparent = paint.getAlpha() == 0; + did_draw_ |= !isTransparent; +} + +bool CanvasSpy::DidDrawIntoCanvas() { + return did_draw_canvas_->DidDrawIntoCanvas(); +} + +bool DidDrawCanvas::DidDrawIntoCanvas() { + return did_draw_; +} + +void DidDrawCanvas::willSave() {} + +SkCanvas::SaveLayerStrategy DidDrawCanvas::getSaveLayerStrategy( + const SaveLayerRec& rec) { + return kNoLayer_SaveLayerStrategy; +} + +bool DidDrawCanvas::onDoSaveBehind(const SkRect* bounds) { + return false; +} + +void DidDrawCanvas::willRestore() {} + +void DidDrawCanvas::didConcat44(const SkM44&) {} + +void DidDrawCanvas::didScale(SkScalar, SkScalar) {} + +void DidDrawCanvas::didTranslate(SkScalar, SkScalar) {} + +void DidDrawCanvas::onClipRect(const SkRect& rect, + SkClipOp op, + ClipEdgeStyle edgeStyle) {} + +void DidDrawCanvas::onClipRRect(const SkRRect& rrect, + SkClipOp op, + ClipEdgeStyle edgeStyle) {} + +void DidDrawCanvas::onClipPath(const SkPath& path, + SkClipOp op, + ClipEdgeStyle edgeStyle) {} + +void DidDrawCanvas::onClipRegion(const SkRegion& deviceRgn, SkClipOp op) {} + +void DidDrawCanvas::onDrawPaint(const SkPaint& paint) { + MarkDrawIfNonTransparentPaint(paint); +} + +void DidDrawCanvas::onDrawBehind(const SkPaint& paint) { + MarkDrawIfNonTransparentPaint(paint); +} + +void DidDrawCanvas::onDrawPoints(PointMode mode, + size_t count, + const SkPoint pts[], + const SkPaint& paint) { + MarkDrawIfNonTransparentPaint(paint); +} + +void DidDrawCanvas::onDrawRect(const SkRect& rect, const SkPaint& paint) { + MarkDrawIfNonTransparentPaint(paint); +} + +void DidDrawCanvas::onDrawRegion(const SkRegion& region, const SkPaint& paint) { + MarkDrawIfNonTransparentPaint(paint); +} + +void DidDrawCanvas::onDrawOval(const SkRect& rect, const SkPaint& paint) { + MarkDrawIfNonTransparentPaint(paint); +} + +void DidDrawCanvas::onDrawArc(const SkRect& rect, + SkScalar startAngle, + SkScalar sweepAngle, + bool useCenter, + const SkPaint& paint) { + MarkDrawIfNonTransparentPaint(paint); +} + +void DidDrawCanvas::onDrawRRect(const SkRRect& rrect, const SkPaint& paint) { + MarkDrawIfNonTransparentPaint(paint); +} + +void DidDrawCanvas::onDrawDRRect(const SkRRect& outer, + const SkRRect& inner, + const SkPaint& paint) { + MarkDrawIfNonTransparentPaint(paint); +} + +void DidDrawCanvas::onDrawPath(const SkPath& path, const SkPaint& paint) { + MarkDrawIfNonTransparentPaint(paint); +} + +#ifdef SK_SUPPORT_LEGACY_ONDRAWIMAGERECT +void DidDrawCanvas::onDrawImage(const SkImage* image, + SkScalar left, + SkScalar top, + const SkPaint* paint) { + did_draw_ = true; +} + +void DidDrawCanvas::onDrawImageRect(const SkImage* image, + const SkRect* src, + const SkRect& dst, + const SkPaint* paint, + SrcRectConstraint constraint) { + did_draw_ = true; +} + +void DidDrawCanvas::onDrawImageLattice(const SkImage* image, + const Lattice& lattice, + const SkRect& dst, + const SkPaint* paint) { + did_draw_ = true; +} + +void DidDrawCanvas::onDrawAtlas(const SkImage* image, + const SkRSXform xform[], + const SkRect tex[], + const SkColor colors[], + int count, + SkBlendMode bmode, + const SkRect* cull, + const SkPaint* paint) { + did_draw_ = true; +} + +void DidDrawCanvas::onDrawEdgeAAImageSet(const ImageSetEntry set[], + int count, + const SkPoint dstClips[], + const SkMatrix preViewMatrices[], + const SkPaint* paint, + SrcRectConstraint constraint) { + did_draw_ = true; +} +#endif + +void DidDrawCanvas::onDrawImage2(const SkImage* image, + SkScalar left, + SkScalar top, + const SkSamplingOptions&, + const SkPaint* paint) { + did_draw_ = true; +} + +void DidDrawCanvas::onDrawImageRect2(const SkImage* image, + const SkRect& src, + const SkRect& dst, + const SkSamplingOptions&, + const SkPaint* paint, + SrcRectConstraint constraint) { + did_draw_ = true; +} + +void DidDrawCanvas::onDrawImageLattice2(const SkImage* image, + const Lattice& lattice, + const SkRect& dst, + SkFilterMode, + const SkPaint* paint) { + did_draw_ = true; +} + +void DidDrawCanvas::onDrawTextBlob(const SkTextBlob* blob, + SkScalar x, + SkScalar y, + const SkPaint& paint) { + MarkDrawIfNonTransparentPaint(paint); +} + +void DidDrawCanvas::onDrawPicture(const SkPicture* picture, + const SkMatrix* matrix, + const SkPaint* paint) { + did_draw_ = true; +} + +void DidDrawCanvas::onDrawDrawable(SkDrawable* drawable, + const SkMatrix* matrix) { + did_draw_ = true; +} + +void DidDrawCanvas::onDrawVerticesObject(const SkVertices* vertices, + SkBlendMode bmode, + const SkPaint& paint) { + MarkDrawIfNonTransparentPaint(paint); +} + +void DidDrawCanvas::onDrawPatch(const SkPoint cubics[12], + const SkColor colors[4], + const SkPoint texCoords[4], + SkBlendMode bmode, + const SkPaint& paint) { + MarkDrawIfNonTransparentPaint(paint); +} + +void DidDrawCanvas::onDrawAtlas2(const SkImage* image, + const SkRSXform xform[], + const SkRect tex[], + const SkColor colors[], + int count, + SkBlendMode bmode, + const SkSamplingOptions&, + const SkRect* cull, + const SkPaint* paint) { + did_draw_ = true; +} + +void DidDrawCanvas::onDrawShadowRec(const SkPath& path, + const SkDrawShadowRec& rec) { + did_draw_ = true; +} + +void DidDrawCanvas::onDrawAnnotation(const SkRect& rect, + const char key[], + SkData* data) { + did_draw_ = true; +} + +void DidDrawCanvas::onDrawEdgeAAQuad(const SkRect& rect, + const SkPoint clip[4], + SkCanvas::QuadAAFlags aa, + const SkColor4f& color, + SkBlendMode mode) { + did_draw_ = true; +} + +void DidDrawCanvas::onDrawEdgeAAImageSet2(const ImageSetEntry set[], + int count, + const SkPoint dstClips[], + const SkMatrix preViewMatrices[], + const SkSamplingOptions&, + const SkPaint* paint, + SrcRectConstraint constraint) { + did_draw_ = true; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/canvas_spy.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/canvas_spy.h new file mode 100644 index 0000000000000000000000000000000000000000..fa781cbcb3861b4e30782a06e3a9470c0976a0af --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/canvas_spy.h @@ -0,0 +1,258 @@ + +// 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/display_list/skia/dl_sk_canvas.h" +#include "flutter/fml/macros.h" +#include "third_party/skia/include/core/SkCanvas.h" +#include "third_party/skia/include/core/SkCanvasVirtualEnforcer.h" +#include "third_party/skia/include/utils/SkNWayCanvas.h" +#include "third_party/skia/include/utils/SkNoDrawCanvas.h" + +#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_CANVAS_SPY_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_CANVAS_SPY_H_ + +namespace flutter { + +class DidDrawCanvas; + +//------------------------------------------------------------------------------ +/// Facilitates spying on drawing commands to an SkCanvas. +/// +/// This is used to determine whether anything was drawn into +/// a canvas so it is possible to implement optimizations that +/// are specific to empty canvases. +class CanvasSpy { + public: + explicit CanvasSpy(SkCanvas* target_canvas); + + //---------------------------------------------------------------------------- + /// @brief Returns true if any non transparent content has been drawn + /// into + /// the spying canvas. Note that this class does tries to detect + /// empty canvases but in some cases may return true even for + /// empty canvases (e.g when a transparent image is drawn into the + /// canvas). + bool DidDrawIntoCanvas(); + + //---------------------------------------------------------------------------- + /// @brief The returned canvas delegate all operations to the target + /// canvas + /// while spying on them. + DlCanvas* GetSpyingCanvas(); + + //---------------------------------------------------------------------------- + /// @brief The underlying Skia canvas that implements the spying + /// (mainly for testing) + SkCanvas* GetRawSpyingCanvas(); + + private: + std::unique_ptr n_way_canvas_; + std::unique_ptr did_draw_canvas_; + DlSkCanvasAdapter adapter_; + + FML_DISALLOW_COPY_AND_ASSIGN(CanvasSpy); +}; + +class DidDrawCanvas final : public SkCanvasVirtualEnforcer { + public: + DidDrawCanvas(int width, int height); + ~DidDrawCanvas() override; + bool DidDrawIntoCanvas(); + + private: + bool did_draw_ = false; + + // |SkCanvasVirtualEnforcer| + void willSave() override; + + // |SkCanvasVirtualEnforcer| + SaveLayerStrategy getSaveLayerStrategy(const SaveLayerRec&) override; + + // |SkCanvasVirtualEnforcer| + bool onDoSaveBehind(const SkRect*) override; + + // |SkCanvasVirtualEnforcer| + void willRestore() override; + + // |SkCanvasVirtualEnforcer| + void didConcat44(const SkM44&) override; + void didScale(SkScalar, SkScalar) override; + void didTranslate(SkScalar, SkScalar) override; + + // |SkCanvasVirtualEnforcer| + void onDrawDRRect(const SkRRect&, const SkRRect&, const SkPaint&) override; + + // |SkCanvasVirtualEnforcer| + virtual void onDrawTextBlob(const SkTextBlob* blob, + SkScalar x, + SkScalar y, + const SkPaint& paint) override; + // |SkCanvasVirtualEnforcer| + virtual void onDrawPatch(const SkPoint cubics[12], + const SkColor colors[4], + const SkPoint texCoords[4], + SkBlendMode, + const SkPaint& paint) override; + + // |SkCanvasVirtualEnforcer| + void onDrawPaint(const SkPaint&) override; + + // |SkCanvasVirtualEnforcer| + void onDrawBehind(const SkPaint&) override; + + // |SkCanvasVirtualEnforcer| + void onDrawPoints(PointMode, + size_t count, + const SkPoint pts[], + const SkPaint&) override; + + // |SkCanvasVirtualEnforcer| + void onDrawRect(const SkRect&, const SkPaint&) override; + + // |SkCanvasVirtualEnforcer| + void onDrawRegion(const SkRegion&, const SkPaint&) override; + + // |SkCanvasVirtualEnforcer| + void onDrawOval(const SkRect&, const SkPaint&) override; + + // |SkCanvasVirtualEnforcer| + void onDrawArc(const SkRect&, + SkScalar, + SkScalar, + bool, + const SkPaint&) override; + + // |SkCanvasVirtualEnforcer| + void onDrawRRect(const SkRRect&, const SkPaint&) override; + + // |SkCanvasVirtualEnforcer| + void onDrawPath(const SkPath&, const SkPaint&) override; + +#ifdef SK_SUPPORT_LEGACY_ONDRAWIMAGERECT + // |SkCanvasVirtualEnforcer| + void onDrawImage(const SkImage*, + SkScalar left, + SkScalar top, + const SkPaint*) override; + + // |SkCanvasVirtualEnforcer| + void onDrawImageRect(const SkImage*, + const SkRect* src, + const SkRect& dst, + const SkPaint*, + SrcRectConstraint) override; + + // |SkCanvasVirtualEnforcer| + void onDrawImageLattice(const SkImage*, + const Lattice&, + const SkRect&, + const SkPaint*) override; + + // |SkCanvasVirtualEnforcer| + void onDrawAtlas(const SkImage*, + const SkRSXform[], + const SkRect[], + const SkColor[], + int, + SkBlendMode, + const SkRect*, + const SkPaint*) override; + // |SkCanvasVirtualEnforcer| + void onDrawEdgeAAImageSet(const ImageSetEntry[], + int count, + const SkPoint[], + const SkMatrix[], + const SkPaint*, + SrcRectConstraint) override; +#endif + + // |SkCanvasVirtualEnforcer| + void onDrawImage2(const SkImage*, + SkScalar left, + SkScalar top, + const SkSamplingOptions&, + const SkPaint*) override; + + // |SkCanvasVirtualEnforcer| + void onDrawImageRect2(const SkImage*, + const SkRect& src, + const SkRect& dst, + const SkSamplingOptions&, + const SkPaint*, + SrcRectConstraint) override; + + // |SkCanvasVirtualEnforcer| + void onDrawImageLattice2(const SkImage*, + const Lattice&, + const SkRect&, + SkFilterMode, + const SkPaint*) override; + + // |SkCanvasVirtualEnforcer| + void onDrawVerticesObject(const SkVertices*, + SkBlendMode, + const SkPaint&) override; + + // |SkCanvasVirtualEnforcer| + void onDrawAtlas2(const SkImage*, + const SkRSXform[], + const SkRect[], + const SkColor[], + int, + SkBlendMode, + const SkSamplingOptions&, + const SkRect*, + const SkPaint*) override; + + // |SkCanvasVirtualEnforcer| + void onDrawShadowRec(const SkPath&, const SkDrawShadowRec&) override; + + // |SkCanvasVirtualEnforcer| + void onClipRect(const SkRect&, SkClipOp, ClipEdgeStyle) override; + + // |SkCanvasVirtualEnforcer| + void onClipRRect(const SkRRect&, SkClipOp, ClipEdgeStyle) override; + + // |SkCanvasVirtualEnforcer| + void onClipPath(const SkPath&, SkClipOp, ClipEdgeStyle) override; + + // |SkCanvasVirtualEnforcer| + void onClipRegion(const SkRegion&, SkClipOp) override; + + // |SkCanvasVirtualEnforcer| + void onDrawPicture(const SkPicture*, + const SkMatrix*, + const SkPaint*) override; + + // |SkCanvasVirtualEnforcer| + void onDrawDrawable(SkDrawable*, const SkMatrix*) override; + + // |SkCanvasVirtualEnforcer| + void onDrawAnnotation(const SkRect&, const char[], SkData*) override; + + // |SkCanvasVirtualEnforcer| + void onDrawEdgeAAQuad(const SkRect&, + const SkPoint[4], + SkCanvas::QuadAAFlags, + const SkColor4f&, + SkBlendMode) override; + + // |SkCanvasVirtualEnforcer| + void onDrawEdgeAAImageSet2(const ImageSetEntry[], + int count, + const SkPoint[], + const SkMatrix[], + const SkSamplingOptions&, + const SkPaint*, + SrcRectConstraint) override; + + void MarkDrawIfNonTransparentPaint(const SkPaint& paint); + + FML_DISALLOW_COPY_AND_ASSIGN(DidDrawCanvas); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_CANVAS_SPY_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/canvas_spy_unittests.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/canvas_spy_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..8946133b9e2206655735938f2c0ece17e151409d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/canvas_spy_unittests.cc @@ -0,0 +1,67 @@ +// 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/shell/platform/fuchsia/flutter/canvas_spy.h" + +#include "gtest/gtest.h" +#include "third_party/skia/include/core/SkPictureRecorder.h" +#include "third_party/skia/include/core/SkSurface.h" + +namespace flutter { +namespace testing { + +TEST(CanvasSpyTest, DrawingIsTracked) { + SkPictureRecorder picture_recorder; + SkCanvas* canvas = picture_recorder.beginRecording(100, 100); + CanvasSpy canvas_spy = CanvasSpy(canvas); + DlCanvas* spy = canvas_spy.GetSpyingCanvas(); + + ASSERT_FALSE(canvas_spy.DidDrawIntoCanvas()); + + spy->Translate(128, 128); + spy->Clear(DlColor::kTransparent()); + ASSERT_FALSE(canvas_spy.DidDrawIntoCanvas()); + + DlPaint paint; + spy->DrawCircle(DlPoint(0, 0), 60, paint); + ASSERT_TRUE(canvas_spy.DidDrawIntoCanvas()); +} + +TEST(CanvasSpyTest, SpiedCanvasIsDrawing) { + auto actual_surface = + SkSurfaces::Raster(SkImageInfo::MakeN32Premul(100, 100)); + SkCanvas* actual_canvas = actual_surface->getCanvas(); + + auto expected_surface = + SkSurfaces::Raster(SkImageInfo::MakeN32Premul(100, 100)); + SkCanvas* expected_canvas = expected_surface->getCanvas(); + + CanvasSpy canvas_spy = CanvasSpy(actual_canvas); + SkCanvas* spy = canvas_spy.GetRawSpyingCanvas(); + + SkNWayCanvas multi_canvas = SkNWayCanvas(100, 100); + multi_canvas.addCanvas(spy); + multi_canvas.addCanvas(expected_canvas); + + multi_canvas.clipRect(SkRect::MakeWH(100, 100)); + multi_canvas.clear(SK_ColorRED); + multi_canvas.scale(.5, .5); + multi_canvas.clipRect(SkRect::MakeWH(100, 100)); + multi_canvas.clear(SK_ColorBLUE); + + ASSERT_TRUE(canvas_spy.DidDrawIntoCanvas()); + + SkPixmap actual; + SkPixmap expected; + + ASSERT_TRUE(actual_surface->peekPixels(&actual)); + ASSERT_TRUE(expected_surface->peekPixels(&expected)); + + const auto size = actual.rowBytes() * actual.height(); + ASSERT_NE(size, 0u); + + ASSERT_EQ(::memcmp(actual.addr(), expected.addr(), size), 0); +} +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/component_v2.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/component_v2.cc new file mode 100644 index 0000000000000000000000000000000000000000..5df9b1b0361c2eddad9058347935b5cb6045081e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/component_v2.cc @@ -0,0 +1,669 @@ +// 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 "component_v2.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "file_in_namespace_buffer.h" +#include "flutter/fml/command_line.h" +#include "flutter/fml/mapping.h" +#include "flutter/fml/platform/fuchsia/task_observers.h" +#include "flutter/fml/synchronization/waitable_event.h" +#include "flutter/fml/unique_fd.h" +#include "flutter/runtime/dart_vm_lifecycle.h" +#include "flutter/shell/common/switches.h" +#include "runtime/dart/utils/files.h" +#include "runtime/dart/utils/handle_exception.h" +#include "runtime/dart/utils/mapped_resource.h" +#include "runtime/dart/utils/tempfs.h" +#include "runtime/dart/utils/vmo.h" + +namespace flutter_runner { +namespace { + +// "data" and "assets" are arguments that are specific to the Flutter runner. +// They will likely go away if we migrate to the ELF runner. +constexpr char kDataKey[] = "data"; +constexpr char kAssetsKey[] = "assets"; + +// "args" are how the component specifies arguments to the runner. +constexpr char kArgsKey[] = "args"; +constexpr char kOldGenHeapSizeKey[] = "old_gen_heap_size"; +constexpr char kExposeDirsKey[] = "expose_dirs"; + +constexpr char kTmpPath[] = "/tmp"; +constexpr char kServiceRootPath[] = "/svc"; +constexpr char kRunnerConfigPath[] = "/config/data/flutter_runner_config"; + +std::string DebugLabelForUrl(const std::string& url) { + auto found = url.rfind("/"); + if (found == std::string::npos) { + return url; + } else { + return {url, found + 1}; + } +} + +/// Parses the |args| field from the "program" field into +/// |metadata|. +void ParseArgs(std::vector& args, ProgramMetadata* metadata) { + // fml::CommandLine expects the first argument to be the name of the program, + // so we prepend a dummy argument so we can use fml::CommandLine to parse the + // arguments for us. + std::vector command_line_args = {""}; + command_line_args.insert(command_line_args.end(), args.begin(), args.end()); + fml::CommandLine parsed_args = fml::CommandLineFromIterators( + command_line_args.begin(), command_line_args.end()); + + std::string old_gen_heap_size_option; + if (parsed_args.GetOptionValue(kOldGenHeapSizeKey, + &old_gen_heap_size_option)) { + int64_t specified_old_gen_heap_size = strtol( + old_gen_heap_size_option.c_str(), nullptr /* endptr */, 10 /* base */); + if (specified_old_gen_heap_size != 0) { + metadata->old_gen_heap_size = specified_old_gen_heap_size; + } else { + FML_LOG(ERROR) << "Invalid old_gen_heap_size: " + << old_gen_heap_size_option; + } + } + + std::string expose_dirs_option; + if (parsed_args.GetOptionValue(kExposeDirsKey, &expose_dirs_option)) { + // Parse the comma delimited string + std::vector expose_dirs; + std::stringstream s(expose_dirs_option); + while (s.good()) { + std::string dir; + getline(s, dir, ','); // get first string delimited by comma + metadata->expose_dirs.push_back(dir); + } + } +} + +} // namespace + +ProgramMetadata ComponentV2::ParseProgramMetadata( + const fuchsia::data::Dictionary& program_metadata) { + ProgramMetadata result; + + for (const auto& entry : program_metadata.entries()) { + if (entry.key.compare(kDataKey) == 0 && entry.value != nullptr) { + result.data_path = "pkg/" + entry.value->str(); + } else if (entry.key.compare(kAssetsKey) == 0 && entry.value != nullptr) { + result.assets_path = "pkg/" + entry.value->str(); + } else if (entry.key.compare(kArgsKey) == 0 && entry.value != nullptr) { + ParseArgs(entry.value->str_vec(), &result); + } + } + + // assets_path defaults to the same as data_path if omitted. + if (result.assets_path.empty()) { + result.assets_path = result.data_path; + } + + return result; +} + +ActiveComponentV2 ComponentV2::Create( + TerminationCallback termination_callback, + fuchsia::component::runner::ComponentStartInfo start_info, + std::shared_ptr runner_incoming_services, + fidl::InterfaceRequest + controller) { + auto thread = std::make_unique(); + std::unique_ptr component; + + fml::AutoResetWaitableEvent latch; + thread->GetTaskRunner()->PostTask([&]() mutable { + component.reset( + new ComponentV2(std::move(termination_callback), std::move(start_info), + runner_incoming_services, std::move(controller))); + latch.Signal(); + }); + + latch.Wait(); + return {.platform_thread = std::move(thread), + .component = std::move(component)}; +} + +ComponentV2::ComponentV2( + TerminationCallback termination_callback, + fuchsia::component::runner::ComponentStartInfo start_info, + std::shared_ptr runner_incoming_services, + fidl::InterfaceRequest + component_controller_request) + : termination_callback_(std::move(termination_callback)), + debug_label_(DebugLabelForUrl(start_info.resolved_url())), + component_controller_(this), + outgoing_dir_(new vfs::PseudoDir()), + runtime_dir_(new vfs::PseudoDir()), + runner_incoming_services_(runner_incoming_services), + weak_factory_(this) { + component_controller_.set_error_handler([this](zx_status_t status) { + FML_LOG(ERROR) << "ComponentController binding error for component(" + << debug_label_ << "): " << zx_status_get_string(status); + KillWithEpitaph( + zx_status_t(fuchsia::component::Error::INSTANCE_CANNOT_START)); + }); + + FML_DCHECK(fdio_ns_.is_valid()); + + // TODO(fxb/88391): Dart launch arguments. + FML_LOG(WARNING) << "program() arguments are currently ignored (fxb/88391)."; + + ProgramMetadata metadata = ParseProgramMetadata(start_info.program()); + + if (metadata.data_path.empty()) { + FML_LOG(ERROR) << "Could not find a /pkg/data directory for " + << start_info.resolved_url(); + return; + } + + dart_utils::BindTemp(fdio_ns_.get()); + + // ComponentStartInfo::ns (optional) + if (start_info.has_ns()) { + for (auto& entry : *start_info.mutable_ns()) { + // /tmp/ is mapped separately to to a process-local virtual filesystem, + // so we ignore it here. + const auto& path = entry.path(); + if (path == kTmpPath) { + continue; + } + + // We should never receive namespace entries without a directory, but we + // check it anyways to avoid crashing if we do. + if (!entry.has_directory()) { + FML_LOG(ERROR) << "Namespace entry at path (" << path + << ") has no directory."; + continue; + } + + zx::channel dir; + if (path == kServiceRootPath) { + svc_ = std::make_unique( + std::move(*entry.mutable_directory())); + dir = svc_->CloneChannel().TakeChannel(); + } else { + dir = entry.mutable_directory()->TakeChannel(); + } + + zx_handle_t dir_handle = dir.release(); + if (fdio_ns_bind(fdio_ns_.get(), path.data(), dir_handle) != ZX_OK) { + FML_LOG(ERROR) << "Could not bind path to namespace: " << path; + zx_handle_close(dir_handle); + } + } + } + + // Open the data and assets directories inside our namespace. + { + fml::UniqueFD ns_fd(fdio_ns_opendir(fdio_ns_.get())); + FML_DCHECK(ns_fd.is_valid()); + + constexpr mode_t mode = O_RDONLY | O_DIRECTORY; + + component_assets_directory_.reset( + openat(ns_fd.get(), metadata.assets_path.c_str(), mode)); + FML_DCHECK(component_assets_directory_.is_valid()); + + component_data_directory_.reset( + openat(ns_fd.get(), metadata.data_path.c_str(), mode)); + FML_DCHECK(component_data_directory_.is_valid()); + } + + // ComponentStartInfo::runtime_dir (optional). + if (start_info.has_runtime_dir()) { + fidl::ServerEnd server_end{ + start_info.mutable_runtime_dir()->TakeChannel()}; + runtime_dir_->Serve( + fuchsia_io::wire::kPermReadable | fuchsia_io::wire::kPermWritable, + std::move(server_end)); + } + + // ComponentStartInfo::outgoing_dir (optional). + if (start_info.has_outgoing_dir()) { + fidl::ServerEnd server_end{ + start_info.mutable_outgoing_dir()->TakeChannel()}; + outgoing_dir_->Serve( + fuchsia_io::wire::kPermReadable | fuchsia_io::wire::kPermWritable, + std::move(server_end)); + } + + directory_request_ = directory_ptr_.NewRequest(); + + fuchsia::io::DirectoryHandle flutter_public_dir; + { + auto request = flutter_public_dir.NewRequest().TakeChannel(); + const zx_status_t status = + fdio_open3_at(directory_ptr_.channel().get(), "svc", + uint64_t{fuchsia::io::PERM_READABLE}, request.release()); + if (status != ZX_OK) { + FML_LOG(ERROR) << "Failed to open /svc in outgoing directory: " + << zx_status_get_string(status); + return; + } + } + + auto composed_service_dir = std::make_unique(); + composed_service_dir->SetFallback( + fidl::ClientEnd(flutter_public_dir.TakeChannel())); + + // Request an event from the directory to ensure it is servicing requests. + directory_ptr_->Open3(".", + fuchsia::io::Flags::PROTOCOL_NODE | + fuchsia::io::Flags::FLAG_SEND_REPRESENTATION, + {}, cloned_directory_ptr_.NewRequest().TakeChannel()); + + // Collect our standard set of directories along with directories that are + // included in the cml file to expose. + std::vector other_dirs = {"debug", "ctrl"}; + for (auto dir : metadata.expose_dirs) { + other_dirs.push_back(dir); + } + + cloned_directory_ptr_.events().OnRepresentation = [this, + other_dirs](auto unused) { + cloned_directory_ptr_.Unbind(); + // add other directories as RemoteDirs. + for (auto& dir_str : other_dirs) { + fuchsia::io::DirectoryHandle dir; + auto request = dir.NewRequest().TakeChannel(); + const zx_status_t status = + fdio_open3_at(directory_ptr_.channel().get(), dir_str.c_str(), + uint64_t{fuchsia::io::Flags::PROTOCOL_DIRECTORY | + fuchsia::io::PERM_READABLE}, + request.release()); + if (status == ZX_OK) { + outgoing_dir_->AddEntry( + dir_str.c_str(), + std::make_unique(dir.TakeChannel())); + } else { + FML_LOG(ERROR) << "could not add out directory entry(" << dir_str + << ") for flutter component(" << debug_label_ + << "): " << zx_status_get_string(status); + } + } + }; + + cloned_directory_ptr_.set_error_handler( + [this](zx_status_t status) { cloned_directory_ptr_.Unbind(); }); + + // TODO(fxb/89162): Close handles from ComponentStartInfo::numbered_handles + // since we're not using them. See documentation from ComponentController: + // https://cs.opensource.google/fuchsia/fuchsia/+/main:sdk/fidl/fuchsia.component.runner/component_runner.fidl;l=97;drc=e3b39f2b57e720770773b857feca4f770ee0619e + + // TODO(fxb/89162): There's an OnPublishDiagnostics event we may want to + // fire for diagnostics. See documentation from ComponentController: + // https://cs.opensource.google/fuchsia/fuchsia/+/main:sdk/fidl/fuchsia.component.runner/component_runner.fidl;l=181;drc=e3b39f2b57e720770773b857feca4f770ee0619e + + // All launch arguments have been read. Perform service binding and + // final settings configuration. The next call will be to create a view + // for this component. + composed_service_dir->AddService( + fuchsia::ui::app::ViewProvider::Name_, + std::make_unique( + [this](zx::channel channel, async_dispatcher_t* dispatcher) { + shells_bindings_.AddBinding( + this, fidl::InterfaceRequest( + std::move(channel))); + })); + outgoing_dir_->AddEntry("svc", std::move(composed_service_dir)); + + // Setup the component controller binding. + if (component_controller_request) { + component_controller_.Bind(std::move(component_controller_request)); + } + + // Load and use runner-specific configuration, if it exists. + std::string json_string; + if (dart_utils::ReadFileToString(kRunnerConfigPath, &json_string)) { + product_config_ = FlutterRunnerProductConfiguration(json_string); + FML_LOG(INFO) << "Successfully loaded runner configuration: " + << json_string; + } else { + FML_LOG(WARNING) << "Failed to load runner configuration from " + << kRunnerConfigPath << "; using default config values."; + } + + // Load VM and component bytecode. + // For AOT, compare with flutter_aot_app in flutter_app.gni. + // For JIT, compare flutter_jit_runner in BUILD.gn. + if (flutter::DartVM::IsRunningPrecompiledCode()) { + std::shared_ptr snapshot = + std::make_shared(); + if (snapshot->Load(component_data_directory_.get(), + "app_aot_snapshot.so")) { + const uint8_t* isolate_data = snapshot->IsolateData(); + const uint8_t* isolate_instructions = snapshot->IsolateInstrs(); + const uint8_t* vm_data = snapshot->VmData(); + const uint8_t* vm_instructions = snapshot->VmInstrs(); + if (isolate_data == nullptr || isolate_instructions == nullptr || + vm_data == nullptr || vm_instructions == nullptr) { + FML_LOG(FATAL) << "ELF snapshot missing AOT symbols."; + return; + } + auto hold_snapshot = [snapshot](const uint8_t* _, size_t __) {}; + settings_.vm_snapshot_data = [hold_snapshot, vm_data]() { + return std::make_unique(vm_data, 0, hold_snapshot, + true /* dontneed_safe */); + }; + settings_.vm_snapshot_instr = [hold_snapshot, vm_instructions]() { + return std::make_unique( + vm_instructions, 0, hold_snapshot, true /* dontneed_safe */); + }; + settings_.isolate_snapshot_data = [hold_snapshot, isolate_data]() { + return std::make_unique( + isolate_data, 0, hold_snapshot, true /* dontneed_safe */); + }; + settings_.isolate_snapshot_instr = [hold_snapshot, + isolate_instructions]() { + return std::make_unique( + isolate_instructions, 0, hold_snapshot, true /* dontneed_safe */); + }; + isolate_snapshot_ = fml::MakeRefCounted( + std::make_shared(isolate_data, 0, hold_snapshot, + true /* dontneed_safe */), + std::make_shared(isolate_instructions, 0, + hold_snapshot, + true /* dontneed_safe */)); + } else { + const int namespace_fd = component_data_directory_.get(); + settings_.vm_snapshot_data = [namespace_fd]() { + return LoadFile(namespace_fd, "vm_snapshot_data.bin", + false /* executable */); + }; + settings_.vm_snapshot_instr = [namespace_fd]() { + return LoadFile(namespace_fd, "vm_snapshot_instructions.bin", + true /* executable */); + }; + settings_.isolate_snapshot_data = [namespace_fd]() { + return LoadFile(namespace_fd, "isolate_snapshot_data.bin", + false /* executable */); + }; + settings_.isolate_snapshot_instr = [namespace_fd]() { + return LoadFile(namespace_fd, "isolate_snapshot_instructions.bin", + true /* executable */); + }; + } + } else { + settings_.vm_snapshot_data = []() { + return MakeFileMapping("/pkg/data/vm_snapshot_data.bin", + false /* executable */); + }; + settings_.isolate_snapshot_data = []() { + return MakeFileMapping("/pkg/data/isolate_core_snapshot_data.bin", + false /* executable */); + }; + } + +#if defined(DART_PRODUCT) + settings_.enable_vm_service = false; +#else + settings_.enable_vm_service = true; + + // TODO(cbracken): pass this in as a param to allow 0.0.0.0, ::1, etc. + settings_.vm_service_host = "127.0.0.1"; +#endif + + // Controls whether category "skia" trace events are enabled. + settings_.trace_skia = true; + + settings_.verbose_logging = true; + + settings_.advisory_script_uri = debug_label_; + + settings_.advisory_script_entrypoint = debug_label_; + + settings_.icu_data_path = ""; + + settings_.assets_dir = component_assets_directory_.get(); + + // Compare flutter_jit_app in flutter_app.gni. + settings_.application_kernel_list_asset = "app.dilplist"; + + settings_.log_tag = debug_label_ + std::string{"(flutter)"}; + + if (metadata.old_gen_heap_size.has_value()) { + settings_.old_gen_heap_size = *metadata.old_gen_heap_size; + } + + // No asserts in debug or release product. + // No asserts in release with flutter_profile=true (non-product) + // Yes asserts in non-product debug. +#if !defined(DART_PRODUCT) && (!defined(FLUTTER_PROFILE) || !defined(NDEBUG)) + // Debug mode + settings_.disable_dart_asserts = false; +#else + // Release mode + settings_.disable_dart_asserts = true; +#endif + + // Do not leak the VM; allow it to shut down normally when the last shell + // terminates. + settings_.leak_vm = false; + + settings_.task_observer_add = + std::bind(&fml::CurrentMessageLoopAddAfterTaskObserver, + std::placeholders::_1, std::placeholders::_2); + + settings_.task_observer_remove = std::bind( + &fml::CurrentMessageLoopRemoveAfterTaskObserver, std::placeholders::_1); + + settings_.log_message_callback = [](const std::string& tag, + const std::string& message) { + if (!tag.empty()) { + std::cout << tag << ": "; + } + std::cout << message << std::endl; + }; + + settings_.dart_flags = {}; + + // Don't collect CPU samples from Dart VM C++ code. + settings_.dart_flags.push_back("--no_profile_vm"); + + // Scale back CPU profiler sampling period on ARM64 to avoid overloading + // the tracing engine. +#if defined(__aarch64__) + settings_.dart_flags.push_back("--profile_period=10000"); +#endif // defined(__aarch64__) + + auto platform_task_runner = fml::MessageLoop::GetCurrent().GetTaskRunner(); + const std::string component_url = start_info.resolved_url(); + settings_.unhandled_exception_callback = [weak = weak_factory_.GetWeakPtr(), + platform_task_runner, + runner_incoming_services, + component_url]( + const std::string& error, + const std::string& stack_trace) { + if (weak) { + // TODO(cbracken): unsafe. The above check and the PostTask below are + // happening on the UI thread. If the Component dtor and thread + // termination happen (on the platform thread) between the previous + // line and the next line, a crash will occur since we'll be posting + // to a dead thread. See Runner::OnComponentV2Terminate() in + // runner.cc. + platform_task_runner->PostTask([weak, runner_incoming_services, + component_url, error, stack_trace]() { + if (weak) { + dart_utils::HandleException(runner_incoming_services, component_url, + error, stack_trace); + } else { + FML_LOG(WARNING) + << "Exception was thrown which was not caught in Flutter app: " + << error; + } + }); + } else { + FML_LOG(WARNING) + << "Exception was thrown which was not caught in Flutter app: " + << error; + } + // Ideally we would return whether HandleException returned ZX_OK, but + // short of knowing if the exception was correctly handled, we return + // false to have the error and stack trace printed in the logs. + return false; + }; +} + +ComponentV2::~ComponentV2() = default; + +const std::string& ComponentV2::GetDebugLabel() const { + return debug_label_; +} + +void ComponentV2::Kill() { + FML_VLOG(1) << "received Kill event"; + + // From the documentation for ComponentController, ZX_OK should be sent when + // the ComponentController receives a termination request. However, if the + // component exited with a non-zero return code, we indicate this by sending + // an INTERNAL epitaph instead. + // + // TODO(fxb/86666): Communicate return code from the ComponentController once + // v2 has support. + auto [got_return_code, return_code] = last_return_code_; + if (got_return_code && return_code == 0) { + KillWithEpitaph(ZX_OK); + } else { + if (got_return_code) { + FML_LOG(ERROR) << "Component exited with non-zero return code: " + << return_code; + } else { + FML_LOG(ERROR) << "Failed to get return code for component"; + } + + KillWithEpitaph(zx_status_t(fuchsia::component::Error::INTERNAL)); + } + + // WARNING: Don't do anything past this point as this instance may have been + // collected. +} + +void ComponentV2::KillWithEpitaph(zx_status_t epitaph_status) { + component_controller_.set_error_handler(nullptr); + component_controller_.Close(epitaph_status); + + termination_callback_(this); + // WARNING: Don't do anything past this point as this instance may have been + // collected. +} + +void ComponentV2::Stop() { + FML_VLOG(1) << "received Stop event"; + + // TODO(fxb/89162): Any other cleanup logic we should do that's appropriate + // for Stop but not for Kill? + KillWithEpitaph(ZX_OK); +} + +void ComponentV2::OnEngineTerminate(const Engine* shell_holder) { + auto found = std::find_if(shell_holders_.begin(), shell_holders_.end(), + [shell_holder](const auto& holder) { + return holder.get() == shell_holder; + }); + + if (found == shell_holders_.end()) { + // This indicates a deeper issue with memory management and should never + // happen. + FML_LOG(ERROR) << "Tried to terminate an unregistered shell holder."; + FML_DCHECK(false); + + return; + } + + // We may launch multiple shells in this component. However, we will + // terminate when the last shell goes away. The error code returned to the + // component controller will be the last isolate that had an error. + auto return_code = shell_holder->GetEngineReturnCode(); + if (return_code.has_value()) { + last_return_code_ = {true, return_code.value()}; + } else { + FML_LOG(ERROR) << "Failed to get return code from terminated shell holder."; + } + + shell_holders_.erase(found); + + if (shell_holders_.empty()) { + FML_VLOG(1) << "Killing component because all shell holders have been " + "terminated."; + Kill(); + // WARNING: Don't do anything past this point because the delegate may have + // collected this instance via the termination callback. + } +} + +void ComponentV2::CreateView2(fuchsia::ui::app::CreateView2Args view_args) { + if (!svc_) { + FML_LOG(ERROR) + << "Component incoming services was invalid when attempting to " + "create a shell for a view provider request."; + return; + } + + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ZX_ASSERT(status == ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + auto view_ref_pair = + std::make_pair(std::move(view_ref_control), std::move(view_ref)); + + shell_holders_.emplace(std::make_unique( + *this, // delegate + debug_label_, // thread label + svc_, // Component incoming services + runner_incoming_services_, // Runner incoming services + settings_, // settings + std::move( + *view_args.mutable_view_creation_token()), // view creation token + std::move(view_ref_pair), // view ref pair + std::move(fdio_ns_), // FDIO namespace + std::move(directory_request_), // outgoing request + product_config_, // product configuration + std::vector() // dart entrypoint args + )); +} + +#if !defined(DART_PRODUCT) +void ComponentV2::WriteProfileToTrace() const { + for (const auto& engine : shell_holders_) { + engine->WriteProfileToTrace(); + } +} +#endif // !defined(DART_PRODUCT) + +void ComponentV2::handle_unknown_method(uint64_t ordinal, + bool method_has_response) { + FML_LOG(ERROR) << "Unknown method called on ComponentV2. Ordinal: " + << ordinal; +} + +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/component_v2.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/component_v2.h new file mode 100644 index 0000000000000000000000000000000000000000..2892bbc659066094ef54eb15c79a95e2709b8295 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/component_v2.h @@ -0,0 +1,153 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_COMPONENT_V2_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_COMPONENT_V2_H_ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "flutter/common/settings.h" +#include "flutter/fml/macros.h" + +#include "engine.h" +#include "flutter_runner_product_configuration.h" +#include "program_metadata.h" +#include "unique_fdio_ns.h" + +namespace flutter_runner { + +class ComponentV2; + +struct ActiveComponentV2 { + std::unique_ptr platform_thread; + std::unique_ptr component; + + ActiveComponentV2& operator=(ActiveComponentV2&& other) noexcept { + if (this != &other) { + this->platform_thread.reset(other.platform_thread.release()); + this->component.reset(other.component.release()); + } + return *this; + } + + ~ActiveComponentV2() = default; +}; + +// Represents an instance of a CF v2 Flutter component that contains one or more +// Flutter engine instances. +// +// TODO(fxb/50694): Add unit tests once we've verified that the current behavior +// is working correctly. +class ComponentV2 final + : public Engine::Delegate, + public fuchsia::component::runner::ComponentController, + public fuchsia::ui::app::ViewProvider { + public: + using TerminationCallback = fit::function; + + // Creates a dedicated thread to run the component and creates the + // component on it. The component can be accessed only on this thread. + // This is a synchronous operation. + static ActiveComponentV2 Create( + TerminationCallback termination_callback, + fuchsia::component::runner::ComponentStartInfo start_info, + std::shared_ptr runner_incoming_services, + fidl::InterfaceRequest + controller); + + // Must be called on the same thread returned from the create call. The thread + // may be collected after. + ~ComponentV2(); + + /// Parses the program metadata that was provided for the component. + /// + /// |old_gen_heap_size| will be set to -1 if no value was specified. + static ProgramMetadata ParseProgramMetadata( + const fuchsia::data::Dictionary& program_metadata); + + const std::string& GetDebugLabel() const; + +#if !defined(DART_PRODUCT) + void WriteProfileToTrace() const; +#endif // !defined(DART_PRODUCT) + + void handle_unknown_method(uint64_t ordinal, + bool method_has_response) override; + + private: + ComponentV2( + TerminationCallback termination_callback, + fuchsia::component::runner::ComponentStartInfo start_info, + std::shared_ptr runner_incoming_services, + fidl::InterfaceRequest + controller); + + // |fuchsia::component::runner::ComponentController| + void Kill() override; + + /// Helper to actually |Kill| the component, closing the connection via an + /// epitaph with the given |epitaph_status|. Call this instead of + /// Kill() in the implementation of this class, as |Kill| is only intended for + /// clients of the ComponentController protocol to call. + /// + /// To determine what |epitaph_status| is appropriate for your situation, + /// see the documentation for |fuchsia.component.runner.ComponentController|. + void KillWithEpitaph(zx_status_t epitaph_status); + + // |fuchsia::component::runner::ComponentController| + void Stop() override; + + // |fuchsia::ui::app::ViewProvider| + void CreateView2(fuchsia::ui::app::CreateView2Args view_args) override; + void CreateViewWithViewRef( + ::zx::eventpair token, + ::fuchsia::ui::views::ViewRefControl view_ref_control, + ::fuchsia::ui::views::ViewRef view_ref) override {} + + // |flutter::Engine::Delegate| + void OnEngineTerminate(const Engine* holder) override; + + flutter::Settings settings_; + FlutterRunnerProductConfiguration product_config_; + TerminationCallback termination_callback_; + const std::string debug_label_; + UniqueFDIONS fdio_ns_ = UniqueFDIONSCreate(); + fml::UniqueFD component_data_directory_; + fml::UniqueFD component_assets_directory_; + + fidl::Binding + component_controller_; + fuchsia::io::DirectoryPtr directory_ptr_; + fuchsia::io::NodePtr cloned_directory_ptr_; + fidl::InterfaceRequest directory_request_; + std::unique_ptr outgoing_dir_; + std::unique_ptr runtime_dir_; + std::shared_ptr svc_; + std::shared_ptr runner_incoming_services_; + fidl::BindingSet shells_bindings_; + + fml::RefPtr isolate_snapshot_; + std::set> shell_holders_; + std::pair last_return_code_; + fml::WeakPtrFactory weak_factory_; // Must be the last member. + FML_DISALLOW_COPY_AND_ASSIGN(ComponentV2); +}; + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_COMPONENT_V2_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/component_v2_unittest.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/component_v2_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..34c803e7357fb35264ec8191d2bfb0b6a5a575df --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/component_v2_unittest.cc @@ -0,0 +1,180 @@ +// 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 "component_v2.h" + +#include +#include + +namespace flutter_runner { +namespace { + +TEST(ComponentV2, ParseProgramMetadataDefaultAssets) { + // The assets_path defaults to the "data" value if unspecified. + std::vector entries; + + fuchsia::data::DictionaryEntry data_entry; + data_entry.key = "data"; + data_entry.value = std::make_unique( + fuchsia::data::DictionaryValue::WithStr("foobar")); + entries.push_back(std::move(data_entry)); + + fuchsia::data::Dictionary program_metadata; + program_metadata.set_entries(std::move(entries)); + + ProgramMetadata result = ComponentV2::ParseProgramMetadata(program_metadata); + + EXPECT_EQ(result.data_path, "pkg/foobar"); + EXPECT_EQ(result.assets_path, "pkg/foobar"); + EXPECT_EQ(result.old_gen_heap_size, std::nullopt); +} + +TEST(ComponentV2, ParseProgramMetadataIgnoreInvalidKeys) { + // Invalid keys are ignored. + std::vector entries; + + fuchsia::data::DictionaryEntry not_data_entry; + not_data_entry.key = "not_data"; + not_data_entry.value = std::make_unique( + fuchsia::data::DictionaryValue::WithStr("foo")); + entries.push_back(std::move(not_data_entry)); + + fuchsia::data::DictionaryEntry data_entry; + data_entry.key = "data"; + data_entry.value = std::make_unique( + fuchsia::data::DictionaryValue::WithStr("bar")); + entries.push_back(std::move(data_entry)); + + fuchsia::data::DictionaryEntry assets_entry; + assets_entry.key = "assets"; + assets_entry.value = std::make_unique( + fuchsia::data::DictionaryValue::WithStr("baz")); + entries.push_back(std::move(assets_entry)); + + fuchsia::data::Dictionary program_metadata; + program_metadata.set_entries(std::move(entries)); + + ProgramMetadata result = ComponentV2::ParseProgramMetadata(program_metadata); + + EXPECT_EQ(result.data_path, "pkg/bar"); + EXPECT_EQ(result.assets_path, "pkg/baz"); + EXPECT_EQ(result.old_gen_heap_size, std::nullopt); +} + +TEST(ComponentV2, ParseProgramMetadataOldGenHeapSize) { + // The old_gen_heap_size can be specified. + std::vector entries; + + fuchsia::data::DictionaryEntry args_entry; + args_entry.key = "args"; + args_entry.value = std::make_unique( + fuchsia::data::DictionaryValue::WithStrVec({"--old_gen_heap_size=100"})); + entries.push_back(std::move(args_entry)); + + fuchsia::data::Dictionary program_metadata; + program_metadata.set_entries(std::move(entries)); + + ProgramMetadata result = ComponentV2::ParseProgramMetadata(program_metadata); + + EXPECT_EQ(result.data_path, ""); + EXPECT_EQ(result.assets_path, ""); + EXPECT_EQ(result.old_gen_heap_size, 100); +} + +TEST(ComponentV2, ParseProgramMetadataOldGenHeapSizeInvalid) { + // Invalid old_gen_heap_sizes should be ignored. + std::vector entries; + + fuchsia::data::DictionaryEntry args_entry; + args_entry.key = "args"; + args_entry.value = std::make_unique( + fuchsia::data::DictionaryValue::WithStrVec( + {"--old_gen_heap_size=asdf100"})); + entries.push_back(std::move(args_entry)); + + fuchsia::data::Dictionary program_metadata; + program_metadata.set_entries(std::move(entries)); + + ProgramMetadata result = ComponentV2::ParseProgramMetadata(program_metadata); + + EXPECT_EQ(result.data_path, ""); + EXPECT_EQ(result.assets_path, ""); + EXPECT_EQ(result.old_gen_heap_size, std::nullopt); +} + +TEST(ComponentV2, ParseProgramMetadataNoExposeDirs) { + // Should always have a valid expose_dirs entry + std::vector entries; + + fuchsia::data::Dictionary program_metadata; + program_metadata.set_entries(std::move(entries)); + + ProgramMetadata result = ComponentV2::ParseProgramMetadata(program_metadata); + + EXPECT_EQ(result.expose_dirs.empty(), true); +} + +TEST(ComponentV2, ParseProgramMetadataWithSingleExposeDirs) { + // Can parse a single exposed dir + std::vector entries; + + fuchsia::data::DictionaryEntry args_entry; + args_entry.key = "args"; + args_entry.value = std::make_unique( + fuchsia::data::DictionaryValue::WithStrVec({"--expose_dirs=foo"})); + entries.push_back(std::move(args_entry)); + + fuchsia::data::Dictionary program_metadata; + program_metadata.set_entries(std::move(entries)); + + ProgramMetadata result = ComponentV2::ParseProgramMetadata(program_metadata); + + ASSERT_EQ(result.expose_dirs.size(), 1u); + EXPECT_EQ(result.expose_dirs[0], "foo"); +} + +TEST(ComponentV2, ParseProgramMetadataWithMultipleExposeDirs) { + // Can parse a multiple exposed dirs + std::vector entries; + + fuchsia::data::DictionaryEntry args_entry; + args_entry.key = "args"; + args_entry.value = std::make_unique( + fuchsia::data::DictionaryValue::WithStrVec( + {"--expose_dirs=foo,bar,baz"})); + entries.push_back(std::move(args_entry)); + + fuchsia::data::Dictionary program_metadata; + program_metadata.set_entries(std::move(entries)); + + ProgramMetadata result = ComponentV2::ParseProgramMetadata(program_metadata); + + ASSERT_EQ(result.expose_dirs.size(), 3u); + EXPECT_EQ(result.expose_dirs[0], "foo"); + EXPECT_EQ(result.expose_dirs[1], "bar"); + EXPECT_EQ(result.expose_dirs[2], "baz"); +} + +TEST(ComponentV2, ParseProgramMetadataWithSingleExposeDirsAndOtherArgs) { + // Can parse a single exposed dir when other args are present + std::vector entries; + + fuchsia::data::DictionaryEntry args_entry; + args_entry.key = "args"; + args_entry.value = std::make_unique( + fuchsia::data::DictionaryValue::WithStrVec( + {"--expose_dirs=foo", "--foo=bar"})); + entries.push_back(std::move(args_entry)); + + fuchsia::data::Dictionary program_metadata; + program_metadata.set_entries(std::move(entries)); + + ProgramMetadata result = ComponentV2::ParseProgramMetadata(program_metadata); + + ASSERT_EQ(result.expose_dirs.size(), 1u); + EXPECT_EQ(result.expose_dirs[0], "foo"); +} + +} // anonymous namespace +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/engine.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/engine.cc new file mode 100644 index 0000000000000000000000000000000000000000..17678f222b566f2d685e0ec2154dad41ad9b86b4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/engine.cc @@ -0,0 +1,988 @@ +// 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 "engine.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "flutter/common/graphics/persistent_cache.h" +#include "flutter/common/task_runners.h" +#include "flutter/fml/make_copyable.h" +#include "flutter/fml/message_loop.h" +#include "flutter/fml/synchronization/waitable_event.h" +#include "flutter/fml/task_runner.h" +#include "flutter/runtime/dart_vm_lifecycle.h" +#include "flutter/shell/common/rasterizer.h" +#include "flutter/shell/common/run_configuration.h" +#include "flutter/shell/common/serialization_callbacks.h" +#include "flutter/shell/common/thread_host.h" +#include "third_party/skia/include/core/SkPicture.h" +#include "third_party/skia/include/core/SkSerialProcs.h" +#include "third_party/skia/include/gpu/ganesh/GrTypes.h" +#include "third_party/skia/include/ports/SkFontMgr_fuchsia.h" + +#include "../runtime/dart/utils/files.h" +#include "../runtime/dart/utils/root_inspect_node.h" +#include "focus_delegate.h" +#include "fuchsia_intl.h" +#include "platform_view.h" +#include "software_surface_producer.h" +#include "surface.h" +#include "vsync_waiter.h" +#include "vulkan_surface_producer.h" + +namespace flutter_runner { +namespace { +constexpr static int64_t kImplicitViewId = 0; + +zx_koid_t GetKoid(const fuchsia::ui::views::ViewRef& view_ref) { + zx_handle_t handle = view_ref.reference.get(); + zx_info_handle_basic_t info; + zx_status_t status = zx_object_get_info(handle, ZX_INFO_HANDLE_BASIC, &info, + sizeof(info), nullptr, nullptr); + return status == ZX_OK ? info.koid : ZX_KOID_INVALID; +} + +std::unique_ptr MakeLocalizationPlatformMessage( + const fuchsia::intl::Profile& intl_profile) { + return std::make_unique( + "flutter/localization", MakeLocalizationPlatformMessageData(intl_profile), + nullptr); +} + +// +// Fuchsia scheduler role naming scheme employed here: +// +// Roles based on thread function: +// .type.{platform,ui,raster,io,profiler} +// +// Roles based on fml::Thread::ThreadPriority: +// .thread.{background,display,raster,normal} +// + +void SetThreadRole( + const fuchsia::media::ProfileProviderSyncPtr& profile_provider, + const std::string& role) { + ZX_ASSERT(profile_provider); + + zx::thread dup; + const zx_status_t dup_status = + zx::thread::self()->duplicate(ZX_RIGHT_SAME_RIGHTS, &dup); + if (dup_status != ZX_OK) { + FML_LOG(WARNING) + << "Failed to duplicate thread handle when setting thread config: " + << zx_status_get_string(dup_status) + << ". Thread will run at default priority."; + return; + } + + int64_t unused_period; + int64_t unused_capacity; + const zx_status_t status = profile_provider->RegisterHandlerWithCapacity( + std::move(dup), role, 0, 0.f, &unused_period, &unused_capacity); + if (status != ZX_OK) { + FML_LOG(WARNING) << "Failed to set thread role to \"" << role + << "\": " << zx_status_get_string(status) + << ". Thread will run at default priority."; + return; + } +} + +void SetThreadConfig( + const std::string& name_prefix, + const fuchsia::media::ProfileProviderSyncPtr& profile_provider, + const fml::Thread::ThreadConfig& config) { + ZX_ASSERT(profile_provider); + + fml::Thread::SetCurrentThreadName(config); + + // Derive the role name from the prefix and priority. See comment above about + // the role naming scheme. + std::string role; + switch (config.priority) { + case fml::Thread::ThreadPriority::kBackground: + role = name_prefix + ".thread.background"; + break; + case fml::Thread::ThreadPriority::kDisplay: + role = name_prefix + ".thread.display"; + break; + case fml::Thread::ThreadPriority::kRaster: + role = name_prefix + ".thread.raster"; + break; + case fml::Thread::ThreadPriority::kNormal: + role = name_prefix + ".thread.normal"; + break; + default: + FML_LOG(WARNING) << "Unknown thread priority " + << static_cast(config.priority) + << ". Thread will run at default priority."; + return; + } + ZX_ASSERT(!role.empty()); + + SetThreadRole(profile_provider, role); +} + +} // namespace + +flutter::ThreadHost Engine::CreateThreadHost( + const std::string& name_prefix, + const std::shared_ptr& services) { + fml::Thread::SetCurrentThreadName( + fml::Thread::ThreadConfig(name_prefix + ".platform")); + + // Default the config setter to setup the thread name only. + flutter::ThreadConfigSetter config_setter = fml::Thread::SetCurrentThreadName; + + // Override the config setter if the media profile provider is available. + if (services) { + // Connect to the media profile provider to assign thread priorities using + // Fuchsia's scheduler role API. Failure to connect will print a warning and + // proceed with engine initialization, leaving threads created by the engine + // at default priority. + // + // The use of std::shared_ptr here is to work around the unfortunate + // requirement for flutter::ThreadConfigSetter (i.e. std::function<>) that + // the target callable be copy-constructible. This awkwardly conflicts with + // fuchsia::media::ProfileProviderSyncPtr being move-only. std::shared_ptr + // provides copyable object that references the move-only SyncPtr. + std::shared_ptr + media_profile_provider = + std::make_shared(); + + const zx_status_t connect_status = + services->Connect(media_profile_provider->NewRequest()); + if (connect_status != ZX_OK) { + FML_LOG(WARNING) + << "Failed to connect to " << fuchsia::media::ProfileProvider::Name_ + << ": " << zx_status_get_string(connect_status) + << " This is not a fatal error, but threads created by the engine " + "will run at default priority, regardless of the requested " + "priority."; + } else { + // Set the role for (this) platform thread. See comment above about the + // role naming scheme. + SetThreadRole(*media_profile_provider, name_prefix + ".type.platform"); + + // This lambda must be copyable or the assignment fails to compile, + // necessitating the use of std::shared_ptr for the profile provider. + config_setter = [name_prefix, media_profile_provider]( + const fml::Thread::ThreadConfig& config) { + SetThreadConfig(name_prefix, *media_profile_provider, config); + }; + } + } + + flutter::ThreadHost::ThreadHostConfig thread_host_config{config_setter}; + + thread_host_config.SetRasterConfig( + {flutter::ThreadHost::ThreadHostConfig::MakeThreadName( + flutter::ThreadHost::Type::kRaster, name_prefix), + fml::Thread::ThreadPriority::kRaster}); + thread_host_config.SetUIConfig( + {flutter::ThreadHost::ThreadHostConfig::MakeThreadName( + flutter::ThreadHost::Type::kUi, name_prefix), + fml::Thread::ThreadPriority::kDisplay}); + thread_host_config.SetIOConfig( + {flutter::ThreadHost::ThreadHostConfig::MakeThreadName( + flutter::ThreadHost::Type::kIo, name_prefix), + fml::Thread::ThreadPriority::kNormal}); + + return flutter::ThreadHost(thread_host_config); +} + +Engine::Engine(Delegate& delegate, + std::string thread_label, + std::shared_ptr svc, + std::shared_ptr runner_services, + flutter::Settings settings, + fuchsia::ui::views::ViewCreationToken view_creation_token, + std::pair view_ref_pair, + UniqueFDIONS fdio_ns, + fidl::InterfaceRequest directory_request, + FlutterRunnerProductConfiguration product_config, + const std::vector& dart_entrypoint_args) + : delegate_(delegate), + thread_label_(std::move(thread_label)), + thread_host_(CreateThreadHost(thread_label_, runner_services)), + view_creation_token_(std::move(view_creation_token)), + memory_pressure_watcher_binding_(this), + latest_memory_pressure_level_(fuchsia::memorypressure::Level::NORMAL), + intercept_all_input_(product_config.get_intercept_all_input()), + weak_factory_(this) { + Initialize(std::move(view_ref_pair), std::move(svc), + std::move(runner_services), std::move(settings), + std::move(fdio_ns), std::move(directory_request), + std::move(product_config), dart_entrypoint_args); +} + +void Engine::Initialize( + std::pair + view_ref_pair, + std::shared_ptr svc, + std::shared_ptr runner_services, + flutter::Settings settings, + UniqueFDIONS fdio_ns, + fidl::InterfaceRequest directory_request, + FlutterRunnerProductConfiguration product_config, + const std::vector& dart_entrypoint_args) { + // Flatland uses |view_creation_token_| for linking. + FML_CHECK(view_creation_token_.value.is_valid()); + + // Get the task runners from the managed threads. The current thread will be + // used as the "platform" thread. + fml::RefPtr platform_task_runner = + fml::MessageLoop::GetCurrent().GetTaskRunner(); + + const flutter::TaskRunners task_runners( + thread_label_, // Dart thread labels + platform_task_runner, // platform + thread_host_.raster_thread->GetTaskRunner(), // raster + thread_host_.ui_thread->GetTaskRunner(), // ui + thread_host_.io_thread->GetTaskRunner() // io + ); + + fuchsia::ui::views::FocuserHandle focuser; + fuchsia::ui::views::ViewRefFocusedHandle view_ref_focused; + fuchsia::ui::pointer::TouchSourceHandle touch_source; + fuchsia::ui::pointer::MouseSourceHandle mouse_source; + + fuchsia::ui::composition::ViewBoundProtocols view_protocols; + view_protocols.set_view_focuser(focuser.NewRequest()); + view_protocols.set_view_ref_focused(view_ref_focused.NewRequest()); + view_protocols.set_touch_source(touch_source.NewRequest()); + view_protocols.set_mouse_source(mouse_source.NewRequest()); + + // Connect to Flatland. + fuchsia::ui::composition::FlatlandHandle flatland; + zx_status_t flatland_status = + runner_services->Connect( + flatland.NewRequest()); + if (flatland_status != ZX_OK) { + FML_LOG(WARNING) << "fuchsia::ui::composition::Flatland connection failed: " + << zx_status_get_string(flatland_status); + } + + // Connect to SemanticsManager service. + fuchsia::accessibility::semantics::SemanticsManagerHandle semantics_manager; + zx_status_t semantics_status = + runner_services + ->Connect( + semantics_manager.NewRequest()); + if (semantics_status != ZX_OK) { + FML_LOG(WARNING) + << "fuchsia::accessibility::semantics::SemanticsManager connection " + "failed: " + << zx_status_get_string(semantics_status); + } + + // Connect to ImeService service. + fuchsia::ui::input::ImeServiceHandle ime_service; + zx_status_t ime_status = + runner_services->Connect( + ime_service.NewRequest()); + if (ime_status != ZX_OK) { + FML_LOG(WARNING) << "fuchsia::ui::input::ImeService connection failed: " + << zx_status_get_string(ime_status); + } + + // Connect to Keyboard service. + fuchsia::ui::input3::KeyboardHandle keyboard; + zx_status_t keyboard_status = + runner_services->Connect( + keyboard.NewRequest()); + FML_DCHECK(keyboard_status == ZX_OK) + << "fuchsia::ui::input3::Keyboard connection failed: " + << zx_status_get_string(keyboard_status); + + // Connect to Pointerinjector service. + fuchsia::ui::pointerinjector::RegistryHandle pointerinjector_registry; + zx_status_t pointerinjector_registry_status = + runner_services->Connect( + pointerinjector_registry.NewRequest()); + if (pointerinjector_registry_status != ZX_OK) { + FML_LOG(WARNING) + << "fuchsia::ui::pointerinjector::Registry connection failed: " + << zx_status_get_string(pointerinjector_registry_status); + } + + // Make clones of the `ViewRef` before sending it to various places. + fuchsia::ui::views::ViewRef platform_view_ref; + view_ref_pair.second.Clone(&platform_view_ref); + fuchsia::ui::views::ViewRef accessibility_view_ref; + view_ref_pair.second.Clone(&accessibility_view_ref); + fuchsia::ui::views::ViewRef isolate_view_ref; + view_ref_pair.second.Clone(&isolate_view_ref); + + // Session is terminated on the raster thread, but we must terminate ourselves + // on the platform thread. + // + // This handles the fidl error callback when the Session connection is + // broken. The SessionListener interface also has an OnError method, which is + // invoked on the platform thread (in PlatformView). + fml::closure session_error_callback = [task_runner = platform_task_runner, + weak = weak_factory_.GetWeakPtr()]() { + task_runner->PostTask([weak]() { + if (weak) { + FML_LOG(ERROR) << "Terminating from session_error_callback"; + weak->Terminate(); + } + }); + }; + + // Set up the session connection and other Scenic helpers on the raster + // thread. We also need to wait for the external view embedder to be set up + // before creating the shell. + fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher; + fml::AutoResetWaitableEvent view_embedder_latch; + auto session_inspect_node = + dart_utils::RootInspectNode::CreateRootChild("vsync_stats"); + task_runners.GetRasterTaskRunner()->PostTask(fml::MakeCopyable( + [this, &view_embedder_latch, + session_inspect_node = std::move(session_inspect_node), + flatland = std::move(flatland), + session_error_callback = std::move(session_error_callback), + view_creation_token = std::move(view_creation_token_), + view_protocols = std::move(view_protocols), + request = parent_viewport_watcher.NewRequest(), + view_ref_pair = std::move(view_ref_pair), + software_rendering = product_config.software_rendering()]() mutable { + if (software_rendering) { + surface_producer_ = std::make_shared(); + } else { + surface_producer_ = std::make_shared(); + } + + flatland_connection_ = std::make_shared( + thread_label_, std::move(flatland), + std::move(session_error_callback), [](auto) {}); + + fuchsia::ui::views::ViewIdentityOnCreation view_identity = { + .view_ref = std::move(view_ref_pair.second), + .view_ref_control = std::move(view_ref_pair.first)}; + view_embedder_ = std::make_shared( + std::move(view_creation_token), std::move(view_identity), + std::move(view_protocols), std::move(request), flatland_connection_, + surface_producer_, intercept_all_input_); + + view_embedder_latch.Signal(); + })); + view_embedder_latch.Wait(); + + AccessibilityBridge::SetSemanticsEnabledCallback + set_semantics_enabled_callback = [this](bool enabled) { + auto platform_view = shell_->GetPlatformView(); + + if (platform_view) { + platform_view->SetSemanticsEnabled(enabled); + } + }; + + AccessibilityBridge::DispatchSemanticsActionCallback + dispatch_semantics_action_callback = + [this](int32_t node_id, flutter::SemanticsAction action) { + auto platform_view = shell_->GetPlatformView(); + + if (platform_view) { + // TODO(fuchsia): Remove implicit view assumption. + // https://github.com/flutter/flutter/issues/142845 + platform_view->DispatchSemanticsAction(kImplicitViewId, node_id, + action, {}); + } + }; + + const std::string accessibility_inspect_name = + std::to_string(GetKoid(accessibility_view_ref)); + accessibility_bridge_ = std::make_unique( + std::move(set_semantics_enabled_callback), + std::move(dispatch_semantics_action_callback), + std::move(semantics_manager), std::move(accessibility_view_ref), + dart_utils::RootInspectNode::CreateRootChild( + std::move(accessibility_inspect_name))); + + OnEnableWireframeCallback on_enable_wireframe_callback = std::bind( + &Engine::DebugWireframeSettingsChanged, this, std::placeholders::_1); + + OnCreateViewCallback on_create_view_callback = std::bind( + &Engine::CreateView, this, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3, std::placeholders::_4, std::placeholders::_5); + + OnUpdateViewCallback on_update_view_callback = std::bind( + &Engine::UpdateView, this, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3, std::placeholders::_4); + + OnDestroyViewCallback on_destroy_view_callback = std::bind( + &Engine::DestroyView, this, std::placeholders::_1, std::placeholders::_2); + + OnCreateSurfaceCallback on_create_surface_callback = + std::bind(&Engine::CreateSurface, this); + + // SessionListener has a OnScenicError method; invoke this callback on the + // platform thread when that happens. The Session itself should also be + // disconnected when this happens, and it will also attempt to terminate. + fit::closure on_session_listener_error_callback = + [task_runner = platform_task_runner, + weak = weak_factory_.GetWeakPtr()]() { + task_runner->PostTask([weak]() { + if (weak) { + FML_LOG(ERROR) << "Terminating from " + "on_session_listener_error_callback"; + weak->Terminate(); + } + }); + }; + + // Launch the engine in the appropriate configuration. + // Note: this initializes the Asset Manager on the global PersistantCache + // so it must be called before WarmupSkps() is called below. + auto run_configuration = flutter::RunConfiguration::InferFromSettings( + settings, task_runners.GetIOTaskRunner()); + run_configuration.SetEntrypointArgs(std::move(dart_entrypoint_args)); + + OnSemanticsNodeUpdateCallback on_semantics_node_update_callback = + [this](flutter::SemanticsNodeUpdates updates, float pixel_ratio) { + accessibility_bridge_->AddSemanticsNodeUpdate(updates, pixel_ratio); + }; + + OnRequestAnnounceCallback on_request_announce_callback = + [this](const std::string& message) { + accessibility_bridge_->RequestAnnounce(message); + }; + + // Setup the callback that will instantiate the platform view. + flutter::Shell::CreateCallback + on_create_platform_view = fml::MakeCopyable( + [this, view_ref = std::move(platform_view_ref), + parent_viewport_watcher = std::move(parent_viewport_watcher), + ime_service = std::move(ime_service), keyboard = std::move(keyboard), + focuser = std::move(focuser), + view_ref_focused = std::move(view_ref_focused), + touch_source = std::move(touch_source), + mouse_source = std::move(mouse_source), + pointerinjector_registry = std::move(pointerinjector_registry), + on_session_listener_error_callback = + std::move(on_session_listener_error_callback), + on_enable_wireframe_callback = + std::move(on_enable_wireframe_callback), + on_create_view_callback = std::move(on_create_view_callback), + on_update_view_callback = std::move(on_update_view_callback), + on_destroy_view_callback = std::move(on_destroy_view_callback), + on_create_surface_callback = std::move(on_create_surface_callback), + on_semantics_node_update_callback = + std::move(on_semantics_node_update_callback), + on_request_announce_callback = + std::move(on_request_announce_callback), + external_view_embedder = GetExternalViewEmbedder(), + await_vsync_callback = + [this](FireCallbackCallback cb) { + flatland_connection_->AwaitVsync(cb); + }, + await_vsync_for_secondary_callback_callback = + [this](FireCallbackCallback cb) { + flatland_connection_->AwaitVsyncForSecondaryCallback(cb); + }, + product_config, svc](flutter::Shell& shell) mutable { + OnShaderWarmupCallback on_shader_warmup_callback = nullptr; + if (product_config.enable_shader_warmup()) { + FML_DCHECK(surface_producer_); + if (product_config.enable_shader_warmup_dart_hooks()) { + on_shader_warmup_callback = + [this, &shell]( + const std::vector& skp_names, + std::function completion_callback, + uint64_t width, uint64_t height) { + WarmupSkps( + shell.GetDartVM() + ->GetConcurrentMessageLoop() + ->GetTaskRunner() + .get(), + shell.GetTaskRunners().GetRasterTaskRunner().get(), + surface_producer_, SkISize::Make(width, height), + flutter::PersistentCache::GetCacheForProcess() + ->asset_manager(), + skp_names, completion_callback); + }; + } else { + WarmupSkps(shell.GetDartVM() + ->GetConcurrentMessageLoop() + ->GetTaskRunner() + .get(), + shell.GetTaskRunners().GetRasterTaskRunner().get(), + surface_producer_, SkISize::Make(1024, 600), + flutter::PersistentCache::GetCacheForProcess() + ->asset_manager(), + std::nullopt, std::nullopt); + } + } + + return std::make_unique( + shell, shell.GetTaskRunners(), std::move(view_ref), + std::move(external_view_embedder), std::move(ime_service), + std::move(keyboard), std::move(touch_source), + std::move(mouse_source), std::move(focuser), + std::move(view_ref_focused), std::move(parent_viewport_watcher), + std::move(pointerinjector_registry), + std::move(on_enable_wireframe_callback), + std::move(on_create_view_callback), + std::move(on_update_view_callback), + std::move(on_destroy_view_callback), + std::move(on_create_surface_callback), + std::move(on_semantics_node_update_callback), + std::move(on_request_announce_callback), + std::move(on_shader_warmup_callback), + std::move(await_vsync_callback), + std::move(await_vsync_for_secondary_callback_callback), + std::move(svc)); + }); + + // Setup the callback that will instantiate the rasterizer. + flutter::Shell::CreateCallback on_create_rasterizer = + [](flutter::Shell& shell) { + return std::make_unique(shell); + }; + + settings.root_isolate_create_callback = + std::bind(&Engine::OnMainIsolateStart, this); + settings.root_isolate_shutdown_callback = + std::bind([weak = weak_factory_.GetWeakPtr(), + runner = task_runners.GetPlatformTaskRunner()]() { + runner->PostTask([weak = std::move(weak)] { + if (weak) { + weak->OnMainIsolateShutdown(); + } + }); + }); + + // Connect and set up the system font provider. + fuchsia::fonts::ProviderSyncPtr sync_font_provider; + runner_services->Connect(sync_font_provider.NewRequest()); + settings.font_initialization_data = + sync_font_provider.Unbind().TakeChannel().release(); + + { + TRACE_EVENT0("flutter", "CreateShell"); + shell_ = flutter::Shell::Create( + flutter::PlatformData(), // default window data + std::move(task_runners), // host task runners + std::move(settings), // shell launch settings + std::move(on_create_platform_view), // platform view create callback + std::move(on_create_rasterizer) // rasterizer create callback + ); + } + + if (!shell_) { + FML_LOG(ERROR) << "Could not launch the shell."; + return; + } + + // Shell has been created. Before we run the engine, set up the isolate + // configurator. + isolate_configurator_ = std::make_unique( + std::move(fdio_ns), directory_request.TakeChannel(), + std::move(isolate_view_ref.reference)); + + // This platform does not get a separate surface platform view creation + // notification. Fire one eagerly. + shell_->GetPlatformView()->NotifyCreated(); + + // Connect to the memory pressure provider. If the connection fails, the + // initialization of the engine will simply proceed, printing a warning + // message. The engine will be fully functional, except that the Flutter + // shell will not be notified when memory is low. + { + memory_pressure_provider_.set_error_handler([](zx_status_t status) { + FML_LOG(WARNING) + << "Failed to connect to " << fuchsia::memorypressure::Provider::Name_ + << ": " << zx_status_get_string(status) + << " This is not a fatal error, but the heap will not be " + << " compacted when memory is low."; + }); + + // Note that we're using the runner's services, not the component's. + // The Flutter Shell should be notified when memory is low regardless of + // whether the component has direct access to the + // fuchsia.memorypressure.Provider service. + ZX_ASSERT(runner_services->Connect( + memory_pressure_provider_.NewRequest()) == ZX_OK); + + FML_VLOG(1) << "Registering memorypressure watcher"; + + // Register for changes, which will make the request for the initial + // memory level. + memory_pressure_provider_->RegisterWatcher( + memory_pressure_watcher_binding_.NewBinding()); + } + + // Connect to the intl property provider. If the connection fails, the + // initialization of the engine will simply proceed, printing a warning + // message. The engine will be fully functional, except that the user's + // locale preferences would not be communicated to flutter engine. + { + intl_property_provider_.set_error_handler([](zx_status_t status) { + FML_LOG(WARNING) << "Failed to connect to " + << fuchsia::intl::PropertyProvider::Name_ << ": " + << zx_status_get_string(status) + << " This is not a fatal error, but the user locale " + << " preferences will not be forwarded to flutter apps"; + }); + + // Note that we're using the runner's services, not the component's. + // Flutter locales should be updated regardless of whether the component has + // direct access to the fuchsia.intl.PropertyProvider service. + ZX_ASSERT(runner_services->Connect(intl_property_provider_.NewRequest()) == + ZX_OK); + + auto get_profile_callback = [weak = weak_factory_.GetWeakPtr()]( + const fuchsia::intl::Profile& profile) { + if (!weak) { + return; + } + if (!profile.has_locales()) { + FML_LOG(WARNING) << "Got intl Profile without locales"; + } + auto message = MakeLocalizationPlatformMessage(profile); + FML_VLOG(1) << "Sending LocalizationPlatformMessage"; + weak->shell_->GetPlatformView()->DispatchPlatformMessage( + std::move(message)); + }; + + FML_VLOG(1) << "Requesting intl Profile"; + + // Make the initial request + intl_property_provider_->GetProfile(get_profile_callback); + + // And register for changes + intl_property_provider_.events().OnChange = [this, runner_services, + get_profile_callback]() { + FML_VLOG(1) << fuchsia::intl::PropertyProvider::Name_ << ": OnChange"; + runner_services->Connect(intl_property_provider_.NewRequest()); + intl_property_provider_->GetProfile(get_profile_callback); + }; + } + + auto on_run_failure = [weak = weak_factory_.GetWeakPtr()]() { + // The engine could have been killed by the caller right after the + // constructor was called but before it could run on the UI thread. + if (weak) { + FML_LOG(ERROR) << "Terminating from on_run_failure"; + weak->Terminate(); + } + }; + + shell_->GetTaskRunners().GetUITaskRunner()->PostTask( + fml::MakeCopyable([engine = shell_->GetEngine(), // + run_configuration = std::move(run_configuration), // + on_run_failure // + ]() mutable { + if (!engine) { + return; + } + + if (engine->Run(std::move(run_configuration)) == + flutter::Engine::RunStatus::Failure) { + on_run_failure(); + } + })); +} + +Engine::~Engine() { + shell_.reset(); + + // Destroy rendering objects on the raster thread. + fml::AutoResetWaitableEvent view_embedder_latch; + thread_host_.raster_thread->GetTaskRunner()->PostTask( + fml::MakeCopyable([this, &view_embedder_latch]() mutable { + view_embedder_.reset(); + flatland_connection_.reset(); + surface_producer_.reset(); + view_embedder_latch.Signal(); + })); + view_embedder_latch.Wait(); +} + +std::optional Engine::GetEngineReturnCode() const { + if (!shell_) { + return std::nullopt; + } + std::optional code; + fml::AutoResetWaitableEvent latch; + fml::TaskRunner::RunNowOrPostTask( + shell_->GetTaskRunners().GetUITaskRunner(), + [&latch, &code, engine = shell_->GetEngine()]() { + if (engine) { + code = engine->GetUIIsolateReturnCode(); + } + latch.Signal(); + }); + latch.Wait(); + return code; +} + +void Engine::OnMainIsolateStart() { + if (!isolate_configurator_ || + !isolate_configurator_->ConfigureCurrentIsolate()) { + FML_LOG(ERROR) << "Could not configure some native embedder bindings for a " + "new root isolate."; + } +} + +void Engine::OnMainIsolateShutdown() { + Terminate(); +} + +void Engine::Terminate() { + delegate_.OnEngineTerminate(this); + // Warning. Do not do anything after this point as the delegate may have + // collected this object. +} + +void Engine::DebugWireframeSettingsChanged(bool enabled) { + FML_CHECK(shell_); + + shell_->GetTaskRunners().GetRasterTaskRunner()->PostTask([]() { + // TODO(fxbug.dev/116000): Investigate if we can add flatland wireframe code + // for debugging. + }); +} + +void Engine::CreateView(int64_t view_id, + ViewCallback on_view_created, + ViewCreatedCallback on_view_bound, + bool hit_testable, + bool focusable) { + FML_CHECK(shell_); + shell_->GetTaskRunners().GetRasterTaskRunner()->PostTask( + [this, view_id, hit_testable, focusable, + on_view_created = std::move(on_view_created), + on_view_bound = std::move(on_view_bound)]() { + FML_CHECK(view_embedder_); + view_embedder_->CreateView(view_id, std::move(on_view_created), + std::move(on_view_bound)); + view_embedder_->SetViewProperties(view_id, SkRect::MakeEmpty(), + hit_testable, focusable); + }); +} + +void Engine::UpdateView(int64_t view_id, + SkRect occlusion_hint, + bool hit_testable, + bool focusable) { + FML_CHECK(shell_); + shell_->GetTaskRunners().GetRasterTaskRunner()->PostTask( + [this, view_id, occlusion_hint, hit_testable, focusable]() { + FML_CHECK(view_embedder_); + view_embedder_->SetViewProperties(view_id, occlusion_hint, hit_testable, + focusable); + }); +} + +void Engine::DestroyView(int64_t view_id, ViewIdCallback on_view_unbound) { + FML_CHECK(shell_); + + shell_->GetTaskRunners().GetRasterTaskRunner()->PostTask( + [this, view_id, on_view_unbound = std::move(on_view_unbound)]() { + FML_CHECK(view_embedder_); + view_embedder_->DestroyView(view_id, std::move(on_view_unbound)); + }); +} + +std::unique_ptr Engine::CreateSurface() { + return std::make_unique(thread_label_, GetExternalViewEmbedder(), + surface_producer_->gr_context()); +} + +std::shared_ptr +Engine::GetExternalViewEmbedder() { + FML_CHECK(view_embedder_); + return view_embedder_; +} + +#if !defined(DART_PRODUCT) +void Engine::WriteProfileToTrace() const { + Dart_Port main_port = shell_->GetEngine()->GetUIIsolateMainPort(); + char* error = NULL; + bool success = Dart_WriteProfileToTimeline(main_port, &error); + if (!success) { + FML_LOG(ERROR) << "Failed to write Dart profile to trace: " << error; + free(error); + } +} +#endif // !defined(DART_PRODUCT) + +void Engine::WarmupSkps( + fml::BasicTaskRunner* concurrent_task_runner, + fml::BasicTaskRunner* raster_task_runner, + std::shared_ptr surface_producer, + SkISize size, + std::shared_ptr asset_manager, + std::optional> skp_names, + std::optional> maybe_completion_callback, + bool synchronous) { + // Wrap the optional validity checks up in a lambda to simplify the various + // callsites below + auto completion_callback = [maybe_completion_callback](uint32_t skp_count) { + if (maybe_completion_callback.has_value() && + maybe_completion_callback.value()) { + maybe_completion_callback.value()(skp_count); + } + }; + + // We use this bizzare raw pointer to a smart pointer thing here because we + // want to keep the surface alive until all gpu work is done and the + // callbacks skia takes for this are function pointers so we are unable to + // use a lambda that captures the smart pointer. We need two levels of + // indirection because it needs to be the same across all invocations of the + // raster task lambda from a single invocation of WarmupSkps, but be + // different across different invocations of WarmupSkps (so we cant + // statically initialialize it in the lambda itself). Basically the result + // of a mashup of wierd call dynamics, multithreading, and lifecycle + // management with C style Skia callbacks. + std::unique_ptr* skp_warmup_surface = + new std::unique_ptr(nullptr); + + // tell concurrent task runner to deserialize all skps available from + // the asset manager + concurrent_task_runner->PostTask([raster_task_runner, size, + skp_warmup_surface, surface_producer, + asset_manager, skp_names, + completion_callback, synchronous]() { + TRACE_DURATION("flutter", "DeserializeSkps"); + std::vector> skp_mappings; + if (skp_names) { + for (auto& skp_name : skp_names.value()) { + auto skp_mapping = asset_manager->GetAsMapping(skp_name); + if (skp_mapping) { + skp_mappings.push_back(std::move(skp_mapping)); + } else { + FML_LOG(ERROR) << "Failed to get mapping for " << skp_name; + } + } + } else { + skp_mappings = asset_manager->GetAsMappings(".*\\.skp$", "shaders"); + } + + if (skp_mappings.empty()) { + FML_LOG(WARNING) + << "Engine::WarmupSkps got zero SKP mappings, returning early"; + completion_callback(0); + return; + } + + size_t total_size = 0; + for (auto& mapping : skp_mappings) { + total_size += mapping->GetSize(); + } + + FML_LOG(INFO) << "Shader warmup got " << skp_mappings.size() + << " skp's with a total size of " << total_size << " bytes"; + + std::vector> pictures; + unsigned int i = 0; + for (auto& mapping : skp_mappings) { + std::unique_ptr stream = + SkMemoryStream::MakeDirect(mapping->GetMapping(), mapping->GetSize()); + SkDeserialProcs procs = {0}; + procs.fImageProc = flutter::DeserializeImageWithoutData; + procs.fTypefaceProc = flutter::DeserializeTypefaceWithoutData; + sk_sp picture = + SkPicture::MakeFromStream(stream.get(), &procs); + if (!picture) { + FML_LOG(ERROR) << "Failed to deserialize picture " << i; + continue; + } + + // Tell raster task runner to warmup have the compositor + // context warm up the newly deserialized picture + raster_task_runner->PostTask([picture, skp_warmup_surface, size, + surface_producer, completion_callback, i, + count = skp_mappings.size(), synchronous] { + TRACE_DURATION("flutter", "WarmupSkp"); + if (*skp_warmup_surface == nullptr) { + skp_warmup_surface->reset( + surface_producer->ProduceOffscreenSurface(size).release()); + + if (*skp_warmup_surface == nullptr) { + FML_LOG(ERROR) << "Failed to create offscreen warmup surface"; + // Tell client that zero shaders were warmed up because warmup + // failed. + completion_callback(0); + return; + } + } + + // Do the actual warmup + (*skp_warmup_surface) + ->GetSkiaSurface() + ->getCanvas() + ->drawPicture(picture); + + if (i == count - 1) { + // We call this here instead of inside fFinishedProc below because + // we want to unblock the dart animation code as soon as the + // raster thread is free to enque work, rather than waiting for + // the GPU work itself to finish. + completion_callback(count); + } + + if (surface_producer->gr_context()) { + if (i < count - 1) { + // For all but the last skp we fire and forget + surface_producer->gr_context()->flushAndSubmit(); + } else { + // For the last skp we provide a callback that frees the warmup + // surface and calls the completion callback + struct GrFlushInfo flush_info; + flush_info.fFinishedContext = skp_warmup_surface; + flush_info.fFinishedProc = [](void* skp_warmup_surface) { + delete static_cast*>( + skp_warmup_surface); + }; + + surface_producer->gr_context()->flush(flush_info); + surface_producer->gr_context()->submit( + synchronous ? GrSyncCpu::kYes : GrSyncCpu::kNo); + } + } else { + if (i == count - 1) { + delete skp_warmup_surface; + } + } + }); + i++; + } + }); +} + +void Engine::OnLevelChanged( + fuchsia::memorypressure::Level level, + fuchsia::memorypressure::Watcher::OnLevelChangedCallback callback) { + // The callback must be invoked immediately to acknowledge the message. + // This is the "Throttle push using acknowledgements" pattern: + // https://fuchsia.dev/fuchsia-src/concepts/api/fidl#throttle_push_using_acknowledgements + callback(); + + FML_LOG(WARNING) << "memorypressure watcher: OnLevelChanged from " + << static_cast(latest_memory_pressure_level_) << " to " + << static_cast(level); + + if (latest_memory_pressure_level_ == fuchsia::memorypressure::Level::NORMAL && + (level == fuchsia::memorypressure::Level::WARNING || + level == fuchsia::memorypressure::Level::CRITICAL)) { + FML_LOG(WARNING) + << "memorypressure watcher: notifying Flutter that memory is low"; + shell_->NotifyLowMemoryWarning(); + } + latest_memory_pressure_level_ = level; +} + +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/engine.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/engine.h new file mode 100644 index 0000000000000000000000000000000000000000..a2e8ca33812874b6e28486b95fa0732f53cab65b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/engine.h @@ -0,0 +1,156 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_ENGINE_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_ENGINE_H_ + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "flutter/flow/embedded_views.h" +#include "flutter/flow/surface.h" +#include "flutter/fml/macros.h" +#include "flutter/shell/common/shell.h" +#include "flutter/shell/common/thread_host.h" +#include "flutter/shell/platform/fuchsia/flutter/accessibility_bridge.h" + +#include "external_view_embedder.h" +#include "flatland_connection.h" +#include "flutter_runner_product_configuration.h" +#include "isolate_configurator.h" +#include "surface_producer.h" + +namespace flutter_runner { + +namespace testing { +class EngineTest; +} + +// Represents an instance of running Flutter engine along with the threads +// that host the same. +class Engine final : public fuchsia::memorypressure::Watcher { + public: + class Delegate { + public: + virtual void OnEngineTerminate(const Engine* holder) = 0; + }; + + static flutter::ThreadHost CreateThreadHost( + const std::string& name_prefix, + const std::shared_ptr& runner_services = nullptr); + + Engine(Delegate& delegate, + std::string thread_label, + std::shared_ptr svc, + std::shared_ptr runner_services, + flutter::Settings settings, + fuchsia::ui::views::ViewCreationToken view_creation_token, + std::pair view_ref_pair, + UniqueFDIONS fdio_ns, + fidl::InterfaceRequest directory_request, + FlutterRunnerProductConfiguration product_config, + const std::vector& dart_entrypoint_args); + + ~Engine(); + + // Returns the Dart return code for the root isolate if one is present. This + // call is thread safe and synchronous. This call must be made infrequently. + std::optional GetEngineReturnCode() const; + +#if !defined(DART_PRODUCT) + void WriteProfileToTrace() const; +#endif // !defined(DART_PRODUCT) + + private: + void Initialize( + std::pair + view_ref_pair, + std::shared_ptr svc, + std::shared_ptr runner_services, + flutter::Settings settings, + UniqueFDIONS fdio_ns, + fidl::InterfaceRequest directory_request, + FlutterRunnerProductConfiguration product_config, + const std::vector& dart_entrypoint_args); + + static void WarmupSkps( + fml::BasicTaskRunner* concurrent_task_runner, + fml::BasicTaskRunner* raster_task_runner, + std::shared_ptr surface_producer, + SkISize size, + std::shared_ptr asset_manager, + std::optional> skp_names, + std::optional> completion_callback, + bool synchronous = false); + + void OnMainIsolateStart(); + + void OnMainIsolateShutdown(); + + void Terminate(); + + void DebugWireframeSettingsChanged(bool enabled); + void CreateView(int64_t view_id, + ViewCallback on_view_created, + ViewCreatedCallback on_view_bound, + bool hit_testable, + bool focusable); + void UpdateView(int64_t view_id, + SkRect occlusion_hint, + bool hit_testable, + bool focusable); + void DestroyView(int64_t view_id, ViewIdCallback on_view_unbound); + + // |fuchsia::memorypressure::Watcher| + void OnLevelChanged(fuchsia::memorypressure::Level level, + fuchsia::memorypressure::Watcher::OnLevelChangedCallback + callback) override; + + std::shared_ptr GetExternalViewEmbedder(); + + std::unique_ptr CreateSurface(); + + Delegate& delegate_; + + const std::string thread_label_; + flutter::ThreadHost thread_host_; + + fuchsia::ui::views::ViewCreationToken view_creation_token_; + std::shared_ptr + flatland_connection_; // Must come before surface_producer_ + std::shared_ptr surface_producer_; + std::shared_ptr view_embedder_; + + std::unique_ptr isolate_configurator_; + std::unique_ptr shell_; + std::unique_ptr accessibility_bridge_; + + fuchsia::intl::PropertyProviderPtr intl_property_provider_; + + fuchsia::memorypressure::ProviderPtr memory_pressure_provider_; + fidl::Binding + memory_pressure_watcher_binding_; + // We need to track the latest memory pressure level to determine + // the direction of change when a new level is provided. + fuchsia::memorypressure::Level latest_memory_pressure_level_; + + bool intercept_all_input_ = false; + + fml::WeakPtrFactory weak_factory_; + friend class testing::EngineTest; + + FML_DISALLOW_COPY_AND_ASSIGN(Engine); +}; + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_ENGINE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/external_view_embedder.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/external_view_embedder.cc new file mode 100644 index 0000000000000000000000000000000000000000..70a2a927d07f74ba47164cd2c79d5c52c4b9fa00 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/external_view_embedder.cc @@ -0,0 +1,665 @@ +// 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 "external_view_embedder.h" + +#include +#include + +#include "flutter/common/constants.h" +#include "flutter/fml/trace_event.h" +#include "third_party/skia/include/core/SkPicture.h" +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/include/gpu/ganesh/GrDirectContext.h" +#include "third_party/skia/include/gpu/ganesh/GrRecordingContext.h" + +namespace flutter_runner { +namespace { + +void AttachClipTransformChild( + FlatlandConnection* flatland, + ExternalViewEmbedder::ClipTransform* parent_clip_transform, + const fuchsia::ui::composition::TransformId& child_transform_id) { + flatland->flatland()->AddChild(parent_clip_transform->transform_id, + child_transform_id); + parent_clip_transform->children.push_back(child_transform_id); +} + +void DetachClipTransformChildren( + FlatlandConnection* flatland, + ExternalViewEmbedder::ClipTransform* clip_transform) { + for (auto& child : clip_transform->children) { + flatland->flatland()->RemoveChild(clip_transform->transform_id, child); + } + clip_transform->children.clear(); +} + +} // namespace + +ExternalViewEmbedder::ExternalViewEmbedder( + fuchsia::ui::views::ViewCreationToken view_creation_token, + fuchsia::ui::views::ViewIdentityOnCreation view_identity, + fuchsia::ui::composition::ViewBoundProtocols view_protocols, + fidl::InterfaceRequest + parent_viewport_watcher_request, + std::shared_ptr flatland, + std::shared_ptr surface_producer, + bool intercept_all_input) + : flatland_(flatland), surface_producer_(surface_producer) { + flatland_->flatland()->CreateView2( + std::move(view_creation_token), std::move(view_identity), + std::move(view_protocols), std::move(parent_viewport_watcher_request)); + + root_transform_id_ = flatland_->NextTransformId(); + flatland_->flatland()->CreateTransform(root_transform_id_); + flatland_->flatland()->SetRootTransform(root_transform_id_); + + if (intercept_all_input) { + input_interceptor_transform_ = flatland_->NextTransformId(); + flatland_->flatland()->CreateTransform(*input_interceptor_transform_); + flatland_->flatland()->SetInfiniteHitRegion( + *input_interceptor_transform_, + fuchsia::ui::composition::HitTestInteraction::SEMANTICALLY_INVISIBLE); + + flatland_->flatland()->AddChild(root_transform_id_, + *input_interceptor_transform_); + child_transforms_.emplace_back(*input_interceptor_transform_); + } +} + +ExternalViewEmbedder::~ExternalViewEmbedder() = default; + +flutter::DlCanvas* ExternalViewEmbedder::GetRootCanvas() { + auto found = frame_layers_.find(kRootLayerId); + if (found == frame_layers_.end()) { + FML_LOG(WARNING) + << "No root canvas could be found. This is extremely unlikely and " + "indicates that the external view embedder did not receive the " + "notification to begin the frame."; + return nullptr; + } + + return found->second.canvas_spy->GetSpyingCanvas(); +} + +void ExternalViewEmbedder::PrerollCompositeEmbeddedView( + int64_t view_id, + std::unique_ptr params) { + zx_handle_t handle = static_cast(view_id); + FML_CHECK(frame_layers_.count(handle) == 0); + + frame_layers_.emplace(std::make_pair( + EmbedderLayerId{handle}, + EmbedderLayer(frame_size_, *params, flutter::RTreeFactory()))); + frame_composition_order_.push_back(handle); +} + +flutter::DlCanvas* ExternalViewEmbedder::CompositeEmbeddedView( + int64_t view_id) { + zx_handle_t handle = static_cast(view_id); + auto found = frame_layers_.find(handle); + FML_CHECK(found != frame_layers_.end()); + + return found->second.canvas_spy->GetSpyingCanvas(); +} + +flutter::PostPrerollResult ExternalViewEmbedder::PostPrerollAction( + const fml::RefPtr& raster_thread_merger) { + return flutter::PostPrerollResult::kSuccess; +} + +void ExternalViewEmbedder::BeginFrame( + GrDirectContext* context, + const fml::RefPtr& raster_thread_merger) {} + +// |ExternalViewEmbedder| +void ExternalViewEmbedder::PrepareFlutterView(SkISize frame_size, + double device_pixel_ratio) { + // Reset for new view. + Reset(); + frame_size_ = frame_size; + frame_dpr_ = device_pixel_ratio; + + // Create the root layer. + frame_layers_.emplace(std::make_pair( + kRootLayerId, + EmbedderLayer(frame_size, std::nullopt, flutter::RTreeFactory()))); + frame_composition_order_.push_back(kRootLayerId); +} + +void ExternalViewEmbedder::EndFrame( + bool should_resubmit_frame, + const fml::RefPtr& raster_thread_merger) { + TRACE_EVENT0("flutter", "ExternalViewEmbedder::EndFrame"); +} + +void ExternalViewEmbedder::SubmitFlutterView( + int64_t flutter_view_id, + GrDirectContext* context, + const std::shared_ptr& aiks_context, + std::unique_ptr frame) { + // Fuchsia only supports operating the implicit view for now. + FML_DCHECK(flutter_view_id == flutter::kFlutterImplicitViewId); + + TRACE_EVENT0("flutter", "ExternalViewEmbedder::SubmitFlutterView"); + std::vector> frame_surfaces; + std::unordered_map frame_surface_indices; + + // Create surfaces for the frame and associate them with layer IDs. + { + TRACE_EVENT0("flutter", "CreateSurfaces"); + + for (const auto& layer : frame_layers_) { + if (!layer.second.canvas_spy->DidDrawIntoCanvas()) { + continue; + } + + auto surface = + surface_producer_->ProduceSurface(layer.second.surface_size); + if (!surface) { + const std::string layer_id_str = + layer.first.has_value() ? std::to_string(layer.first.value()) + : "Background"; + FML_LOG(ERROR) << "Failed to create surface for layer " << layer_id_str + << "; size (" << layer.second.surface_size.width() + << ", " << layer.second.surface_size.height() << ")"; + FML_DCHECK(false); + continue; + } + + // If we receive an unitialized surface, we need to first create flatland + // resource. + if (surface->GetImageId() == 0) { + auto image_id = flatland_->NextContentId().value; + const auto& size = surface->GetSize(); + fuchsia::ui::composition::ImageProperties image_properties; + image_properties.set_size({static_cast(size.width()), + static_cast(size.height())}); + flatland_->flatland()->CreateImage( + {image_id}, surface->GetBufferCollectionImportToken(), 0, + std::move(image_properties)); + + surface->SetImageId(image_id); + surface->SetReleaseImageCallback([flatland = flatland_, image_id]() { + flatland->flatland()->ReleaseImage({image_id}); + }); + } + + // Enqueue fences for the next present. + flatland_->EnqueueAcquireFence(surface->GetAcquireFence()); + flatland_->EnqueueReleaseFence(surface->GetReleaseFence()); + + frame_surface_indices.emplace( + std::make_pair(layer.first, frame_surfaces.size())); + frame_surfaces.emplace_back(std::move(surface)); + } + } + + // Finish recording SkPictures. + { + TRACE_EVENT0("flutter", "FinishRecordingPictures"); + + for (const auto& surface_index : frame_surface_indices) { + const auto& layer = frame_layers_.find(surface_index.first); + FML_CHECK(layer != frame_layers_.end()); + layer->second.picture = + layer->second.recorder->finishRecordingAsPicture(); + FML_CHECK(layer->second.picture != nullptr); + } + } + + // Submit layers and platform views to Scenic in composition order. + { + TRACE_EVENT0("flutter", "SubmitLayers"); + + // First re-scale everything according to the DPR. + const float inv_dpr = 1.0f / frame_dpr_; + flatland_->flatland()->SetScale(root_transform_id_, {inv_dpr, inv_dpr}); + + size_t layer_index = 0; + for (const auto& layer_id : frame_composition_order_) { + const auto& layer = frame_layers_.find(layer_id); + FML_CHECK(layer != frame_layers_.end()); + + // Draw the PlatformView associated with each layer first. + if (layer_id.has_value()) { + FML_CHECK(layer->second.embedded_view_params.has_value()); + auto& view_params = layer->second.embedded_view_params.value(); + + // Get the View structure corresponding to the platform view. + auto found = views_.find(layer_id.value()); + FML_CHECK(found != views_.end()) + << "No View for layer_id = " << layer_id.value() + << ". This typically indicates that the Dart code in " + "Fuchsia's fuchsia_scenic_flutter library failed to create " + "the platform view, leading to a crash later down the road in " + "the Flutter Engine code that tries to find that platform view. " + "Check the Flutter Framework for changes to PlatformView that " + "might have caused a regression."; + auto& viewport = found->second; + + // Compute mutators, and size for the platform view. + const ViewMutators view_mutators = + ParseMutatorStack(view_params.mutatorsStack()); + const SkSize view_size = view_params.sizePoints(); + + // Verify that we're unpacking the mutators' transform matrix correctly. + // Use built-in get method for SkMatrix to get values, see: + // https://source.corp.google.com/piper///depot/google3/third_party/skia/HEAD/include/core/SkMatrix.h;l=391 + for (int index = 0; index < 9; index++) { + const SkScalar mutators_transform_value = + view_mutators.total_transform.get(index); + const SkScalar params_transform_value = + view_params.transformMatrix().get(index); + if (!SkScalarNearlyEqual(mutators_transform_value, + params_transform_value, 0.0005f)) { + FML_LOG(ERROR) + << "Assertion failed: view_mutators.total_transform[" << index + << "] (" << mutators_transform_value + << ") != view_params.transformMatrix()[" << index << "] (" + << params_transform_value + << "). This likely means there is a bug with the " + << "logic for parsing embedded views' transform matrices."; + } + } + + if (viewport.pending_create_viewport_callback) { + if (view_size.fWidth && view_size.fHeight) { + viewport.pending_create_viewport_callback( + view_size, viewport.pending_occlusion_hint); + viewport.size = view_size; + viewport.occlusion_hint = viewport.pending_occlusion_hint; + } else { + FML_DLOG(WARNING) + << "Failed to create viewport because width or height is zero."; + } + } + + // Set transform for the viewport. + if (view_mutators.transform != viewport.mutators.transform) { + flatland_->flatland()->SetTranslation( + viewport.transform_id, + {static_cast(view_mutators.transform.getTranslateX()), + static_cast(view_mutators.transform.getTranslateY())}); + flatland_->flatland()->SetScale( + viewport.transform_id, {view_mutators.transform.getScaleX(), + view_mutators.transform.getScaleY()}); + viewport.mutators.transform = view_mutators.transform; + } + + // Set clip regions. + if (view_mutators.clips != viewport.mutators.clips) { + // Expand the clip_transforms array to fit any new transforms. + while (viewport.clip_transforms.size() < view_mutators.clips.size()) { + ClipTransform clip_transform; + clip_transform.transform_id = flatland_->NextTransformId(); + flatland_->flatland()->CreateTransform(clip_transform.transform_id); + viewport.clip_transforms.emplace_back(std::move(clip_transform)); + } + FML_CHECK(viewport.clip_transforms.size() >= + view_mutators.clips.size()); + + // Adjust and re-parent all clip transforms. + for (auto& clip_transform : viewport.clip_transforms) { + DetachClipTransformChildren(flatland_.get(), &clip_transform); + } + + for (size_t c = 0; c < view_mutators.clips.size(); c++) { + const SkMatrix& clip_matrix = view_mutators.clips[c].transform; + const SkRect& clip_rect = view_mutators.clips[c].rect; + + flatland_->flatland()->SetTranslation( + viewport.clip_transforms[c].transform_id, + {static_cast(clip_matrix.getTranslateX()), + static_cast(clip_matrix.getTranslateY())}); + flatland_->flatland()->SetScale( + viewport.clip_transforms[c].transform_id, + {clip_matrix.getScaleX(), clip_matrix.getScaleY()}); + fuchsia::math::Rect rect = { + static_cast(clip_rect.x()), + static_cast(clip_rect.y()), + static_cast(clip_rect.width()), + static_cast(clip_rect.height())}; + flatland_->flatland()->SetClipBoundary( + viewport.clip_transforms[c].transform_id, + std::make_unique(std::move(rect))); + + const auto child_transform_id = + c != (view_mutators.clips.size() - 1) + ? viewport.clip_transforms[c + 1].transform_id + : viewport.transform_id; + AttachClipTransformChild(flatland_.get(), + &(viewport.clip_transforms[c]), + child_transform_id); + } + viewport.mutators.clips = view_mutators.clips; + } + + // Set opacity. + if (view_mutators.opacity != viewport.mutators.opacity) { + flatland_->flatland()->SetOpacity(viewport.transform_id, + view_mutators.opacity); + viewport.mutators.opacity = view_mutators.opacity; + } + + // Set size and occlusion hint. + if (view_size != viewport.size || + viewport.pending_occlusion_hint != viewport.occlusion_hint) { + fuchsia::ui::composition::ViewportProperties properties; + properties.set_logical_size( + {static_cast(view_size.fWidth), + static_cast(view_size.fHeight)}); + properties.set_inset( + {static_cast(viewport.pending_occlusion_hint.fTop), + static_cast(viewport.pending_occlusion_hint.fRight), + static_cast(viewport.pending_occlusion_hint.fBottom), + static_cast(viewport.pending_occlusion_hint.fLeft)}); + flatland_->flatland()->SetViewportProperties(viewport.viewport_id, + std::move(properties)); + viewport.size = view_size; + viewport.occlusion_hint = viewport.pending_occlusion_hint; + } + + // Attach the View to the main scene graph. + const auto main_child_transform = + viewport.mutators.clips.empty() + ? viewport.transform_id + : viewport.clip_transforms[0].transform_id; + flatland_->flatland()->AddChild(root_transform_id_, + main_child_transform); + child_transforms_.emplace_back(main_child_transform); + } + + // Acquire the surface associated with the layer. + SurfaceProducerSurface* surface_for_layer = nullptr; + if (layer->second.canvas_spy->DidDrawIntoCanvas()) { + const auto& surface_index = frame_surface_indices.find(layer_id); + if (surface_index != frame_surface_indices.end()) { + FML_CHECK(surface_index->second < frame_surfaces.size()); + surface_for_layer = frame_surfaces[surface_index->second].get(); + FML_CHECK(surface_for_layer != nullptr); + } else { + const std::string layer_id_str = + layer_id.has_value() ? std::to_string(layer_id.value()) + : "Background"; + FML_LOG(ERROR) << "Missing surface for layer " << layer_id_str + << "; skipping scene graph add of layer."; + FML_DCHECK(false); + } + } + + // Draw the layer if we acquired a surface for it successfully. + if (surface_for_layer != nullptr) { + // Create a new layer if needed for the surface. + FML_CHECK(layer_index <= layers_.size()); + if (layer_index == layers_.size()) { + Layer new_layer{.transform_id = flatland_->NextTransformId()}; + flatland_->flatland()->CreateTransform(new_layer.transform_id); + layers_.emplace_back(std::move(new_layer)); + } + + // Update the image content and set size. + flatland_->flatland()->SetContent(layers_[layer_index].transform_id, + {surface_for_layer->GetImageId()}); + flatland_->flatland()->SetImageDestinationSize( + {surface_for_layer->GetImageId()}, + {static_cast(surface_for_layer->GetSize().width()), + static_cast(surface_for_layer->GetSize().height())}); + + // Flutter Embedder lacks an API to detect if a layer has alpha or not. + // For now, we assume any layer beyond the first has alpha. + flatland_->flatland()->SetImageBlendingFunction( + {surface_for_layer->GetImageId()}, + layer_index == 0 ? fuchsia::ui::composition::BlendMode::SRC + : fuchsia::ui::composition::BlendMode::SRC_OVER); + + // Set hit regions for this layer; these hit regions correspond to the + // portions of the layer on which skia drew content. + { + FML_CHECK(layer->second.rtree); + std::list intersection_rects = + layer->second.rtree->searchNonOverlappingDrawnRects( + SkRect::Make(layer->second.surface_size)); + + std::vector hit_regions; + for (const SkRect& rect : intersection_rects) { + hit_regions.emplace_back(); + auto& new_hit_region = hit_regions.back(); + new_hit_region.region.x = rect.x(); + new_hit_region.region.y = rect.y(); + new_hit_region.region.width = rect.width(); + new_hit_region.region.height = rect.height(); + new_hit_region.hit_test = + fuchsia::ui::composition::HitTestInteraction::DEFAULT; + } + + flatland_->flatland()->SetHitRegions( + layers_[layer_index].transform_id, std::move(hit_regions)); + } + + // Attach the Layer to the main scene graph. + flatland_->flatland()->AddChild(root_transform_id_, + layers_[layer_index].transform_id); + child_transforms_.emplace_back(layers_[layer_index].transform_id); + } + + // Reset for the next pass: + layer_index++; + } + + // Set up the input interceptor at the top of the scene, if applicable. It + // will capture all input, and any unwanted input will be reinjected into + // embedded views. + if (input_interceptor_transform_.has_value()) { + flatland_->flatland()->AddChild(root_transform_id_, + *input_interceptor_transform_); + child_transforms_.emplace_back(*input_interceptor_transform_); + } + } + + // Present the session to Scenic, along with surface acquire/release fences. + { + TRACE_EVENT0("flutter", "SessionPresent"); + + flatland_->Present(); + } + + // Render the recorded SkPictures into the surfaces. + { + TRACE_EVENT0("flutter", "RasterizeSurfaces"); + + for (const auto& surface_index : frame_surface_indices) { + TRACE_EVENT0("flutter", "RasterizeSurface"); + + FML_CHECK(surface_index.second < frame_surfaces.size()); + SurfaceProducerSurface* surface = + frame_surfaces[surface_index.second].get(); + FML_CHECK(surface != nullptr); + + sk_sp sk_surface = surface->GetSkiaSurface(); + FML_CHECK(sk_surface != nullptr); + FML_CHECK(SkISize::Make(sk_surface->width(), sk_surface->height()) == + frame_size_); + SkCanvas* canvas = sk_surface->getCanvas(); + FML_CHECK(canvas != nullptr); + + const auto& layer = frame_layers_.find(surface_index.first); + FML_CHECK(layer != frame_layers_.end()); + + canvas->setMatrix(SkMatrix::I()); + canvas->clear(SK_ColorTRANSPARENT); + canvas->drawPicture(layer->second.picture); + if (GrDirectContext* direct_context = + GrAsDirectContext(canvas->recordingContext())) { + direct_context->flushAndSubmit(); + } + } + } + + // Flush deferred Skia work and inform Scenic that render targets are ready. + { + TRACE_EVENT0("flutter", "PresentSurfaces"); + + surface_producer_->SubmitSurfaces(std::move(frame_surfaces)); + } + + // Submit the underlying render-backend-specific frame for processing. + frame->Submit(); +} + +void ExternalViewEmbedder::CreateView(int64_t view_id, + ViewCallback on_view_created, + ViewCreatedCallback on_view_bound) { + FML_CHECK(views_.find(view_id) == views_.end()); + + const auto transform_id = flatland_->NextTransformId(); + const auto viewport_id = flatland_->NextContentId(); + View new_view = {.transform_id = transform_id, .viewport_id = viewport_id}; + flatland_->flatland()->CreateTransform(new_view.transform_id); + fuchsia::ui::composition::ChildViewWatcherHandle child_view_watcher; + new_view.pending_create_viewport_callback = + [this, transform_id, viewport_id, view_id, + child_view_watcher_request = child_view_watcher.NewRequest()]( + const SkSize& size, const SkRect& inset) mutable { + fuchsia::ui::composition::ViewportProperties properties; + properties.set_logical_size({static_cast(size.fWidth), + static_cast(size.fHeight)}); + properties.set_inset({static_cast(inset.fTop), + static_cast(inset.fRight), + static_cast(inset.fBottom), + static_cast(inset.fLeft)}); + flatland_->flatland()->CreateViewport( + viewport_id, {zx::channel((zx_handle_t)view_id)}, + std::move(properties), std::move(child_view_watcher_request)); + flatland_->flatland()->SetContent(transform_id, viewport_id); + }; + + on_view_created(); + on_view_bound(new_view.viewport_id, std::move(child_view_watcher)); + views_.emplace(std::make_pair(view_id, std::move(new_view))); +} + +void ExternalViewEmbedder::DestroyView(int64_t view_id, + ViewIdCallback on_view_unbound) { + auto view = views_.find(view_id); + FML_CHECK(view != views_.end()); + + auto viewport_id = view->second.viewport_id; + auto transform_id = view->second.transform_id; + auto& clip_transforms = view->second.clip_transforms; + if (!view->second.pending_create_viewport_callback) { + flatland_->flatland()->ReleaseViewport(viewport_id, [](auto) {}); + } + auto itr = std::find_if( + child_transforms_.begin(), child_transforms_.end(), + [transform_id, + &clip_transforms](fuchsia::ui::composition::TransformId id) { + return id.value == transform_id.value || + (!clip_transforms.empty() && + (id.value == clip_transforms[0].transform_id.value)); + }); + if (itr != child_transforms_.end()) { + flatland_->flatland()->RemoveChild(root_transform_id_, *itr); + child_transforms_.erase(itr); + } + for (auto& clip_transform : clip_transforms) { + DetachClipTransformChildren(flatland_.get(), &clip_transform); + } + flatland_->flatland()->ReleaseTransform(transform_id); + for (auto& clip_transform : clip_transforms) { + flatland_->flatland()->ReleaseTransform(clip_transform.transform_id); + } + + views_.erase(view); + on_view_unbound(viewport_id); +} + +void ExternalViewEmbedder::SetViewProperties(int64_t view_id, + const SkRect& occlusion_hint, + bool hit_testable, + bool focusable) { + auto found = views_.find(view_id); + FML_CHECK(found != views_.end()); + + // Note that pending_create_viewport_callback might not have run at this + // point. + auto& viewport = found->second; + viewport.pending_occlusion_hint = occlusion_hint; +} + +void ExternalViewEmbedder::Reset() { + frame_layers_.clear(); + frame_composition_order_.clear(); + frame_size_ = SkISize::Make(0, 0); + frame_dpr_ = 1.f; + + // Clear all children from root. + for (const auto& transform : child_transforms_) { + flatland_->flatland()->RemoveChild(root_transform_id_, transform); + } + child_transforms_.clear(); + + // Clear images on all layers so they aren't cached unnecessarily. + for (const auto& layer : layers_) { + flatland_->flatland()->SetContent(layer.transform_id, {0}); + } +} + +ExternalViewEmbedder::ViewMutators ExternalViewEmbedder::ParseMutatorStack( + const flutter::MutatorsStack& mutators_stack) { + ViewMutators mutators; + flutter::DlMatrix total_transform; + flutter::DlMatrix transform_accumulator; + + for (auto i = mutators_stack.Begin(); i != mutators_stack.End(); ++i) { + const auto& mutator = *i; + switch (mutator->GetType()) { + case flutter::MutatorType::kOpacity: { + mutators.opacity *= std::clamp(mutator->GetAlphaFloat(), 0.f, 1.f); + } break; + case flutter::MutatorType::kTransform: { + total_transform = total_transform * mutator->GetMatrix(); + transform_accumulator = transform_accumulator * mutator->GetMatrix(); + } break; + case flutter::MutatorType::kClipRect: { + mutators.clips.emplace_back(TransformedClip{ + .transform = flutter::ToSkMatrix(transform_accumulator), + .rect = flutter::ToSkRect(mutator->GetRect()), + }); + transform_accumulator = flutter::DlMatrix(); + } break; + case flutter::MutatorType::kClipRRect: { + mutators.clips.emplace_back(TransformedClip{ + .transform = flutter::ToSkMatrix(transform_accumulator), + .rect = flutter::ToSkRect(mutator->GetRRect().GetBounds()), + }); + transform_accumulator = flutter::DlMatrix(); + } break; + case flutter::MutatorType::kClipRSE: { + mutators.clips.emplace_back(TransformedClip{ + .transform = flutter::ToSkMatrix(transform_accumulator), + .rect = flutter::ToSkRect(mutator->GetRSE().GetBounds()), + }); + transform_accumulator = flutter::DlMatrix(); + } break; + case flutter::MutatorType::kClipPath: { + mutators.clips.emplace_back(TransformedClip{ + .transform = flutter::ToSkMatrix(transform_accumulator), + .rect = flutter::ToSkRect(mutator->GetPath().GetBounds()), + }); + transform_accumulator = flutter::DlMatrix(); + } break; + default: { + break; + } + } + } + mutators.total_transform = flutter::ToSkMatrix(total_transform); + mutators.transform = flutter::ToSkMatrix(transform_accumulator); + mutators.opacity = std::clamp(mutators.opacity, 0.f, 1.f); + + return mutators; +} + +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/external_view_embedder.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/external_view_embedder.h new file mode 100644 index 0000000000000000000000000000000000000000..27605ffcdeb8a6d245dc373476220acd402d7e0b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/external_view_embedder.h @@ -0,0 +1,222 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_EXTERNAL_VIEW_EMBEDDER_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_EXTERNAL_VIEW_EMBEDDER_H_ + +#include +#include +#include + +#include // For uint32_t & uint64_t +#include +#include +#include +#include + +#include "flutter/flow/embedded_views.h" +#include "flutter/fml/logging.h" +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/fuchsia/flutter/canvas_spy.h" +#include "flutter/shell/platform/fuchsia/flutter/rtree.h" +#include "third_party/skia/include/core/SkPictureRecorder.h" +#include "third_party/skia/include/core/SkPoint.h" +#include "third_party/skia/include/core/SkRect.h" +#include "third_party/skia/include/core/SkSize.h" +#include "third_party/skia/include/gpu/ganesh/GrDirectContext.h" + +#include "flatland_connection.h" +#include "surface_producer.h" + +namespace flutter_runner { + +using ViewCallback = std::function; +using ViewCreatedCallback = std::function; +using ViewIdCallback = std::function; + +// This class orchestrates interaction with the Scenic's compositor on +// Fuchsia. It ensures that flutter content and platform view content are both +// rendered correctly in a unified scene. +class ExternalViewEmbedder final : public flutter::ExternalViewEmbedder { + public: + constexpr static uint32_t kDefaultViewportSize = 32; + + ExternalViewEmbedder( + fuchsia::ui::views::ViewCreationToken view_creation_token, + fuchsia::ui::views::ViewIdentityOnCreation view_identity, + fuchsia::ui::composition::ViewBoundProtocols endpoints, + fidl::InterfaceRequest + parent_viewport_watcher_request, + std::shared_ptr flatland, + std::shared_ptr surface_producer, + bool intercept_all_input = false); + ~ExternalViewEmbedder(); + + // |ExternalViewEmbedder| + flutter::DlCanvas* GetRootCanvas() override; + + // |ExternalViewEmbedder| + void PrerollCompositeEmbeddedView( + int64_t view_id, + std::unique_ptr params) override; + + // |ExternalViewEmbedder| + flutter::DlCanvas* CompositeEmbeddedView(int64_t view_id) override; + + // |ExternalViewEmbedder| + flutter::PostPrerollResult PostPrerollAction( + const fml::RefPtr& raster_thread_merger) + override; + + // |ExternalViewEmbedder| + void BeginFrame(GrDirectContext* context, + const fml::RefPtr& + raster_thread_merger) override; + + // |ExternalViewEmbedder| + void PrepareFlutterView(SkISize frame_size, + double device_pixel_ratio) override; + + // |ExternalViewEmbedder| + void EndFrame(bool should_resubmit_frame, + const fml::RefPtr& + raster_thread_merger) override; + + // |ExternalViewEmbedder| + void SubmitFlutterView( + int64_t flutter_view_id, + GrDirectContext* context, + const std::shared_ptr& aiks_context, + std::unique_ptr frame) override; + + // |ExternalViewEmbedder| + void CancelFrame() override { Reset(); } + + // |ExternalViewEmbedder| + bool SupportsDynamicThreadMerging() override { return false; } + + // View manipulation. + // |SetViewProperties| doesn't manipulate the view directly -- it sets pending + // properties for the next |UpdateView| call. + void CreateView(int64_t view_id, + ViewCallback on_view_created, + ViewCreatedCallback on_view_bound); + void DestroyView(int64_t view_id, ViewIdCallback on_view_unbound); + void SetViewProperties(int64_t view_id, + const SkRect& occlusion_hint, + bool hit_testable, + bool focusable); + + // Holds the clip transform that may be applied on a View. + struct ClipTransform { + fuchsia::ui::composition::TransformId transform_id; + std::vector children; + }; + + private: + void Reset(); // Reset state for a new frame. + + // This struct represents a transformed clip rect. + struct TransformedClip { + SkMatrix transform = SkMatrix::I(); + SkRect rect = SkRect::MakeEmpty(); + + bool operator==(const TransformedClip& other) const { + return transform == other.transform && rect == other.rect; + } + }; + + // This struct represents all the mutators that can be applied to a + // PlatformView, unpacked from the `MutatorStack`. + struct ViewMutators { + std::vector clips; + SkMatrix total_transform = SkMatrix::I(); + SkMatrix transform = SkMatrix::I(); + SkScalar opacity = 1.f; + + bool operator==(const ViewMutators& other) const { + return clips == other.clips && total_transform == other.total_transform && + transform == other.transform && opacity == other.opacity; + } + }; + + ViewMutators ParseMutatorStack(const flutter::MutatorsStack& mutators_stack); + + struct EmbedderLayer { + EmbedderLayer(const SkISize& frame_size, + std::optional view_params, + flutter::RTreeFactory rtree_factory) + : rtree(rtree_factory.getInstance()), + embedded_view_params(std::move(view_params)), + recorder(std::make_unique()), + canvas_spy(std::make_unique( + recorder->beginRecording(SkRect::Make(frame_size), + &rtree_factory))), + surface_size(frame_size), + picture(nullptr) {} + + // Records paint operations applied to this layer's `SkCanvas`. + // These records are used to determine which portions of this layer + // contain content. The embedder propagates this information to scenic, so + // that scenic can accurately decide which portions of this layer may + // interact with input. + sk_sp rtree; + + std::optional embedded_view_params; + std::unique_ptr recorder; + // TODO(cyanglaz: use DlOpSpy instead. + // https://github.com/flutter/flutter/issues/123805 + std::unique_ptr canvas_spy; + SkISize surface_size; + sk_sp picture; + }; + using EmbedderLayerId = std::optional; + constexpr static EmbedderLayerId kRootLayerId = EmbedderLayerId{}; + + struct View { + std::vector clip_transforms; + fuchsia::ui::composition::TransformId transform_id; + fuchsia::ui::composition::ContentId viewport_id; + ViewMutators mutators; + SkSize size = SkSize::MakeEmpty(); + SkRect pending_occlusion_hint = SkRect::MakeEmpty(); + SkRect occlusion_hint = SkRect::MakeEmpty(); + fit::callback + pending_create_viewport_callback; + }; + + struct Layer { + // Transform on which Images are set. + fuchsia::ui::composition::TransformId transform_id; + }; + + std::shared_ptr flatland_; + std::shared_ptr surface_producer_; + + fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher_; + + fuchsia::ui::composition::TransformId root_transform_id_; + + std::unordered_map views_; + std::vector layers_; + + std::unordered_map frame_layers_; + std::vector frame_composition_order_; + std::vector child_transforms_; + SkISize frame_size_ = SkISize::Make(0, 0); + float frame_dpr_ = 1.f; + + // TransformId for the input interceptor node when input shield is turned on, + // std::nullptr otherwise. + std::optional + input_interceptor_transform_; + + FML_DISALLOW_COPY_AND_ASSIGN(ExternalViewEmbedder); +}; + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_EXTERNAL_VIEW_EMBEDDER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/file_in_namespace_buffer.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/file_in_namespace_buffer.cc new file mode 100644 index 0000000000000000000000000000000000000000..509eb900f60b7076af62f6eea61cbd7728d36077 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/file_in_namespace_buffer.cc @@ -0,0 +1,104 @@ +// 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 "file_in_namespace_buffer.h" + +#include +#include +#include + +#include "flutter/fml/trace_event.h" +#include "runtime/dart/utils/files.h" +#include "runtime/dart/utils/handle_exception.h" +#include "runtime/dart/utils/mapped_resource.h" +#include "runtime/dart/utils/tempfs.h" +#include "runtime/dart/utils/vmo.h" + +namespace flutter_runner { + +FileInNamespaceBuffer::FileInNamespaceBuffer(int namespace_fd, + const char* path, + bool executable) + : address_(nullptr), size_(0) { + fuchsia::mem::Buffer buffer; + if (!dart_utils::VmoFromFilenameAt(namespace_fd, path, executable, &buffer) || + buffer.size == 0) { + return; + } + + uint32_t flags = ZX_VM_PERM_READ; + if (executable) { + flags |= ZX_VM_PERM_EXECUTE; + } + + uintptr_t addr; + const zx_status_t status = + zx::vmar::root_self()->map(flags, 0, buffer.vmo, 0, buffer.size, &addr); + if (status != ZX_OK) { + FML_LOG(FATAL) << "Failed to map " << path << ": " + << zx_status_get_string(status); + } + + address_ = reinterpret_cast(addr); + size_ = buffer.size; +} + +FileInNamespaceBuffer::~FileInNamespaceBuffer() { + if (address_ != nullptr) { + zx::vmar::root_self()->unmap(reinterpret_cast(address_), size_); + address_ = nullptr; + size_ = 0; + } +} + +const uint8_t* FileInNamespaceBuffer::GetMapping() const { + return reinterpret_cast(address_); +} + +size_t FileInNamespaceBuffer::GetSize() const { + return size_; +} + +bool FileInNamespaceBuffer::IsDontNeedSafe() const { + return true; +} + +std::unique_ptr LoadFile(int namespace_fd, + const char* path, + bool executable) { + FML_TRACE_EVENT("flutter", "LoadFile", "path", path); + return std::make_unique(namespace_fd, path, + executable); +} + +std::unique_ptr MakeFileMapping(const char* path, + bool executable) { + fuchsia::io::Flags flags = fuchsia::io::PERM_READABLE; + if (executable) { + flags |= fuchsia::io::PERM_EXECUTABLE; + } + + // The returned file descriptor is compatible with standard posix operations + // such as close, mmap, etc. We only need to treat open/open_at specially. + int fd; + const zx_status_t status = fdio_open3_fd(path, uint64_t{flags}, &fd); + if (status != ZX_OK) { + return nullptr; + } + + using Protection = fml::FileMapping::Protection; + + std::initializer_list protection_execute = {Protection::kRead, + Protection::kExecute}; + std::initializer_list protection_read = {Protection::kRead}; + auto mapping = std::make_unique( + fml::UniqueFD{fd}, executable ? protection_execute : protection_read); + + if (!mapping->IsValid()) { + return nullptr; + } + return mapping; +} + +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/file_in_namespace_buffer.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/file_in_namespace_buffer.h new file mode 100644 index 0000000000000000000000000000000000000000..5eeba20f3697ddf60f617960df7c6b250123b550 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/file_in_namespace_buffer.h @@ -0,0 +1,59 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_FILE_IN_NAMESPACE_BUFFER_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FILE_IN_NAMESPACE_BUFFER_H_ + +#include "flutter/fml/mapping.h" + +namespace flutter_runner { + +/// A mapping to a buffer for a file that has been loaded into a namespace. +class FileInNamespaceBuffer final : public fml::Mapping { + public: + /// Loads the file at |path| into the namespace |namespace_fd|, creating + /// a mapping to the loaded buffer. + /// + /// The file will be loaded with the readable permission. If |executable| is + /// true, the file will also be loaded with the executable permission. + FileInNamespaceBuffer(int namespace_fd, const char* path, bool executable); + ~FileInNamespaceBuffer(); + + // |fml::Mapping| + const uint8_t* GetMapping() const override; + + // |fml::Mapping| + size_t GetSize() const override; + + // |fml::Mapping| + bool IsDontNeedSafe() const override; + + private: + /// The address that was mapped to the buffer. + void* address_; + + /// The size of the buffer. + size_t size_; + + FML_DISALLOW_COPY_AND_ASSIGN(FileInNamespaceBuffer); +}; + +/// Loads a file from |file_path| into the namespace |namespace_fd|, returning +/// the mapping for that file. +/// +/// The file will be loaded with the readable permission. If |executable| is +/// true, the file will be also be loaded with the executable permission. +std::unique_ptr LoadFile(int namespace_fd, + const char* path, + bool executable); + +/// Opens the file at |path| and creates a file mapping for the file. +/// +/// The file will be opened with the readable permission. If |executable| is +/// true, the file will also be opened with the executable permission. +std::unique_ptr MakeFileMapping(const char* path, + bool executable); + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FILE_IN_NAMESPACE_BUFFER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_connection.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_connection.cc new file mode 100644 index 0000000000000000000000000000000000000000..0973a7846a86a08cac9d04f1998c4da1ed1c65a1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_connection.cc @@ -0,0 +1,418 @@ +// 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 "flatland_connection.h" + +#include +#include + +#include +#include +#include + +#include + +#include "flutter/fml/logging.h" + +namespace flutter_runner { + +namespace { + +// Helper function for traces. +double DeltaFromNowInNanoseconds(const fml::TimePoint& now, + const fml::TimePoint& time) { + return (time - now).ToNanoseconds(); +} + +} // namespace + +FlatlandConnection::FlatlandConnection( + const std::string& debug_label, + fuchsia::ui::composition::FlatlandHandle flatland, + fml::closure error_callback, + on_frame_presented_event on_frame_presented_callback, + async_dispatcher_t* dispatcher) + : dispatcher_(dispatcher), + flatland_(flatland.Bind()), + error_callback_(std::move(error_callback)), + on_frame_presented_callback_(std::move(on_frame_presented_callback)) { + flatland_.set_error_handler([callback = error_callback_](zx_status_t status) { + FML_LOG(ERROR) << "Flatland disconnected: " << zx_status_get_string(status); + callback(); + }); + debug_label_ = debug_label; + flatland_->SetDebugName(debug_label); + flatland_.events().OnError = + fit::bind_member(this, &FlatlandConnection::OnError); + flatland_.events().OnFramePresented = + fit::bind_member(this, &FlatlandConnection::OnFramePresented); + flatland_.events().OnNextFrameBegin = + fit::bind_member(this, &FlatlandConnection::OnNextFrameBegin); +} + +FlatlandConnection::~FlatlandConnection() = default; + +// This method is called from the raster thread. +void FlatlandConnection::Present() { + TRACE_DURATION("flutter", "FlatlandConnection::Present"); + std::scoped_lock lock(threadsafe_state_.mutex_); + if (threadsafe_state_.present_credits_ > 0) { + DoPresent(); + } else { + present_waiting_for_credit_ = true; + } +} + +// This method is called from the raster thread. +void FlatlandConnection::DoPresent() { + TRACE_DURATION("flutter", "FlatlandConnection::DoPresent"); + + std::string per_app_tracing_name = + "Flatland::PerAppPresent[" + debug_label_ + "]"; + TRACE_FLOW_BEGIN("gfx", per_app_tracing_name.c_str(), next_present_trace_id_); + ++next_present_trace_id_; + + FML_CHECK(threadsafe_state_.present_credits_ > 0); + --threadsafe_state_.present_credits_; + + fuchsia::ui::composition::PresentArgs present_args; + present_args.set_requested_presentation_time(0); + present_args.set_acquire_fences(std::move(acquire_fences_)); + + // Schedule acquire fence overflow signaling if there is one. + if (acquire_overflow_ != nullptr) { + FML_CHECK(acquire_overflow_->event_.is_valid()); + async::PostTask(dispatcher_, [dispatcher = dispatcher_, + overflow = acquire_overflow_]() { + const size_t fences_size = overflow->fences_.size(); + std::shared_ptr fences_completed = std::make_shared(0); + std::shared_ptr> closures; + + for (auto i = 0u; i < fences_size; i++) { + auto wait = std::make_unique( + overflow->fences_[i].get(), ZX_EVENT_SIGNALED, 0u); + auto wait_ptr = wait.get(); + wait_ptr->Begin( + dispatcher, + [wait = std::move(wait), overflow, fences_size, fences_completed, + closures](async_dispatcher_t*, async::WaitOnce*, + zx_status_t status, const zx_packet_signal_t*) { + (*fences_completed)++; + FML_CHECK(status == ZX_OK) + << "status: " << zx_status_get_string(status); + if (*fences_completed == fences_size) { + // Signal the acquire fence passed on to Flatland. + const zx_status_t status = + overflow->event_.signal(0, ZX_EVENT_SIGNALED); + FML_CHECK(status == ZX_OK) + << "status: " << zx_status_get_string(status); + } + }); + } + }); + acquire_overflow_.reset(); + } + FML_CHECK(acquire_overflow_ == nullptr); + + present_args.set_release_fences(std::move(previous_present_release_fences_)); + // Frame rate over latency. + present_args.set_unsquashable(true); + flatland_->Present(std::move(present_args)); + + // In Flatland, release fences apply to the content of the previous present. + // Keeping track of the old frame's release fences and swapping ensure we set + // the correct ones for VulkanSurface's interpretation. + previous_present_release_fences_.clear(); + previous_present_release_fences_.swap(current_present_release_fences_); + previous_release_overflow_ = current_release_overflow_; + current_release_overflow_ = nullptr; + + // Similar to the treatment of acquire_fences_overflow_ above. Except in + // the other direction. + if (previous_release_overflow_ != nullptr) { + FML_CHECK(previous_release_overflow_->event_.is_valid()); + + std::shared_ptr fences = previous_release_overflow_; + + async::PostTask(dispatcher_, [dispatcher = dispatcher_, + fences = previous_release_overflow_]() { + FML_CHECK(fences != nullptr); + FML_CHECK(fences->event_.is_valid()); + + auto wait = std::make_unique(fences->event_.get(), + ZX_EVENT_SIGNALED, 0u); + auto wait_ptr = wait.get(); + + wait_ptr->Begin( + dispatcher, [_wait = std::move(wait), fences]( + async_dispatcher_t*, async::WaitOnce*, + zx_status_t status, const zx_packet_signal_t*) { + FML_CHECK(status == ZX_OK) + << "status: " << zx_status_get_string(status); + + // Multiplex signaling all events. + for (auto& event : fences->fences_) { + const zx_status_t status = event.signal(0, ZX_EVENT_SIGNALED); + FML_CHECK(status == ZX_OK) + << "status: " << zx_status_get_string(status); + } + }); + }); + previous_release_overflow_ = nullptr; + } + FML_CHECK(previous_release_overflow_ == nullptr); // Moved. + + acquire_fences_.clear(); +} + +// This method is called from the UI thread. +void FlatlandConnection::AwaitVsync(FireCallbackCallback callback) { + TRACE_DURATION("flutter", "FlatlandConnection::AwaitVsync"); + + std::scoped_lock lock(threadsafe_state_.mutex_); + threadsafe_state_.pending_fire_callback_ = nullptr; + const auto now = fml::TimePoint::Now(); + + // Initial case. + if (MaybeRunInitialVsyncCallback(now, callback)) { + return; + } + + // Throttle case. + if (threadsafe_state_.present_credits_ == 0) { + threadsafe_state_.pending_fire_callback_ = std::move(callback); + return; + } + + // Regular case. + RunVsyncCallback(now, callback); +} + +// This method is called from the UI thread. +void FlatlandConnection::AwaitVsyncForSecondaryCallback( + FireCallbackCallback callback) { + TRACE_DURATION("flutter", + "FlatlandConnection::AwaitVsyncForSecondaryCallback"); + + std::scoped_lock lock(threadsafe_state_.mutex_); + const auto now = fml::TimePoint::Now(); + + // Initial case. + if (MaybeRunInitialVsyncCallback(now, callback)) { + return; + } + + // Regular case. + RunVsyncCallback(now, callback); +} + +// This method is called from the raster thread. +void FlatlandConnection::OnError( + fuchsia::ui::composition::FlatlandError error) { + FML_LOG(ERROR) << "Flatland error: " << static_cast(error); + error_callback_(); +} + +// This method is called from the raster thread. +void FlatlandConnection::OnNextFrameBegin( + fuchsia::ui::composition::OnNextFrameBeginValues values) { + // Collect now before locking because this is an important timing information + // from Scenic. + const auto now = fml::TimePoint::Now(); + + std::scoped_lock lock(threadsafe_state_.mutex_); + threadsafe_state_.present_credits_ += values.additional_present_credits(); + TRACE_DURATION("flutter", "FlatlandConnection::OnNextFrameBegin", + "present_credits", threadsafe_state_.present_credits_); + + if (present_waiting_for_credit_ && threadsafe_state_.present_credits_ > 0) { + DoPresent(); + present_waiting_for_credit_ = false; + } + + // Update vsync_interval_ by calculating the difference between the first two + // presentation times. Flatland always returns >1 presentation_infos, so this + // check is to guard against any changes to this assumption. + if (values.has_future_presentation_infos() && + values.future_presentation_infos().size() > 1) { + threadsafe_state_.vsync_interval_ = fml::TimeDelta::FromNanoseconds( + values.future_presentation_infos().at(1).presentation_time() - + values.future_presentation_infos().at(0).presentation_time()); + } else { + FML_LOG(WARNING) + << "Flatland didn't send enough future_presentation_infos to update " + "vsync interval."; + } + + // Update next_presentation_times_. + std::queue new_times; + for (const auto& info : values.future_presentation_infos()) { + new_times.emplace(fml::TimePoint::FromEpochDelta( + fml::TimeDelta::FromNanoseconds(info.presentation_time()))); + } + threadsafe_state_.next_presentation_times_.swap(new_times); + + // Update vsync_offset_. + // We use modulo here because Flatland may point to the following vsync if + // OnNextFrameBegin() is called after the current frame's latch point. + auto vsync_offset = + (fml::TimePoint::FromEpochDelta(fml::TimeDelta::FromNanoseconds( + values.future_presentation_infos().front().presentation_time())) - + now) % + threadsafe_state_.vsync_interval_; + // Thread contention may result in OnNextFrameBegin() being called after the + // presentation time. Ignore these outliers. + if (vsync_offset > fml::TimeDelta::Zero()) { + threadsafe_state_.vsync_offset_ = vsync_offset; + } + + // Throttle case. + if (threadsafe_state_.pending_fire_callback_ && + threadsafe_state_.present_credits_ > 0) { + RunVsyncCallback(now, threadsafe_state_.pending_fire_callback_); + threadsafe_state_.pending_fire_callback_ = nullptr; + } +} + +// This method is called from the raster thread. +void FlatlandConnection::OnFramePresented( + fuchsia::scenic::scheduling::FramePresentedInfo info) { + on_frame_presented_callback_(std::move(info)); +} + +// Parses and updates next_presentation_times_. +fml::TimePoint FlatlandConnection::GetNextPresentationTime( + const fml::TimePoint& now) { + const fml::TimePoint& cutoff = + now > threadsafe_state_.last_presentation_time_ + ? now + : threadsafe_state_.last_presentation_time_; + + // Remove presentation times that may have been passed. This may happen after + // a long draw call. + while (!threadsafe_state_.next_presentation_times_.empty() && + threadsafe_state_.next_presentation_times_.front() <= cutoff) { + threadsafe_state_.next_presentation_times_.pop(); + } + + // Calculate a presentation time based on + // |threadsafe_state_.last_presentation_time_| that is later than cutoff using + // |vsync_interval| increments if we don't have any future presentation times + // left. + if (threadsafe_state_.next_presentation_times_.empty()) { + auto result = threadsafe_state_.last_presentation_time_; + while (result <= cutoff) { + result = result + threadsafe_state_.vsync_interval_; + } + return result; + } + + // Return the next presentation time in the queue for the regular case. + const auto result = threadsafe_state_.next_presentation_times_.front(); + threadsafe_state_.next_presentation_times_.pop(); + return result; +} + +// This method is called from the UI thread. +bool FlatlandConnection::MaybeRunInitialVsyncCallback( + const fml::TimePoint& now, + FireCallbackCallback& callback) { + // Only sent maybe_run_initial_vsync once. + if (threadsafe_state_.initial_vsync_callback_ran_) { + return false; + } + TRACE_DURATION("flutter", "FlatlandConnection::MaybeRunInitialVsyncCallback"); + const auto frame_end = now + kInitialFlatlandVsyncOffset; + threadsafe_state_.last_presentation_time_ = frame_end; + threadsafe_state_.initial_vsync_callback_ran_ = true; + callback(now, frame_end); + return true; +} + +// This method may be called from the raster or UI thread, but it is safe +// because VsyncWaiter posts the vsync callback on UI thread. +void FlatlandConnection::RunVsyncCallback(const fml::TimePoint& now, + FireCallbackCallback& callback) { + const auto& frame_end = GetNextPresentationTime(now); + const auto& frame_start = frame_end - threadsafe_state_.vsync_offset_; + threadsafe_state_.last_presentation_time_ = frame_end; + TRACE_DURATION("flutter", "FlatlandConnection::RunVsyncCallback", + "frame_start_delta", + DeltaFromNowInNanoseconds(now, frame_start), "frame_end_delta", + DeltaFromNowInNanoseconds(now, frame_end)); + callback(frame_start, frame_end); +} + +// Enqueue a single fence into either the "base" vector of fences, or a +// "special" overflow multiplexer. +// +// Args: +// - fence: the fence to add +// - fences: the "regular" fences vector to add to. +// - overflow: the overflow fences vector. Fences added here if there are +// more than can fit in `fences`. +static void Enqueue(zx::event fence, + std::vector* fences, + std::shared_ptr* overflow) { + constexpr size_t kMaxFences = + fuchsia::ui::composition::MAX_ACQUIRE_RELEASE_FENCE_COUNT; + + // Number of all previously added fences, plus this one. + const auto num_all_fences = + fences->size() + 1 + + ((*overflow == nullptr) ? 0 : (*overflow)->fences_.size()); + + // If more than max number of fences come in, schedule any further fences into + // an overflow. The overflow fences are scheduled for processing here, but are + // processed in DoPresent(). + if (num_all_fences <= kMaxFences) { + fences->push_back(std::move(fence)); + } else if (num_all_fences == kMaxFences + 1) { + // The ownership of the overflow will be handed over to the signaling + // closure on DoPresent call. So we always expect that we enter here with + // overflow not set. + FML_CHECK((*overflow) == nullptr) << "overflow is still active"; + *overflow = std::make_shared(); + + // Set up the overflow fences. Creates an overflow handle, places it + // into `fences` instead of the previous fence, and puts the prior fence + // and this one into overflow. + zx::event overflow_handle = std::move(fences->back()); + fences->pop_back(); + + zx::event overflow_fence; + zx_status_t status = zx::event::create(0, &overflow_fence); + FML_CHECK(status == ZX_OK) << "status: " << zx_status_get_string(status); + + // Every DoPresent should invalidate this handle. Holler if not. + FML_CHECK(!(*overflow)->event_.is_valid()) << "overflow valid"; + status = + overflow_fence.duplicate(ZX_RIGHT_SAME_RIGHTS, &(*overflow)->event_); + FML_CHECK(status == ZX_OK) << "status: " << zx_status_get_string(status); + fences->push_back(std::move(overflow_fence)); + + // Prepare for wait_many call. + (*overflow)->fences_.push_back(std::move(overflow_handle)); + (*overflow)->fences_.push_back(std::move(fence)); + + FML_LOG(INFO) << "Enqueue using fence overflow, expect a performance hit."; + } else { + FML_CHECK((*overflow) != nullptr); + // Just add to the overflow fences. + (*overflow)->fences_.push_back(std::move(fence)); + } +} + +// This method is called from the raster thread. +void FlatlandConnection::EnqueueAcquireFence(zx::event fence) { + Enqueue(std::move(fence), &acquire_fences_, &acquire_overflow_); +} + +// This method is called from the raster thread. +void FlatlandConnection::EnqueueReleaseFence(zx::event fence) { + Enqueue(std::move(fence), ¤t_present_release_fences_, + ¤t_release_overflow_); +} + +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_connection.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_connection.h new file mode 100644 index 0000000000000000000000000000000000000000..e41c945f7fd661d77c2c3a512b9705de35b2acc7 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_connection.h @@ -0,0 +1,165 @@ +// 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. + +// Maintains a connection to Fuchsia's Flatland protocol used for rendering +// 2D graphics scenes. + +#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FLATLAND_CONNECTION_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FLATLAND_CONNECTION_H_ + +#include +#include + +#include "flutter/fml/closure.h" +#include "flutter/fml/macros.h" +#include "flutter/fml/time/time_delta.h" +#include "flutter/fml/time/time_point.h" + +#include "vsync_waiter.h" + +#include +#include +#include +#include + +namespace flutter_runner { + +// The maximum number of fences that can be signaled at a time. +static constexpr size_t kMaxFences = + fuchsia::ui::composition::MAX_ACQUIRE_RELEASE_FENCE_COUNT; + +// A helper to ferry around multiplexed events for signaling. Helps move +// non-copyable events into closures. +class Overflow { + public: + std::vector fences_; + zx::event event_; + Overflow() { fences_.reserve(kMaxFences); }; +}; + +using on_frame_presented_event = + std::function; + +// 10ms interval to target vsync is only used until Scenic sends presentation +// feedback. +static constexpr fml::TimeDelta kInitialFlatlandVsyncOffset = + fml::TimeDelta::FromMilliseconds(10); + +// The component residing on the raster thread that is responsible for +// maintaining the Flatland instance connection and presenting updates. +class FlatlandConnection final { + public: + FlatlandConnection( + const std::string& debug_label, + fuchsia::ui::composition::FlatlandHandle flatland, + fml::closure error_callback, + on_frame_presented_event on_frame_presented_callback, + async_dispatcher_t* dispatcher = async_get_default_dispatcher()); + + ~FlatlandConnection(); + + void Present(); + + // Used to implement VsyncWaiter functionality. + // Note that these two methods are called from the UI thread while the + // rest of the methods on this class are called from the raster thread. + void AwaitVsync(FireCallbackCallback callback); + void AwaitVsyncForSecondaryCallback(FireCallbackCallback callback); + + fuchsia::ui::composition::Flatland* flatland() { return flatland_.get(); } + + fuchsia::ui::composition::TransformId NextTransformId() { + return {++next_transform_id_}; + } + + fuchsia::ui::composition::ContentId NextContentId() { + return {++next_content_id_}; + } + + // Adds a new acquire fence to be sent out to the next Present() call. + // + // Acquire fences must all be signaled by the user. + // + // PERFORMANCE NOTES: + // + // Enqueuing more than 16 fences per frame incurs a performance penalty, so + // use them sparingly. + // + // Skipped frames may cause the number of fences to increase, leading to + // more performance issues. Ideally, the flow of the frames should be smooth. + void EnqueueAcquireFence(zx::event fence); + + // Adds a new release fence to be sent out to the next Present() call. + // + // Release fences are all signaled by Scenic (Flatland server). + // + // See the performance notes on EnqueueAcquireFence for performance details. + void EnqueueReleaseFence(zx::event fence); + + private: + void OnError(fuchsia::ui::composition::FlatlandError error); + + void OnNextFrameBegin( + fuchsia::ui::composition::OnNextFrameBeginValues values); + void OnFramePresented(fuchsia::scenic::scheduling::FramePresentedInfo info); + void DoPresent(); + + fml::TimePoint GetNextPresentationTime(const fml::TimePoint& now); + bool MaybeRunInitialVsyncCallback(const fml::TimePoint& now, + FireCallbackCallback& callback); + void RunVsyncCallback(const fml::TimePoint& now, + FireCallbackCallback& callback); + + async_dispatcher_t* dispatcher_; + + fuchsia::ui::composition::FlatlandPtr flatland_; + + fml::closure error_callback_; + + uint64_t next_transform_id_ = 0; + uint64_t next_content_id_ = 0; + + on_frame_presented_event on_frame_presented_callback_; + bool present_waiting_for_credit_ = false; + + // A flow event trace id for following |Flatland::Present| calls into Scenic. + uint64_t next_present_trace_id_ = 0; + + // This struct contains state that is accessed from both from the UI thread + // (in AwaitVsync) and the raster thread (in OnNextFrameBegin and Present). + // You should always lock mutex_ before touching anything in this struct + struct { + std::mutex mutex_; + std::queue next_presentation_times_; + fml::TimeDelta vsync_interval_ = kInitialFlatlandVsyncOffset; + fml::TimeDelta vsync_offset_ = kInitialFlatlandVsyncOffset; + fml::TimePoint last_presentation_time_; + FireCallbackCallback pending_fire_callback_; + uint32_t present_credits_ = 1; + bool initial_vsync_callback_ran_ = false; + } threadsafe_state_; + + // Acquire fences sent to Flatland. + std::vector acquire_fences_; + + // Multiplexed acquire fences over the critical number of ~16. + std::shared_ptr acquire_overflow_; + + // Release fences sent to Flatland. Similar to acquire fences above. + std::vector current_present_release_fences_; + std::shared_ptr current_release_overflow_; + + // Release fences from the prior call to DoPresent(). + // Similar to acquire fences above. + std::vector previous_present_release_fences_; + std::shared_ptr previous_release_overflow_; + + std::string debug_label_; + + FML_DISALLOW_COPY_AND_ASSIGN(FlatlandConnection); +}; + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FLATLAND_CONNECTION_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/flutter_runner_fakes.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/flutter_runner_fakes.h new file mode 100644 index 0000000000000000000000000000000000000000..c0dbf776b8d0c458206b3a6fe35f16251b8cf0a4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/flutter_runner_fakes.h @@ -0,0 +1,140 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_FLUTTER_RUNNER_FAKES_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FLUTTER_RUNNER_FAKES_H_ + +#include + +namespace flutter_runner_test { +using fuchsia::accessibility::semantics::SemanticsManager; + +class MockSemanticsManager + : public SemanticsManager, + public fuchsia::accessibility::semantics::SemanticTree { + public: + MockSemanticsManager() : tree_binding_(this) {} + + // |fuchsia::accessibility::semantics::SemanticsManager|: + void RegisterViewForSemantics( + fuchsia::ui::views::ViewRef view_ref, + fuchsia::accessibility::semantics::SemanticListenerHandle handle, + fidl::InterfaceRequest + semantic_tree) override { + tree_binding_.Bind(std::move(semantic_tree)); + has_view_ref_ = true; + } + + fidl::InterfaceRequestHandler GetHandler( + async_dispatcher_t* dispatcher) { + return bindings_.GetHandler(this, dispatcher); + } + + bool RegisterViewCalled() { return has_view_ref_; } + + void ResetTree() { + update_count_ = 0; + delete_count_ = 0; + commit_count_ = 0; + last_updated_nodes_.clear(); + last_deleted_node_ids_.clear(); + delete_overflowed_ = false; + update_overflowed_ = false; + } + + void UpdateSemanticNodes( + std::vector nodes) override { + update_count_++; + if (!update_overflowed_) { + size_t size = 0; + for (const auto& node : nodes) { + size += sizeof(node); + size += sizeof(node.attributes().label().size()); + } + update_overflowed_ = size > ZX_CHANNEL_MAX_MSG_BYTES; + } + last_updated_nodes_ = std::move(nodes); + } + + void DeleteSemanticNodes(std::vector node_ids) override { + delete_count_++; + if (!delete_overflowed_) { + size_t size = + sizeof(node_ids) + + (node_ids.size() * flutter_runner::AccessibilityBridge::kNodeIdSize); + delete_overflowed_ = size > ZX_CHANNEL_MAX_MSG_BYTES; + } + last_deleted_node_ids_ = std::move(node_ids); + } + + const std::vector& LastDeletedNodeIds() const { + return last_deleted_node_ids_; + } + + int DeleteCount() const { return delete_count_; } + bool DeleteOverflowed() const { return delete_overflowed_; } + + int UpdateCount() const { return update_count_; } + bool UpdateOverflowed() const { return update_overflowed_; } + + bool ShouldHoldCommitResponse() const { return should_hold_commit_response_; } + + void SetShouldHoldCommitResponse(bool value) { + should_hold_commit_response_ = value; + } + + void InvokeCommitCallback() { + if (commit_callback_) { + commit_callback_(); + } + } + + int CommitCount() const { return commit_count_; } + + const std::vector& LastUpdatedNodes() + const { + return last_updated_nodes_; + } + + void CommitUpdates(CommitUpdatesCallback callback) override { + commit_count_++; + if (should_hold_commit_response_) { + commit_callback_ = std::move(callback); + return; + } + callback(); + } + + void SendSemanticEvent( + fuchsia::accessibility::semantics::SemanticEvent semantic_event, + SendSemanticEventCallback callback) override { + last_events_.emplace_back(std::move(semantic_event)); + callback(); + } + + std::vector& + GetLastEvents() { + return last_events_; + } + + private: + bool has_view_ref_ = false; + fidl::BindingSet bindings_; + fidl::Binding tree_binding_; + + std::vector last_updated_nodes_; + bool update_overflowed_; + int update_count_; + int delete_count_; + bool delete_overflowed_; + std::vector last_deleted_node_ids_; + bool should_hold_commit_response_ = false; + CommitUpdatesCallback commit_callback_; + int commit_count_; + std::vector last_events_; +}; + +} // namespace flutter_runner_test + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FLUTTER_RUNNER_FAKES_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/flutter_runner_product_configuration.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/flutter_runner_product_configuration.cc new file mode 100644 index 0000000000000000000000000000000000000000..6a536d585b0fe42255595d75ac3248dc4865168f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/flutter_runner_product_configuration.cc @@ -0,0 +1,52 @@ +// 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_runner_product_configuration.h" + +#include + +#include "flutter/fml/logging.h" +#include "rapidjson/document.h" + +namespace flutter_runner { + +FlutterRunnerProductConfiguration::FlutterRunnerProductConfiguration( + std::string json_string) { + rapidjson::Document document; + document.Parse(json_string); + + if (!document.IsObject()) { + FML_LOG(ERROR) << "Failed to parse configuration; using defaults: " + << json_string; + return; + } + + // Parse out all values we're expecting. + if (document.HasMember("intercept_all_input")) { + auto& val = document["intercept_all_input"]; + if (val.IsBool()) { + intercept_all_input_ = val.GetBool(); + } + } + if (document.HasMember("software_rendering")) { + auto& val = document["software_rendering"]; + if (val.IsBool()) { + software_rendering_ = val.GetBool(); + } + } + if (document.HasMember("enable_shader_warmup")) { + auto& val = document["enable_shader_warmup"]; + if (val.IsBool()) { + enable_shader_warmup_ = val.GetBool(); + } + } + if (document.HasMember("enable_shader_warmup_dart_hooks")) { + auto& val = document["enable_shader_warmup_dart_hooks"]; + if (val.IsBool()) { + enable_shader_warmup_dart_hooks_ = val.GetBool(); + } + } +} + +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/flutter_runner_product_configuration.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/flutter_runner_product_configuration.h new file mode 100644 index 0000000000000000000000000000000000000000..bcd5d6ab58d211485e898613f99b9eca1cca8b0b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/flutter_runner_product_configuration.h @@ -0,0 +1,32 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_FLUTTER_RUNNER_PRODUCT_CONFIGURATION_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FLUTTER_RUNNER_PRODUCT_CONFIGURATION_H_ + +#include + +namespace flutter_runner { + +class FlutterRunnerProductConfiguration { + public: + FlutterRunnerProductConfiguration() {} + explicit FlutterRunnerProductConfiguration(std::string json_string); + + bool get_intercept_all_input() { return intercept_all_input_; } + bool software_rendering() { return software_rendering_; } + bool enable_shader_warmup() { return enable_shader_warmup_; } + bool enable_shader_warmup_dart_hooks() { + return enable_shader_warmup_dart_hooks_; + } + + private: + bool intercept_all_input_ = false; + bool software_rendering_ = false; + bool enable_shader_warmup_ = false; + bool enable_shader_warmup_dart_hooks_ = true; +}; + +} // namespace flutter_runner +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FLUTTER_RUNNER_PRODUCT_CONFIGURATION_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/focus_delegate.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/focus_delegate.cc new file mode 100644 index 0000000000000000000000000000000000000000..60af4c36419495da5b236902013898708efd774f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/focus_delegate.cc @@ -0,0 +1,153 @@ +// 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 + +#include "focus_delegate.h" + +namespace flutter_runner { + +void FocusDelegate::WatchLoop(std::function callback) { + if (watch_loop_) { + FML_LOG(ERROR) << "FocusDelegate::WatchLoop() must be called once."; + return; + } + + watch_loop_ = [this, /*copy*/ callback](auto focus_state) { + callback(is_focused_ = focus_state.focused()); + Complete(std::exchange(next_focus_request_, nullptr), + is_focused_ ? "[true]" : "[false]"); + view_ref_focused_->Watch(/*copy*/ watch_loop_); + }; + + view_ref_focused_->Watch(/*copy*/ watch_loop_); +} + +bool FocusDelegate::HandlePlatformMessage( + rapidjson::Value request, + fml::RefPtr response) { + auto method = request.FindMember("method"); + if (method == request.MemberEnd() || !method->value.IsString()) { + return false; + } + + if (method->value == "View.focus.getCurrent") { + Complete(std::move(response), is_focused_ ? "[true]" : "[false]"); + } else if (method->value == "View.focus.getNext") { + if (next_focus_request_) { + FML_LOG(ERROR) << "An outstanding PlatformMessageResponse already exists " + "for the next focus state!"; + Complete(std::move(response), "[null]"); + } else { + next_focus_request_ = std::move(response); + } + } else if (method->value == "View.focus.request") { + auto args_it = request.FindMember("args"); + if (args_it == request.MemberEnd() || !args_it->value.IsObject()) { + FML_LOG(ERROR) << "No arguments found."; + return false; + } + const auto& args = args_it->value; + + auto view_ref = args.FindMember("viewRef"); + if (!view_ref->value.IsUint64()) { + FML_LOG(ERROR) << "Argument 'viewRef' is not a uint64"; + return false; + } + + zx_handle_t handle = view_ref->value.GetUint64(); + zx_handle_t out_handle; + zx_status_t status = + zx_handle_duplicate(handle, ZX_RIGHT_SAME_RIGHTS, &out_handle); + if (status != ZX_OK) { + FML_LOG(ERROR) << "Argument 'viewRef' is not valid"; + return false; + } + auto ref = fuchsia::ui::views::ViewRef({ + .reference = zx::eventpair(out_handle), + }); + return RequestFocusByViewRef(std::move(ref), std::move(response)); + + } else if (method->value == "View.focus.requestById") { + auto args_it = request.FindMember("args"); + if (args_it == request.MemberEnd() || !args_it->value.IsObject()) { + FML_LOG(ERROR) << "No arguments found."; + return false; + } + const auto& args = args_it->value; + + auto view_id = args.FindMember("viewId"); + if (!view_id->value.IsUint64()) { + FML_LOG(ERROR) << "Argument 'viewId' is not a uint64"; + return false; + } + + auto id = view_id->value.GetUint64(); + if (child_view_view_refs_.count(id) != 1) { + FML_LOG(ERROR) << "Argument 'viewId' (" << id + << ") does not refer to a valid ChildView"; + Complete(std::move(response), "[1]"); + return true; + } + + return RequestFocusById(id, std::move(response)); + } else { + return false; + } + // All of our methods complete the platform message response. + return true; +} + +void FocusDelegate::OnChildViewViewRef(uint64_t view_id, + fuchsia::ui::views::ViewRef view_ref) { + FML_CHECK(child_view_view_refs_.count(view_id) == 0); + child_view_view_refs_[view_id] = std::move(view_ref); +} + +void FocusDelegate::OnDisposeChildView(uint64_t view_id) { + FML_CHECK(child_view_view_refs_.count(view_id) == 1); + child_view_view_refs_.erase(view_id); +} + +void FocusDelegate::Complete( + fml::RefPtr response, + std::string value) { + if (response) { + response->Complete(std::make_unique( + std::vector(value.begin(), value.end()))); + } +} + +bool FocusDelegate::RequestFocusById( + uint64_t view_id, + fml::RefPtr response) { + fuchsia::ui::views::ViewRef ref; + auto status = child_view_view_refs_[view_id].Clone(&ref); + if (status != ZX_OK) { + FML_LOG(ERROR) << "Failed to clone ViewRef"; + return false; + } + + return RequestFocusByViewRef(std::move(ref), std::move(response)); +} + +bool FocusDelegate::RequestFocusByViewRef( + fuchsia::ui::views::ViewRef view_ref, + fml::RefPtr response) { + focuser_->RequestFocus( + std::move(view_ref), + [this, response = std::move(response)]( + fuchsia::ui::views::Focuser_RequestFocus_Result result) { + int result_code = + result.is_err() + ? static_cast< + std::underlying_type_t>( + result.err()) + : 0; + Complete(std::move(response), "[" + std::to_string(result_code) + "]"); + }); + return true; +} + +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/focus_delegate.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/focus_delegate.h new file mode 100644 index 0000000000000000000000000000000000000000..aa18fcf7b144de502c6ef8e25bf5c26a469587e5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/focus_delegate.h @@ -0,0 +1,84 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_FOCUS_DELEGATE_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FOCUS_DELEGATE_H_ + +#include + +#include + +#include "flutter/fml/macros.h" +#include "flutter/lib/ui/window/platform_message.h" +#include "third_party/rapidjson/include/rapidjson/document.h" + +namespace flutter_runner { + +class FocusDelegate { + public: + FocusDelegate(fuchsia::ui::views::ViewRefFocusedHandle view_ref_focused, + fuchsia::ui::views::FocuserHandle focuser) + : view_ref_focused_(view_ref_focused.Bind()), focuser_(focuser.Bind()) {} + + /// Continuously watches the host viewRef for focus events, invoking a + /// callback each time. + /// + /// The callback is invoked on each Watch() call, which consumes the callback + /// argument. Hence, the callback argument must be copyable, so that a copy + /// can be freely moved into the Watch() call. + /// + /// This method can only be called once. + void WatchLoop(std::function callback); + + /// Handles the following focus-related platform message requests: + /// View.focus.getCurrent + /// - Completes with the FocusDelegate's most recent focus state, either + /// [true] or [false]. + /// View.focus.getNext + /// - Completes with the FocusDelegate's next focus state, either [true] or + /// [false]. + /// - Only one outstanding request may exist at a time. Any others will be + /// completed with [null]. + /// View.focus.request + /// - Attempts to give focus for a given viewRef. Completes with [0] on + /// success, or [fuchsia::ui::views::Error] on failure. + /// + /// Returns false if a malformed/invalid request needs to be completed empty. + bool HandlePlatformMessage( + rapidjson::Value request, + fml::RefPtr response); + + void OnChildViewViewRef(uint64_t view_id, + fuchsia::ui::views::ViewRef view_ref); + + void OnDisposeChildView(uint64_t view_id); + + private: + fuchsia::ui::views::ViewRefFocusedPtr view_ref_focused_; + fuchsia::ui::views::FocuserPtr focuser_; + + std::unordered_map + child_view_view_refs_; + + std::function watch_loop_; + bool is_focused_ = false; + fml::RefPtr next_focus_request_; + + void Complete(fml::RefPtr response, + std::string value); + + /// Completes a platform message request by attempting to give focus for a + /// given view. + bool RequestFocusById(uint64_t view_id, + fml::RefPtr response); + bool RequestFocusByViewRef( + fuchsia::ui::views::ViewRef view_ref, + fml::RefPtr response); + + FML_DISALLOW_COPY_AND_ASSIGN(FocusDelegate); +}; + +} // namespace flutter_runner +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FOCUS_DELEGATE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/focus_delegate_unittests.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/focus_delegate_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..f8e9bda254dc822d6c3bd9f9aa76da4bcf6ec323 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/focus_delegate_unittests.cc @@ -0,0 +1,198 @@ +// 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 +#include +#include +#include +#include +#include + +#include "focus_delegate.h" +#include "tests/fakes/focuser.h" +#include "tests/fakes/platform_message.h" +#include "tests/fakes/view_ref_focused.h" +#include "third_party/rapidjson/include/rapidjson/document.h" + +rapidjson::Value ParsePlatformMessage(std::string json) { + rapidjson::Document document; + document.Parse(json); + if (document.HasParseError() || !document.IsObject()) { + FML_LOG(ERROR) << "Could not parse document"; + return rapidjson::Value(); + } + return document.GetObject(); +} + +namespace flutter_runner::testing { + +class FocusDelegateTest : public ::testing::Test { + protected: + FocusDelegateTest() : loop_(&kAsyncLoopConfigAttachToCurrentThread) {} + + void RunLoopUntilIdle() { loop_.RunUntilIdle(); } + + void SetUp() override { + vrf_ = std::make_unique(); + focuser_ = std::make_unique(); + focus_delegate_ = std::make_unique( + vrf_bindings.AddBinding(vrf_.get()), + focuser_bindings.AddBinding(focuser_.get())); + } + + void TearDown() override { + vrf_bindings.CloseAll(); + focuser_bindings.CloseAll(); + loop_.Quit(); + loop_.ResetQuit(); + } + + std::unique_ptr vrf_; + std::unique_ptr focuser_; + std::unique_ptr focus_delegate_; + + private: + async::Loop loop_; + fidl::BindingSet vrf_bindings; + fidl::BindingSet focuser_bindings; + + FML_DISALLOW_COPY_AND_ASSIGN(FocusDelegateTest); +}; + +// Tests that WatchLoop() should callback and complete PlatformMessageResponses +// correctly, given a series of vrf invocations. +TEST_F(FocusDelegateTest, WatchCallbackSeries) { + std::vector vrf_states{false, true, true, false, + true, false, true, true}; + std::size_t vrf_index = 0; + std::size_t callback_index = 0; + focus_delegate_->WatchLoop([&](bool focus_state) { + // Make sure the focus state that FocusDelegate gives us is consistent with + // what was fired from the vrf. + EXPECT_EQ(vrf_states[callback_index], focus_state); + + // View.focus.getCurrent should complete with the current (up to date) focus + // state. + auto response = FakePlatformMessageResponse::Create(); + EXPECT_TRUE(focus_delegate_->HandlePlatformMessage( + ParsePlatformMessage("{\"method\":\"View.focus.getCurrent\"}"), + response)); + response->ExpectCompleted(focus_state ? "[true]" : "[false]"); + + // Ensure this callback always happens in lockstep with + // vrf_->ScheduleCallback. + EXPECT_EQ(vrf_index, callback_index++); + }); + + // Subsequent WatchLoop calls should not be respected. + focus_delegate_->WatchLoop([](bool _) { + ADD_FAILURE() << "Subsequent WatchLoops should not be respected!"; + }); + + do { + // Ensure the next focus state is handled correctly. + auto response1 = FakePlatformMessageResponse::Create(); + EXPECT_TRUE(focus_delegate_->HandlePlatformMessage( + ParsePlatformMessage("{\"method\":\"View.focus.getNext\"}"), + response1)); + + // Since there's already an outstanding PlatformMessageResponse, this one + // should be completed null. + auto response2 = FakePlatformMessageResponse::Create(); + EXPECT_TRUE(focus_delegate_->HandlePlatformMessage( + ParsePlatformMessage("{\"method\":\"View.focus.getNext\"}"), + response2)); + response2->ExpectCompleted("[null]"); + + // Post watch events and trigger the next vrf event. + RunLoopUntilIdle(); + vrf_->ScheduleCallback(vrf_states[vrf_index]); + RunLoopUntilIdle(); + + // Next focus state should be completed by now. + response1->ExpectCompleted(vrf_states[vrf_index] ? "[true]" : "[false]"); + + // Check View.focus.getCurrent again, and increment vrf_index since we move + // on to the next focus state. + auto response3 = FakePlatformMessageResponse::Create(); + EXPECT_TRUE(focus_delegate_->HandlePlatformMessage( + ParsePlatformMessage("{\"method\":\"View.focus.getCurrent\"}"), + response3)); + response3->ExpectCompleted(vrf_states[vrf_index++] ? "[true]" : "[false]"); + + // vrf_->times_watched should always be 1 more than the amount of vrf events + // emitted. + EXPECT_EQ(vrf_index + 1, vrf_->times_watched); + } while (vrf_index < vrf_states.size()); +} + +// Tests that HandlePlatformMessage() completes a "View.focus.request" response +// with a non-error status code. +TEST_F(FocusDelegateTest, RequestFocusTest) { + // This "Mock" ViewRef serves as the target for the RequestFocus operation. + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ZX_ASSERT(status == ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + + // Create the platform message request. + std::ostringstream message; + message << "{" << " \"method\":\"View.focus.request\"," + << " \"args\": {" + << " \"viewRef\":" << view_ref.reference.get() << " }" + << "}"; + + // Dispatch the plaform message request with an expected completion response. + auto response = FakePlatformMessageResponse::Create(); + EXPECT_TRUE(focus_delegate_->HandlePlatformMessage( + ParsePlatformMessage(message.str()), response)); + RunLoopUntilIdle(); + + response->ExpectCompleted("[0]"); + EXPECT_TRUE(focuser_->request_focus_called()); +} + +// Tests that HandlePlatformMessage() completes a "View.focus.request" response +// with a Error::DENIED status code. +TEST_F(FocusDelegateTest, RequestFocusFailTest) { + // This "Mock" ViewRef serves as the target for the RequestFocus operation. + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ZX_ASSERT(status == ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + // We're testing the focus failure case. + focuser_->fail_request_focus(); + // Create the platform message request. + std::ostringstream message; + message << "{" << " \"method\":\"View.focus.request\"," + << " \"args\": {" + << " \"viewRef\":" << view_ref.reference.get() << " }" + << "}"; + + // Dispatch the plaform message request with an expected completion response. + auto response = FakePlatformMessageResponse::Create(); + EXPECT_TRUE(focus_delegate_->HandlePlatformMessage( + ParsePlatformMessage(message.str()), response)); + RunLoopUntilIdle(); + + response->ExpectCompleted( + "[" + + std::to_string( + static_cast>( + fuchsia::ui::views::Error::DENIED)) + + "]"); + EXPECT_TRUE(focuser_->request_focus_called()); +} + +} // namespace flutter_runner::testing diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/fuchsia_intl.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/fuchsia_intl.cc new file mode 100644 index 0000000000000000000000000000000000000000..85c91b4d8662b66c45178e8355c6589c3c1f34bd --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/fuchsia_intl.cc @@ -0,0 +1,71 @@ +// 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 "fuchsia_intl.h" + +#include +#include +#include + +#include "rapidjson/document.h" +#include "rapidjson/stringbuffer.h" +#include "rapidjson/writer.h" +#include "runner.h" +#include "runtime/dart/utils/tempfs.h" +#include "third_party/icu/source/common/unicode/bytestream.h" +#include "third_party/icu/source/common/unicode/errorcode.h" +#include "third_party/icu/source/common/unicode/locid.h" +#include "third_party/icu/source/common/unicode/strenum.h" +#include "third_party/icu/source/common/unicode/stringpiece.h" +#include "third_party/icu/source/common/unicode/uloc.h" + +using icu::Locale; + +namespace flutter_runner { + +using fuchsia::intl::Profile; + +fml::MallocMapping MakeLocalizationPlatformMessageData( + const Profile& intl_profile) { + rapidjson::Document document; + auto& allocator = document.GetAllocator(); + document.SetObject(); + document.AddMember("method", "setLocale", allocator); + rapidjson::Value args(rapidjson::kArrayType); + + for (const auto& locale_id : intl_profile.locales()) { + UErrorCode error_code = U_ZERO_ERROR; + icu::Locale locale = icu::Locale::forLanguageTag(locale_id.id, error_code); + if (U_FAILURE(error_code)) { + FML_LOG(ERROR) << "Error parsing locale ID \"" << locale_id.id << "\""; + continue; + } + args.PushBack(rapidjson::Value().SetString(locale.getLanguage(), allocator), + allocator); + + auto country = locale.getCountry() != nullptr ? locale.getCountry() : ""; + args.PushBack(rapidjson::Value().SetString(country, allocator), allocator); + + auto script = locale.getScript() != nullptr ? locale.getScript() : ""; + args.PushBack(rapidjson::Value().SetString(script, allocator), allocator); + + std::string variant = + locale.getVariant() != nullptr ? locale.getVariant() : ""; + // ICU4C capitalizes the variant for backward compatibility, even though + // the preferred form is lowercase. So we lowercase here. + std::transform(begin(variant), end(variant), begin(variant), + [](unsigned char c) { return std::tolower(c); }); + args.PushBack(rapidjson::Value().SetString(variant, allocator), allocator); + } + + document.AddMember("args", args, allocator); + + rapidjson::StringBuffer buffer; + rapidjson::Writer writer(buffer); + document.Accept(writer); + auto data = reinterpret_cast(buffer.GetString()); + return fml::MallocMapping::Copy(data, buffer.GetSize()); +} + +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/fuchsia_intl.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/fuchsia_intl.h new file mode 100644 index 0000000000000000000000000000000000000000..20799c9d5e42e2b9a758c05cd565dcd4e3dee5b6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/fuchsia_intl.h @@ -0,0 +1,24 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_FUCHSIA_INTL_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FUCHSIA_INTL_H_ + +#include +#include "flutter/fml/mapping.h" + +namespace flutter_runner { + +// Make a byte vector containing the JSON string used for a localization +// PlatformMessage, using the locale list in the given Profile. +// +// This method does not return a `std::unique_ptr` for +// testing convenience; that would require an unreasonably large set of +// dependencies for the unit tests. +fml::MallocMapping MakeLocalizationPlatformMessageData( + const fuchsia::intl::Profile& intl_profile); + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FUCHSIA_INTL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/fuchsia_intl_unittest.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/fuchsia_intl_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..dddca90303dad1cf0c1fbfd65a4f3b381ec3c2fa --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/fuchsia_intl_unittest.cc @@ -0,0 +1,75 @@ +// 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 + +#include "flutter/fml/icu_util.h" +#include "gtest/gtest.h" + +#include "fuchsia_intl.h" + +using fuchsia::intl::CalendarId; +using fuchsia::intl::LocaleId; +using fuchsia::intl::Profile; +using fuchsia::intl::TemperatureUnit; +using fuchsia::intl::TimeZoneId; + +namespace flutter_runner { +namespace { + +class FuchsiaIntlTest : public testing::Test { + public: + static void SetUpTestCase() { + testing::Test::SetUpTestCase(); + // The icudtl data must be present as a resource in the package for this + // load to succeed. + fml::icu::InitializeICU("/pkg/data/icudtl.dat"); + } +}; + +TEST_F(FuchsiaIntlTest, MakeLocalizationPlatformMessageData_SimpleLocale) { + Profile profile{}; + profile.set_locales({LocaleId{.id = "en-US"}}); + const std::string expected = + R"({"method":"setLocale","args":["en","US","",""]})"; + const auto actual = MakeLocalizationPlatformMessageData(profile); + ASSERT_EQ(expected, std::string(actual.GetMapping(), + actual.GetMapping() + actual.GetSize())); +} + +TEST_F(FuchsiaIntlTest, MakeLocalizationPlatformMessageData_OneLocale) { + Profile profile{}; + profile + .set_locales({LocaleId{.id = "en-US-u-ca-gregory-fw-sun-hc-h12-ms-" + "ussystem-nu-latn-tz-usnyc"}}) + .set_calendars({CalendarId{.id = "und-u-gregory"}}) + .set_time_zones({TimeZoneId{.id = "America/New_York"}}) + .set_temperature_unit(TemperatureUnit::FAHRENHEIT); + const std::string expected = + R"({"method":"setLocale","args":["en","US","",""]})"; + const auto actual = MakeLocalizationPlatformMessageData(profile); + ASSERT_EQ(expected, std::string(actual.GetMapping(), + actual.GetMapping() + actual.GetSize())); +} + +TEST_F(FuchsiaIntlTest, MakeLocalizationPlatformMessageData_MultipleLocales) { + Profile profile{}; + profile + .set_locales({LocaleId{.id = "en-US-u-ca-gregory-fw-sun-hc-h12-ms-" + "ussystem-nu-latn-tz-usnyc"}, + LocaleId{.id = "sl-Latn-IT-nedis"}, + LocaleId{.id = "zh-Hans"}, LocaleId{.id = "sr-Cyrl-CS"}}) + .set_calendars({CalendarId{.id = "und-u-gregory"}}) + .set_time_zones({TimeZoneId{.id = "America/New_York"}}) + .set_temperature_unit(TemperatureUnit::FAHRENHEIT); + const std::string expected = + R"({"method":"setLocale","args":["en","US","","","sl","IT","Latn","nedis",)" + R"("zh","","Hans","","sr","CS","Cyrl",""]})"; + const auto actual = MakeLocalizationPlatformMessageData(profile); + ASSERT_EQ(expected, std::string(actual.GetMapping(), + actual.GetMapping() + actual.GetSize())); +} + +} // namespace +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/isolate_configurator.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/isolate_configurator.cc new file mode 100644 index 0000000000000000000000000000000000000000..8c3d457a6a6c8a38aad88832bcfb24c95c1b3512 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/isolate_configurator.cc @@ -0,0 +1,90 @@ +// 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 "isolate_configurator.h" + +#include "dart-pkg/fuchsia/sdk_ext/fuchsia.h" +#include "dart-pkg/zircon/sdk_ext/handle.h" +#include "third_party/dart/runtime/include/dart_api.h" +#include "third_party/tonic/converter/dart_converter.h" +#include "third_party/tonic/dart_state.h" +#include "third_party/tonic/logging/dart_error.h" + +namespace flutter_runner { + +IsolateConfigurator::IsolateConfigurator(UniqueFDIONS fdio_ns, + zx::channel directory_request, + zx::eventpair view_ref) + : fdio_ns_(std::move(fdio_ns)), + directory_request_(std::move(directory_request)), + view_ref_(std::move(view_ref)) {} + +IsolateConfigurator::~IsolateConfigurator() = default; + +bool IsolateConfigurator::ConfigureCurrentIsolate() { + if (used_) { + return false; + } + used_ = true; + + BindFuchsia(); + BindZircon(); + BindDartIO(); + + // This is now owned by the Dart bindings. So relinquish our ownership of the + // handle. + (void)fdio_ns_.release(); + + return true; +} + +void IsolateConfigurator::BindFuchsia() { + fuchsia::dart::Initialize(std::move(directory_request_), + std::move(view_ref_)); +} + +void IsolateConfigurator::BindZircon() { + // Tell dart:zircon about the FDIO namespace configured for this instance. + Dart_Handle zircon_lib = Dart_LookupLibrary(tonic::ToDart("dart:zircon")); + FML_CHECK(!tonic::CheckAndHandleError(zircon_lib)); + + Dart_Handle namespace_type = Dart_GetNonNullableType( + zircon_lib, tonic::ToDart("_Namespace"), 0, nullptr); + FML_CHECK(!tonic::CheckAndHandleError(namespace_type)); + + Dart_Handle result = + Dart_SetField(namespace_type, // + tonic::ToDart("_namespace"), // + tonic::ToDart(reinterpret_cast(fdio_ns_.get()))); + FML_CHECK(!tonic::CheckAndHandleError(result)); +} + +void IsolateConfigurator::BindDartIO() { + // Grab the dart:io lib. + Dart_Handle io_lib = Dart_LookupLibrary(tonic::ToDart("dart:io")); + FML_CHECK(!tonic::CheckAndHandleError(io_lib)); + + // Disable dart:io exit() + Dart_Handle embedder_config_type = Dart_GetNonNullableType( + io_lib, tonic::ToDart("_EmbedderConfig"), 0, nullptr); + FML_CHECK(!tonic::CheckAndHandleError(embedder_config_type)); + + Dart_Handle result = Dart_SetField(embedder_config_type, + tonic::ToDart("_mayExit"), Dart_False()); + FML_CHECK(!tonic::CheckAndHandleError(result)); + + // Tell dart:io about the FDIO namespace configured for this instance. + Dart_Handle namespace_type = + Dart_GetNonNullableType(io_lib, tonic::ToDart("_Namespace"), 0, nullptr); + FML_CHECK(!tonic::CheckAndHandleError(namespace_type)); + + Dart_Handle namespace_args[] = { + Dart_NewInteger(reinterpret_cast(fdio_ns_.get())), // + }; + result = Dart_Invoke(namespace_type, tonic::ToDart("_setupNamespace"), 1, + namespace_args); + FML_CHECK(!tonic::CheckAndHandleError(result)); +} + +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/isolate_configurator.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/isolate_configurator.h new file mode 100644 index 0000000000000000000000000000000000000000..69580600b938cf68125a692552e6e9fdc03c56bc --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/isolate_configurator.h @@ -0,0 +1,47 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_ISOLATE_CONFIGURATOR_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_ISOLATE_CONFIGURATOR_H_ + +#include +#include +#include "flutter/fml/macros.h" +#include "unique_fdio_ns.h" + +namespace flutter_runner { + +// Contains all the information necessary to configure a new root isolate. This +// is a single use item. The lifetime of this object must extend past that of +// the root isolate. +class IsolateConfigurator final { + public: + IsolateConfigurator(UniqueFDIONS fdio_ns, + zx::channel directory_request, + zx::eventpair view_ref); + + ~IsolateConfigurator(); + + // Can be used only once and only on the UI thread with the newly created + // isolate already current. + bool ConfigureCurrentIsolate(); + + private: + bool used_ = false; + UniqueFDIONS fdio_ns_; + zx::channel directory_request_; + zx::eventpair view_ref_; + + void BindFuchsia(); + + void BindZircon(); + + void BindDartIO(); + + FML_DISALLOW_COPY_AND_ASSIGN(IsolateConfigurator); +}; + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_ISOLATE_CONFIGURATOR_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/kernel/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/kernel/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..76cba08883e9ce888236155bb00ac85f52ccd15c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/kernel/BUILD.gn @@ -0,0 +1,89 @@ +# 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. + +import("//build/compiled_action.gni") +import("//flutter/common/config.gni") +import("//flutter/tools/fuchsia/dart.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") +import("$dart_src/utils/compile_platform.gni") + +compile_platform("kernel_platform_files") { + single_root_scheme = "org-dartlang-sdk" + single_root_base = rebase_path("../../../../../../") + + libraries_specification_uri = "org-dartlang-sdk:///flutter/shell/platform/fuchsia/flutter/kernel/libraries.json" + + outputs = [ + "$root_out_dir/flutter_runner_patched_sdk/platform_strong.dill", + "$root_out_dir/flutter_runner_patched_sdk/vm_outline_strong.dill", + ] + + args = [ + "--nnbd-strong", + "--target=flutter_runner", + "dart:core", + ] +} + +template("core_snapshot") { + assert(defined(invoker.product), + "core_snapshot requires 'product' to be defined") + + suffix = "" + + if (invoker.product) { + suffix = "${suffix}_product" + } + + compiled_action(target_name) { + deps = [ ":kernel_platform_files" ] + + platform_dill = + "$root_out_dir/flutter_runner_patched_sdk/platform_strong.dill" + inputs = [ platform_dill ] + + vm_snapshot_data = "$target_gen_dir/vm_isolate_snapshot${suffix}.bin" + isolate_snapshot_data = "$target_gen_dir/isolate_snapshot${suffix}.bin" + snapshot_profile = "$target_gen_dir/snapshot_profile${suffix}.json" + outputs = [ + vm_snapshot_data, + isolate_snapshot_data, + snapshot_profile, + ] + + gen_snapshot_to_use = gen_snapshot + if (invoker.product) { + gen_snapshot_to_use = gen_snapshot_product + } + + tool = gen_snapshot_to_use + + args = [ + "--enable_mirrors=false", + "--deterministic", + "--snapshot_kind=core", + "--vm_snapshot_data=" + rebase_path(vm_snapshot_data, root_build_dir), + "--isolate_snapshot_data=" + + rebase_path(isolate_snapshot_data, root_build_dir), + "--write_v8_snapshot_profile_to=" + + rebase_path(snapshot_profile, root_build_dir), + ] + + # No asserts in debug or release product. + # No asserts in release with flutter_profile=true (non-product) + # Yes asserts in non-product debug. + if (!invoker.product && (is_debug || flutter_runtime_mode == "debug")) { + args += [ "--enable_asserts" ] + } + args += [ rebase_path(platform_dill) ] + } +} + +core_snapshot("kernel_core_snapshot") { + product = false +} + +core_snapshot("kernel_core_snapshot_product") { + product = true +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/kernel/analysis_options.yaml b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/kernel/analysis_options.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7eb15db6a49e528733e2928dc328e09b89f17106 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/kernel/analysis_options.yaml @@ -0,0 +1,12 @@ +# 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: ../../../../../analysis_options.yaml +analyzer: + errors: + avoid_catches_without_on_clauses: ignore + cascade_invocations: ignore + only_throw_errors: ignore # adds noise to error messages + prefer_foreach: ignore # for-in is preferable to closurization + prefer_single_quotes: ignore diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/kernel/framework_shim.dart b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/kernel/framework_shim.dart new file mode 100644 index 0000000000000000000000000000000000000000..8c1443f141254b32b3a8f7ea48426fca7229034f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/kernel/framework_shim.dart @@ -0,0 +1,7 @@ +// 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. + +import 'package:flutter/material.dart'; + +main() {} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/kernel/libraries.json b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/kernel/libraries.json new file mode 100644 index 0000000000000000000000000000000000000000..85c1bce6f246b20d8062cc397ec3d49db1d63f94 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/kernel/libraries.json @@ -0,0 +1,29 @@ +{ + "comment:0": "NOTE: THIS FILE IS GENERATED. DO NOT EDIT.", + "comment:1": "Instead modify 'flutter/shell/platform/fuchsia/flutter/kernel/libraries.yaml' and follow the instructions therein.", + "flutter_runner": { + "include": [ + { + "path": "../../../../../third_party/dart/sdk/lib/libraries.json", + "target": "vm_common" + } + ], + "libraries": { + "fuchsia.builtin": { + "uri": "../../dart_runner/embedder/builtin.dart" + }, + "zircon": { + "uri": "../../dart-pkg/zircon/lib/zircon.dart" + }, + "zircon_ffi": { + "uri": "../../dart-pkg/zircon_ffi/lib/zircon_ffi.dart" + }, + "fuchsia": { + "uri": "../../dart-pkg/fuchsia/lib/fuchsia.dart" + }, + "ui": { + "uri": "../../../../../lib/ui/ui.dart" + } + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/kernel/libraries.yaml b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/kernel/libraries.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1fcb27c975933158148e152fa5e47dcc75b1afd6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/kernel/libraries.yaml @@ -0,0 +1,33 @@ +# Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file +# for details. All rights reserved. Use of this source code is governed by a +# BSD-style license that can be found in the LICENSE file. + +# Note: if you edit this file, you must also generate libraries.json in this +# directory: +# +# dart third_party/dart/tools/yaml2json.dart flutter/shell/platform/fuchsia/flutter/kernel/libraries.yaml flutter/shell/platform/fuchsia/flutter/kernel/libraries.json +# +# We currently have several different files that needs to be updated when +# changing libraries, sources, and patch files. See +# https://github.com/dart-lang/sdk/issues/28836. + +flutter_runner: + include: + - {path: "../../../../../../third_party/dart/sdk/lib/libraries.json", target: vm_common} + libraries: + fuchsia.builtin: + uri: "../../dart_runner/embedder/builtin.dart" + + zircon: + uri: "../../dart-pkg/zircon/lib/zircon.dart" + + zircon_ffi: + uri: "../../dart-pkg/zircon_ffi/lib/zircon_ffi.dart" + + fuchsia: + uri: "../../dart-pkg/fuchsia/lib/fuchsia.dart" + + ui: + uri: "../../../../../lib/ui/ui.dart" + + diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/kernel/pubspec.yaml b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/kernel/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fdacaaf5bde03bcc9d9f7a0a44173762596a70ce --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/kernel/pubspec.yaml @@ -0,0 +1,6 @@ +# 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. + +environment: + sdk: ^3.7.0-0 diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/keyboard.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/keyboard.cc new file mode 100644 index 0000000000000000000000000000000000000000..25c23ab913382209adbf08e1d87b9a893b2e87c5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/keyboard.cc @@ -0,0 +1,353 @@ +// 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/shell/platform/fuchsia/flutter/keyboard.h" + +#include +#include +#include + +#include + +namespace flutter_runner { + +using fuchsia::input::Key; +using fuchsia::ui::input::kModifierCapsLock; +using fuchsia::ui::input::kModifierLeftAlt; +using fuchsia::ui::input::kModifierLeftControl; +using fuchsia::ui::input::kModifierLeftShift; +using fuchsia::ui::input::kModifierNone; +using fuchsia::ui::input::kModifierRightAlt; +using fuchsia::ui::input::kModifierRightControl; +using fuchsia::ui::input::kModifierRightShift; +using fuchsia::ui::input3::KeyEvent; +using fuchsia::ui::input3::KeyEventType; + +namespace { + +// A simple keymap from a QWERTY keyboard to code points. A value 0 means no +// code point has been assigned for the respective keypress. Column 0 is the +// code point without a level modifier active, and Column 1 is the code point +// with a level modifier (e.g. Shift key) active. +static const uint32_t QWERTY_TO_CODE_POINTS[][2] = { + // 0x00 + {}, + {}, + {}, + {}, + // 0x04, + {'a', 'A'}, + {'b', 'B'}, + {'c', 'C'}, + {'d', 'D'}, + // 0x08 + {'e', 'E'}, + {'f', 'F'}, + {'g', 'G'}, + {'h', 'H'}, + // 0x0c + {'i', 'I'}, + {'j', 'J'}, + {'k', 'K'}, + {'l', 'L'}, + // 0x10 + {'m', 'M'}, + {'n', 'N'}, + {'o', 'O'}, + {'p', 'P'}, + // 0x14 + {'q', 'Q'}, + {'r', 'R'}, + {'s', 'S'}, + {'t', 'T'}, + // 0x18 + {'u', 'U'}, + {'v', 'V'}, + {'w', 'W'}, + {'x', 'X'}, + // 0x1c + {'y', 'Y'}, + {'z', 'Z'}, + {'1', '!'}, + {'2', '@'}, + // 0x20 + {'3', '#'}, + {'4', '$'}, + {'5', '%'}, + {'6', '^'}, + // 0x24 + {'7', '&'}, + {'8', '*'}, + {'9', '('}, + {'0', ')'}, + // 0x28 + {}, + {}, + {}, + {}, + // 0x2c + {' ', ' '}, + {'-', '_'}, + {'=', '+'}, + {'[', '{'}, + // 0x30 + {']', '}'}, + {'\\', '|'}, + {}, + {';', ':'}, + // 0x34 + {'\'', '"'}, + {'`', '~'}, + {',', '<'}, + {'.', '>'}, + // 0x38 + {'/', '?'}, + {}, + {}, + {}, + // 0x3c + {}, + {}, + {}, + {}, + // 0x40 + {}, + {}, + {}, + {}, + // 0x44 + {}, + {}, + {}, + {}, + // 0x48 + {}, + {}, + {}, + {}, + // 0x4c + {}, + {}, + {}, + {}, + // 0x50 + {}, + {}, + {}, + {}, + // 0x54 + {'/', 0}, + {'*', 0}, + {'-', 0}, + {'+', 0}, + // 0x58 + {}, + {'1', 0}, + {'2', 0}, + {'3', 0}, + // 0x5c + {'4', 0}, + {'5', 0}, + {'6', 0}, + {'7', 0}, + // 0x60 + {'8', 0}, + {'9', 0}, + {'0', 0}, + {'.', 0}, +}; + +} // namespace + +Keyboard::Keyboard() + : any_events_received_(false), + stateful_caps_lock_(false), + left_shift_(false), + right_shift_(false), + left_alt_(false), + right_alt_(false), + left_ctrl_(false), + right_ctrl_(false), + last_event_() {} + +bool Keyboard::ConsumeEvent(KeyEvent event) { + if (!event.has_type()) { + return false; + } + if (!event.has_key() && !event.has_key_meaning()) { + return false; + } + // Check if the time sequence of the events is correct. + last_event_ = std::move(event); + any_events_received_ = true; + + if (!event.has_key()) { + // The key only has key meaning. Key meaning currently can not + // update the modifier state, so we just short-circuit the table + // below. + return true; + } + + const Key& key = last_event_.key(); + const KeyEventType& event_type = last_event_.type(); + switch (event_type) { + // For modifier keys, a SYNC is the same as a press. + case KeyEventType::SYNC: + switch (key) { + case Key::CAPS_LOCK: + stateful_caps_lock_ = true; + break; + case Key::LEFT_ALT: + left_alt_ = true; + break; + case Key::LEFT_CTRL: + left_ctrl_ = true; + break; + case Key::LEFT_SHIFT: + left_shift_ = true; + break; + case Key::RIGHT_ALT: + right_alt_ = true; + break; + case Key::RIGHT_CTRL: + right_ctrl_ = true; + break; + case Key::RIGHT_SHIFT: + right_shift_ = true; + break; + default: + // no-op + break; + } + break; + case KeyEventType::PRESSED: + switch (key) { + case Key::CAPS_LOCK: + stateful_caps_lock_ = !stateful_caps_lock_; + break; + case Key::LEFT_ALT: + left_alt_ = true; + break; + case Key::LEFT_CTRL: + left_ctrl_ = true; + break; + case Key::LEFT_SHIFT: + left_shift_ = true; + break; + case Key::RIGHT_ALT: + right_alt_ = true; + break; + case Key::RIGHT_CTRL: + right_ctrl_ = true; + break; + case Key::RIGHT_SHIFT: + right_shift_ = true; + break; + default: + // No-op + break; + } + break; + case KeyEventType::RELEASED: + switch (key) { + case Key::CAPS_LOCK: + // No-op. + break; + case Key::LEFT_ALT: + left_alt_ = false; + break; + case Key::LEFT_CTRL: + left_ctrl_ = false; + break; + case Key::LEFT_SHIFT: + left_shift_ = false; + break; + case Key::RIGHT_ALT: + right_alt_ = false; + break; + case Key::RIGHT_CTRL: + right_ctrl_ = false; + break; + case Key::RIGHT_SHIFT: + right_shift_ = false; + break; + default: + // No-op + break; + } + break; + case KeyEventType::CANCEL: + // No-op? + break; + default: + // No-op + break; + } + return true; +} + +bool Keyboard::IsShift() { + return left_shift_ | right_shift_ | stateful_caps_lock_; +} + +bool Keyboard::IsKeys() { + return LastHIDUsagePage() == 0x7; +} + +uint32_t Keyboard::Modifiers() { + return kModifierNone + (kModifierLeftShift * left_shift_) + + (kModifierLeftAlt * left_alt_) + (kModifierLeftControl * left_ctrl_) + + (kModifierRightShift * right_shift_) + + (kModifierRightAlt * right_alt_) + + (kModifierRightControl * right_ctrl_) + + (kModifierCapsLock * stateful_caps_lock_); +} + +uint32_t Keyboard::LastCodePoint() { + // If the key has a meaning, and if the meaning is a code point, always have + // that code point take precedence over any other keymap. + if (last_event_.has_key_meaning()) { + const auto& key_meaning = last_event_.key_meaning(); + if (key_meaning.is_codepoint()) { + return key_meaning.codepoint(); + } + } + static const int qwerty_map_size = + sizeof(QWERTY_TO_CODE_POINTS) / sizeof(QWERTY_TO_CODE_POINTS[0]); + if (!IsKeys()) { + return 0; + } + const auto usage = LastHIDUsageID(); + if (usage < qwerty_map_size) { + return QWERTY_TO_CODE_POINTS[usage][IsShift() & 1]; + } + // Any other keys don't have a code point. + return 0; +} + +uint32_t Keyboard::GetLastKey() { + // For logical key determination, the physical key does not matter as long + // as code point is set. + // https://github.com/flutter/flutter/blob/570e39d38b799e91abe4f73f120ce494049c4ff0/packages/flutter/lib/src/services/raw_keyboard_fuchsia.dart#L71 + // It is not quite clear what happens to the physical key, though: + // https://github.com/flutter/flutter/blob/570e39d38b799e91abe4f73f120ce494049c4ff0/packages/flutter/lib/src/services/raw_keyboard_fuchsia.dart#L88 + if (!last_event_.has_key()) { + return 0; + } + return static_cast(last_event_.key()); +} + +uint32_t Keyboard::LastHIDUsage() { + return GetLastKey() & 0xFFFFFFFF; +} + +uint16_t Keyboard::LastHIDUsageID() { + return GetLastKey() & 0xFFFF; +} + +uint16_t Keyboard::LastHIDUsagePage() { + return (GetLastKey() >> 16) & 0xFFFF; +} + +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/keyboard.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/keyboard.h new file mode 100644 index 0000000000000000000000000000000000000000..a0a92c493ac9c50538e7503e02f2f0cfd27cbf88 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/keyboard.h @@ -0,0 +1,85 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_KEYBOARD_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_KEYBOARD_H_ + +#include + +namespace flutter_runner { + +// Keyboard handles the keyboard signals from fuchsia.ui.input3. Specifically, +// input3 has no notion of a code point, and does not track stateful versions +// of the modifier keys. +class Keyboard final { + public: + explicit Keyboard(); + + // Consumes the given keyboard event. Keyboard will adjust the modifier + // state based on the info given in the event. Returns true if the event has + // been integrated into the internal state successfully, or false otherwise. + bool ConsumeEvent(fuchsia::ui::input3::KeyEvent event); + + // Gets the currently active modifier keys. + uint32_t Modifiers(); + + // Gets the last encountered code point. The reported code point depends on + // the state of the modifier keys. + uint32_t LastCodePoint(); + + // Gets the last encountered HID usage. This is a 32-bit number, with the + // upper 16 bits equal to `LastHidUsagePage()`, and the lower 16 bits equal + // to `LastHIDUsageID()`. + // + // The key corresponding to A will have the usage 0x7004. This function will + // return 0x7004 in that case. + uint32_t LastHIDUsage(); + + // Gets the last encountered HID usage page. + // + // The key corresponding to A will have the usage 0x7004. This function will + // return 0x7 in that case. + uint16_t LastHIDUsagePage(); + + // Gets the last encountered HID usage ID. + // + // The key corresponding to A will have the usage 0x7004. This function will + // return 0x4 in that case. + uint16_t LastHIDUsageID(); + + private: + // Return true if any level shift is active. + bool IsShift(); + + // Returns true if the last key event was about a key that may have a code + // point associated. + bool IsKeys(); + + // Returns the value of the last key as a uint32_t. + // If there isn't such a value (as in the case of on-screen keyboards), this + // will return a 0; + uint32_t GetLastKey(); + + // Set to false until any event is received. + bool any_events_received_ : 1; + + // The flags below show the state of the keyboard modifiers after the last + // event has been processed. Stateful keys remain in the same state after + // a release and require an additional press to toggle. + bool stateful_caps_lock_ : 1; + bool left_shift_ : 1; + bool right_shift_ : 1; + bool left_alt_ : 1; + bool right_alt_ : 1; + bool left_ctrl_ : 1; + bool right_ctrl_ : 1; + + // The last received key event. If any_events_received_ is not set, this is + // not valid. + fuchsia::ui::input3::KeyEvent last_event_; +}; + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_KEYBOARD_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/keyboard_unittest.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/keyboard_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..c283ff0e4c1402bfeea9f63a4135937fb4daf92e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/keyboard_unittest.cc @@ -0,0 +1,236 @@ +// 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. + +// Testing the stateful Fuchsia Input3 keyboard interactions. This test case +// is not intended to be exhaustive: it is intended to capture the tests that +// demonstrate how we think Input3 interaction should work, and possibly +// regression tests if we catch some behavior that needs to be guarded long +// term. Pragmatically, this should be enough to ensure no specific bug +// happens twice. + +#include "flutter/shell/platform/fuchsia/flutter/keyboard.h" + +#include +#include +#include + +#include +#include +#include + +namespace flutter_runner { +namespace { + +using fuchsia::input::Key; +using fuchsia::ui::input::kModifierCapsLock; +using fuchsia::ui::input::kModifierLeftAlt; +using fuchsia::ui::input::kModifierLeftControl; +using fuchsia::ui::input::kModifierLeftShift; +using fuchsia::ui::input::kModifierNone; +using fuchsia::ui::input::kModifierRightAlt; +using fuchsia::ui::input::kModifierRightControl; +using fuchsia::ui::input::kModifierRightShift; +using fuchsia::ui::input3::KeyEvent; +using fuchsia::ui::input3::KeyEventType; +using fuchsia::ui::input3::KeyMeaning; + +class KeyboardTest : public testing::Test { + protected: + static void SetUpTestCase() { testing::Test::SetUpTestCase(); } + + // Creates a new key event for testing. + KeyEvent NewKeyEvent(KeyEventType event_type, Key key) { + KeyEvent event; + // Assume events are delivered with correct timing. + event.set_timestamp(++timestamp_); + event.set_type(event_type); + event.set_key(key); + return event; + } + + KeyEvent NewKeyEventWithMeaning(KeyEventType event_type, + KeyMeaning key_meaning) { + KeyEvent event; + // Assume events are delivered with correct timing. + event.set_timestamp(++timestamp_); + event.set_type(event_type); + event.set_key_meaning(std::move(key_meaning)); + return event; + } + + // Makes the keyboard consume all the provided `events`. The end state of + // the keyboard is as if all of the specified events happened between the + // start state of the keyboard and its end state. Returns false if any of + // the event was not consumed. + bool ConsumeEvents(Keyboard* keyboard, const std::vector& events) { + for (const auto& event : events) { + KeyEvent e; + event.Clone(&e); + if (keyboard->ConsumeEvent(std::move(e)) == false) { + return false; + } + } + return true; + } + + // Converts a pressed key to usage value. + uint32_t ToUsage(Key key) { return static_cast(key) & 0xFFFFFFFF; } + + private: + zx_time_t timestamp_ = 0; +}; + +// Checks whether the HID usage, page and ID values are reported correctly. +TEST_F(KeyboardTest, UsageValues) { + std::vector keys; + keys.emplace_back(NewKeyEvent(KeyEventType::SYNC, Key::CAPS_LOCK)); + Keyboard keyboard; + ASSERT_TRUE(ConsumeEvents(&keyboard, keys)); + + // Values for Caps Lock. + // See spec at: + // https://cs.opensource.google/fuchsia/fuchsia/+/main:sdk/fidl/fuchsia.input/keys.fidl;l=177;drc=e3b39f2b57e720770773b857feca4f770ee0619e + EXPECT_EQ(0x07u, keyboard.LastHIDUsagePage()); + EXPECT_EQ(0x39u, keyboard.LastHIDUsageID()); + EXPECT_EQ(0x70039u, keyboard.LastHIDUsage()); + + // Try also an usage that is not on page 7. This one is on page 0x0C. + // See spec at: + // https://cs.opensource.google/fuchsia/fuchsia/+/main:sdk/fidl/fuchsia.input/keys.fidl;l=339;drc=e3b39f2b57e720770773b857feca4f770ee0619e + // Note that Fuchsia does not define constants for every key you may think of, + // rather only those that we had the need for. However it is not an issue + // to add more keys if needed. + keys.clear(); + keys.emplace_back(NewKeyEvent(KeyEventType::SYNC, Key::MEDIA_MUTE)); + ASSERT_TRUE(ConsumeEvents(&keyboard, keys)); + EXPECT_EQ(0x0Cu, keyboard.LastHIDUsagePage()); + EXPECT_EQ(0xE2u, keyboard.LastHIDUsageID()); + EXPECT_EQ(0xC00E2u, keyboard.LastHIDUsage()); + + // Don't crash when a key with only a meaning comes in. + keys.clear(); + keys.emplace_back(NewKeyEventWithMeaning(KeyEventType::SYNC, + KeyMeaning::WithCodepoint(32))); + ASSERT_TRUE(ConsumeEvents(&keyboard, keys)); + EXPECT_EQ(0x0u, keyboard.LastHIDUsagePage()); + EXPECT_EQ(0x0u, keyboard.LastHIDUsageID()); + EXPECT_EQ(0x0u, keyboard.LastHIDUsage()); + EXPECT_EQ(0x20u, keyboard.LastCodePoint()); + + keys.clear(); + auto key = + NewKeyEventWithMeaning(KeyEventType::SYNC, KeyMeaning::WithCodepoint(65)); + key.set_key(Key::A); + keys.emplace_back(std::move(key)); + ASSERT_TRUE(ConsumeEvents(&keyboard, keys)); + EXPECT_EQ(0x07u, keyboard.LastHIDUsagePage()); + EXPECT_EQ(0x04u, keyboard.LastHIDUsageID()); + EXPECT_EQ(0x70004u, keyboard.LastHIDUsage()); + EXPECT_EQ(65u, keyboard.LastCodePoint()); +} + +// This test checks that if a caps lock has been pressed when we didn't have +// focus, the effect of caps lock remains. Only this first test case is +// commented to explain how the test case works. +TEST_F(KeyboardTest, CapsLockSync) { + // Place the key events since the beginning of time into `keys`. + std::vector keys; + keys.emplace_back(NewKeyEvent(KeyEventType::SYNC, Key::CAPS_LOCK)); + + // Replay them on the keyboard. + Keyboard keyboard; + ASSERT_TRUE(ConsumeEvents(&keyboard, keys)); + + // Verify the state of the keyboard's public API: + // - check that the key sync had no code point (it was a caps lock press). + // - check that the registered usage was that of caps lock. + // - check that the net effect is that the caps lock modifier is locked + // active. + EXPECT_EQ(0u, keyboard.LastCodePoint()); + EXPECT_EQ(ToUsage(Key::CAPS_LOCK), keyboard.LastHIDUsage()); + EXPECT_EQ(kModifierCapsLock, keyboard.Modifiers()); +} + +TEST_F(KeyboardTest, CapsLockPress) { + std::vector keys; + keys.emplace_back(NewKeyEvent(KeyEventType::PRESSED, Key::CAPS_LOCK)); + + Keyboard keyboard; + ASSERT_TRUE(ConsumeEvents(&keyboard, keys)); + + EXPECT_EQ(0u, keyboard.LastCodePoint()); + EXPECT_EQ(ToUsage(Key::CAPS_LOCK), keyboard.LastHIDUsage()); + EXPECT_EQ(kModifierCapsLock, keyboard.Modifiers()); +} + +TEST_F(KeyboardTest, CapsLockPressRelease) { + std::vector keys; + keys.emplace_back(NewKeyEvent(KeyEventType::PRESSED, Key::CAPS_LOCK)); + keys.emplace_back(NewKeyEvent(KeyEventType::RELEASED, Key::CAPS_LOCK)); + + Keyboard keyboard; + ASSERT_TRUE(ConsumeEvents(&keyboard, keys)); + + EXPECT_EQ(0u, keyboard.LastCodePoint()); + EXPECT_EQ(ToUsage(Key::CAPS_LOCK), keyboard.LastHIDUsage()); + EXPECT_EQ(kModifierCapsLock, keyboard.Modifiers()); +} + +TEST_F(KeyboardTest, ShiftA) { + std::vector keys; + keys.emplace_back(NewKeyEvent(KeyEventType::PRESSED, Key::LEFT_SHIFT)); + keys.emplace_back(NewKeyEvent(KeyEventType::PRESSED, Key::A)); + + Keyboard keyboard; + ASSERT_TRUE(ConsumeEvents(&keyboard, keys)); + + EXPECT_EQ(static_cast('A'), keyboard.LastCodePoint()); + EXPECT_EQ(ToUsage(Key::A), keyboard.LastHIDUsage()); + EXPECT_EQ(kModifierLeftShift, keyboard.Modifiers()); +} + +TEST_F(KeyboardTest, ShiftAWithRelease) { + std::vector keys; + keys.emplace_back(NewKeyEvent(KeyEventType::PRESSED, Key::LEFT_SHIFT)); + keys.emplace_back(NewKeyEvent(KeyEventType::PRESSED, Key::A)); + keys.emplace_back(NewKeyEvent(KeyEventType::RELEASED, Key::A)); + + Keyboard keyboard; + ASSERT_TRUE(ConsumeEvents(&keyboard, keys)); + + EXPECT_EQ(static_cast('A'), keyboard.LastCodePoint()); + EXPECT_EQ(ToUsage(Key::A), keyboard.LastHIDUsage()); + EXPECT_EQ(kModifierLeftShift, keyboard.Modifiers()); +} + +TEST_F(KeyboardTest, ShiftAWithReleaseShift) { + std::vector keys; + keys.emplace_back(NewKeyEvent(KeyEventType::PRESSED, Key::LEFT_SHIFT)); + keys.emplace_back(NewKeyEvent(KeyEventType::PRESSED, Key::A)); + keys.emplace_back(NewKeyEvent(KeyEventType::RELEASED, Key::LEFT_SHIFT)); + keys.emplace_back(NewKeyEvent(KeyEventType::RELEASED, Key::A)); + + Keyboard keyboard; + ASSERT_TRUE(ConsumeEvents(&keyboard, keys)); + + EXPECT_EQ(static_cast('a'), keyboard.LastCodePoint()); + EXPECT_EQ(ToUsage(Key::A), keyboard.LastHIDUsage()); + EXPECT_EQ(kModifierNone, keyboard.Modifiers()); +} + +TEST_F(KeyboardTest, LowcaseA) { + std::vector keys; + keys.emplace_back(NewKeyEvent(KeyEventType::PRESSED, Key::A)); + keys.emplace_back(NewKeyEvent(KeyEventType::RELEASED, Key::A)); + + Keyboard keyboard; + ASSERT_TRUE(ConsumeEvents(&keyboard, keys)); + + EXPECT_EQ(static_cast('a'), keyboard.LastCodePoint()); + EXPECT_EQ(ToUsage(Key::A), keyboard.LastHIDUsage()); + EXPECT_EQ(kModifierNone, keyboard.Modifiers()); +} + +} // namespace +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/logging.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/logging.h new file mode 100644 index 0000000000000000000000000000000000000000..165a16031299d92bcadfab75a82f83067be185b5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/logging.h @@ -0,0 +1,17 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_LOGGING_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_LOGGING_H_ + +#include "flutter/fml/logging.h" + +namespace flutter_runner { + +// Use to mark logs published via the syslog API. +#define LOG_TAG "flutter-runner" + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_LOGGING_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/main.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/main.cc new file mode 100644 index 0000000000000000000000000000000000000000..21162214a8d547c65685f6d17b33304bf8531338 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/main.cc @@ -0,0 +1,61 @@ +// 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 +#include +#include +#include + +#include + +#include "fml/message_loop.h" +#include "fml/platform/fuchsia/log_interest_listener.h" +#include "fml/platform/fuchsia/log_state.h" +#include "lib/async/default.h" +#include "logging.h" +#include "platform/utils.h" +#include "runner.h" +#include "runtime/dart/utils/build_info.h" +#include "runtime/dart/utils/root_inspect_node.h" +#include "runtime/dart/utils/tempfs.h" + +int main(int argc, char const* argv[]) { + fml::MessageLoop::EnsureInitializedForCurrentThread(); + + // Setup logging. + fml::LogState::Default().SetTags({LOG_TAG}); + fml::LogInterestListener listener(fml::LogState::Default().TakeClientEnd(), + async_get_default_dispatcher()); + listener.AsyncWaitForInterestChanged(); + + // Create our component context which is served later. + auto context = sys::ComponentContext::Create(); + dart_utils::RootInspectNode::Initialize(context.get()); + auto build_info = dart_utils::RootInspectNode::CreateRootChild("build_info"); + dart_utils::BuildInfo::Dump(build_info); + + // We inject the 'vm' node into the dart vm so that it can add any inspect + // data that it needs to the inspect tree. + dart::SetDartVmNode(std::make_unique( + dart_utils::RootInspectNode::CreateRootChild("vm"))); + + std::unique_ptr provider; + { + bool already_started; + // Use CreateSynchronously to prevent loss of early events. + trace::TraceProviderWithFdio::CreateSynchronously( + async_get_default_dispatcher(), "flutter_runner", &provider, + &already_started); + } + + fml::MessageLoop& loop = fml::MessageLoop::GetCurrent(); + flutter_runner::Runner runner(loop.GetTaskRunner(), context.get()); + + // Wait to serve until we have finished all of our setup. + context->outgoing()->ServeFromStartupInfo(); + + loop.Run(); + + return EXIT_SUCCESS; +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/meta/common.shard.cml b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/meta/common.shard.cml new file mode 100644 index 0000000000000000000000000000000000000000..ff2a2b6e4b423d0c9b6aa7715caa17d9bcb9e88c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/meta/common.shard.cml @@ -0,0 +1,60 @@ +// 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: [ "syslog/client.shard.cml", "inspect/client.shard.cml" ], + use: [ + // This is used by the Dart VM to communicate from Dart code to C++ code. + { + storage: "tmp", + path: "/tmp", + }, + // This is used by the Dart VM to load i18n data. + { + directory: "config-data", + rights: [ "r*" ], + path: "/config/data", + }, + // The ICU time zone data, factored out of `config-data`. + // See: + // https://fuchsia.dev/fuchsia-src/concepts/process/namespaces?typical_directory_structure + { + directory: "tzdata-icu", + rights: [ "r*" ], + path: "/config/tzdata/icu", + }, + { + directory: "root-ssl-certificates", + rights: [ "r*" ], + path: "/config/ssl", + }, + { + protocol: [ + "fuchsia.accessibility.semantics.SemanticsManager", + "fuchsia.device.NameProvider", + "fuchsia.feedback.CrashReporter", + "fuchsia.fonts.Provider", + "fuchsia.intl.PropertyProvider", + "fuchsia.media.ProfileProvider", + "fuchsia.memorypressure.Provider", + "fuchsia.scheduler.RoleManager", + "fuchsia.net.name.Lookup", + "fuchsia.posix.socket.Provider", + "fuchsia.sysmem.Allocator", + "fuchsia.sysmem2.Allocator", + "fuchsia.ui.composition.Allocator", + "fuchsia.ui.composition.Flatland", + "fuchsia.ui.input.ImeService", + "fuchsia.ui.input3.Keyboard", + "fuchsia.ui.pointerinjector.Registry", + "fuchsia.vulkan.loader.Loader", // Copied from vulkan/client.shard.cml. + ], + }, + { + protocol: [ + "fuchsia.tracing.provider.Registry", // Copied from vulkan/client.shard.cml. + ], + availability: "optional", + }, + ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_aot_product_runner.cml b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_aot_product_runner.cml new file mode 100644 index 0000000000000000000000000000000000000000..988c31747271cc26ec3f6b811da84f3fd63f0934 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_aot_product_runner.cml @@ -0,0 +1,24 @@ +// 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: [ "common.shard.cml" ], + program: { + runner: "elf", + binary: "bin/app", + forward_stdout_to: "log", + forward_stderr_to: "log", + }, + capabilities: [ + { + runner: "flutter_aot_product_runner", + path: "/svc/fuchsia.component.runner.ComponentRunner", + }, + ], + expose: [ + { + runner: "flutter_aot_product_runner", + from: "self", + }, + ], +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_aot_runner.cml b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_aot_runner.cml new file mode 100644 index 0000000000000000000000000000000000000000..4ae391f3ac5aa97b5c55063117c7e28760ca9f28 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_aot_runner.cml @@ -0,0 +1,24 @@ +// 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: [ "common.shard.cml" ], + program: { + runner: "elf", + binary: "bin/app", + forward_stdout_to: "log", + forward_stderr_to: "log", + }, + capabilities: [ + { + runner: "flutter_aot_runner", + path: "/svc/fuchsia.component.runner.ComponentRunner", + }, + ], + expose: [ + { + runner: "flutter_aot_runner", + from: "self", + }, + ], +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_jit_product_runner.cml b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_jit_product_runner.cml new file mode 100644 index 0000000000000000000000000000000000000000..11d6634ee5fe896db6c0bc1cd5f9956661bbf90a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_jit_product_runner.cml @@ -0,0 +1,26 @@ +// 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: [ "common.shard.cml" ], + program: { + runner: "elf", + binary: "bin/app", + forward_stdout_to: "log", + forward_stderr_to: "log", + // Needed for JIT builds. + job_policy_ambient_mark_vmo_exec: "true" + }, + capabilities: [ + { + runner: "flutter_jit_product_runner", + path: "/svc/fuchsia.component.runner.ComponentRunner", + }, + ], + expose: [ + { + runner: "flutter_jit_product_runner", + from: "self", + }, + ], +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_jit_runner.cml b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_jit_runner.cml new file mode 100644 index 0000000000000000000000000000000000000000..4f206231601ab7b9ba0b0983e472f7e3ebcb628a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_jit_runner.cml @@ -0,0 +1,26 @@ +// 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: [ "common.shard.cml" ], + program: { + runner: "elf", + binary: "bin/app", + forward_stdout_to: "log", + forward_stderr_to: "log", + // Needed for JIT builds. + job_policy_ambient_mark_vmo_exec: "true" + }, + capabilities: [ + { + runner: "flutter_jit_runner", + path: "/svc/fuchsia.component.runner.ComponentRunner", + }, + ], + expose: [ + { + runner: "flutter_jit_runner", + from: "self", + }, + ], +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/platform_view.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/platform_view.cc new file mode 100644 index 0000000000000000000000000000000000000000..35147128eef402815c0bbffaa1664fec01c3bf0a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/platform_view.cc @@ -0,0 +1,1171 @@ +// 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. + +#define RAPIDJSON_HAS_STDSTRING 1 + +#include "platform_view.h" + +#include +#include + +#include +#include +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/make_copyable.h" +#include "flutter/lib/ui/window/pointer_data.h" +#include "flutter/shell/platform/common/client_wrapper/include/flutter/encodable_value.h" +#include "flutter/shell/platform/common/client_wrapper/include/flutter/standard_message_codec.h" +#include "third_party/rapidjson/include/rapidjson/document.h" +#include "third_party/rapidjson/include/rapidjson/stringbuffer.h" +#include "third_party/rapidjson/include/rapidjson/writer.h" + +#include "flutter/fml/make_copyable.h" +#include "logging.h" +#include "pointer_injector_delegate.h" +#include "runtime/dart/utils/inlines.h" +#include "text_delegate.h" +#include "vsync_waiter.h" + +namespace { +// Helper to extract a given member with a given type from a rapidjson object. +template +bool CallWithMember(O obj, const char* member_name, F func) { + auto it = obj.FindMember(member_name); + if (it == obj.MemberEnd()) { + return false; + } + if (!it->value.template Is()) { + return false; + } + func(it->value.template Get()); + return true; +} +} // namespace + +namespace flutter_runner { + +static constexpr char kFlutterPlatformChannel[] = "flutter/platform"; +static constexpr char kAccessibilityChannel[] = "flutter/accessibility"; +static constexpr char kFlutterPlatformViewsChannel[] = "flutter/platform_views"; +static constexpr char kFuchsiaShaderWarmupChannel[] = "fuchsia/shader_warmup"; +static constexpr char kFuchsiaInputTestChannel[] = "fuchsia/input_test"; +static constexpr char kFuchsiaChildViewChannel[] = "fuchsia/child_view"; +static constexpr int64_t kFlutterImplicitViewId = 0ll; + +PlatformView::PlatformView( + flutter::PlatformView::Delegate& delegate, + flutter::TaskRunners task_runners, + fuchsia::ui::views::ViewRef view_ref, + std::shared_ptr external_view_embedder, + fuchsia::ui::input::ImeServiceHandle ime_service, + fuchsia::ui::input3::KeyboardHandle keyboard, + fuchsia::ui::pointer::TouchSourceHandle touch_source, + fuchsia::ui::pointer::MouseSourceHandle mouse_source, + fuchsia::ui::views::FocuserHandle focuser, + fuchsia::ui::views::ViewRefFocusedHandle view_ref_focused, + fuchsia::ui::composition::ParentViewportWatcherHandle + parent_viewport_watcher, + fuchsia::ui::pointerinjector::RegistryHandle pointerinjector_registry, + OnEnableWireframeCallback wireframe_enabled_callback, + OnCreateViewCallback on_create_view_callback, + OnUpdateViewCallback on_update_view_callback, + OnDestroyViewCallback on_destroy_view_callback, + OnCreateSurfaceCallback on_create_surface_callback, + OnSemanticsNodeUpdateCallback on_semantics_node_update_callback, + OnRequestAnnounceCallback on_request_announce_callback, + OnShaderWarmupCallback on_shader_warmup_callback, + AwaitVsyncCallback await_vsync_callback, + AwaitVsyncForSecondaryCallbackCallback + await_vsync_for_secondary_callback_callback, + std::shared_ptr dart_application_svc) + : flutter::PlatformView(delegate, std::move(task_runners)), + external_view_embedder_(external_view_embedder), + focus_delegate_( + std::make_shared(std::move(view_ref_focused), + std::move(focuser))), + pointer_delegate_( + std::make_shared(std::move(touch_source), + std::move(mouse_source))), + wireframe_enabled_callback_(std::move(wireframe_enabled_callback)), + on_update_view_callback_(std::move(on_update_view_callback)), + on_create_surface_callback_(std::move(on_create_surface_callback)), + on_semantics_node_update_callback_( + std::move(on_semantics_node_update_callback)), + on_request_announce_callback_(std::move(on_request_announce_callback)), + on_create_view_callback_(std::move(on_create_view_callback)), + on_destroy_view_callback_(std::move(on_destroy_view_callback)), + on_shader_warmup_callback_(std::move(on_shader_warmup_callback)), + await_vsync_callback_(await_vsync_callback), + await_vsync_for_secondary_callback_callback_( + await_vsync_for_secondary_callback_callback), + dart_application_svc_(dart_application_svc), + parent_viewport_watcher_(parent_viewport_watcher.Bind()), + weak_factory_(this) { + fuchsia::ui::views::ViewRef view_ref_clone; + fidl::Clone(view_ref, &view_ref_clone); + + text_delegate_ = + std::make_unique( + std::move(view_ref), std::move(ime_service), std::move(keyboard), + [weak = weak_factory_.GetWeakPtr()]( + std::unique_ptr message) { + if (!weak) { + FML_LOG(WARNING) + << "PlatformView use-after-free attempted. Ignoring."; + } + weak->delegate_.OnPlatformViewDispatchPlatformMessage( + std::move(message)); + }); + + // Begin watching for focus changes. + focus_delegate_->WatchLoop([weak = weak_factory_.GetWeakPtr()](bool focused) { + if (!weak) { + FML_LOG(WARNING) << "PlatformView use-after-free attempted. Ignoring."; + return; + } + + // Ensure last_text_state_ is set to make sure Flutter actually wants + // an IME. + if (focused && weak->text_delegate_->HasTextState()) { + weak->text_delegate_->ActivateIme(); + } else if (!focused) { + weak->text_delegate_->DeactivateIme(); + } + }); + + // Begin watching for pointer events. + pointer_delegate_->WatchLoop([weak = weak_factory_.GetWeakPtr()]( + std::vector events) { + if (!weak) { + FML_LOG(WARNING) << "PlatformView use-after-free attempted. Ignoring."; + return; + } + + if (events.empty()) { + return; // No work, bounce out. + } + + // If pixel ratio hasn't been set, use a default value of 1. + const float pixel_ratio = weak->view_pixel_ratio_.value_or(1.f); + auto packet = std::make_unique(events.size()); + for (size_t i = 0; i < events.size(); ++i) { + auto& event = events[i]; + // Translate logical to physical coordinates, as per + // flutter::PointerData contract. Done here because pixel ratio comes + // from the graphics API. + event.physical_x = event.physical_x * pixel_ratio; + event.physical_y = event.physical_y * pixel_ratio; + packet->SetPointerData(i, event); + } + weak->DispatchPointerDataPacket(std::move(packet)); + }); + + // Configure the pointer injector delegate. + pointer_injector_delegate_ = std::make_unique( + std::move(pointerinjector_registry), std::move(view_ref_clone)); + + // This is only used by the integration tests. + if (dart_application_svc) { + // Connect to TouchInputListener + fuchsia::ui::test::input::TouchInputListenerHandle touch_input_listener; + zx_status_t touch_input_listener_status = + dart_application_svc + ->Connect( + touch_input_listener.NewRequest()); + if (touch_input_listener_status != ZX_OK) { + FML_LOG(WARNING) + << "fuchsia::ui::test::input::TouchInputListener connection failed: " + << zx_status_get_string(touch_input_listener_status); + } else { + touch_input_listener_.Bind(std::move(touch_input_listener)); + } + + // Connect to KeyboardInputListener + fuchsia::ui::test::input::KeyboardInputListenerHandle + keyboard_input_listener; + zx_status_t keyboard_input_listener_status = + dart_application_svc + ->Connect( + keyboard_input_listener.NewRequest()); + if (keyboard_input_listener_status != ZX_OK) { + FML_LOG(WARNING) << "fuchsia::ui::test::input::KeyboardInputListener " + "connection failed: " + << zx_status_get_string(keyboard_input_listener_status); + } else { + keyboard_input_listener_.Bind(std::move(keyboard_input_listener)); + } + // Connect to MouseInputListener + fuchsia::ui::test::input::MouseInputListenerHandle mouse_input_listener; + zx_status_t mouse_input_listener_status = + dart_application_svc + ->Connect( + mouse_input_listener.NewRequest()); + if (mouse_input_listener_status != ZX_OK) { + FML_LOG(WARNING) + << "fuchsia::ui::test::input::MouseInputListener connection failed: " + << zx_status_get_string(mouse_input_listener_status); + } else { + mouse_input_listener_.Bind(std::move(mouse_input_listener)); + } + } + + // Finally! Register the native platform message handlers. + RegisterPlatformMessageHandlers(); + + parent_viewport_watcher_.set_error_handler([](zx_status_t status) { + FML_LOG(ERROR) << "Interface error on: ParentViewportWatcher status: " + << status; + }); + + parent_viewport_watcher_->GetLayout( + fit::bind_member(this, &PlatformView::OnGetLayout)); + parent_viewport_watcher_->GetStatus( + fit::bind_member(this, &PlatformView::OnParentViewportStatus)); +} + +PlatformView::~PlatformView() = default; + +void PlatformView::RegisterPlatformMessageHandlers() { + platform_message_handlers_[kFlutterPlatformChannel] = + std::bind(&PlatformView::HandleFlutterPlatformChannelPlatformMessage, + this, std::placeholders::_1); + platform_message_handlers_[kTextInputChannel] = + std::bind(&TextDelegate::HandleFlutterTextInputChannelPlatformMessage, + text_delegate_.get(), std::placeholders::_1); + platform_message_handlers_[kAccessibilityChannel] = + std::bind(&PlatformView::HandleAccessibilityChannelPlatformMessage, this, + std::placeholders::_1); + platform_message_handlers_[kFlutterPlatformViewsChannel] = + std::bind(&PlatformView::HandleFlutterPlatformViewsChannelPlatformMessage, + this, std::placeholders::_1); + platform_message_handlers_[kFuchsiaShaderWarmupChannel] = + std::bind(&HandleFuchsiaShaderWarmupChannelPlatformMessage, + on_shader_warmup_callback_, std::placeholders::_1); + platform_message_handlers_[kFuchsiaInputTestChannel] = + std::bind(&PlatformView::HandleFuchsiaInputTestChannelPlatformMessage, + this, std::placeholders::_1); + platform_message_handlers_[kFuchsiaChildViewChannel] = + std::bind(&PlatformView::HandleFuchsiaChildViewChannelPlatformMessage, + this, std::placeholders::_1); +} + +static flutter::PointerData::Change GetChangeFromPointerEventPhase( + fuchsia::ui::input::PointerEventPhase phase) { + switch (phase) { + case fuchsia::ui::input::PointerEventPhase::ADD: + return flutter::PointerData::Change::kAdd; + case fuchsia::ui::input::PointerEventPhase::HOVER: + return flutter::PointerData::Change::kHover; + case fuchsia::ui::input::PointerEventPhase::DOWN: + return flutter::PointerData::Change::kDown; + case fuchsia::ui::input::PointerEventPhase::MOVE: + return flutter::PointerData::Change::kMove; + case fuchsia::ui::input::PointerEventPhase::UP: + return flutter::PointerData::Change::kUp; + case fuchsia::ui::input::PointerEventPhase::REMOVE: + return flutter::PointerData::Change::kRemove; + case fuchsia::ui::input::PointerEventPhase::CANCEL: + return flutter::PointerData::Change::kCancel; + default: + return flutter::PointerData::Change::kCancel; + } +} + +static flutter::PointerData::DeviceKind GetKindFromPointerType( + fuchsia::ui::input::PointerEventType type) { + switch (type) { + case fuchsia::ui::input::PointerEventType::TOUCH: + return flutter::PointerData::DeviceKind::kTouch; + case fuchsia::ui::input::PointerEventType::MOUSE: + return flutter::PointerData::DeviceKind::kMouse; + default: + return flutter::PointerData::DeviceKind::kTouch; + } +} + +// TODO(SCN-1278): Remove this. +// Turns two floats (high bits, low bits) into a 64-bit uint. +static trace_flow_id_t PointerTraceHACK(float fa, float fb) { + uint32_t ia, ib; + memcpy(&ia, &fa, sizeof(uint32_t)); + memcpy(&ib, &fb, sizeof(uint32_t)); + return (((uint64_t)ia) << 32) | ib; +} + +// For certain scenarios that must avoid floating-point drift, compute a +// coordinate that falls within the logical view bounding box. +std::array PlatformView::ClampToViewSpace(const float x, + const float y) const { + if (!view_logical_size_.has_value() || !view_logical_origin_.has_value()) { + return {x, y}; // If we can't do anything, return the original values. + } + + const auto origin = view_logical_origin_.value(); + const auto size = view_logical_size_.value(); + const float min_x = origin[0]; + const float max_x = origin[0] + size[0]; + const float min_y = origin[1]; + const float max_y = origin[1] + size[1]; + if (min_x <= x && x < max_x && min_y <= y && y < max_y) { + return {x, y}; // No clamping to perform. + } + + // View boundary is [min_x, max_x) x [min_y, max_y). Note that min is + // inclusive, but max is exclusive - so we subtract epsilon. + const float max_x_inclusive = max_x - std::numeric_limits::epsilon(); + const float max_y_inclusive = max_y - std::numeric_limits::epsilon(); + const float& clamped_x = std::clamp(x, min_x, max_x_inclusive); + const float& clamped_y = std::clamp(y, min_y, max_y_inclusive); + FML_LOG(INFO) << "Clamped (" << x << ", " << y << ") to (" << clamped_x + << ", " << clamped_y << ")."; + return {clamped_x, clamped_y}; +} + +void PlatformView::OnGetLayout(fuchsia::ui::composition::LayoutInfo info) { + view_logical_size_ = {static_cast(info.logical_size().width), + static_cast(info.logical_size().height)}; + + if (info.has_device_pixel_ratio()) { + // Both values should be identical for the Vec2 for DPR. + FML_DCHECK(info.device_pixel_ratio().x == info.device_pixel_ratio().y); + view_pixel_ratio_ = info.device_pixel_ratio().x; + } + + float pixel_ratio = view_pixel_ratio_ ? *view_pixel_ratio_ : 1.0f; + flutter::ViewportMetrics metrics{ + pixel_ratio, // device_pixel_ratio + std::round(view_logical_size_.value()[0] * + pixel_ratio), // physical_width + std::round(view_logical_size_.value()[1] * + pixel_ratio), // physical_height + 0.0f, // physical_padding_top + 0.0f, // physical_padding_right + 0.0f, // physical_padding_bottom + 0.0f, // physical_padding_left + 0.0f, // physical_view_inset_top + 0.0f, // physical_view_inset_right + 0.0f, // physical_view_inset_bottom + 0.0f, // physical_view_inset_left + 0.0f, // p_physical_system_gesture_inset_top + 0.0f, // p_physical_system_gesture_inset_right + 0.0f, // p_physical_system_gesture_inset_bottom + 0.0f, // p_physical_system_gesture_inset_left, + -1.0, // p_physical_touch_slop, + {}, // p_physical_display_features_bounds + {}, // p_physical_display_features_type + {}, // p_physical_display_features_state + 0, // p_display_id + }; + SetViewportMetrics(kFlutterImplicitViewId, metrics); + + parent_viewport_watcher_->GetLayout( + fit::bind_member(this, &PlatformView::OnGetLayout)); +} + +void PlatformView::OnParentViewportStatus( + fuchsia::ui::composition::ParentViewportStatus status) { + // TODO(fxbug.dev/116001): Investigate if it is useful to send hidden/shown + // signals. + parent_viewport_status_ = status; + parent_viewport_watcher_->GetStatus( + fit::bind_member(this, &PlatformView::OnParentViewportStatus)); +} + +void PlatformView::OnChildViewStatus( + uint64_t content_id, + fuchsia::ui::composition::ChildViewStatus status) { + FML_DCHECK(child_view_info_.count(content_id) == 1); + + std::ostringstream out; + out << "{" << "\"method\":\"View.viewStateChanged\"," << "\"args\":{" + << " \"viewId\":" << child_view_info_.at(content_id).view_id + << "," // ViewId + << " \"is_rendering\":true," // IsViewRendering + << " \"state\":true" // IsViewRendering + << " }" << "}"; + auto call = out.str(); + + std::unique_ptr message = + std::make_unique( + "flutter/platform_views", + fml::MallocMapping::Copy(call.c_str(), call.size()), nullptr); + DispatchPlatformMessage(std::move(message)); + + child_view_info_.at(content_id) + .child_view_watcher->GetStatus( + [this, content_id](fuchsia::ui::composition::ChildViewStatus status) { + OnChildViewStatus(content_id, status); + }); +} + +void PlatformView::OnChildViewViewRef(uint64_t content_id, + uint64_t view_id, + fuchsia::ui::views::ViewRef view_ref) { + FML_CHECK(child_view_info_.count(content_id) == 1); + + fuchsia::ui::views::ViewRef view_ref_clone; + fidl::Clone(view_ref, &view_ref_clone); + + focus_delegate_->OnChildViewViewRef(view_id, std::move(view_ref)); + + pointer_injector_delegate_->OnCreateView(view_id, std::move(view_ref_clone)); + OnChildViewConnected(content_id); +} + +void PlatformView::OnCreateView(ViewCallback on_view_created, + int64_t view_id_raw, + bool hit_testable, + bool focusable) { + auto on_view_bound = [weak = weak_factory_.GetWeakPtr(), + platform_task_runner = + task_runners_.GetPlatformTaskRunner(), + view_id = view_id_raw]( + fuchsia::ui::composition::ContentId content_id, + fuchsia::ui::composition::ChildViewWatcherHandle + child_view_watcher_handle) { + FML_CHECK(weak); + FML_CHECK(weak->child_view_info_.count(content_id.value) == 0); + + platform_task_runner->PostTask(fml::MakeCopyable( + [weak, view_id, content_id, + watcher_handle = std::move(child_view_watcher_handle)]() mutable { + if (!weak) { + FML_LOG(WARNING) + << "View bound to PlatformView after PlatformView was " + "destroyed; ignoring."; + return; + } + + // Bind the child view watcher to the platform thread so that the FIDL + // calls are handled on the platform thread. + fuchsia::ui::composition::ChildViewWatcherPtr child_view_watcher = + watcher_handle.Bind(); + FML_CHECK(child_view_watcher); + + child_view_watcher.set_error_handler([weak, view_id, content_id]( + zx_status_t status) { + FML_LOG(WARNING) + << "Child disconnected. ChildViewWatcher status: " << status; + + if (!weak) { + FML_LOG(WARNING) << "View bound to PlatformView after " + "PlatformView was " + "destroyed; ignoring."; + return; + } + + // Disconnected views cannot listen to pointer events. + weak->pointer_injector_delegate_->OnDestroyView(view_id); + + weak->OnChildViewDisconnected(content_id.value); + }); + + weak->child_view_info_.emplace( + std::piecewise_construct, std::forward_as_tuple(content_id.value), + std::forward_as_tuple(view_id, std::move(child_view_watcher))); + + weak->child_view_info_.at(content_id.value) + .child_view_watcher->GetStatus( + [weak, id = content_id.value]( + fuchsia::ui::composition::ChildViewStatus status) { + weak->OnChildViewStatus(id, status); + }); + + weak->child_view_info_.at(content_id.value) + .child_view_watcher->GetViewRef( + [weak, content_id = content_id.value, + view_id](fuchsia::ui::views::ViewRef view_ref) { + weak->OnChildViewViewRef(content_id, view_id, + std::move(view_ref)); + }); + })); + }; + + on_create_view_callback_(view_id_raw, std::move(on_view_created), + std::move(on_view_bound), hit_testable, focusable); +} + +void PlatformView::OnDisposeView(int64_t view_id_raw) { + auto on_view_unbound = + [weak = weak_factory_.GetWeakPtr(), + platform_task_runner = task_runners_.GetPlatformTaskRunner(), + view_id_raw](fuchsia::ui::composition::ContentId content_id) { + platform_task_runner->PostTask([weak, content_id, view_id_raw]() { + if (!weak) { + FML_LOG(WARNING) + << "View unbound from PlatformView after PlatformView" + "was destroyed; ignoring."; + return; + } + + FML_DCHECK(weak->child_view_info_.count(content_id.value) == 1); + weak->OnChildViewDisconnected(content_id.value); + weak->child_view_info_.erase(content_id.value); + weak->focus_delegate_->OnDisposeChildView(view_id_raw); + weak->pointer_injector_delegate_->OnDestroyView(view_id_raw); + }); + }; + on_destroy_view_callback_(view_id_raw, std::move(on_view_unbound)); +} + +void PlatformView::OnChildViewConnected(uint64_t content_id) { + FML_CHECK(child_view_info_.count(content_id) == 1); + std::ostringstream out; + out << "{" << "\"method\":\"View.viewConnected\"," << "\"args\":{" + << " \"viewId\":" << child_view_info_.at(content_id).view_id << " }" + << "}"; + auto call = out.str(); + + std::unique_ptr message = + std::make_unique( + "flutter/platform_views", + fml::MallocMapping::Copy(call.c_str(), call.size()), nullptr); + DispatchPlatformMessage(std::move(message)); +} + +void PlatformView::OnChildViewDisconnected(uint64_t content_id) { + FML_CHECK(child_view_info_.count(content_id) == 1); + std::ostringstream out; + out << "{" << "\"method\":\"View.viewDisconnected\"," << "\"args\":{" + << " \"viewId\":" << child_view_info_.at(content_id).view_id << " }" + << "}"; + auto call = out.str(); + + std::unique_ptr message = + std::make_unique( + "flutter/platform_views", + fml::MallocMapping::Copy(call.c_str(), call.size()), nullptr); + DispatchPlatformMessage(std::move(message)); +} + +bool PlatformView::OnHandlePointerEvent( + const fuchsia::ui::input::PointerEvent& pointer) { + TRACE_EVENT0("flutter", "PlatformView::OnHandlePointerEvent"); + + // TODO(SCN-1278): Use proper trace_id for tracing flow. + trace_flow_id_t trace_id = + PointerTraceHACK(pointer.radius_major, pointer.radius_minor); + TRACE_FLOW_END("input", "dispatch_event_to_client", trace_id); + + const float pixel_ratio = + view_pixel_ratio_.has_value() ? *view_pixel_ratio_ : 0.f; + + flutter::PointerData pointer_data; + pointer_data.Clear(); + pointer_data.time_stamp = pointer.event_time / 1000; + pointer_data.change = GetChangeFromPointerEventPhase(pointer.phase); + pointer_data.kind = GetKindFromPointerType(pointer.type); + pointer_data.device = pointer.pointer_id; + // Pointer events are in logical pixels, so scale to physical. + pointer_data.physical_x = pointer.x * pixel_ratio; + pointer_data.physical_y = pointer.y * pixel_ratio; + // Buttons are single bit values starting with kMousePrimaryButton = 1. + pointer_data.buttons = static_cast(pointer.buttons); + + switch (pointer_data.change) { + case flutter::PointerData::Change::kDown: { + // Make the pointer start in the view space, despite numerical drift. + auto clamped_pointer = ClampToViewSpace(pointer.x, pointer.y); + pointer_data.physical_x = clamped_pointer[0] * pixel_ratio; + pointer_data.physical_y = clamped_pointer[1] * pixel_ratio; + + down_pointers_.insert(pointer_data.device); + break; + } + case flutter::PointerData::Change::kCancel: + case flutter::PointerData::Change::kUp: + down_pointers_.erase(pointer_data.device); + break; + case flutter::PointerData::Change::kMove: + if (down_pointers_.count(pointer_data.device) == 0) { + pointer_data.change = flutter::PointerData::Change::kHover; + } + break; + case flutter::PointerData::Change::kAdd: + if (down_pointers_.count(pointer_data.device) != 0) { + FML_LOG(ERROR) << "Received add event for down pointer."; + } + break; + case flutter::PointerData::Change::kRemove: + if (down_pointers_.count(pointer_data.device) != 0) { + FML_LOG(ERROR) << "Received remove event for down pointer."; + } + break; + case flutter::PointerData::Change::kHover: + if (down_pointers_.count(pointer_data.device) != 0) { + FML_LOG(ERROR) << "Received hover event for down pointer."; + } + break; + case flutter::PointerData::Change::kPanZoomStart: + case flutter::PointerData::Change::kPanZoomUpdate: + case flutter::PointerData::Change::kPanZoomEnd: + FML_DLOG(ERROR) << "Unexpectedly received pointer pan/zoom event"; + break; + } + + auto packet = std::make_unique(1); + packet->SetPointerData(0, pointer_data); + DispatchPointerDataPacket(std::move(packet)); + return true; +} + +// |flutter::PlatformView| +std::unique_ptr PlatformView::CreateVSyncWaiter() { + return std::make_unique( + await_vsync_callback_, await_vsync_for_secondary_callback_callback_, + task_runners_); +} + +// |flutter::PlatformView| +std::unique_ptr PlatformView::CreateRenderingSurface() { + return on_create_surface_callback_ ? on_create_surface_callback_() : nullptr; +} + +// |flutter::PlatformView| +std::shared_ptr +PlatformView::CreateExternalViewEmbedder() { + return external_view_embedder_; +} + +// |flutter::PlatformView| +void PlatformView::HandlePlatformMessage( + std::unique_ptr message) { + if (!message) { + return; + } + const std::string channel = message->channel(); + auto found = platform_message_handlers_.find(channel); + if (found == platform_message_handlers_.end()) { + const bool already_errored = unregistered_channels_.count(channel); + if (!already_errored) { + FML_LOG(INFO) + << "Platform view received message on channel '" << message->channel() + << "' with no registered handler. An empty response will be " + "generated. Please implement the native message handler. This " + "message will appear only once per channel."; + unregistered_channels_.insert(channel); + } + flutter::PlatformView::HandlePlatformMessage(std::move(message)); + return; + } + auto response = message->response(); + bool response_handled = found->second(std::move(message)); + + // Ensure all responses are completed. + if (response && !response_handled) { + // response_handled should be true if the response was completed. + FML_DCHECK(!response->is_complete()); + response->CompleteEmpty(); + } +} + +// |flutter::PlatformView| +void PlatformView::SetSemanticsEnabled(bool enabled) { + flutter::PlatformView::SetSemanticsEnabled(enabled); + if (enabled) { + SetAccessibilityFeatures(static_cast( + flutter::AccessibilityFeatureFlag::kAccessibleNavigation)); + } else { + SetAccessibilityFeatures(0); + } +} + +// |flutter::PlatformView| +void PlatformView::UpdateSemantics( + int64_t view_id, + flutter::SemanticsNodeUpdates update, + flutter::CustomAccessibilityActionUpdates actions) { + const float pixel_ratio = + view_pixel_ratio_.has_value() ? *view_pixel_ratio_ : 0.f; + + on_semantics_node_update_callback_(update, pixel_ratio); +} + +// Channel handler for kAccessibilityChannel +bool PlatformView::HandleAccessibilityChannelPlatformMessage( + std::unique_ptr message) { + FML_DCHECK(message->channel() == kAccessibilityChannel); + + const flutter::StandardMessageCodec& standard_message_codec = + flutter::StandardMessageCodec::GetInstance(nullptr); + std::unique_ptr decoded = + standard_message_codec.DecodeMessage(message->data().GetMapping(), + message->data().GetSize()); + + flutter::EncodableMap map = std::get(*decoded); + std::string type = + std::get(map.at(flutter::EncodableValue("type"))); + if (type == "announce") { + flutter::EncodableMap data_map = std::get( + map.at(flutter::EncodableValue("data"))); + std::string text = + std::get(data_map.at(flutter::EncodableValue("message"))); + + on_request_announce_callback_(text); + } + + // Complete with an empty response. + return false; +} + +// Channel handler for kFlutterPlatformChannel +bool PlatformView::HandleFlutterPlatformChannelPlatformMessage( + std::unique_ptr message) { + FML_DCHECK(message->channel() == kFlutterPlatformChannel); + + // Fuchsia does not handle any platform messages at this time. + + // Complete with an empty response. + return false; +} + +bool PlatformView::HandleFlutterPlatformViewsChannelPlatformMessage( + std::unique_ptr message) { + FML_DCHECK(message->channel() == kFlutterPlatformViewsChannel); + const auto& data = message->data(); + rapidjson::Document document; + document.Parse(reinterpret_cast(data.GetMapping()), + data.GetSize()); + if (document.HasParseError() || !document.IsObject()) { + FML_LOG(ERROR) << "Could not parse document"; + return false; + } + auto root = document.GetObject(); + auto method_member = root.FindMember("method"); + if (method_member == root.MemberEnd() || !method_member->value.IsString()) { + return false; + } + std::string method(method_member->value.GetString()); + + if (method == "View.enableWireframe") { + auto args_it = root.FindMember("args"); + if (args_it == root.MemberEnd() || !args_it->value.IsObject()) { + FML_LOG(ERROR) << "No arguments found."; + return false; + } + const auto& args = args_it->value; + + auto enable = args.FindMember("enable"); + if (!enable->value.IsBool()) { + FML_LOG(ERROR) << "Argument 'enable' is not a bool"; + return false; + } + + wireframe_enabled_callback_(enable->value.GetBool()); + } else if (method == "View.create") { + auto args_it = root.FindMember("args"); + if (args_it == root.MemberEnd() || !args_it->value.IsObject()) { + FML_LOG(ERROR) << "No arguments found."; + return false; + } + const auto& args = args_it->value; + + auto view_id = args.FindMember("viewId"); + if (!view_id->value.IsUint64()) { + FML_LOG(ERROR) << "Argument 'viewId' is not a int64"; + return false; + } + + auto hit_testable = args.FindMember("hitTestable"); + if (!hit_testable->value.IsBool()) { + FML_LOG(ERROR) << "Argument 'hitTestable' is not a bool"; + return false; + } + + auto focusable = args.FindMember("focusable"); + if (!focusable->value.IsBool()) { + FML_LOG(ERROR) << "Argument 'focusable' is not a bool"; + return false; + } + + auto on_view_created = fml::MakeCopyable( + [platform_task_runner = task_runners_.GetPlatformTaskRunner(), + message = std::move(message)]() { + // The client is waiting for view creation. Send an empty response + // back to signal the view was created. + if (message->response()) { + message->response()->Complete(std::make_unique( + std::vector({'[', '0', ']'}))); + } + }); + OnCreateView(std::move(on_view_created), view_id->value.GetUint64(), + hit_testable->value.GetBool(), focusable->value.GetBool()); + return true; + } else if (method == "View.update") { + auto args_it = root.FindMember("args"); + if (args_it == root.MemberEnd() || !args_it->value.IsObject()) { + FML_LOG(ERROR) << "No arguments found."; + return false; + } + const auto& args = args_it->value; + + auto view_id = args.FindMember("viewId"); + if (!view_id->value.IsUint64()) { + FML_LOG(ERROR) << "Argument 'viewId' is not a int64"; + return false; + } + + auto hit_testable = args.FindMember("hitTestable"); + if (!hit_testable->value.IsBool()) { + FML_LOG(ERROR) << "Argument 'hitTestable' is not a bool"; + return false; + } + + auto focusable = args.FindMember("focusable"); + if (!focusable->value.IsBool()) { + FML_LOG(ERROR) << "Argument 'focusable' is not a bool"; + return false; + } + + SkRect view_occlusion_hint_raw = SkRect::MakeEmpty(); + auto view_occlusion_hint = args.FindMember("viewOcclusionHintLTRB"); + if (view_occlusion_hint != args.MemberEnd()) { + if (view_occlusion_hint->value.IsArray()) { + const auto& view_occlusion_hint_array = + view_occlusion_hint->value.GetArray(); + if (view_occlusion_hint_array.Size() == 4) { + bool parse_error = false; + for (int i = 0; i < 4; i++) { + auto& array_val = view_occlusion_hint_array[i]; + if (!array_val.IsDouble()) { + FML_LOG(ERROR) << "Argument 'viewOcclusionHintLTRB' element " << i + << " is not a double"; + parse_error = true; + break; + } + } + + if (!parse_error) { + view_occlusion_hint_raw = + SkRect::MakeLTRB(view_occlusion_hint_array[0].GetDouble(), + view_occlusion_hint_array[1].GetDouble(), + view_occlusion_hint_array[2].GetDouble(), + view_occlusion_hint_array[3].GetDouble()); + } + } else { + FML_LOG(ERROR) + << "Argument 'viewOcclusionHintLTRB' expected size 4; got " + << view_occlusion_hint_array.Size(); + } + } else { + FML_LOG(ERROR) + << "Argument 'viewOcclusionHintLTRB' is not a double array"; + } + } else { + FML_LOG(WARNING) << "Argument 'viewOcclusionHintLTRB' is missing"; + } + + on_update_view_callback_( + view_id->value.GetUint64(), view_occlusion_hint_raw, + hit_testable->value.GetBool(), focusable->value.GetBool()); + if (message->response()) { + message->response()->Complete(std::make_unique( + std::vector({'[', '0', ']'}))); + return true; + } + } else if (method == "View.dispose") { + auto args_it = root.FindMember("args"); + if (args_it == root.MemberEnd() || !args_it->value.IsObject()) { + FML_LOG(ERROR) << "No arguments found."; + return false; + } + const auto& args = args_it->value; + + auto view_id = args.FindMember("viewId"); + if (!view_id->value.IsUint64()) { + FML_LOG(ERROR) << "Argument 'viewId' is not a int64"; + return false; + } + + OnDisposeView(view_id->value.GetUint64()); + if (message->response()) { + message->response()->Complete(std::make_unique( + std::vector({'[', '0', ']'}))); + return true; + } + } else if (method.rfind("View.focus", 0) == 0) { + return focus_delegate_->HandlePlatformMessage(root, message->response()); + } else if (method.rfind(PointerInjectorDelegate::kPointerInjectorMethodPrefix, + 0) == 0) { + return pointer_injector_delegate_->HandlePlatformMessage( + root, message->response()); + } else { + FML_LOG(ERROR) << "Unknown " << message->channel() << " method " << method; + } + // Complete with an empty response by default. + return false; +} + +bool PlatformView::HandleFuchsiaShaderWarmupChannelPlatformMessage( + OnShaderWarmupCallback on_shader_warmup_callback, + std::unique_ptr message) { + FML_DCHECK(message->channel() == kFuchsiaShaderWarmupChannel); + + if (!on_shader_warmup_callback) { + FML_LOG(ERROR) << "No shader warmup callback set!"; + std::string result = "[0]"; + message->response()->Complete( + std::make_unique(std::vector( + (const uint8_t*)result.c_str(), + (const uint8_t*)result.c_str() + result.length()))); + return true; + } + + const auto& data = message->data(); + rapidjson::Document document; + document.Parse(reinterpret_cast(data.GetMapping()), + data.GetSize()); + if (document.HasParseError() || !document.IsObject()) { + FML_LOG(ERROR) << "Could not parse document"; + return false; + } + auto root = document.GetObject(); + auto method = root.FindMember("method"); + if (method == root.MemberEnd() || !method->value.IsString() || + method->value != "WarmupSkps") { + FML_LOG(ERROR) << "Invalid method name"; + return false; + } + + auto args_it = root.FindMember("args"); + if (args_it == root.MemberEnd() || !args_it->value.IsObject()) { + FML_LOG(ERROR) << "No arguments found."; + return false; + } + + auto shaders_it = root["args"].FindMember("shaders"); + if (shaders_it == root["args"].MemberEnd() || !shaders_it->value.IsArray()) { + FML_LOG(ERROR) << "No shaders found."; + return false; + } + + auto width_it = root["args"].FindMember("width"); + auto height_it = root["args"].FindMember("height"); + if (width_it == root["args"].MemberEnd() || !width_it->value.IsNumber()) { + FML_LOG(ERROR) << "Invalid width"; + return false; + } + if (height_it == root["args"].MemberEnd() || !height_it->value.IsNumber()) { + FML_LOG(ERROR) << "Invalid height"; + return false; + } + auto width = width_it->value.GetUint64(); + auto height = height_it->value.GetUint64(); + + std::vector skp_paths; + const auto& shaders = shaders_it->value; + for (rapidjson::Value::ConstValueIterator itr = shaders.Begin(); + itr != shaders.End(); ++itr) { + skp_paths.push_back((*itr).GetString()); + } + + auto completion_callback = [response = + message->response()](uint32_t num_successes) { + std::ostringstream result_stream; + result_stream << "[" << num_successes << "]"; + + std::string result(result_stream.str()); + + response->Complete(std::make_unique(std::vector( + (const uint8_t*)result.c_str(), + (const uint8_t*)result.c_str() + result.length()))); + }; + + on_shader_warmup_callback(skp_paths, completion_callback, width, height); + // The response has already been completed by us. + return true; +} + +// Channel handler for kFuchsiaInputTestChannel +bool PlatformView::HandleFuchsiaInputTestChannelPlatformMessage( + std::unique_ptr message) { + FML_DCHECK(message->channel() == kFuchsiaInputTestChannel); + + const auto& data = message->data(); + rapidjson::Document document; + document.Parse(reinterpret_cast(data.GetMapping()), + data.GetSize()); + if (document.HasParseError() || !document.IsObject()) { + FML_LOG(ERROR) << "Could not parse document"; + return false; + } + auto root = document.GetObject(); + auto method = root.FindMember("method"); + if (method == root.MemberEnd() || !method->value.IsString()) { + FML_LOG(ERROR) << "Missing method"; + return false; + } + + FML_LOG(INFO) << "fuchsia/input_test: method=" << method->value.GetString(); + + if (method->value == "TouchInputListener.ReportTouchInput") { + if (!touch_input_listener_) { + FML_LOG(ERROR) << "TouchInputListener not found."; + return false; + } + + fuchsia::ui::test::input::TouchInputListenerReportTouchInputRequest request; + CallWithMember( + root, "local_x", [&](double local_x) { request.set_local_x(local_x); }); + CallWithMember( + root, "local_y", [&](double local_y) { request.set_local_y(local_y); }); + CallWithMember(root, "time_received", [&](uint64_t time_received) { + request.set_time_received(time_received); + }); + CallWithMember(root, "component_name", + [&](std::string component_name) { + request.set_component_name(component_name); + }); + + touch_input_listener_->ReportTouchInput(std::move(request)); + return true; + } + + if (method->value == "KeyboardInputListener.ReportTextInput") { + if (!keyboard_input_listener_) { + FML_LOG(ERROR) << "KeyboardInputListener not found."; + return false; + } + + fuchsia::ui::test::input::KeyboardInputListenerReportTextInputRequest + request; + CallWithMember( + root, "text", [&](std::string text) { request.set_text(text); }); + + keyboard_input_listener_->ReportTextInput(std::move(request)); + return true; + } + + if (method->value == "MouseInputListener.ReportMouseInput") { + if (!mouse_input_listener_) { + FML_LOG(ERROR) << "MouseInputListener not found."; + return false; + } + + fuchsia::ui::test::input::MouseInputListenerReportMouseInputRequest request; + CallWithMember( + root, "local_x", [&](double local_x) { request.set_local_x(local_x); }); + CallWithMember( + root, "local_y", [&](double local_y) { request.set_local_y(local_y); }); + CallWithMember(root, "time_received", [&](uint64_t time_received) { + request.set_time_received(time_received); + }); + CallWithMember(root, "component_name", + [&](std::string component_name) { + request.set_component_name(component_name); + }); + CallWithMember(root, "buttons", [&](int button_mask) { + std::vector buttons; + if (button_mask & 1) { + buttons.push_back(fuchsia::ui::test::input::MouseButton::FIRST); + } + if (button_mask & 2) { + buttons.push_back(fuchsia::ui::test::input::MouseButton::SECOND); + } + if (button_mask & 4) { + buttons.push_back(fuchsia::ui::test::input::MouseButton::THIRD); + } + request.set_buttons(buttons); + }); + CallWithMember(root, "phase", [&](std::string phase) { + if (phase == "add") { + request.set_phase(fuchsia::ui::test::input::MouseEventPhase::ADD); + } else if (phase == "hover") { + request.set_phase(fuchsia::ui::test::input::MouseEventPhase::HOVER); + } else if (phase == "down") { + request.set_phase(fuchsia::ui::test::input::MouseEventPhase::DOWN); + } else if (phase == "move") { + request.set_phase(fuchsia::ui::test::input::MouseEventPhase::MOVE); + } else if (phase == "up") { + request.set_phase(fuchsia::ui::test::input::MouseEventPhase::UP); + } else { + FML_LOG(ERROR) << "Unexpected mouse phase: " << phase; + } + }); + CallWithMember( + root, "wheel_x_physical_pixel", [&](double wheel_x_physical_pixel) { + request.set_wheel_x_physical_pixel(wheel_x_physical_pixel); + }); + CallWithMember( + root, "wheel_y_physical_pixel", [&](double wheel_y_physical_pixel) { + request.set_wheel_y_physical_pixel(wheel_y_physical_pixel); + }); + + mouse_input_listener_->ReportMouseInput(std::move(request)); + return true; + } + + FML_LOG(ERROR) << "fuchsia/input_test: unrecognized method " + << method->value.GetString(); + return false; +} + +// Channel handler for kFuchsiaChildViewChannel +bool PlatformView::HandleFuchsiaChildViewChannelPlatformMessage( + std::unique_ptr message) { + FML_DCHECK(message->channel() == kFuchsiaChildViewChannel); + + if (message->data().GetSize() != 1 || + (message->data().GetMapping()[0] != '1')) { + FML_LOG(ERROR) << kFuchsiaChildViewChannel + << " data must be singularly '1'."; + return false; + } + + FML_DCHECK(message->data().GetMapping()[0] == '1'); + + if (!message->response()) { + FML_LOG(ERROR) << kFuchsiaChildViewChannel + << " must have a response callback."; + return false; + } + + if (!dart_application_svc_) { + FML_LOG(ERROR) << "No service directory."; + return false; + } + + fuchsia::ui::app::ViewProviderHandle view_provider_handle; + zx_status_t status = + dart_application_svc_->Connect(view_provider_handle.NewRequest()); + if (status != ZX_OK) { + FML_LOG(ERROR) << "Failed to connect to view provider."; + return false; + } + fuchsia::ui::app::ViewProviderPtr view_provider; + view_provider.Bind(std::move(view_provider_handle)); + + zx::handle view_id; + + zx::channel view_tokens[2]; + fuchsia::ui::views::ViewportCreationToken viewport_creation_token; + fuchsia::ui::views::ViewCreationToken view_creation_token; + status = zx::channel::create(0, &viewport_creation_token.value, + &view_creation_token.value); + if (status != ZX_OK) { + FML_LOG(ERROR) << "Creating view tokens: " << zx_status_get_string(status); + return false; + } + + fuchsia::ui::app::CreateView2Args create_view_args; + create_view_args.set_view_creation_token(std::move(view_creation_token)); + view_provider->CreateView2(std::move(create_view_args)); + + view_id = std::move(viewport_creation_token.value); + + if (view_id) { + message->response()->Complete( + std::make_unique(std::to_string(view_id.release()) + + )); + return true; + } else { + return false; + } +} + +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/platform_view.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/platform_view.h new file mode 100644 index 0000000000000000000000000000000000000000..b9314728f47b219fab7f32bdecb80ae3fa909d7e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/platform_view.h @@ -0,0 +1,260 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_PLATFORM_VIEW_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_PLATFORM_VIEW_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include "flutter/fml/memory/weak_ptr.h" +#include "flutter/shell/platform/fuchsia/flutter/external_view_embedder.h" + +#include "flow/embedded_views.h" +#include "flutter/fml/macros.h" +#include "flutter/fml/memory/weak_ptr.h" +#include "flutter/fml/time/time_delta.h" +#include "flutter/shell/common/platform_view.h" +#include "flutter/shell/platform/fuchsia/flutter/keyboard.h" +#include "flutter/shell/platform/fuchsia/flutter/vsync_waiter.h" +#include "focus_delegate.h" +#include "pointer_delegate.h" +#include "pointer_injector_delegate.h" +#include "text_delegate.h" + +namespace flutter_runner { + +using OnEnableWireframeCallback = fit::function; +using ViewCallback = std::function; +using OnUpdateViewCallback = fit::function; +using OnCreateSurfaceCallback = + fit::function()>; +using OnSemanticsNodeUpdateCallback = + fit::function; +using OnRequestAnnounceCallback = fit::function; +using OnCreateViewCallback = + fit::function; +using OnDestroyViewCallback = fit::function; + +// we use an std::function here because the fit::funtion causes problems with +// std:bind since HandleFuchsiaShaderWarmupChannelPlatformMessage takes one of +// these as its first argument. +using OnShaderWarmupCallback = + std::function&, + std::function, + uint64_t, + uint64_t)>; + +// PlatformView is the per-engine component residing on the platform thread that +// is responsible for all platform specific integrations -- particularly +// integration with the platform's accessibility, input, and windowing features. +// +// PlatformView communicates with the Dart code via "platform messages" handled +// in HandlePlatformMessage. This communication is bidirectional. Platform +// messages are notably responsible for communication related to input and +// external views / windowing. +class PlatformView : public flutter::PlatformView { + public: + PlatformView( + flutter::PlatformView::Delegate& delegate, + flutter::TaskRunners task_runners, + fuchsia::ui::views::ViewRef view_ref, + std::shared_ptr external_view_embedder, + fuchsia::ui::input::ImeServiceHandle ime_service, + fuchsia::ui::input3::KeyboardHandle keyboard, + fuchsia::ui::pointer::TouchSourceHandle touch_source, + fuchsia::ui::pointer::MouseSourceHandle mouse_source, + fuchsia::ui::views::FocuserHandle focuser, + fuchsia::ui::views::ViewRefFocusedHandle view_ref_focused, + fuchsia::ui::composition::ParentViewportWatcherHandle + parent_viewport_watcher, + fuchsia::ui::pointerinjector::RegistryHandle pointerinjector_registry, + OnEnableWireframeCallback wireframe_enabled_callback, + OnCreateViewCallback on_create_view_callback, + OnUpdateViewCallback on_update_view_callback, + OnDestroyViewCallback on_destroy_view_callback, + OnCreateSurfaceCallback on_create_surface_callback, + OnSemanticsNodeUpdateCallback on_semantics_node_update_callback, + OnRequestAnnounceCallback on_request_announce_callback, + OnShaderWarmupCallback on_shader_warmup_callback, + AwaitVsyncCallback await_vsync_callback, + AwaitVsyncForSecondaryCallbackCallback + await_vsync_for_secondary_callback_callback, + std::shared_ptr dart_application_svc); + + ~PlatformView() override; + + void OnGetLayout(fuchsia::ui::composition::LayoutInfo info); + void OnParentViewportStatus( + fuchsia::ui::composition::ParentViewportStatus status); + void OnChildViewStatus(uint64_t content_id, + fuchsia::ui::composition::ChildViewStatus status); + void OnChildViewViewRef(uint64_t content_id, + uint64_t view_id, + fuchsia::ui::views::ViewRef view_ref); + + // |flutter::PlatformView| + void SetSemanticsEnabled(bool enabled) override; + + // |flutter::PlatformView| + std::shared_ptr CreateExternalViewEmbedder() + override; + + private: + void RegisterPlatformMessageHandlers(); + + bool OnHandlePointerEvent(const fuchsia::ui::input::PointerEvent& pointer); + + bool OnHandleFocusEvent(const fuchsia::ui::input::FocusEvent& focus); + + // |flutter::PlatformView| + std::unique_ptr CreateVSyncWaiter() override; + + // |flutter::PlatformView| + std::unique_ptr CreateRenderingSurface() override; + + // |flutter::PlatformView| + void HandlePlatformMessage( + std::unique_ptr message) override; + + // |flutter::PlatformView| + void UpdateSemantics( + int64_t view_id, + flutter::SemanticsNodeUpdates update, + flutter::CustomAccessibilityActionUpdates actions) override; + + // Channel handler for kAccessibilityChannel. This is currently not + // being used, but it is necessary to handle accessibility messages + // that are sent by Flutter when semantics is enabled. + bool HandleAccessibilityChannelPlatformMessage( + std::unique_ptr message); + + // Channel handler for kFlutterPlatformChannel + bool HandleFlutterPlatformChannelPlatformMessage( + std::unique_ptr message); + + // Channel handler for kPlatformViewsChannel. + bool HandleFlutterPlatformViewsChannelPlatformMessage( + std::unique_ptr message); + + // Channel handler for kFuchsiaShaderWarmupChannel. + static bool HandleFuchsiaShaderWarmupChannelPlatformMessage( + OnShaderWarmupCallback on_shader_warmup_callback, + std::unique_ptr message); + + // Channel handler for kFuchsiaInputTestChannel. + bool HandleFuchsiaInputTestChannelPlatformMessage( + std::unique_ptr message); + + // Channel handler for kFuchsiaChildViewChannel. + bool HandleFuchsiaChildViewChannelPlatformMessage( + std::unique_ptr message); + + void OnCreateView(ViewCallback on_view_created, + int64_t view_id_raw, + bool hit_testable, + bool focusable); + void OnDisposeView(int64_t view_id_raw); + + // Sends a 'View.viewConnected' platform message over 'flutter/platform_views' + // channel when a view gets created. + void OnChildViewConnected(uint64_t content_id); + + // Sends a 'View.viewDisconnected' platform message over + // 'flutter/platform_views' channel when a view gets destroyed or the child + // view watcher channel of a view closes. + void OnChildViewDisconnected(uint64_t content_id); + + // Utility function for coordinate massaging. + std::array ClampToViewSpace(const float x, const float y) const; + + // Logical size and origin, and logical->physical ratio. These are optional + // to provide an "unset" state during program startup, before Scenic has sent + // any metrics-related events to provide initial values for these. + // + // The engine internally uses a default size of (0.f 0.f) with a default 1.f + // ratio, so there is no need to emit events until Scenic has actually sent a + // valid size and ratio. + std::optional> view_logical_size_; + std::optional> view_logical_origin_; + std::optional view_pixel_ratio_; + + std::shared_ptr external_view_embedder_; + + std::shared_ptr focus_delegate_; + std::shared_ptr pointer_delegate_; + std::unique_ptr pointer_injector_delegate_; + + // Text delegate is responsible for handling keyboard input and text editing. + std::unique_ptr text_delegate_; + + std::set down_pointers_; + std::map /* message */)> /* handler */> + platform_message_handlers_; + // These are the channels that aren't registered and have been notified as + // such. Notifying via logs multiple times results in log-spam. See: + // https://github.com/flutter/flutter/issues/55966 + std::set unregistered_channels_; + + OnEnableWireframeCallback wireframe_enabled_callback_; + OnUpdateViewCallback on_update_view_callback_; + OnCreateSurfaceCallback on_create_surface_callback_; + OnSemanticsNodeUpdateCallback on_semantics_node_update_callback_; + OnRequestAnnounceCallback on_request_announce_callback_; + OnCreateViewCallback on_create_view_callback_; + OnDestroyViewCallback on_destroy_view_callback_; + OnShaderWarmupCallback on_shader_warmup_callback_; + AwaitVsyncCallback await_vsync_callback_; + AwaitVsyncForSecondaryCallbackCallback + await_vsync_for_secondary_callback_callback_; + + // Proxies for input tests. + fuchsia::ui::test::input::TouchInputListenerPtr touch_input_listener_; + fuchsia::ui::test::input::KeyboardInputListenerPtr keyboard_input_listener_; + fuchsia::ui::test::input::MouseInputListenerPtr mouse_input_listener_; + + // Component's service directory. + std::shared_ptr dart_application_svc_; + + // child_view_ids_ maintains a persistent mapping from Flatland ContentId's to + // flutter view ids, which are really zx_handle_t of ViewCreationToken. + struct ChildViewInfo { + ChildViewInfo(zx_handle_t token, + fuchsia::ui::composition::ChildViewWatcherPtr watcher) + : view_id(token), child_view_watcher(std::move(watcher)) {} + zx_handle_t view_id; + fuchsia::ui::composition::ChildViewWatcherPtr child_view_watcher; + }; + std::unordered_map + child_view_info_; + + fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher_; + fuchsia::ui::composition::ParentViewportStatus parent_viewport_status_; + + fml::WeakPtrFactory weak_factory_; // Must be the last member. + + FML_DISALLOW_COPY_AND_ASSIGN(PlatformView); +}; + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_PLATFORM_VIEW_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_delegate.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_delegate.cc new file mode 100644 index 0000000000000000000000000000000000000000..1977521468a776087806da88890474a338681f9d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_delegate.cc @@ -0,0 +1,455 @@ +// 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 "pointer_delegate.h" + +#include +#include +#include + +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/trace_event.h" + +// TODO(fxbug.dev/87076): Add MouseSource tests. + +namespace fuchsia::ui::pointer { +// For using TouchInteractionId as a map key. +bool operator==(const fuchsia::ui::pointer::TouchInteractionId& a, + const fuchsia::ui::pointer::TouchInteractionId& b) { + return a.device_id == b.device_id && a.pointer_id == b.pointer_id && + a.interaction_id == b.interaction_id; +} +} // namespace fuchsia::ui::pointer + +namespace flutter_runner { + +using fup_EventPhase = fuchsia::ui::pointer::EventPhase; +using fup_MouseDeviceInfo = fuchsia::ui::pointer::MouseDeviceInfo; +using fup_MouseEvent = fuchsia::ui::pointer::MouseEvent; +using fup_TouchEvent = fuchsia::ui::pointer::TouchEvent; +using fup_TouchIxnStatus = fuchsia::ui::pointer::TouchInteractionStatus; +using fup_TouchResponse = fuchsia::ui::pointer::TouchResponse; +using fup_TouchResponseType = fuchsia::ui::pointer::TouchResponseType; +using fup_ViewParameters = fuchsia::ui::pointer::ViewParameters; + +namespace { +void IssueTouchTraceEvent(const fup_TouchEvent& event) { + FML_DCHECK(event.has_trace_flow_id()) << "API guarantee"; + TRACE_FLOW_END("input", "dispatch_event_to_client", event.trace_flow_id()); +} + +void IssueMouseTraceEvent(const fup_MouseEvent& event) { + FML_DCHECK(event.has_trace_flow_id()) << "API guarantee"; + TRACE_FLOW_END("input", "dispatch_event_to_client", event.trace_flow_id()); +} + +bool HasValidatedTouchSample(const fup_TouchEvent& event) { + if (!event.has_pointer_sample()) { + return false; + } + FML_DCHECK(event.pointer_sample().has_interaction()) << "API guarantee"; + FML_DCHECK(event.pointer_sample().has_phase()) << "API guarantee"; + FML_DCHECK(event.pointer_sample().has_position_in_viewport()) + << "API guarantee"; + return true; +} + +bool HasValidatedMouseSample(const fup_MouseEvent& event) { + if (!event.has_pointer_sample()) { + return false; + } + const auto& sample = event.pointer_sample(); + FML_DCHECK(sample.has_device_id()) << "API guarantee"; + FML_DCHECK(sample.has_position_in_viewport()) << "API guarantee"; + FML_DCHECK(!sample.has_pressed_buttons() || !sample.pressed_buttons().empty()) + << "API guarantee"; + + return true; +} + +std::array ViewportToViewCoordinates( + std::array viewport_coordinates, + const std::array& viewport_to_view_transform) { + // The transform matrix is a FIDL array with matrix data in column-major + // order. For a matrix with data [a b c d e f g h i], and with the viewport + // coordinates expressed as homogeneous coordinates, the logical view + // coordinates are obtained with the following formula: + // |a d g| |x| |x'| + // |b e h| * |y| = |y'| + // |c f i| |1| |w'| + // which we then normalize based on the w component: + // if z' not zero: (x'/w', y'/w') + // else (x', y') + const auto& M = viewport_to_view_transform; + const float x = viewport_coordinates[0]; + const float y = viewport_coordinates[1]; + const float xp = M[0] * x + M[3] * y + M[6]; + const float yp = M[1] * x + M[4] * y + M[7]; + const float wp = M[2] * x + M[5] * y + M[8]; + if (wp != 0) { + return {xp / wp, yp / wp}; + } else { + return {xp, yp}; + } +} + +flutter::PointerData::Change GetChangeFromTouchEventPhase( + fup_EventPhase phase) { + switch (phase) { + case fup_EventPhase::ADD: + return flutter::PointerData::Change::kAdd; + case fup_EventPhase::CHANGE: + return flutter::PointerData::Change::kMove; + case fup_EventPhase::REMOVE: + return flutter::PointerData::Change::kRemove; + case fup_EventPhase::CANCEL: + return flutter::PointerData::Change::kCancel; + default: + return flutter::PointerData::Change::kCancel; + } +} + +std::array ClampToViewSpace(const float x, + const float y, + const fup_ViewParameters& p) { + const float min_x = p.view.min[0]; + const float min_y = p.view.min[1]; + const float max_x = p.view.max[0]; + const float max_y = p.view.max[1]; + if (min_x <= x && x < max_x && min_y <= y && y < max_y) { + return {x, y}; // No clamping to perform. + } + + // View boundary is [min_x, max_x) x [min_y, max_y). Note that min is + // inclusive, but max is exclusive - so we subtract epsilon. + const float max_x_inclusive = max_x - std::numeric_limits::epsilon(); + const float max_y_inclusive = max_y - std::numeric_limits::epsilon(); + const float& clamped_x = std::clamp(x, min_x, max_x_inclusive); + const float& clamped_y = std::clamp(y, min_y, max_y_inclusive); + FML_LOG(INFO) << "Clamped (" << x << ", " << y << ") to (" << clamped_x + << ", " << clamped_y << ")."; + return {clamped_x, clamped_y}; +} + +flutter::PointerData::Change ComputePhase( + bool any_button_down, + std::unordered_set& mouse_down, + uint32_t id) { + if (!mouse_down.count(id) && !any_button_down) { + return flutter::PointerData::Change::kHover; + } else if (!mouse_down.count(id) && any_button_down) { + mouse_down.insert(id); + return flutter::PointerData::Change::kDown; + } else if (mouse_down.count(id) && any_button_down) { + return flutter::PointerData::Change::kMove; + } else if (mouse_down.count(id) && !any_button_down) { + mouse_down.erase(id); + return flutter::PointerData::Change::kUp; + } + + FML_UNREACHABLE(); + return flutter::PointerData::Change::kCancel; +} + +// Flutter's PointerData.device field is 64 bits and is expected to be unique +// for each pointer. We pack Fuchsia's device ID (hi) and pointer ID (lo) into +// 64 bits to retain uniqueness across multiple touch devices. +uint64_t PackFuchsiaDeviceIdAndPointerId(uint32_t fuchsia_device_id, + uint32_t fuchsia_pointer_id) { + return (((uint64_t)fuchsia_device_id) << 32) | fuchsia_pointer_id; +} + +// It returns a "draft" because the coordinates are logical. Later, view pixel +// ratio is applied to obtain physical coordinates. +// +// The flutter pointerdata state machine has extra phases, which this function +// synthesizes on the fly. Hence the return data is a flutter pointerdata, and +// optionally a second one. +// For example: , , . +// TODO(fxbug.dev/87074): Let PointerDataPacketConverter synthesize events. +// +// Flutter gestures expect a gesture to start within the logical view space, and +// is not tolerant of floating point drift. This function coerces just the DOWN +// event's coordinate to start within the logical view. +std::pair> +CreateTouchDraft(const fup_TouchEvent& event, + const fup_ViewParameters& view_parameters) { + FML_DCHECK(HasValidatedTouchSample(event)) << "precondition"; + const auto& sample = event.pointer_sample(); + const auto& ixn = sample.interaction(); + + flutter::PointerData ptr; + ptr.Clear(); + ptr.time_stamp = event.timestamp() / 1000; // in microseconds + ptr.change = GetChangeFromTouchEventPhase(sample.phase()); + ptr.kind = flutter::PointerData::DeviceKind::kTouch; + // Load Fuchsia's pointer ID onto Flutter's |device| field, and not the + // |pointer_identifier| field. The latter is written by + // PointerDataPacketConverter, to track individual gesture interactions. + ptr.device = PackFuchsiaDeviceIdAndPointerId(ixn.device_id, ixn.pointer_id); + // View parameters can change mid-interaction; apply transform on the fly. + auto logical = + ViewportToViewCoordinates(sample.position_in_viewport(), + view_parameters.viewport_to_view_transform); + ptr.physical_x = logical[0]; // Not yet physical; adjusted in PlatformView. + ptr.physical_y = logical[1]; // Not yet physical; adjusted in PlatformView. + + // Match Flutter pointer's state machine with synthesized events. + if (ptr.change == flutter::PointerData::Change::kAdd) { + flutter::PointerData down; + memcpy(&down, &ptr, sizeof(flutter::PointerData)); + down.change = flutter::PointerData::Change::kDown; + { // Ensure gesture recognition: DOWN starts in the logical view space. + auto [x, y] = + ClampToViewSpace(down.physical_x, down.physical_y, view_parameters); + down.physical_x = x; + down.physical_y = y; + } + return {std::move(ptr), std::move(down)}; + } else if (ptr.change == flutter::PointerData::Change::kRemove) { + flutter::PointerData up; + memcpy(&up, &ptr, sizeof(flutter::PointerData)); + up.change = flutter::PointerData::Change::kUp; + return {std::move(up), std::move(ptr)}; + } else { + return {std::move(ptr), std::nullopt}; + } +} + +// It returns a "draft" because the coordinates are logical. Later, view pixel +// ratio is applied to obtain physical coordinates. +// +// Phase data is computed before this call; it involves state tracking based on +// button-down state. +// +// Button data, if available, gets packed into the |buttons| field, in flutter +// button order (kMousePrimaryButton, etc). The device-assigned button IDs are +// provided in priority order in MouseEvent.device_info (at the start of channel +// connection), and maps from device button ID (given in fup_MouseEvent) to +// flutter button ID (flutter::PointerData). +// +// Scroll data, if available, gets packed into the |scroll_delta_x| or +// |scroll_delta_y| fields, and the |signal_kind| field is set to kScroll. +// The PointerDataPacketConverter reads this field to synthesize events to match +// Flutter's expected pointer stream. +// TODO(fxbug.dev/87073): PointerDataPacketConverter should synthesize a +// discrete scroll event on kDown or kUp, to match engine expectations. +// +// Flutter gestures expect a gesture to start within the logical view space, and +// is not tolerant of floating point drift. This function coerces just the DOWN +// event's coordinate to start within the logical view. +flutter::PointerData CreateMouseDraft(const fup_MouseEvent& event, + const flutter::PointerData::Change phase, + const fup_ViewParameters& view_parameters, + const fup_MouseDeviceInfo& device_info) { + FML_DCHECK(HasValidatedMouseSample(event)) << "precondition"; + const auto& sample = event.pointer_sample(); + + flutter::PointerData ptr; + ptr.Clear(); + ptr.time_stamp = event.timestamp() / 1000; // in microseconds + ptr.change = phase; + ptr.kind = flutter::PointerData::DeviceKind::kMouse; + ptr.device = sample.device_id(); + + // View parameters can change mid-interaction; apply transform on the fly. + auto logical = + ViewportToViewCoordinates(sample.position_in_viewport(), + view_parameters.viewport_to_view_transform); + ptr.physical_x = logical[0]; // Not yet physical; adjusted in PlatformView. + ptr.physical_y = logical[1]; // Not yet physical; adjusted in PlatformView. + + // Ensure gesture recognition: DOWN starts in the logical view space. + if (ptr.change == flutter::PointerData::Change::kDown) { + auto [x, y] = + ClampToViewSpace(ptr.physical_x, ptr.physical_y, view_parameters); + ptr.physical_x = x; + ptr.physical_y = y; + } + + if (sample.has_pressed_buttons()) { + int64_t flutter_buttons = 0; + const auto& pressed = sample.pressed_buttons(); + for (size_t idx = 0; idx < pressed.size(); ++idx) { + const uint8_t button_id = pressed[idx]; + FML_DCHECK(device_info.has_buttons()) << "API guarantee"; + // Priority 0 maps to kPrimaryButton, and so on. + for (uint8_t prio = 0; prio < device_info.buttons().size(); ++prio) { + if (button_id == device_info.buttons()[prio]) { + flutter_buttons |= (1 << prio); + } + } + } + FML_DCHECK(flutter_buttons != 0); + ptr.buttons = flutter_buttons; + } + + // Fuchsia previously only provided scroll data in "ticks", not physical + // pixels. On legacy platforms, since Flutter expects scroll data in physical + // pixels, to compensate for lack of guidance, we make up a "reasonable + // amount". + // TODO(fxbug.dev/103443): Remove the tick based scrolling after the + // transition. + const int kScrollOffsetMultiplier = 20; + + double dy = 0; + double dx = 0; + bool is_scroll = false; + + if (sample.has_scroll_v_physical_pixel()) { + dy = -sample.scroll_v_physical_pixel(); + is_scroll = true; + } else if (sample.has_scroll_v()) { + dy = -sample.scroll_v() * + kScrollOffsetMultiplier; // logical amount, not yet physical; adjusted + // in Platform View. + is_scroll = true; + } + + if (sample.has_scroll_h_physical_pixel()) { + dx = sample.scroll_h_physical_pixel(); + is_scroll = true; + } else if (sample.has_scroll_h()) { + dx = sample.scroll_h() * kScrollOffsetMultiplier; // logical amount + is_scroll = true; + } + + if (is_scroll) { + ptr.signal_kind = flutter::PointerData::SignalKind::kScroll; + ptr.scroll_delta_y = dy; + ptr.scroll_delta_x = dx; + } + + return ptr; +} + +// Helper to insert one or two events into a vector buffer. +void InsertIntoBuffer( + std::pair> events, + std::vector* buffer) { + FML_DCHECK(buffer); + buffer->emplace_back(std::move(events.first)); + if (events.second.has_value()) { + buffer->emplace_back(std::move(events.second.value())); + } +} +} // namespace + +PointerDelegate::PointerDelegate( + fuchsia::ui::pointer::TouchSourceHandle touch_source, + fuchsia::ui::pointer::MouseSourceHandle mouse_source) + : touch_source_(touch_source.Bind()), mouse_source_(mouse_source.Bind()) { + if (touch_source_) { + touch_source_.set_error_handler([](zx_status_t status) { + FML_LOG(ERROR) << "TouchSource channel error: << " + << zx_status_get_string(status); + }); + } + if (mouse_source_) { + mouse_source_.set_error_handler([](zx_status_t status) { + FML_LOG(ERROR) << "MouseSource channel error: << " + << zx_status_get_string(status); + }); + } +} +// Core logic of this class. +// Aim to keep state management in this function. +void PointerDelegate::WatchLoop( + std::function)> callback) { + FML_LOG(INFO) << "Flutter - PointerDelegate started."; + if (touch_responder_) { + FML_LOG(ERROR) << "PointerDelegate::WatchLoop() must be called once."; + return; + } + + touch_responder_ = [this, callback](std::vector events) { + TRACE_EVENT0("flutter", "PointerDelegate::TouchHandler"); + FML_DCHECK(touch_responses_.empty()) << "precondition"; + std::vector to_client; + for (const fup_TouchEvent& event : events) { + IssueTouchTraceEvent(event); + fup_TouchResponse + response; // Response per event, matched on event's index. + if (event.has_view_parameters()) { + touch_view_parameters_ = std::move(event.view_parameters()); + } + if (HasValidatedTouchSample(event)) { + const auto& sample = event.pointer_sample(); + const auto& ixn = sample.interaction(); + if (sample.phase() == fup_EventPhase::ADD && + !event.has_interaction_result()) { + touch_buffer_.emplace(ixn, std::vector()); + } + + FML_DCHECK(touch_view_parameters_.has_value()) << "API guarantee"; + auto events = CreateTouchDraft(event, touch_view_parameters_.value()); + if (touch_buffer_.count(ixn) > 0) { + InsertIntoBuffer(std::move(events), &touch_buffer_[ixn]); + } else { + InsertIntoBuffer(std::move(events), &to_client); + } + // For this simple client, always claim we want the gesture. + response.set_response_type(fup_TouchResponseType::YES); + } + if (event.has_interaction_result()) { + const auto& result = event.interaction_result(); + const auto& ixn = result.interaction; + if (result.status == fup_TouchIxnStatus::GRANTED && + touch_buffer_.count(ixn) > 0) { + FML_DCHECK(to_client.empty()) << "invariant"; + to_client.insert(to_client.end(), touch_buffer_[ixn].begin(), + touch_buffer_[ixn].end()); + } + touch_buffer_.erase(ixn); // Result seen, delete the buffer. + } + touch_responses_.push_back(std::move(response)); + } + callback(std::move(to_client)); // Notify client of touch events, if any. + + touch_source_->Watch(std::move(touch_responses_), + /*copy*/ touch_responder_); + touch_responses_.clear(); + }; + + mouse_responder_ = [this, callback](std::vector events) { + TRACE_EVENT0("flutter", "PointerDelegate::MouseHandler"); + std::vector to_client; + for (fup_MouseEvent& event : events) { + IssueMouseTraceEvent(event); + if (event.has_device_info()) { + const auto& id = event.device_info().id(); + mouse_device_info_[id] = std::move(*event.mutable_device_info()); + } + if (event.has_view_parameters()) { + mouse_view_parameters_ = std::move(event.view_parameters()); + } + if (HasValidatedMouseSample(event)) { + const auto& sample = event.pointer_sample(); + const auto& id = sample.device_id(); + const bool any_button_down = sample.has_pressed_buttons(); + FML_DCHECK(mouse_view_parameters_.has_value()) << "API guarantee"; + FML_DCHECK(mouse_device_info_.count(id) > 0) << "API guarantee"; + + const auto phase = ComputePhase(any_button_down, mouse_down_, id); + flutter::PointerData data = + CreateMouseDraft(event, phase, mouse_view_parameters_.value(), + mouse_device_info_[id]); + to_client.emplace_back(std::move(data)); + } + } + callback(std::move(to_client)); + mouse_source_->Watch(/*copy*/ mouse_responder_); + }; + + // Start watching both channels. + touch_source_->Watch(std::move(touch_responses_), /*copy*/ touch_responder_); + touch_responses_.clear(); + if (mouse_source_) { + mouse_source_->Watch(/*copy*/ mouse_responder_); + } +} + +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_delegate.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_delegate.h new file mode 100644 index 0000000000000000000000000000000000000000..650c2b3300834ec7507ddb7a7a3e3f062d687bb1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_delegate.h @@ -0,0 +1,143 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_POINTER_DELEGATE_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_POINTER_DELEGATE_H_ + +#include + +#include +#include +#include +#include +#include +#include + +#include "flutter/lib/ui/window/pointer_data.h" + +namespace flutter_runner { + +// Helper class for keying into a map. +struct IxnHasher { + std::size_t operator()( + const fuchsia::ui::pointer::TouchInteractionId& ixn) const { + return std::hash()(ixn.device_id) ^ + std::hash()(ixn.pointer_id) ^ + std::hash()(ixn.interaction_id); + } +}; + +// Channel processors for fuchsia.ui.pointer.TouchSource and MouseSource +// protocols. It manages the channel state, collects touch and mouse events, and +// surfaces them to PlatformView as flutter::PointerData events for further +// processing and dispatch. +class PointerDelegate { + public: + PointerDelegate(fuchsia::ui::pointer::TouchSourceHandle touch_source, + fuchsia::ui::pointer::MouseSourceHandle mouse_source); + + // This function collects Fuchsia's TouchPointerSample and MousePointerSample + // data and transforms them into flutter::PointerData structs. It then calls + // the supplied callback with a vector of flutter::PointerData, which (1) does + // last processing (applies metrics), and (2) packs these flutter::PointerData + // in a flutter::PointerDataPacket for transport to the Engine. + void WatchLoop( + std::function)> callback); + + private: + /***** TOUCH STATE *****/ + + // Channel for touch events from Scenic. + fuchsia::ui::pointer::TouchSourcePtr touch_source_; + + // Receive touch events from Scenic. Must be copyable. + std::function)> + touch_responder_; + + // Per-interaction buffer of touch events from Scenic. When an interaction + // starts with event.pointer_sample.phase == ADD, we allocate a buffer and + // store samples. When interaction ownership becomes + // event.interaction_result.status == GRANTED, we flush the buffer to client, + // delete the buffer, and all future events in this interaction are flushed + // direct to client. When interaction ownership becomes DENIED, we delete the + // buffer, and the client does not get any previous or future events in this + // interaction. + // + // There are three basic interaction forms that we need to handle, and the API + // guarantees we see only these three forms. S=sample, R(g)=result-granted, + // R(d)=result-denied, and + means packaged in the same table. Time flows from + // left to right. Samples start with ADD, and end in REMOVE or CANCEL. Each + // interaction receives just one ownership result. + // (1) Late grant. S S S R(g) S S S + // (1-a) Combo. S S S+R(g) S S S + // (2) Early grant. S+R(g) S S S S S + // (3) Late deny. S S S R(d) + // (3-a) Combo. S S S+R(d) + // + // This results in the following high-level algorithm to correctly deal with + // buffer allocation and deletion, and event flushing or event dropping based + // on ownership. + // if event.sample.phase == ADD && !event.result + // allocate buffer[event.sample.interaction] + // if buffer[event.sample.interaction] + // buffer[event.sample.interaction].push(event.sample) + // else + // flush_to_client(event.sample) + // if event.result + // if event.result == GRANTED + // flush_to_client(buffer[event.result.interaction]) + // delete buffer[event.result.interaction] + std::unordered_map, + IxnHasher> + touch_buffer_; + + // The fuchsia.ui.pointer.TouchSource protocol allows one in-flight + // hanging-get Watch() call to gather touch events, and the client is expected + // to respond with consumption intent on the following hanging-get Watch() + // call. Store responses here for the next call. + std::vector touch_responses_; + + // The fuchsia.ui.pointer.TouchSource protocol issues channel-global view + // parameters on connection and on change. Events must apply these view + // parameters to correctly map to logical view coordinates. The "nullopt" + // state represents the absence of view parameters, early in the protocol + // lifecycle. + std::optional touch_view_parameters_; + + /***** MOUSE STATE *****/ + + // Channel for mouse events from Scenic. + fuchsia::ui::pointer::MouseSourcePtr mouse_source_; + + // Receive mouse events from Scenic. Must be copyable. + std::function)> + mouse_responder_; + + // The set of mouse devices that are currently interacting with the UI. + // A mouse is considered flutter::PointerData::Change::kDown if any button is + // pressed. This set is used to correctly set the phase in + // flutter::PointerData.change, with this high-level algorithm: + // if !mouse_down[id] && !button then: change = kHover + // if !mouse_down[id] && button then: change = kDown; mouse_down.add(id) + // if mouse_down[id] && button then: change = kMove + // if mouse_down[id] && !button then: change = kUp; mouse_down.remove(id) + std::unordered_set mouse_down_; + + // For each mouse device, its device-specific information, such as mouse + // button priority order. + std::unordered_map + mouse_device_info_; + + // The fuchsia.ui.pointer.MouseSource protocol issues channel-global view + // parameters on connection and on change. Events must apply these view + // parameters to correctly map to logical view coordinates. The "nullopt" + // state represents the absence of view parameters, early in the protocol + // lifecycle. + std::optional mouse_view_parameters_; +}; + +} // namespace flutter_runner +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_POINTER_DELEGATE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_delegate_unittests.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_delegate_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..112192bca3d3ffc2379320de411bb3b09fc4d473 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_delegate_unittests.cc @@ -0,0 +1,844 @@ +// 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 +#include +#include +#include +#include + +#include +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/macros.h" +#include "pointer_delegate.h" +#include "tests/fakes/mouse_source.h" +#include "tests/fakes/touch_source.h" +#include "tests/pointer_event_utility.h" + +namespace flutter_runner::testing { + +using fup_EventPhase = fuchsia::ui::pointer::EventPhase; +using fup_TouchEvent = fuchsia::ui::pointer::TouchEvent; +using fup_TouchIxnId = fuchsia::ui::pointer::TouchInteractionId; +using fup_TouchIxnResult = fuchsia::ui::pointer::TouchInteractionResult; +using fup_TouchIxnStatus = fuchsia::ui::pointer::TouchInteractionStatus; +using fup_TouchPointerSample = fuchsia::ui::pointer::TouchPointerSample; +using fup_TouchResponse = fuchsia::ui::pointer::TouchResponse; +using fup_TouchResponseType = fuchsia::ui::pointer::TouchResponseType; +using fup_ViewParameters = fuchsia::ui::pointer::ViewParameters; +using fup_MouseEvent = fuchsia::ui::pointer::MouseEvent; + +constexpr std::array, 2> kRect = {{{0, 0}, {20, 20}}}; +constexpr std::array kIdentity = {1, 0, 0, 0, 1, 0, 0, 0, 1}; +constexpr fup_TouchIxnId kIxnOne = {.device_id = 1u, + .pointer_id = 1u, + .interaction_id = 2u}; + +constexpr uint32_t kMouseDeviceId = 123; +constexpr std::array kNoScrollInPhysicalPixelDelta = {0, 0}; +const bool kNotPrecisionScroll = false; +const bool kPrecisionScroll = true; + +// Fixture to exercise Flutter runner's implementation for +// fuchsia.ui.pointer.TouchSource. +class PointerDelegateTest : public ::testing::Test { + protected: + PointerDelegateTest() : loop_(&kAsyncLoopConfigAttachToCurrentThread) { + touch_source_ = std::make_unique(); + mouse_source_ = std::make_unique(); + pointer_delegate_ = std::make_unique( + touch_source_bindings_.AddBinding(touch_source_.get()), + mouse_source_bindings_.AddBinding(mouse_source_.get())); + } + + void RunLoopUntilIdle() { loop_.RunUntilIdle(); } + + std::unique_ptr touch_source_; + std::unique_ptr mouse_source_; + std::unique_ptr pointer_delegate_; + + private: + async::Loop loop_; + fidl::BindingSet touch_source_bindings_; + fidl::BindingSet mouse_source_bindings_; + + FML_DISALLOW_COPY_AND_ASSIGN(PointerDelegateTest); +}; + +TEST_F(PointerDelegateTest, Data_FuchsiaTimeVersusFlutterTime) { + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + // Fuchsia ADD -> Flutter ADD+DOWN + std::vector events = + TouchEventBuilder::New() + .AddTime(/* in nanoseconds */ 1111789u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) + .AddResult( + {.interaction = kIxnOne, .status = fup_TouchIxnStatus::GRANTED}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers->size(), 2u); + EXPECT_EQ((*pointers)[0].time_stamp, /* in microseconds */ 1111u); + EXPECT_EQ((*pointers)[1].time_stamp, /* in microseconds */ 1111u); +} + +TEST_F(PointerDelegateTest, Phase_FlutterPhasesAreSynthesized) { + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + // Fuchsia ADD -> Flutter ADD+DOWN + std::vector events = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) + .AddResult( + {.interaction = kIxnOne, .status = fup_TouchIxnStatus::GRANTED}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers->size(), 2u); + EXPECT_EQ((*pointers)[0].change, flutter::PointerData::Change::kAdd); + EXPECT_EQ((*pointers)[1].change, flutter::PointerData::Change::kDown); + + // Fuchsia CHANGE -> Flutter MOVE + events = TouchEventBuilder::New() + .AddTime(2222000u) + .AddSample(kIxnOne, fup_EventPhase::CHANGE, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers->size(), 1u); + EXPECT_EQ((*pointers)[0].change, flutter::PointerData::Change::kMove); + + // Fuchsia REMOVE -> Flutter UP+REMOVE + events = TouchEventBuilder::New() + .AddTime(3333000u) + .AddSample(kIxnOne, fup_EventPhase::REMOVE, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers->size(), 2u); + EXPECT_EQ((*pointers)[0].change, flutter::PointerData::Change::kUp); + EXPECT_EQ((*pointers)[1].change, flutter::PointerData::Change::kRemove); +} + +TEST_F(PointerDelegateTest, Phase_FuchsiaCancelBecomesFlutterCancel) { + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + // Fuchsia ADD -> Flutter ADD+DOWN + std::vector events = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) + .AddResult( + {.interaction = kIxnOne, .status = fup_TouchIxnStatus::GRANTED}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers->size(), 2u); + EXPECT_EQ((*pointers)[0].change, flutter::PointerData::Change::kAdd); + EXPECT_EQ((*pointers)[1].change, flutter::PointerData::Change::kDown); + + // Fuchsia CANCEL -> Flutter CANCEL + events = TouchEventBuilder::New() + .AddTime(2222000u) + .AddSample(kIxnOne, fup_EventPhase::CANCEL, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers->size(), 1u); + EXPECT_EQ((*pointers)[0].change, flutter::PointerData::Change::kCancel); +} + +TEST_F(PointerDelegateTest, Coordinates_CorrectMapping) { + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + // Fuchsia ADD event, with a view parameter that maps the viewport identically + // to the view. Then the center point of the viewport should map to the center + // of the view, (10.f, 10.f). + std::vector events = + TouchEventBuilder::New() + .AddTime(2222000u) + .AddViewParameters(/*view*/ {{{0, 0}, {20, 20}}}, + /*viewport*/ {{{0, 0}, {20, 20}}}, + /*matrix*/ {1, 0, 0, 0, 1, 0, 0, 0, 1}) + .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) + .AddResult( + {.interaction = kIxnOne, .status = fup_TouchIxnStatus::GRANTED}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers->size(), 2u); // ADD - DOWN + EXPECT_FLOAT_EQ((*pointers)[0].physical_x, 10.f); + EXPECT_FLOAT_EQ((*pointers)[0].physical_y, 10.f); + pointers = {}; + + // Fuchsia CHANGE event, with a view parameter that translates the viewport by + // (10, 10) within the view. Then the minimal point in the viewport (its + // origin) should map to the center of the view, (10.f, 10.f). + events = TouchEventBuilder::New() + .AddTime(2222000u) + .AddViewParameters(/*view*/ {{{0, 0}, {20, 20}}}, + /*viewport*/ {{{0, 0}, {20, 20}}}, + /*matrix*/ {1, 0, 0, 0, 1, 0, 10, 10, 1}) + .AddSample(kIxnOne, fup_EventPhase::CHANGE, {0.f, 0.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers->size(), 1u); // MOVE + EXPECT_FLOAT_EQ((*pointers)[0].physical_x, 10.f); + EXPECT_FLOAT_EQ((*pointers)[0].physical_y, 10.f); + + // Fuchsia CHANGE event, with a view parameter that scales the viewport by + // (0.5, 0.5) within the view. Then the maximal point in the viewport should + // map to the center of the view, (10.f, 10.f). + events = TouchEventBuilder::New() + .AddTime(2222000u) + .AddViewParameters(/*view*/ {{{0, 0}, {20, 20}}}, + /*viewport*/ {{{0, 0}, {20, 20}}}, + /*matrix*/ {0.5f, 0, 0, 0, 0.5f, 0, 0, 0, 1}) + .AddSample(kIxnOne, fup_EventPhase::CHANGE, {20.f, 20.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers->size(), 1u); // MOVE + EXPECT_FLOAT_EQ((*pointers)[0].physical_x, 10.f); + EXPECT_FLOAT_EQ((*pointers)[0].physical_y, 10.f); +} + +TEST_F(PointerDelegateTest, Coordinates_DownEventClampedToView) { + const float kSmallDiscrepancy = -0.00003f; + + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + std::vector events = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, kSmallDiscrepancy}) + .AddResult( + {.interaction = kIxnOne, .status = fup_TouchIxnStatus::GRANTED}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers->size(), 2u); + + const auto& add_event = (*pointers)[0]; + EXPECT_FLOAT_EQ(add_event.physical_x, 10.f); + EXPECT_FLOAT_EQ(add_event.physical_y, kSmallDiscrepancy); + + const auto& down_event = (*pointers)[1]; + EXPECT_FLOAT_EQ(down_event.physical_x, 10.f); + EXPECT_EQ(down_event.physical_y, 0.f); +} + +TEST_F(PointerDelegateTest, Protocol_FirstResponseIsEmpty) { + bool called = false; + pointer_delegate_->WatchLoop( + [&called](std::vector events) { called = true; }); + RunLoopUntilIdle(); // Server gets Watch call. + + EXPECT_FALSE(called); // No events yet received to forward to client. + // Server sees an initial "response" from client, which is empty, by contract. + const auto responses = touch_source_->UploadedResponses(); + ASSERT_TRUE(responses.has_value()); + ASSERT_EQ(responses->size(), 0u); +} + +TEST_F(PointerDelegateTest, Protocol_ResponseMatchesEarlierEvents) { + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + // Fuchsia view parameter only. Empty response. + std::vector events = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddViewParameters(kRect, kRect, kIdentity) + .BuildAsVector(); + + // Fuchsia ptr 1 ADD sample. Yes response. + fup_TouchEvent e1 = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample({.device_id = 0u, .pointer_id = 1u, .interaction_id = 3u}, + fup_EventPhase::ADD, {10.f, 10.f}) + .Build(); + events.emplace_back(std::move(e1)); + + // Fuchsia ptr 2 ADD sample. Yes response. + fup_TouchEvent e2 = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddSample({.device_id = 0u, .pointer_id = 2u, .interaction_id = 3u}, + fup_EventPhase::ADD, {5.f, 5.f}) + .Build(); + events.emplace_back(std::move(e2)); + + // Fuchsia ptr 3 ADD sample. Yes response. + fup_TouchEvent e3 = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddSample({.device_id = 0u, .pointer_id = 3u, .interaction_id = 3u}, + fup_EventPhase::ADD, {1.f, 1.f}) + .Build(); + events.emplace_back(std::move(e3)); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + const auto responses = touch_source_->UploadedResponses(); + ASSERT_TRUE(responses.has_value()); + ASSERT_EQ(responses.value().size(), 4u); + // Event 0 did not carry a sample, so no response. + EXPECT_FALSE(responses.value()[0].has_response_type()); + // Events 1-3 had a sample, must have a response. + EXPECT_TRUE(responses.value()[1].has_response_type()); + EXPECT_EQ(responses.value()[1].response_type(), fup_TouchResponseType::YES); + EXPECT_TRUE(responses.value()[2].has_response_type()); + EXPECT_EQ(responses.value()[2].response_type(), fup_TouchResponseType::YES); + EXPECT_TRUE(responses.value()[3].has_response_type()); + EXPECT_EQ(responses.value()[3].response_type(), fup_TouchResponseType::YES); +} + +TEST_F(PointerDelegateTest, Protocol_LateGrant) { + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + // Fuchsia ADD, no grant result - buffer it. + std::vector events = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + EXPECT_EQ(pointers.value().size(), 0u); + pointers = {}; + + // Fuchsia CHANGE, no grant result - buffer it. + events = TouchEventBuilder::New() + .AddTime(2222000u) + .AddSample(kIxnOne, fup_EventPhase::CHANGE, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + EXPECT_EQ(pointers.value().size(), 0u); + pointers = {}; + + // Fuchsia result: ownership granted. Buffered pointers released. + events = TouchEventBuilder::New() + .AddTime(3333000u) + .AddResult({kIxnOne, fup_TouchIxnStatus::GRANTED}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers.value().size(), 3u); // ADD - DOWN - MOVE + EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kAdd); + EXPECT_EQ(pointers.value()[1].change, flutter::PointerData::Change::kDown); + EXPECT_EQ(pointers.value()[2].change, flutter::PointerData::Change::kMove); + pointers = {}; + + // Fuchsia CHANGE, grant result - release immediately. + events = TouchEventBuilder::New() + .AddTime(/* in nanoseconds */ 4444000u) + .AddSample(kIxnOne, fup_EventPhase::CHANGE, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers.value().size(), 1u); + EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kMove); + EXPECT_EQ(pointers.value()[0].time_stamp, /* in microseconds */ 4444u); + pointers = {}; +} + +TEST_F(PointerDelegateTest, Protocol_LateGrantCombo) { + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + // Fuchsia ADD, no grant result - buffer it. + std::vector events = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + EXPECT_EQ(pointers.value().size(), 0u); + pointers = {}; + + // Fuchsia CHANGE, no grant result - buffer it. + events = TouchEventBuilder::New() + .AddTime(2222000u) + .AddSample(kIxnOne, fup_EventPhase::CHANGE, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + EXPECT_EQ(pointers.value().size(), 0u); + pointers = {}; + + // Fuchsia CHANGE, with grant result - release buffered events. + events = TouchEventBuilder::New() + .AddTime(3333000u) + .AddSample(kIxnOne, fup_EventPhase::CHANGE, {10.f, 10.f}) + .AddResult({kIxnOne, fup_TouchIxnStatus::GRANTED}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers.value().size(), 4u); // ADD - DOWN - MOVE - MOVE + EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kAdd); + EXPECT_EQ(pointers.value()[0].time_stamp, 1111u); + EXPECT_EQ(pointers.value()[1].change, flutter::PointerData::Change::kDown); + EXPECT_EQ(pointers.value()[1].time_stamp, 1111u); + EXPECT_EQ(pointers.value()[2].change, flutter::PointerData::Change::kMove); + EXPECT_EQ(pointers.value()[2].time_stamp, 2222u); + EXPECT_EQ(pointers.value()[3].change, flutter::PointerData::Change::kMove); + EXPECT_EQ(pointers.value()[3].time_stamp, 3333u); + pointers = {}; +} + +TEST_F(PointerDelegateTest, Protocol_EarlyGrant) { + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + // Fuchsia ADD, with grant result - release immediately. + std::vector events = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) + .AddResult({kIxnOne, fup_TouchIxnStatus::GRANTED}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers.value().size(), 2u); + EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kAdd); + EXPECT_EQ(pointers.value()[1].change, flutter::PointerData::Change::kDown); + pointers = {}; + + // Fuchsia CHANGE, after grant result - release immediately. + events = TouchEventBuilder::New() + .AddTime(2222000u) + .AddSample(kIxnOne, fup_EventPhase::CHANGE, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers.value().size(), 1u); + EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kMove); + pointers = {}; +} + +TEST_F(PointerDelegateTest, Protocol_LateDeny) { + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + // Fuchsia ADD, no grant result - buffer it. + std::vector events = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + EXPECT_EQ(pointers.value().size(), 0u); + pointers = {}; + + // Fuchsia CHANGE, no grant result - buffer it. + events = TouchEventBuilder::New() + .AddTime(2222000u) + .AddSample(kIxnOne, fup_EventPhase::CHANGE, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + EXPECT_EQ(pointers.value().size(), 0u); + pointers = {}; + + // Fuchsia result: ownership denied. Buffered pointers deleted. + events = TouchEventBuilder::New() + .AddTime(3333000u) + .AddResult({kIxnOne, fup_TouchIxnStatus::DENIED}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers.value().size(), 0u); // Do not release to client! + pointers = {}; +} + +TEST_F(PointerDelegateTest, Protocol_LateDenyCombo) { + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + // Fuchsia ADD, no grant result - buffer it. + std::vector events = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + EXPECT_EQ(pointers.value().size(), 0u); + pointers = {}; + + // Fuchsia CHANGE, no grant result - buffer it. + events = TouchEventBuilder::New() + .AddTime(2222000u) + .AddSample(kIxnOne, fup_EventPhase::CHANGE, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + EXPECT_EQ(pointers.value().size(), 0u); + pointers = {}; + + // Fuchsia result: ownership denied. Buffered pointers deleted. + events = TouchEventBuilder::New() + .AddTime(3333000u) + .AddSample(kIxnOne, fup_EventPhase::CANCEL, {10.f, 10.f}) + .AddResult({kIxnOne, fup_TouchIxnStatus::DENIED}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers.value().size(), 0u); // Do not release to client! + pointers = {}; +} + +TEST_F(PointerDelegateTest, Protocol_PointersAreIndependent) { + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + constexpr fup_TouchIxnId kIxnTwo = { + .device_id = 1u, .pointer_id = 2u, .interaction_id = 2u}; + + // Fuchsia ptr1 ADD and ptr2 ADD, no grant result for either - buffer them. + std::vector events = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) + .BuildAsVector(); + fup_TouchEvent ptr2 = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddSample(kIxnTwo, fup_EventPhase::ADD, {15.f, 15.f}) + .Build(); + events.emplace_back(std::move(ptr2)); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + EXPECT_EQ(pointers.value().size(), 0u); + pointers = {}; + + // Server grants win to pointer 2. + events = TouchEventBuilder::New() + .AddTime(2222000u) + .AddResult({kIxnTwo, fup_TouchIxnStatus::GRANTED}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + // Note: Fuchsia's device and pointer IDs (both 32 bit) are coerced together + // to fit in Flutter's 64-bit device ID. However, Flutter's pointer_identifier + // is not set by platform runner code - PointerDataCaptureConverter (PDPC) + // sets it. + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers.value().size(), 2u); + EXPECT_EQ(pointers.value()[0].pointer_identifier, 0); // reserved for PDPC + EXPECT_EQ(pointers.value()[0].device, (int64_t)((1ul << 32) | 2u)); + EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kAdd); + EXPECT_EQ(pointers.value()[1].pointer_identifier, 0); // reserved for PDPC + EXPECT_EQ(pointers.value()[1].device, (int64_t)((1ul << 32) | 2u)); + EXPECT_EQ(pointers.value()[1].change, flutter::PointerData::Change::kDown); + pointers = {}; + + // Server grants win to pointer 1. + events = TouchEventBuilder::New() + .AddTime(3333000u) + .AddResult({kIxnOne, fup_TouchIxnStatus::GRANTED}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers.value().size(), 2u); + EXPECT_EQ(pointers.value()[0].pointer_identifier, 0); // reserved for PDPC + EXPECT_EQ(pointers.value()[0].device, (int64_t)((1ul << 32) | 1u)); + EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kAdd); + EXPECT_EQ(pointers.value()[1].pointer_identifier, 0); // reserved for PDPC + EXPECT_EQ(pointers.value()[1].device, (int64_t)((1ul << 32) | 1u)); + EXPECT_EQ(pointers.value()[1].change, flutter::PointerData::Change::kDown); + pointers = {}; +} + +TEST_F(PointerDelegateTest, MouseWheel_TickBased) { + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + std::vector events = + MouseEventBuilder() + .AddTime(1111789u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kMouseDeviceId, {10.f, 10.f}, {}, {0, 1}, + kNoScrollInPhysicalPixelDelta, kNotPrecisionScroll) + .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) + .BuildAsVector(); + mouse_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers.value().size(), 1u); + EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kHover); + EXPECT_EQ(pointers.value()[0].signal_kind, + flutter::PointerData::SignalKind::kScroll); + EXPECT_EQ(pointers.value()[0].kind, flutter::PointerData::DeviceKind::kMouse); + EXPECT_EQ(pointers.value()[0].buttons, 0); + EXPECT_EQ(pointers.value()[0].scroll_delta_x, 0); + EXPECT_EQ(pointers.value()[0].scroll_delta_y, -20); + pointers = {}; + + // receive a horizontal scroll + events = MouseEventBuilder() + .AddTime(1111789u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kMouseDeviceId, {10.f, 10.f}, {}, {1, 0}, + kNoScrollInPhysicalPixelDelta, kNotPrecisionScroll) + .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) + .BuildAsVector(); + mouse_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers.value().size(), 1u); + EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kHover); + EXPECT_EQ(pointers.value()[0].signal_kind, + flutter::PointerData::SignalKind::kScroll); + EXPECT_EQ(pointers.value()[0].kind, flutter::PointerData::DeviceKind::kMouse); + EXPECT_EQ(pointers.value()[0].buttons, 0); + EXPECT_EQ(pointers.value()[0].scroll_delta_x, 20); + EXPECT_EQ(pointers.value()[0].scroll_delta_y, 0); + pointers = {}; +} + +TEST_F(PointerDelegateTest, MouseWheel_PixelBased) { + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + std::vector events = + MouseEventBuilder() + .AddTime(1111789u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kMouseDeviceId, {10.f, 10.f}, {}, {0, 1}, {0, 120}, + kNotPrecisionScroll) + .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) + .BuildAsVector(); + mouse_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers.value().size(), 1u); + EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kHover); + EXPECT_EQ(pointers.value()[0].signal_kind, + flutter::PointerData::SignalKind::kScroll); + EXPECT_EQ(pointers.value()[0].kind, flutter::PointerData::DeviceKind::kMouse); + EXPECT_EQ(pointers.value()[0].buttons, 0); + EXPECT_EQ(pointers.value()[0].scroll_delta_x, 0); + EXPECT_EQ(pointers.value()[0].scroll_delta_y, -120); + pointers = {}; + + // receive a horizontal scroll + events = MouseEventBuilder() + .AddTime(1111789u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kMouseDeviceId, {10.f, 10.f}, {}, {1, 0}, {120, 0}, + kNotPrecisionScroll) + .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) + .BuildAsVector(); + mouse_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers.value().size(), 1u); + EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kHover); + EXPECT_EQ(pointers.value()[0].signal_kind, + flutter::PointerData::SignalKind::kScroll); + EXPECT_EQ(pointers.value()[0].kind, flutter::PointerData::DeviceKind::kMouse); + EXPECT_EQ(pointers.value()[0].buttons, 0); + EXPECT_EQ(pointers.value()[0].scroll_delta_x, 120); + EXPECT_EQ(pointers.value()[0].scroll_delta_y, 0); + pointers = {}; +} + +TEST_F(PointerDelegateTest, MouseWheel_TouchpadPixelBased) { + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + std::vector events = + MouseEventBuilder() + .AddTime(1111789u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kMouseDeviceId, {10.f, 10.f}, {}, {0, 1}, {0, 120}, + kPrecisionScroll) + .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) + .BuildAsVector(); + mouse_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers.value().size(), 1u); + EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kHover); + EXPECT_EQ(pointers.value()[0].signal_kind, + flutter::PointerData::SignalKind::kScroll); + EXPECT_EQ(pointers.value()[0].kind, flutter::PointerData::DeviceKind::kMouse); + EXPECT_EQ(pointers.value()[0].buttons, 0); + EXPECT_EQ(pointers.value()[0].scroll_delta_x, 0); + EXPECT_EQ(pointers.value()[0].scroll_delta_y, -120); + pointers = {}; + + // receive a horizontal scroll + events = MouseEventBuilder() + .AddTime(1111789u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kMouseDeviceId, {10.f, 10.f}, {}, {1, 0}, {120, 0}, + kPrecisionScroll) + .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) + .BuildAsVector(); + mouse_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers.value().size(), 1u); + EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kHover); + EXPECT_EQ(pointers.value()[0].signal_kind, + flutter::PointerData::SignalKind::kScroll); + EXPECT_EQ(pointers.value()[0].kind, flutter::PointerData::DeviceKind::kMouse); + EXPECT_EQ(pointers.value()[0].buttons, 0); + EXPECT_EQ(pointers.value()[0].scroll_delta_x, 120); + EXPECT_EQ(pointers.value()[0].scroll_delta_y, 0); + pointers = {}; +} + +} // namespace flutter_runner::testing diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_injector_delegate.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_injector_delegate.cc new file mode 100644 index 0000000000000000000000000000000000000000..ba93b9e2bc8e4abff9e5e29c75cbd2ebaa12283d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_injector_delegate.cc @@ -0,0 +1,289 @@ +// 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 "pointer_injector_delegate.h" +#include "flutter/fml/logging.h" + +namespace flutter_runner { + +using fup_Config = fuchsia::ui::pointerinjector::Config; +using fup_Context = fuchsia::ui::pointerinjector::Context; +using fup_Data = fuchsia::ui::pointerinjector::Data; +using fup_DeviceType = fuchsia::ui::pointerinjector::DeviceType; +using fup_DispatchPolicy = fuchsia::ui::pointerinjector::DispatchPolicy; +using fup_Event = fuchsia::ui::pointerinjector::Event; +using fup_EventPhase = fuchsia::ui::pointerinjector::EventPhase; +using fup_PointerSample = fuchsia::ui::pointerinjector::PointerSample; +using fup_Target = fuchsia::ui::pointerinjector::Target; +using fup_Viewport = fuchsia::ui::pointerinjector::Viewport; +using fuv_ViewRef = fuchsia::ui::views::ViewRef; +const auto fup_MAX_INJECT = fuchsia::ui::pointerinjector::MAX_INJECT; + +namespace { + +// clang-format off + static constexpr std::array kIdentityMatrix = { + 1, 0, 0, // column one + 0, 1, 0, // column two + 0, 0, 1, // column three + }; +// clang-format on + +} // namespace + +bool PointerInjectorDelegate::HandlePlatformMessage( + rapidjson::Value request, + fml::RefPtr response) { + if (!registry_->is_bound()) { + FML_LOG(WARNING) + << "Lost connection to fuchsia.ui.pointerinjector.Registry"; + return false; + } + + auto method = request.FindMember("method"); + if (method == request.MemberEnd() || !method->value.IsString()) { + FML_LOG(ERROR) << "No method found in platform message."; + return false; + } + + if (method->value != kPointerInjectorMethodPrefix) { + FML_LOG(ERROR) << "Unexpected platform message method, expected " + "View.pointerinjector.inject."; + return false; + } + + auto args_it = request.FindMember("args"); + if (args_it == request.MemberEnd() || !args_it->value.IsObject()) { + FML_LOG(ERROR) << "No arguments found in platform message's method"; + return false; + } + + const auto& args = args_it->value; + + auto view_id = args.FindMember("viewId"); + if (!view_id->value.IsUint64()) { + FML_LOG(ERROR) << "Argument 'viewId' is not a uint64"; + return false; + } + + auto id = view_id->value.GetUint64(); + if (valid_views_.count(id) == 0) { + // A child view can get destroyed bottom-up, so the parent view may continue + // injecting until all view state processing "catches up". Until then, it's + // okay to accept a request to inject into a view that no longer exists. + // Doing so avoids log pollution regarding "MissingPluginException". + Complete(std::move(response), "[0]"); + return true; + } + + auto phase = args.FindMember("phase"); + if (!phase->value.IsInt()) { + FML_LOG(ERROR) << "Argument 'phase' is not a int"; + return false; + } + + auto pointer_x = args.FindMember("x"); + if (!pointer_x->value.IsFloat() && !pointer_x->value.IsInt()) { + FML_LOG(ERROR) << "Argument 'Pointer.X' is not a float"; + return false; + } + + auto pointer_y = args.FindMember("y"); + if (!pointer_y->value.IsFloat() && !pointer_y->value.IsInt()) { + FML_LOG(ERROR) << "Argument 'Pointer.Y' is not a float"; + return false; + } + + auto pointer_id = args.FindMember("pointerId"); + if (!pointer_id->value.IsUint()) { + FML_LOG(ERROR) << "Argument 'pointerId' is not a uint32"; + return false; + } + + auto trace_flow_id = args.FindMember("traceFlowId"); + if (!trace_flow_id->value.IsInt()) { + FML_LOG(ERROR) << "Argument 'traceFlowId' is not a int"; + return false; + } + + auto width = args.FindMember("logicalWidth"); + if (!width->value.IsFloat() && !width->value.IsInt()) { + FML_LOG(ERROR) << "Argument 'logicalWidth' is not a float"; + return false; + } + + auto height = args.FindMember("logicalHeight"); + if (!height->value.IsFloat() && !height->value.IsInt()) { + FML_LOG(ERROR) << "Argument 'logicalHeight' is not a float"; + return false; + } + + auto timestamp = args.FindMember("timestamp"); + if (!timestamp->value.IsInt() && !timestamp->value.IsUint64()) { + FML_LOG(ERROR) << "Argument 'timestamp' is not a int"; + return false; + } + + PointerInjectorRequest event = { + .x = pointer_x->value.GetFloat(), + .y = pointer_y->value.GetFloat(), + .pointer_id = pointer_id->value.GetUint(), + .phase = static_cast(phase->value.GetInt()), + .trace_flow_id = trace_flow_id->value.GetUint64(), + .logical_size = {width->value.GetFloat(), height->value.GetFloat()}, + .timestamp = timestamp->value.GetInt()}; + + // Inject the pointer event if the view has been created. + valid_views_.at(id).InjectEvent(std::move(event)); + Complete(std::move(response), "[0]"); + return true; +} + +void PointerInjectorDelegate::OnCreateView( + uint64_t view_id, + std::optional view_ref) { + FML_CHECK(valid_views_.count(view_id) == 0); + + auto [_, success] = valid_views_.try_emplace( + view_id, registry_, host_view_ref_, std::move(view_ref)); + + FML_CHECK(success); +} + +fup_Event PointerInjectorDelegate::ExtractPointerEvent( + PointerInjectorRequest request) { + fup_Event event; + event.set_timestamp(request.timestamp); + event.set_trace_flow_id(request.trace_flow_id); + + fup_PointerSample pointer_sample; + pointer_sample.set_pointer_id(request.pointer_id); + pointer_sample.set_phase(request.phase); + pointer_sample.set_position_in_viewport({request.x, request.y}); + + fup_Data data; + data.set_pointer_sample(std::move(pointer_sample)); + + event.set_data(std::move(data)); + return event; +} + +void PointerInjectorDelegate::Complete( + fml::RefPtr response, + std::string value) { + if (response) { + response->Complete(std::make_unique( + std::vector(value.begin(), value.end()))); + } +} + +void PointerInjectorDelegate::PointerInjectorEndpoint::InjectEvent( + PointerInjectorRequest request) { + if (!registered_) { + RegisterInjector(request); + } + + auto event = ExtractPointerEvent(std::move(request)); + + // Add the event to |injector_events_| and dispatch it to the view. + EnqueueEvent(std::move(event)); + + DispatchPendingEvents(); +} + +void PointerInjectorDelegate::PointerInjectorEndpoint::DispatchPendingEvents() { + // Return if there is already a |fuchsia.ui.pointerinjector.Device.Inject| + // call in flight. The new pointer events will be dispatched once the + // in-progress call terminates. + if (injection_in_flight_) { + return; + } + + // Dispatch the events present in |injector_events_|. Note that we recursively + // call |DispatchPendingEvents| in the callback passed to the + // |f.u.p.Device.Inject| call. This ensures that there is only one + // |f.u.p.Device.Inject| call at a time. If a new pointer event comes when + // there is a |f.u.p.Device.Inject| call in progress, it gets buffered in + // |injector_events_| and is picked up later. + if (!injector_events_.empty()) { + auto events = std::move(injector_events_.front()); + injector_events_.pop(); + injection_in_flight_ = true; + + FML_CHECK(device_.is_bound()); + FML_CHECK(events.size() <= fup_MAX_INJECT); + + device_->Inject(std::move(events), [weak = weak_factory_.GetWeakPtr()] { + if (!weak) { + FML_LOG(WARNING) << "Use after free attempted."; + return; + } + weak->injection_in_flight_ = false; + weak->DispatchPendingEvents(); + }); + } +} + +void PointerInjectorDelegate::PointerInjectorEndpoint::EnqueueEvent( + fup_Event event) { + // Add |event| in |injector_events_| keeping in mind that the vector size does + // not exceed |fup_MAX_INJECT|. + if (!injector_events_.empty() && + injector_events_.back().size() < fup_MAX_INJECT) { + injector_events_.back().push_back(std::move(event)); + } else { + std::vector vec; + vec.reserve(fup_MAX_INJECT); + vec.push_back(std::move(event)); + injector_events_.push(std::move(vec)); + } +} + +void PointerInjectorDelegate::PointerInjectorEndpoint::RegisterInjector( + const PointerInjectorRequest& request) { + if (registered_) { + return; + } + + fup_Config config; + config.set_device_id(1); + config.set_device_type(fup_DeviceType::TOUCH); + config.set_dispatch_policy(fup_DispatchPolicy::EXCLUSIVE_TARGET); + + fup_Context context; + fuv_ViewRef context_clone; + fidl::Clone(*host_view_ref_, &context_clone); + context.set_view(std::move(context_clone)); + config.set_context(std::move(context)); + + FML_CHECK(view_ref_.has_value()); + fup_Target target; + fuv_ViewRef target_clone; + + fidl::Clone(*view_ref_, &target_clone); + target.set_view(std::move(target_clone)); + config.set_target(std::move(target)); + + fup_Viewport viewport; + viewport.set_viewport_to_context_transform(kIdentityMatrix); + std::array, 2> extents{ + {/*min*/ {0, 0}, + /*max*/ {request.logical_size[0], request.logical_size[1]}}}; + viewport.set_extents(std::move(extents)); + config.set_viewport(std::move(viewport)); + + FML_CHECK(registry_->is_bound()); + + (*registry_)->Register(std::move(config), device_.NewRequest(), [] {}); + + registered_ = true; +} + +void PointerInjectorDelegate::PointerInjectorEndpoint::Reset() { + injection_in_flight_ = false; + registered_ = false; + injector_events_ = {}; +} + +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_injector_delegate.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_injector_delegate.h new file mode 100644 index 0000000000000000000000000000000000000000..4a9ccce7edbbcf800b54622c593b8115f0c81b90 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_injector_delegate.h @@ -0,0 +1,190 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_POINTER_INJECTOR_DELEGATE_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_POINTER_INJECTOR_DELEGATE_H_ + +#include +#include + +#include +#include +#include + +#include "flutter/fml/macros.h" +#include "flutter/fml/memory/weak_ptr.h" +#include "flutter/lib/ui/window/platform_message.h" +#include "third_party/rapidjson/include/rapidjson/document.h" + +namespace flutter_runner { + +// This class is responsible for handling the platform messages related to +// pointer events and managing the lifecycle of +// |fuchsia.ui.pointerinjector.Device| client side endpoint for embedded views. +class PointerInjectorDelegate { + public: + static constexpr auto kPointerInjectorMethodPrefix = + "View.pointerinjector.inject"; + + PointerInjectorDelegate(fuchsia::ui::pointerinjector::RegistryHandle registry, + fuchsia::ui::views::ViewRef host_view_ref) + : registry_(std::make_shared( + registry.Bind())), + host_view_ref_(std::make_shared( + std::move(host_view_ref))) {} + + // Handles the following pointer event related platform message requests: + // View.Pointerinjector.inject + // - Attempts to dispatch a pointer event to the given viewRef. Completes + // with [0] when the pointer event is sent to the given viewRef. + bool HandlePlatformMessage( + rapidjson::Value request, + fml::RefPtr response); + + // Adds an endpoint for |view_id| in |valid_views_| for lifecycle management. + // Called in |PlatformView::OnChildViewViewRef()|. + void OnCreateView( + uint64_t view_id, + std::optional view_ref = std::nullopt); + + // Closes the |fuchsia.ui.pointerinjector.Device| channel for |view_id| and + // cleans up resources. + void OnDestroyView(uint64_t view_id) { valid_views_.erase(view_id); } + + private: + using ViewId = int64_t; + + struct PointerInjectorRequest { + // The position of the pointer event in viewport's coordinate system. + float x = 0.f, y = 0.f; + + // |fuchsia.ui.pointerinjector.PointerSample.pointer_id|. + uint32_t pointer_id = 0; + + // |fuchsia.ui.pointerinjector.PointerSample.phase|. + fuchsia::ui::pointerinjector::EventPhase phase = + fuchsia::ui::pointerinjector::EventPhase::ADD; + + // |fuchsia.ui.pointerinjector.Event.trace_flow_id|. + uint64_t trace_flow_id = 0; + + // Logical size of the view's coordinate system. + std::array logical_size = {0.f, 0.f}; + + // |fuchsia.ui.pointerinjector.Event.timestamp|. + zx_time_t timestamp = 0; + }; + + // This class is responsible for dispatching pointer events to a view by first + // registering the injector device using + // |fuchsia.ui.pointerinjector.Registry.Register| and then injecting the + // pointer event using |fuchsia.ui.pointerinjector.Device.Inject|. + class PointerInjectorEndpoint { + public: + PointerInjectorEndpoint( + std::shared_ptr registry, + std::shared_ptr host_view_ref, + std::optional view_ref) + : registry_(std::move(registry)), + host_view_ref_(std::move(host_view_ref)), + view_ref_(std::move(view_ref)), + weak_factory_(this) { + // Try to re-register the |device_| if the |device_| gets closed due to + // some error. + device_.set_error_handler( + [weak = weak_factory_.GetWeakPtr()](auto status) { + FML_LOG(WARNING) + << "fuchsia.ui.pointerinjector.Device closed " << status; + if (!weak) { + return; + } + + // Clear all the stale pointer events in |injector_events_| and + // reset the state of |weak| so that any future calls do not inject + // any stale pointer events. + weak->Reset(); + }); + } + + // Registers |device_| if it has not been registered and calls + // |DispatchPendingEvents()| to dispatch |request| to the view. + void InjectEvent(PointerInjectorRequest request); + + private: + // Registers with the pointer injector service. + // + // Sets |registered_| to true immediately after submitting the registration + // request. This means that the registration request may still be in-flight + // on the server side when the function returns. Events can safely be + // injected into the channel while registration is pending ("feed forward"). + void RegisterInjector(const PointerInjectorRequest& request); + + // Recursively calls |fuchsia.ui.pointerinjector.Device.Inject| to dispatch + // the pointer events in |injector_events_| to the view. + void DispatchPendingEvents(); + + void EnqueueEvent(fuchsia::ui::pointerinjector::Event event); + + // Resets |registered_|, |injection_in_flight_| and |injector_events_| so + // that |device_| can be re-registered and future calls to + // |fuchsia.ui.pointerinjector.Device.Inject| do not include any stale + // pointer events. + void Reset(); + + // Set to true if there is a |fuchsia.ui.pointerinjector.Device.Inject| call + // in progress. If true, the |fuchsia.ui.pointerinjector.Event| is buffered + // in |injector_events_|. + bool injection_in_flight_ = false; + + // Set to true if |device_| has been registered using + // |fuchsia.ui.pointerinjector.Registry.Register|. False otherwise. + bool registered_ = false; + + std::shared_ptr registry_; + + // ViewRef for the main flutter app launching the embedded child views. + std::shared_ptr host_view_ref_; + + // ViewRef for a flatland view. + // Set in |OnCreateView|. + std::optional view_ref_; + + fuchsia::ui::pointerinjector::DevicePtr device_; + + // A queue containing all the pending |fuchsia.ui.pointerinjector.Event|s + // which have to be dispatched to the view. + // Note: The size of a vector inside |injector_events_| should not exceed + // |fuchsia.ui.pointerinjector.MAX_INJECT|. + std::queue> + injector_events_; + + fml::WeakPtrFactory + weak_factory_; // Must be the last member. + + FML_DISALLOW_COPY_AND_ASSIGN(PointerInjectorEndpoint); + }; + + void Complete(fml::RefPtr response, + std::string value); + + // Generates a |fuchsia.ui.pointerinjector.Event| from |request| by extracting + // information like timestamp, trace flow id and pointer sample from + // |request|. + static fuchsia::ui::pointerinjector::Event ExtractPointerEvent( + PointerInjectorRequest request); + + // A map of valid views keyed by its view id. A view can receive pointer + // events only if it is present in |valid_views_|. + std::unordered_map valid_views_; + + std::shared_ptr registry_; + + // ViewRef for the main flutter app launching the embedded child views. + std::shared_ptr host_view_ref_; + + FML_DISALLOW_COPY_AND_ASSIGN(PointerInjectorDelegate); +}; + +} // namespace flutter_runner +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_POINTER_INJECTOR_DELEGATE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_injector_delegate_unittest.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_injector_delegate_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..dcf0fd41c6b6d766f7ac73fb383cb1b8b4024e6a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_injector_delegate_unittest.cc @@ -0,0 +1,731 @@ +// 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 +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "pointer_injector_delegate.h" +#include "tests/fakes/mock_injector_registry.h" +#include "tests/fakes/platform_message.h" + +namespace flutter_runner::testing { + +using fup_DeviceType = fuchsia::ui::pointerinjector::DeviceType; +using fup_DispatchPolicy = fuchsia::ui::pointerinjector::DispatchPolicy; +using fup_EventPhase = fuchsia::ui::pointerinjector::EventPhase; +using fup_RegistryHandle = fuchsia::ui::pointerinjector::RegistryHandle; +using fuv_ViewRef = fuchsia::ui::views::ViewRef; + +namespace { + +// clang-format off + static constexpr std::array kIdentityMatrix = { + 1, 0, 0, // column one + 0, 1, 0, // column two + 0, 0, 1, // column three + }; +// clang-format on + +rapidjson::Value ParsePlatformMessage(std::string json) { + rapidjson::Document document; + document.Parse(json); + if (document.HasParseError() || !document.IsObject()) { + FML_LOG(ERROR) << "Could not parse document"; + return rapidjson::Value(); + } + return document.GetObject(); +} + +zx_koid_t ExtractKoid(const zx::object_base& object) { + zx_info_handle_basic_t info{}; + if (object.get_info(ZX_INFO_HANDLE_BASIC, &info, sizeof(info), nullptr, + nullptr) != ZX_OK) { + return ZX_KOID_INVALID; // no info + } + + return info.koid; +} + +zx_koid_t ExtractKoid(const fuv_ViewRef& view_ref) { + return ExtractKoid(view_ref.reference); +} + +class PlatformMessageBuilder { + public: + PlatformMessageBuilder& SetViewId(uint64_t view_id) { + view_id_ = view_id; + return *this; + } + + PlatformMessageBuilder& SetPointerX(float x) { + pointer_x_ = x; + return *this; + } + + PlatformMessageBuilder& SetPointerY(float y) { + pointer_y_ = y; + return *this; + } + + PlatformMessageBuilder& SetPhase(int phase) { + phase_ = phase; + return *this; + } + + PlatformMessageBuilder& SetPointerId(int pointer_id) { + pointer_id_ = pointer_id; + return *this; + } + + PlatformMessageBuilder& SetTraceFlowId(int trace_flow_id) { + trace_flow_id_ = trace_flow_id; + return *this; + } + + PlatformMessageBuilder& SetLogicalWidth(float width) { + width_ = width; + return *this; + } + + PlatformMessageBuilder& SetLogicalHeight(float height) { + height_ = height; + return *this; + } + + PlatformMessageBuilder& SetTimestamp(int timestamp) { + timestamp_ = timestamp; + return *this; + } + + rapidjson::Value Build() { + std::ostringstream message; + message << "{" << " \"method\":\"" + << PointerInjectorDelegate::kPointerInjectorMethodPrefix << "\"," + << " \"args\": {" << " \"viewId\":" << view_id_ << "," + << " \"x\":" << pointer_x_ << "," + << " \"y\":" << pointer_y_ << "," + << " \"phase\":" << phase_ << "," + << " \"pointerId\":" << pointer_id_ << "," + << " \"traceFlowId\":" << trace_flow_id_ << "," + << " \"viewRef\":" << view_ref_.reference.get() << "," + << " \"logicalWidth\":" << width_ << "," + << " \"logicalHeight\":" << height_ << "," + << " \"timestamp\":" << timestamp_ << " }" << "}"; + return ParsePlatformMessage(message.str()); + } + + private: + uint64_t view_id_ = 0; + float pointer_x_ = 0.f, pointer_y_ = 0.f; + int phase_ = 1, pointer_id_ = 0, trace_flow_id_ = 0; + fuv_ViewRef view_ref_; + float width_ = 0.f, height_ = 0.f; + int timestamp_ = 0; +}; + +} // namespace + +class PointerInjectorDelegateTest : public ::testing::Test, + public ::testing::WithParamInterface { + protected: + PointerInjectorDelegateTest() + : loop_(&kAsyncLoopConfigAttachToCurrentThread) {} + + // TODO(fxbug.dev/104285): Replace the RunLoop methods with the one provided + // by the sdk. + void RunLoopUntilIdle() { loop_.RunUntilIdle(); } + + bool RunGivenLoopWithTimeout(async::Loop* loop, zx::duration timeout) { + // This cannot be a local variable because the delayed task below can + // execute after this function returns. + auto canceled = std::make_shared(false); + bool timed_out = false; + async::PostDelayedTask( + loop->dispatcher(), + [loop, canceled, &timed_out] { + if (*canceled) { + return; + } + timed_out = true; + loop->Quit(); + }, + timeout); + loop->Run(); + loop->ResetQuit(); + + if (!timed_out) { + *canceled = true; + } + return timed_out; + } + + bool RunLoopWithTimeoutOrUntil(fit::function condition, + zx::duration timeout, + zx::duration step) { + const zx::time timeout_deadline = zx::deadline_after(timeout); + + while (zx::clock::get_monotonic() < timeout_deadline && + loop_.GetState() == ASYNC_LOOP_RUNNABLE) { + if (condition()) { + loop_.ResetQuit(); + return true; + } + + if (step == zx::duration::infinite()) { + // Performs a single unit of work, possibly blocking until there is work + // to do or the timeout deadline arrives. + loop_.Run(timeout_deadline, true); + } else { + // Performs work until the step deadline arrives. + RunGivenLoopWithTimeout(&loop_, step); + } + } + + loop_.ResetQuit(); + return condition(); + } + + void RunLoopUntil(fit::function condition, + zx::duration step = zx::msec(10)) { + RunLoopWithTimeoutOrUntil(std::move(condition), zx::duration::infinite(), + step); + } + + void SetUp() override { + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ASSERT_EQ(status, ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + + host_view_ref_ = std::move(view_ref); + + fup_RegistryHandle registry; + registry_ = std::make_unique(registry.NewRequest()); + + fuv_ViewRef host_view_ref_clone; + fidl::Clone(host_view_ref_, &host_view_ref_clone); + + pointer_injector_delegate_ = std::make_unique( + std::move(registry), std::move(host_view_ref_clone)); + } + + void CreateView(uint64_t view_id, + std::optional view_ref = std::nullopt) { + fuv_ViewRef ref; + if (view_ref.has_value()) { + ref = std::move(*view_ref); + } else { + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ASSERT_EQ(status, ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + + ref = std::move(view_ref); + } + pointer_injector_delegate_->OnCreateView(view_id, std::move(ref)); + } + + std::unique_ptr pointer_injector_delegate_; + std::unique_ptr registry_; + fuv_ViewRef host_view_ref_; + + private: + async::Loop loop_; +}; + +TEST_P(PointerInjectorDelegateTest, IncorrectPlatformMessage_ShouldFail) { + const uint64_t view_id = 1; + + // Create a view. + CreateView(view_id); + + // A platform message in incorrect JSON format should fail. + { + auto response = FakePlatformMessageResponse::Create(); + + EXPECT_FALSE(pointer_injector_delegate_->HandlePlatformMessage( + ParsePlatformMessage("{Incorrect Json}"), response)); + } + + // |PointerInjectorDelegate| only handles "View.Pointerinjector.inject" + // platform messages. + { + auto response = FakePlatformMessageResponse::Create(); + + EXPECT_FALSE(pointer_injector_delegate_->HandlePlatformMessage( + ParsePlatformMessage("{\"method\":\"View.focus.getCurrent\"}"), + response)); + } + + // A platform message with no args should fail. + { + auto response = FakePlatformMessageResponse::Create(); + + EXPECT_FALSE(pointer_injector_delegate_->HandlePlatformMessage( + ParsePlatformMessage("{\"method\":\"View.Pointerinjector.inject\"}"), + response)); + } +} + +TEST_P(PointerInjectorDelegateTest, ViewsReceiveInjectedEvents) { + const uint64_t num_events = 150; + + // Inject |num_events| platform messages for view 1. + { + const uint64_t view_id = 1; + + CreateView(view_id); + + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ASSERT_EQ(status, ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + + for (size_t i = 0; i < num_events; i++) { + auto response = FakePlatformMessageResponse::Create(); + + EXPECT_TRUE(pointer_injector_delegate_->HandlePlatformMessage( + PlatformMessageBuilder().SetViewId(view_id).Build(), response)); + + response->ExpectCompleted("[0]"); + } + } + + // Inject |num_events| platform messages for view 2. + { + const uint64_t view_id = 2; + + CreateView(view_id); + + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ASSERT_EQ(status, ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + + for (size_t i = 0; i < num_events; i++) { + auto response = FakePlatformMessageResponse::Create(); + + EXPECT_TRUE(pointer_injector_delegate_->HandlePlatformMessage( + PlatformMessageBuilder().SetViewId(view_id).Build(), response)); + + response->ExpectCompleted("[0]"); + } + } + + // The mock Pointerinjector registry server receives |num_events| pointer + // events from |f.u.p.Device.Inject| calls for each view. + RunLoopUntil( + [this] { return registry_->num_events_received() == 2 * num_events; }); + + // The mock Pointerinjector registry server receives a + // |f.u.p.Registry.Register| call for each view. + EXPECT_TRUE(registry_->num_register_calls() == 2); +} + +TEST_P(PointerInjectorDelegateTest, + ViewsDontReceivePointerEventsBeforeCreation) { + const uint64_t num_events = 150; + const uint64_t view_id_1 = 1; + + // Inject |num_events| platform messages for |view_id_1|. + { + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ASSERT_EQ(status, ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + + for (size_t i = 0; i < num_events; i++) { + auto response = FakePlatformMessageResponse::Create(); + + // The platform message is *silently* accepted for non-existent views, in + // order to cleanly handle the lifecycle case where the child view is + // forcibly killed. By doing so, products avoid "MissingPluginException" + // log spam. + EXPECT_TRUE(pointer_injector_delegate_->HandlePlatformMessage( + PlatformMessageBuilder().SetViewId(view_id_1).Build(), response)); + } + } + + const uint64_t view_id_2 = 2; + + // Inject |num_events| platform messages for |view_id_2|. + { + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ASSERT_EQ(status, ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + + for (size_t i = 0; i < num_events; i++) { + auto response = FakePlatformMessageResponse::Create(); + + // The platform message is *silently* accepted for non-existent views, in + // order to cleanly handle the lifecycle case where the child view is + // forcibly killed. By doing so, products avoid "MissingPluginException" + // log spam. + EXPECT_TRUE(pointer_injector_delegate_->HandlePlatformMessage( + PlatformMessageBuilder().SetViewId(view_id_2).Build(), response)); + } + } + + RunLoopUntilIdle(); + + // The views do not receive any pointer events till they get created. + EXPECT_TRUE(registry_->num_events_received() == 0); +} + +// PointerInjectorDelegate should generate a correct |f.u.p.Config| from a +// platform message. +TEST_P(PointerInjectorDelegateTest, ValidRegistrationConfigTest) { + const uint64_t view_id = 1; + + const float x = 2.f, y = 2.f, width = 5.f, height = 5.f; + const int phase = 2, pointer_id = 5, trace_flow_id = 5, timestamp = 10; + + auto response = FakePlatformMessageResponse::Create(); + + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ZX_ASSERT(status == ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + + // Create the view. + fuv_ViewRef view_ref_clone; + fidl::Clone(view_ref, &view_ref_clone); + CreateView(view_id, std::move(view_ref_clone)); + + // Inject a platform message. + EXPECT_TRUE(pointer_injector_delegate_->HandlePlatformMessage( + PlatformMessageBuilder() + .SetViewId(view_id) + .SetPointerX(x) + .SetPointerY(y) + .SetPhase(phase) + .SetPointerId(pointer_id) + .SetTraceFlowId(trace_flow_id) + .SetLogicalWidth(width) + .SetLogicalHeight(height) + .SetTimestamp(timestamp) + .Build(), + response)); + + response->ExpectCompleted("[0]"); + + // The mock Pointerinjector registry server receives a pointer event from + // |f.u.p.Device.Inject| call for the view. + RunLoopUntil([this] { return registry_->num_events_received() == 1; }); + + // The mock Pointerinjector registry server receives a + // |f.u.p.Registry.Register| call for the view. + ASSERT_TRUE(registry_->num_register_calls() == 1); + + const auto& config = registry_->config(); + + ASSERT_TRUE(config.has_device_id()); + EXPECT_EQ(config.device_id(), 1u); + + ASSERT_TRUE(config.has_device_type()); + EXPECT_EQ(config.device_type(), fup_DeviceType::TOUCH); + + ASSERT_TRUE(config.has_dispatch_policy()); + EXPECT_EQ(config.dispatch_policy(), fup_DispatchPolicy::EXCLUSIVE_TARGET); + + ASSERT_TRUE(config.has_context()); + ASSERT_TRUE(config.context().is_view()); + EXPECT_EQ(ExtractKoid(config.context().view()), ExtractKoid(host_view_ref_)); + + ASSERT_TRUE(config.has_target()); + ASSERT_TRUE(config.target().is_view()); + EXPECT_EQ(ExtractKoid(config.target().view()), ExtractKoid(view_ref)); + + ASSERT_TRUE(config.has_viewport()); + ASSERT_TRUE(config.viewport().has_viewport_to_context_transform()); + EXPECT_EQ(config.viewport().viewport_to_context_transform(), kIdentityMatrix); + + std::array, 2> extents{{{0, 0}, {width, height}}}; + ASSERT_TRUE(config.viewport().has_extents()); + EXPECT_EQ(config.viewport().extents(), extents); +} + +// PointerInjectorDelegate generates a correct f.u.p.Event from the platform +// message. +TEST_P(PointerInjectorDelegateTest, ValidPointerEventTest) { + const uint64_t view_id = 1; + + const float x = 2.f, y = 2.f, width = 5.f, height = 5.f; + const int phase = 2, pointer_id = 5, trace_flow_id = 5, timestamp = 10; + + auto response = FakePlatformMessageResponse::Create(); + + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ZX_ASSERT(status == ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + + // Create the view. + fuv_ViewRef view_ref_clone; + fidl::Clone(view_ref, &view_ref_clone); + CreateView(view_id, std::move(view_ref_clone)); + + // Inject a platform message. + EXPECT_TRUE(pointer_injector_delegate_->HandlePlatformMessage( + PlatformMessageBuilder() + .SetViewId(view_id) + .SetPointerX(x) + .SetPointerY(y) + .SetPhase(phase) + .SetPointerId(pointer_id) + .SetTraceFlowId(trace_flow_id) + .SetLogicalWidth(width) + .SetLogicalHeight(height) + .SetTimestamp(timestamp) + .Build(), + response)); + + response->ExpectCompleted("[0]"); + + // The mock Pointerinjector registry server receives a pointer event from + // |f.u.p.Device.Inject| call for the view. + RunLoopUntil([this] { return registry_->num_events_received() == 1; }); + + // The mock Pointerinjector registry server receives a + // |f.u.p.Registry.Register| call for the view. + ASSERT_TRUE(registry_->num_register_calls() == 1); + + const auto& events = registry_->events(); + + ASSERT_EQ(events.size(), 1u); + + const auto& event = events[0]; + + ASSERT_TRUE(event.has_timestamp()); + EXPECT_EQ(event.timestamp(), timestamp); + + ASSERT_TRUE(event.has_trace_flow_id()); + EXPECT_EQ(event.trace_flow_id(), static_cast(trace_flow_id)); + + ASSERT_TRUE(event.has_data()); + ASSERT_TRUE(event.data().is_pointer_sample()); + + const auto& pointer_sample = event.data().pointer_sample(); + + ASSERT_TRUE(pointer_sample.has_pointer_id()); + ASSERT_TRUE(pointer_sample.has_phase()); + ASSERT_TRUE(pointer_sample.has_position_in_viewport()); + EXPECT_EQ(pointer_sample.pointer_id(), static_cast(pointer_id)); + EXPECT_EQ(pointer_sample.phase(), static_cast(phase)); + EXPECT_THAT(pointer_sample.position_in_viewport(), + ::testing::ElementsAre(x, y)); +} + +TEST_P(PointerInjectorDelegateTest, DestroyedViewsDontGetPointerEvents) { + const uint64_t view_id = 1, num_events = 150; + + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ZX_ASSERT(status == ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + + // Create the view. + CreateView(view_id); + + // Inject |num_events| platform messages. + for (size_t i = 0; i < num_events; i++) { + auto response = FakePlatformMessageResponse::Create(); + + EXPECT_TRUE(pointer_injector_delegate_->HandlePlatformMessage( + PlatformMessageBuilder().SetViewId(view_id).Build(), response)); + + response->ExpectCompleted("[0]"); + } + + // Destroy the view. + pointer_injector_delegate_->OnDestroyView(view_id); + + // The view does not receive |num_events| pointer events as it gets destroyed + // before all the pointer events could be dispatched. + const zx::duration timeout = zx::sec(1), step = zx::msec(10); + EXPECT_FALSE(RunLoopWithTimeoutOrUntil( + [this] { return registry_->num_events_received() == num_events; }, + timeout, step)); + + EXPECT_LT(registry_->num_events_received(), num_events); +} + +TEST_P(PointerInjectorDelegateTest, ViewsGetPointerEventsInFIFO) { + const uint64_t view_id = 1, num_events = 150; + + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ZX_ASSERT(status == ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + + // Create the view. + CreateView(view_id); + + // Inject |num_events| platform messages. + for (size_t i = 0; i < num_events; i++) { + auto response = FakePlatformMessageResponse::Create(); + + EXPECT_TRUE(pointer_injector_delegate_->HandlePlatformMessage( + PlatformMessageBuilder() + .SetViewId(view_id) + .SetPointerId(static_cast(i)) + .Build(), + response)); + + response->ExpectCompleted("[0]"); + } + + // The mock Pointerinjector registry server receives |num_events| pointer + // events from |f.u.p.Device.Inject| call for the view. + RunLoopUntil( + [this] { return registry_->num_events_received() == num_events; }); + + // The mock Pointerinjector registry server receives a + // |f.u.p.Registry.Register| call for the view. + ASSERT_TRUE(registry_->num_register_calls() == 1); + + auto& events = registry_->events(); + + // The view should receive the pointer events in a FIFO order. As we injected + // platform messages with an increasing |pointer_id|, the received pointer + // events should also have the |pointer_id| in an increasing order. + for (size_t i = 0; i < events.size() - 1; i++) { + ASSERT_TRUE(events[i].has_data()); + ASSERT_TRUE(events[i + 1].has_data()); + ASSERT_TRUE(events[i].data().is_pointer_sample()); + ASSERT_TRUE(events[i + 1].data().is_pointer_sample()); + + const auto& pointer_sample_1 = events[i].data().pointer_sample(); + const auto& pointer_sample_2 = events[i + 1].data().pointer_sample(); + + ASSERT_TRUE(pointer_sample_1.has_pointer_id()); + ASSERT_TRUE(pointer_sample_2.has_pointer_id()); + + EXPECT_TRUE(pointer_sample_1.pointer_id() < pointer_sample_2.pointer_id()); + } +} + +TEST_P(PointerInjectorDelegateTest, DeviceRetriesRegisterWhenClosed) { + const uint64_t view_id = 1; + const int pointer_id = 1; + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ZX_ASSERT(status == ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + + auto response = FakePlatformMessageResponse::Create(); + auto response_2 = FakePlatformMessageResponse::Create(); + + // Create the view. + fuv_ViewRef view_ref_clone; + fidl::Clone(view_ref, &view_ref_clone); + CreateView(view_id, std::move(view_ref_clone)); + + EXPECT_TRUE(pointer_injector_delegate_->HandlePlatformMessage( + PlatformMessageBuilder() + .SetViewId(view_id) + .SetPointerId(pointer_id) + .Build(), + response)); + + response->ExpectCompleted("[0]"); + + // The mock Pointerinjector registry server receives a pointer event from + // |f.u.p.Device.Inject| call for the view. + RunLoopUntil([this] { return registry_->num_events_received() == 1; }); + + // The mock Pointerinjector registry server receives a + // |f.u.p.Registry.Register| call for the view. + ASSERT_TRUE(registry_->num_register_calls() == 1); + + // Close the device channel. + registry_->ClearBindings(); + RunLoopUntilIdle(); + + EXPECT_TRUE(pointer_injector_delegate_->HandlePlatformMessage( + PlatformMessageBuilder() + .SetViewId(view_id) + .SetPointerId(pointer_id) + .Build(), + response_2)); + + response_2->ExpectCompleted("[0]"); + + // The mock Pointerinjector registry server receives a pointer event from + // |f.u.p.Device.Inject| call for the view. + RunLoopUntil([this] { return registry_->num_events_received() == 2; }); + + // The device tries to register again as the channel got closed. + ASSERT_TRUE(registry_->num_register_calls() == 2); +} + +INSTANTIATE_TEST_SUITE_P(PointerInjectorDelegateParameterizedTest, + PointerInjectorDelegateTest, + ::testing::Bool()); + +} // namespace flutter_runner::testing diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/prebuilt_framework.gni b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/prebuilt_framework.gni new file mode 100644 index 0000000000000000000000000000000000000000..396166d2f310e0477f4c0c0286f028d79b8a8e01 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/prebuilt_framework.gni @@ -0,0 +1,15 @@ +# 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. + +declare_args() { + prebuilt_framework_path = "" + prebuilt_framework_name = "" + framework_packages = [ + "collection", + "flutter", + "meta", + "typed_data", + "vector_math", + ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/program_metadata.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/program_metadata.h new file mode 100644 index 0000000000000000000000000000000000000000..e7117ed46d9a33e84166e6187464c1d235a1506f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/program_metadata.h @@ -0,0 +1,36 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_PROGRAM_METADATA_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_PROGRAM_METADATA_H_ + +#include +#include + +namespace flutter_runner { + +/// The metadata that can be passed by a Flutter component via +/// the `program` field. +struct ProgramMetadata { + /// The path where data for the Flutter component should + /// be stored. + std::string data_path = ""; + + /// The path where assets for the Flutter component should + /// be stored. + /// + /// TODO(fxb/89246): No components appear to be using this field. We + /// may be able to get rid of this. + std::string assets_path = ""; + + /// The preferred heap size for the Flutter component in megabytes. + std::optional old_gen_heap_size = std::nullopt; + + /// A list of additional directories that we will expose in out/ + std::vector expose_dirs; +}; + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_PROGRAM_METADATA_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/rtree.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/rtree.cc new file mode 100644 index 0000000000000000000000000000000000000000..576cb3b6307292f52fe073b6e3b1c793daa054d4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/rtree.cc @@ -0,0 +1,82 @@ +// 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/shell/platform/fuchsia/flutter/rtree.h" + +#include + +#include "flutter/display_list/geometry/dl_region.h" +#include "flutter/fml/logging.h" +#include "third_party/skia/include/core/SkBBHFactory.h" +#include "third_party/skia/include/core/SkRect.h" + +namespace flutter { + +RTree::RTree() : bbh_{SkRTreeFactory{}()}, all_ops_count_(0) {} + +void RTree::insert(const SkRect boundsArray[], + const SkBBoxHierarchy::Metadata metadata[], + int N) { + FML_DCHECK(0 == all_ops_count_); + bbh_->insert(boundsArray, metadata, N); + for (int i = 0; i < N; i++) { + if (metadata != nullptr && metadata[i].isDraw) { + draw_op_[i] = boundsArray[i]; + } + } + all_ops_count_ = N; +} + +void RTree::insert(const SkRect boundsArray[], int N) { + insert(boundsArray, nullptr, N); +} + +void RTree::search(const SkRect& query, std::vector* results) const { + bbh_->search(query, results); +} + +std::list RTree::searchNonOverlappingDrawnRects( + const SkRect& query) const { + // Get the indexes for the operations that intersect with the query rect. + std::vector intermediary_results; + search(query, &intermediary_results); + + std::vector rects; + for (int index : intermediary_results) { + auto draw_op = draw_op_.find(index); + // Ignore records that don't draw anything. + if (draw_op == draw_op_.end()) { + continue; + } + SkIRect current_record_rect; + draw_op->second.roundOut(¤t_record_rect); + rects.push_back(ToDlIRect(current_record_rect)); + } + + DlRegion region(rects); + auto non_overlapping_rects = region.getRects(true); + std::list final_results; + for (const auto& rect : non_overlapping_rects) { + final_results.push_back(SkRect::Make(ToSkIRect(rect))); + } + return final_results; +} + +size_t RTree::bytesUsed() const { + return bbh_->bytesUsed(); +} + +RTreeFactory::RTreeFactory() { + r_tree_ = sk_make_sp(); +} + +sk_sp RTreeFactory::getInstance() { + return r_tree_; +} + +sk_sp RTreeFactory::operator()() const { + return r_tree_; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/rtree.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/rtree.h new file mode 100644 index 0000000000000000000000000000000000000000..ac5334cbdc8f1970ed548bbedac901e6d1218a5c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/rtree.h @@ -0,0 +1,65 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_RTREE_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_RTREE_H_ + +#include +#include + +#include "third_party/skia/include/core/SkBBHFactory.h" +#include "third_party/skia/include/core/SkTypes.h" + +namespace flutter { +/** + * An R-Tree implementation that forwards calls to an SkRTree. + * + * This implementation provides a searchNonOverlappingDrawnRects method, + * which can be used to query the rects for the operations recorded in the tree. + */ +class RTree : public SkBBoxHierarchy { + public: + RTree(); + + void insert(const SkRect[], + const SkBBoxHierarchy::Metadata[], + int N) override; + void insert(const SkRect[], int N) override; + void search(const SkRect& query, std::vector* results) const override; + size_t bytesUsed() const override; + + // Finds the rects in the tree that represent drawing operations and intersect + // with the query rect. + // + // When two rects intersect with each other, they are joined into a single + // rect which also intersects with the query rect. In other words, the bounds + // of each rect in the result list are mutually exclusive. + std::list searchNonOverlappingDrawnRects(const SkRect& query) const; + + // Insertion count (not overall node count, which may be greater). + int getCount() const { return all_ops_count_; } + + private: + // A map containing the draw operation rects keyed off the operation index + // in the insert call. + std::map draw_op_; + sk_sp bbh_; + int all_ops_count_; +}; + +class RTreeFactory : public SkBBHFactory { + public: + RTreeFactory(); + + // Gets the instance to the R-tree. + sk_sp getInstance(); + sk_sp operator()() const override; + + private: + sk_sp r_tree_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_RTREE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/rtree_unittests.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/rtree_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..80bcb35bbb5d667ec093fc3a540876e445bbd8c6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/rtree_unittests.cc @@ -0,0 +1,239 @@ +// 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/shell/platform/fuchsia/flutter/rtree.h" + +#include "flutter/testing/testing.h" +#include "third_party/skia/include/core/SkCanvas.h" +#include "third_party/skia/include/core/SkPicture.h" +#include "third_party/skia/include/core/SkPictureRecorder.h" + +namespace flutter { +namespace testing { + +TEST(RTree, searchNonOverlappingDrawnRectsNoIntersection) { + auto rtree_factory = RTreeFactory(); + auto recorder = std::make_unique(); + auto recording_canvas = + recorder->beginRecording(SkRect::MakeIWH(1000, 1000), &rtree_factory); + + auto rect_paint = SkPaint(); + rect_paint.setColor(SkColors::kCyan); + rect_paint.setStyle(SkPaint::Style::kFill_Style); + + // If no rect is intersected with the query rect, then the result list is + // empty. + recording_canvas->drawRect(SkRect::MakeLTRB(20, 20, 40, 40), rect_paint); + recorder->finishRecordingAsPicture(); + + auto hits = rtree_factory.getInstance()->searchNonOverlappingDrawnRects( + SkRect::MakeLTRB(40, 40, 80, 80)); + ASSERT_TRUE(hits.empty()); +} + +TEST(RTree, searchNonOverlappingDrawnRectsSingleRectIntersection) { + auto rtree_factory = RTreeFactory(); + auto recorder = std::make_unique(); + auto recording_canvas = + recorder->beginRecording(SkRect::MakeIWH(1000, 1000), &rtree_factory); + + auto rect_paint = SkPaint(); + rect_paint.setColor(SkColors::kCyan); + rect_paint.setStyle(SkPaint::Style::kFill_Style); + + // Given a single rect A that intersects with the query rect, + // the result list contains this rect. + recording_canvas->drawRect(SkRect::MakeLTRB(120, 120, 160, 160), rect_paint); + + recorder->finishRecordingAsPicture(); + + auto hits = rtree_factory.getInstance()->searchNonOverlappingDrawnRects( + SkRect::MakeLTRB(140, 140, 150, 150)); + ASSERT_EQ(1UL, hits.size()); + ASSERT_EQ(*hits.begin(), SkRect::MakeLTRB(120, 120, 160, 160)); +} + +TEST(RTree, searchNonOverlappingDrawnRectsIgnoresNonDrawingRecords) { + auto rtree_factory = RTreeFactory(); + auto recorder = std::make_unique(); + auto recording_canvas = + recorder->beginRecording(SkRect::MakeIWH(1000, 1000), &rtree_factory); + + auto rect_paint = SkPaint(); + rect_paint.setColor(SkColors::kCyan); + rect_paint.setStyle(SkPaint::Style::kFill_Style); + + // Creates two non drawing records. + recording_canvas->translate(100, 100); + // The result list should only contain the clipping rect. + recording_canvas->clipRect(SkRect::MakeLTRB(40, 40, 50, 50), + SkClipOp::kIntersect); + recording_canvas->drawRect(SkRect::MakeLTRB(20, 20, 80, 80), rect_paint); + + recorder->finishRecordingAsPicture(); + + // The rtree has a translate, a clip and a rect record. + ASSERT_EQ(3, rtree_factory.getInstance()->getCount()); + + auto hits = rtree_factory.getInstance()->searchNonOverlappingDrawnRects( + SkRect::MakeLTRB(0, 0, 1000, 1000)); + ASSERT_EQ(1UL, hits.size()); + ASSERT_EQ(*hits.begin(), SkRect::MakeLTRB(120, 120, 180, 180)); +} + +TEST(RTree, searchNonOverlappingDrawnRectsMultipleRectIntersection) { + auto rtree_factory = RTreeFactory(); + auto recorder = std::make_unique(); + auto recording_canvas = + recorder->beginRecording(SkRect::MakeIWH(1000, 1000), &rtree_factory); + + auto rect_paint = SkPaint(); + rect_paint.setColor(SkColors::kCyan); + rect_paint.setStyle(SkPaint::Style::kFill_Style); + + // Given the A, B that intersect with the query rect, + // there should be A and B in the result list since + // they don't intersect with each other. + // + // +-----+ +-----+ + // | A | | B | + // +-----+ +-----+ + // A + recording_canvas->drawRect(SkRect::MakeLTRB(100, 100, 200, 200), rect_paint); + // B + recording_canvas->drawRect(SkRect::MakeLTRB(300, 100, 400, 200), rect_paint); + + recorder->finishRecordingAsPicture(); + + auto hits = rtree_factory.getInstance()->searchNonOverlappingDrawnRects( + SkRect::MakeLTRB(0, 0, 1000, 1050)); + ASSERT_EQ(2UL, hits.size()); + ASSERT_EQ(*hits.begin(), SkRect::MakeLTRB(100, 100, 200, 200)); + ASSERT_EQ(*std::next(hits.begin(), 1), SkRect::MakeLTRB(300, 100, 400, 200)); +} + +TEST(RTree, searchNonOverlappingDrawnRectsJoinRectsWhenIntersectedCase1) { + auto rtree_factory = RTreeFactory(); + auto recorder = std::make_unique(); + auto recording_canvas = + recorder->beginRecording(SkRect::MakeIWH(1000, 1000), &rtree_factory); + + auto rect_paint = SkPaint(); + rect_paint.setColor(SkColors::kCyan); + rect_paint.setStyle(SkPaint::Style::kFill_Style); + + // Given the A, and B rects, which intersect with the query rect, + // the result list contains the three rectangles covering same area. + // + // +-----+ +-----+ + // | A | | A | + // | +-----+ +---------+ + // | | | | B | + // +---| B | +---+-----+ + // | | | C | + // +-----+ +-----+ + + // A + recording_canvas->drawRect(SkRect::MakeLTRB(100, 100, 150, 150), rect_paint); + // B + recording_canvas->drawRect(SkRect::MakeLTRB(125, 125, 175, 175), rect_paint); + + recorder->finishRecordingAsPicture(); + + auto hits = rtree_factory.getInstance()->searchNonOverlappingDrawnRects( + SkRect::MakeXYWH(120, 120, 126, 126)); + ASSERT_EQ(3UL, hits.size()); + ASSERT_EQ(*hits.begin(), SkRect::MakeLTRB(100, 100, 150, 125)); + ASSERT_EQ(*std::next(hits.begin(), 1), SkRect::MakeLTRB(100, 125, 175, 150)); + ASSERT_EQ(*std::next(hits.begin(), 2), SkRect::MakeLTRB(125, 150, 175, 175)); +} + +TEST(RTree, searchNonOverlappingDrawnRectsJoinRectsWhenIntersectedCase2) { + auto rtree_factory = RTreeFactory(); + auto recorder = std::make_unique(); + auto recording_canvas = + recorder->beginRecording(SkRect::MakeIWH(1000, 1000), &rtree_factory); + + auto rect_paint = SkPaint(); + rect_paint.setColor(SkColors::kCyan); + rect_paint.setStyle(SkPaint::Style::kFill_Style); + + // Given the A, B, and C rects that intersect with the query rect, + // there should be only C in the result list, + // since A and B are contained in C. + // + // +---------------------+ + // | C | + // | +-----+ +-----+ | + // | | A | | B | | + // | +-----+ +-----+ | + // +---------------------+ + // +-----+ + // | D | + // +-----+ + + // A + recording_canvas->drawRect(SkRect::MakeLTRB(100, 100, 200, 200), rect_paint); + // B + recording_canvas->drawRect(SkRect::MakeLTRB(300, 100, 400, 200), rect_paint); + // C + recording_canvas->drawRect(SkRect::MakeLTRB(50, 50, 500, 250), rect_paint); + // D + recording_canvas->drawRect(SkRect::MakeLTRB(280, 100, 280, 320), rect_paint); + + recorder->finishRecordingAsPicture(); + + auto hits = rtree_factory.getInstance()->searchNonOverlappingDrawnRects( + SkRect::MakeLTRB(30, 30, 550, 270)); + ASSERT_EQ(1UL, hits.size()); + ASSERT_EQ(*hits.begin(), SkRect::MakeLTRB(50, 50, 500, 250)); +} + +TEST(RTree, searchNonOverlappingDrawnRectsJoinRectsWhenIntersectedCase3) { + auto rtree_factory = RTreeFactory(); + auto recorder = std::make_unique(); + auto recording_canvas = + recorder->beginRecording(SkRect::MakeIWH(1000, 1000), &rtree_factory); + + auto rect_paint = SkPaint(); + rect_paint.setColor(SkColors::kCyan); + rect_paint.setStyle(SkPaint::Style::kFill_Style); + + // Given the A, B, C and D rects that intersect with the query rect, + // the result list contains two rects - D and remainder of C + // these four rects. + // + // +------------------------------+ + // | D | + // | +-----+ +-----+ +-----+ | + // | | A | | B | | C | | + // | +-----+ +-----+ | | | + // +----------------------| |-+ + // +-----+ + // +-----+ + // | E | + // +-----+ + + // A + recording_canvas->drawRect(SkRect::MakeLTRB(100, 100, 200, 200), rect_paint); + // B + recording_canvas->drawRect(SkRect::MakeLTRB(300, 100, 400, 200), rect_paint); + // C + recording_canvas->drawRect(SkRect::MakeLTRB(500, 100, 600, 300), rect_paint); + // D + recording_canvas->drawRect(SkRect::MakeLTRB(50, 50, 620, 250), rect_paint); + // E + recording_canvas->drawRect(SkRect::MakeLTRB(280, 100, 280, 320), rect_paint); + + recorder->finishRecordingAsPicture(); + + auto hits = rtree_factory.getInstance()->searchNonOverlappingDrawnRects( + SkRect::MakeLTRB(30, 30, 550, 270)); + ASSERT_EQ(2UL, hits.size()); + ASSERT_EQ(*hits.begin(), SkRect::MakeLTRB(50, 50, 620, 250)); + ASSERT_EQ(*std::next(hits.begin(), 1), SkRect::MakeLTRB(500, 250, 600, 300)); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/runner.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/runner.cc new file mode 100644 index 0000000000000000000000000000000000000000..518e8145402882a34c9b8e70a8b8f1b1e05b46ed --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/runner.cc @@ -0,0 +1,350 @@ +// 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 "runner.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "flutter/fml/make_copyable.h" +#include "flutter/lib/ui/text/font_collection.h" +#include "flutter/runtime/dart_vm.h" +#include "runtime/dart/utils/files.h" +#include "runtime/dart/utils/root_inspect_node.h" +#include "runtime/dart/utils/vmo.h" +#include "runtime/dart/utils/vmservice_object.h" +#include "third_party/icu/source/common/unicode/udata.h" +#include "third_party/skia/include/core/SkGraphics.h" + +namespace flutter_runner { + +namespace { + +static constexpr char kIcuDataPath[] = "/pkg/data/icudtl.dat"; + +// Environment variable containing the path to the directory containing the +// timezone files. +static constexpr char kICUTZEnv[] = "ICU_TIMEZONE_FILES_DIR"; + +// The data directory containing ICU timezone data files. +static constexpr char kICUTZDataDir[] = "/config/data/tzdata/icu/44/le"; + +// Map the memory into the process and return a pointer to the memory. +uintptr_t GetICUData(const fuchsia::mem::Buffer& icu_data) { + uint64_t data_size = icu_data.size; + if (data_size > std::numeric_limits::max()) + return 0u; + + uintptr_t data = 0u; + zx_status_t status = + zx::vmar::root_self()->map(ZX_VM_PERM_READ, 0, icu_data.vmo, 0, + static_cast(data_size), &data); + if (status == ZX_OK) { + return data; + } + + return 0u; +} + +// Initializes the timezone data if available. Timezone data file in Fuchsia +// is at a fixed directory path. Returns true on success. As a side effect +// sets the value of the environment variable "ICU_TIMEZONE_FILES_DIR" to a +// fixed value which is fuchsia-specific. +bool InitializeTZData() { + // We need the ability to change the env variable for testing, so not + // overwriting if set. + setenv(kICUTZEnv, kICUTZDataDir, 0 /* No overwrite */); + + const std::string tzdata_dir = getenv(kICUTZEnv); + // Try opening the path to check if present. No need to verify that it is a + // directory since ICU loading will return an error if the TZ data path is + // wrong. + int fd = openat(AT_FDCWD, tzdata_dir.c_str(), O_RDONLY); + if (fd < 0) { + FML_LOG(INFO) << "Could not open: '" << tzdata_dir + << "', proceeding without loading the timezone database: " + << strerror(errno); + return false; + } + if (close(fd)) { + FML_LOG(WARNING) << "Could not close: " << tzdata_dir << ": " + << strerror(errno); + } + return true; +} + +// Return value indicates if initialization was successful. +bool InitializeICU() { + const char* data_path = kIcuDataPath; + + fuchsia::mem::Buffer icu_data; + if (!dart_utils::VmoFromFilename(data_path, false, &icu_data)) { + return false; + } + + uintptr_t data = GetICUData(icu_data); + if (!data) { + return false; + } + + // If the loading fails, soldier on. The loading is optional as we don't + // want to crash the engine in transition. + InitializeTZData(); + + // Pass the data to ICU. + UErrorCode err = U_ZERO_ERROR; + udata_setCommonData(reinterpret_cast(data), &err); + if (err != U_ZERO_ERROR) { + FML_LOG(ERROR) << "error loading ICU data: " << err; + return false; + } + return true; +} + +} // namespace + +static void SetProcessName() { + std::stringstream stream; +#if defined(DART_PRODUCT) + stream << "io.flutter.product_runner."; +#else + stream << "io.flutter.runner."; +#endif + if (flutter::DartVM::IsRunningPrecompiledCode()) { + stream << "aot"; + } else { + stream << "jit"; + } + const auto name = stream.str(); + zx::process::self()->set_property(ZX_PROP_NAME, name.c_str(), name.size()); +} + +static void SetThreadName(const std::string& thread_name) { + zx::thread::self()->set_property(ZX_PROP_NAME, thread_name.c_str(), + thread_name.size()); +} + +#if !defined(DART_PRODUCT) +// Register native symbol information for the Dart VM's profiler. +static void RegisterProfilerSymbols(const char* symbols_path, + const char* dso_name) { + std::string* symbols = new std::string(); + if (dart_utils::ReadFileToString(symbols_path, symbols)) { + Dart_AddSymbols(dso_name, symbols->data(), symbols->size()); + } else { + FML_LOG(ERROR) << "Failed to load " << symbols_path; + } +} +#endif // !defined(DART_PRODUCT) + +Runner::Runner(fml::RefPtr task_runner, + sys::ComponentContext* context) + : task_runner_(task_runner), context_(context) { +#if !defined(DART_PRODUCT) + // The VM service isolate uses the process-wide namespace. It writes the + // vm service protocol port under /tmp. The VMServiceObject exposes that + // port number to The Hub. + context_->outgoing()->debug_dir()->AddEntry( + dart_utils::VMServiceObject::kPortDirName, + std::make_unique()); + + inspect::Inspector* inspector = dart_utils::RootInspectNode::GetInspector(); + inspector->GetRoot().CreateLazyValues( + "vmservice_port", + [&]() { + inspect::Inspector inspector; + dart_utils::VMServiceObject::LazyEntryVector out; + dart_utils::VMServiceObject().GetContents(&out); + std::string name = ""; + if (!out.empty()) { + name = out[0].name; + } + inspector.GetRoot().CreateString("vm_service_port", name, &inspector); + return fpromise::make_ok_promise(inspector); + }, + inspector); + + SetupTraceObserver(); +#endif // !defined(DART_PRODUCT) + + SkGraphics::Init(); + + SetupICU(); + + SetProcessName(); + + SetThreadName("io.flutter.runner.main"); + + context_->outgoing() + ->AddPublicService( + std::bind(&Runner::RegisterComponentV2, this, std::placeholders::_1)); + +#if !defined(DART_PRODUCT) + if (Dart_IsPrecompiledRuntime()) { + RegisterProfilerSymbols("pkg/data/flutter_aot_runner.dartprofilersymbols", + ""); + } else { + RegisterProfilerSymbols("pkg/data/flutter_jit_runner.dartprofilersymbols", + ""); + } +#endif // !defined(DART_PRODUCT) +} + +Runner::~Runner() { + context_->outgoing() + ->RemovePublicService(); + +#if !defined(DART_PRODUCT) + trace_observer_->Stop(); +#endif // !defined(DART_PRODUCT) +} + +// CF v2 lifecycle methods. + +void Runner::RegisterComponentV2( + fidl::InterfaceRequest + request) { + active_components_v2_bindings_.AddBinding(this, std::move(request)); +} + +void Runner::Start( + fuchsia::component::runner::ComponentStartInfo start_info, + fidl::InterfaceRequest + controller) { + // TRACE_DURATION currently requires that the string data does not change + // in the traced scope. Since |package| gets moved in the ComponentV2::Create + // call below, we cannot ensure that |package.resolved_url| does not move or + // change, so we make a copy to pass to TRACE_DURATION. + // TODO(PT-169): Remove this copy when TRACE_DURATION reads string arguments + // eagerly. + const std::string url_copy = start_info.resolved_url(); + TRACE_EVENT1("flutter", "Start", "url", url_copy.c_str()); + + // Notes on component termination: Components typically terminate on the + // thread on which they were created. This usually means the thread was + // specifically created to host the component. But we want to ensure that + // access to the active components collection is made on the same thread. So + // we capture the runner in the termination callback. There is no risk of + // there being multiple component runner instances in the process at the same + // time. So it is safe to use the raw pointer. + ComponentV2::TerminationCallback termination_callback = + [component_runner = this](const ComponentV2* component) { + component_runner->task_runner_->PostTask( + [component_runner, component]() { + component_runner->OnComponentV2Terminate(component); + }); + }; + + ActiveComponentV2 active_component = ComponentV2::Create( + std::move(termination_callback), std::move(start_info), + context_->svc() /* runner_incoming_services */, std::move(controller)); + + auto key = active_component.component.get(); + active_components_v2_[key] = std::move(active_component); +} + +void Runner::OnComponentV2Terminate(const ComponentV2* component) { + auto active_component_it = active_components_v2_.find(component); + if (active_component_it == active_components_v2_.end()) { + FML_LOG(INFO) + << "The remote end of the component runner tried to terminate an " + "component that has already been terminated, possibly because we " + "initiated the termination"; + return; + } + ActiveComponentV2& active_component = active_component_it->second; + + // Grab the items out of the entry because we will have to rethread the + // destruction. + std::unique_ptr component_to_destroy = + std::move(active_component.component); + std::unique_ptr component_thread = + std::move(active_component.platform_thread); + + // Delete the entry. + active_components_v2_.erase(component); + + // Post the task to destroy the component and quit its message loop. + component_thread->GetTaskRunner()->PostTask(fml::MakeCopyable( + [instance = std::move(component_to_destroy), + thread = component_thread.get()]() mutable { instance.reset(); })); + + // Terminate and join the thread's message loop. + component_thread->Join(); +} + +void Runner::SetupICU() { + // Exposes the TZ data setup for testing. Failing here is not fatal. + Runner::SetupTZDataInternal(); + if (!Runner::SetupICUInternal()) { + FML_LOG(ERROR) << "Could not initialize ICU data."; + } +} + +// static +bool Runner::SetupICUInternal() { + return InitializeICU(); +} + +// static +bool Runner::SetupTZDataInternal() { + return InitializeTZData(); +} + +#if !defined(DART_PRODUCT) +void Runner::SetupTraceObserver() { + fml::AutoResetWaitableEvent latch; + + fml::TaskRunner::RunNowOrPostTask(task_runner_, [&]() { + // Running this initialization code on task_runner_ ensures that the call to + // `async_get_default_dispatcher()` will capture the correct dispatcher. + trace_observer_ = std::make_unique(); + trace_observer_->Start(async_get_default_dispatcher(), [runner = this]() { + if (!trace_is_category_enabled("dart:profiler")) { + return; + } + if (trace_state() == TRACE_STARTED) { + runner->prolonged_context_ = trace_acquire_prolonged_context(); + Dart_StartProfiling(); + } else if (trace_state() == TRACE_STOPPING) { + auto write_profile_trace_for_components = [](auto& components) { + for (auto& it : components) { + fml::AutoResetWaitableEvent latch; + fml::TaskRunner::RunNowOrPostTask( + it.second.platform_thread->GetTaskRunner(), [&]() { + it.second.component->WriteProfileToTrace(); + latch.Signal(); + }); + latch.Wait(); + } + }; + write_profile_trace_for_components(runner->active_components_v2_); + + Dart_StopProfiling(); + trace_release_prolonged_context(runner->prolonged_context_); + } + }); + latch.Signal(); + }); + latch.Wait(); +} +#endif // !defined(DART_PRODUCT) + +void Runner::handle_unknown_method(uint64_t ordinal, bool method_has_response) { + FML_LOG(ERROR) << "Unknown method called on Runner. Ordinal: " << ordinal; +} + +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/runner.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/runner.h new file mode 100644 index 0000000000000000000000000000000000000000..e0f152839372a2b46d9030b95e22b4bc28171941 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/runner.h @@ -0,0 +1,104 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_RUNNER_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_RUNNER_H_ + +#include +#include + +#include +#include +#include +#include +#include + +#include "component_v2.h" +#include "flutter/fml/macros.h" +#include "fml/memory/ref_ptr.h" +#include "fml/task_runner.h" +#include "lib/fidl/cpp/binding_set.h" +#include "runtime/dart/utils/vmservice_object.h" + +namespace flutter_runner { + +/// Publishes the CF v2 runner service. +/// +/// Each component will be run on a separate thread dedicated to that component. +/// +/// TODO(fxb/50694): Add unit tests for CF v2. +class Runner final + : public fuchsia::component::runner::ComponentRunner /* CF v2 */ { + public: + // Does not take ownership of context. + Runner(fml::RefPtr task_runner, + sys::ComponentContext* context); + + ~Runner(); + + void handle_unknown_method(uint64_t ordinal, + bool method_has_response) override; + + private: + // CF v2 lifecycle methods. + + // |fuchsia::component::runner::ComponentRunner| + void Start( + fuchsia::component::runner::ComponentStartInfo start_info, + fidl::InterfaceRequest + controller) override; + + /// Registers a new CF v2 component with this runner, binding the component + /// to this runner. + void RegisterComponentV2( + fidl::InterfaceRequest + request); + + /// Callback that should be fired when a registered CF v2 component is + /// terminated. + void OnComponentV2Terminate(const ComponentV2* component); + + void SetupICU(); + +#if !defined(DART_PRODUCT) + void SetupTraceObserver(); +#endif // !defined(DART_PRODUCT) + + // Called from SetupICU, for testing only. Returns false on error. + static bool SetupICUInternal(); + // Called from SetupICU, for testing only. Returns false on error. + static bool SetupTZDataInternal(); +#if defined(FRIEND_TEST) + FRIEND_TEST(RunnerTZDataTest, LoadsWithTZDataPresent); + FRIEND_TEST(RunnerTZDataTest, LoadsWithoutTZDataPresent); +#endif // defined(FRIEND_TEST) + + fml::RefPtr task_runner_; + + sys::ComponentContext* context_; + + // CF v2 component state. + + /// The components that are currently bound to this runner. + fidl::BindingSet + active_components_v2_bindings_; + + /// The components that are currently actively running on threads. + std::unordered_map + active_components_v2_; + +#if !defined(DART_PRODUCT) + // The connection between the Dart VM service and The Hub. + std::unique_ptr vmservice_object_; + + std::unique_ptr trace_observer_; + trace_prolonged_context_t* prolonged_context_; +#endif // !defined(DART_PRODUCT) + + FML_DISALLOW_COPY_AND_ASSIGN(Runner); +}; + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_RUNNER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/runner_tzdata_missing_unittest.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/runner_tzdata_missing_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..c90239c9170af1e197f7969ae780f33a47a93911 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/runner_tzdata_missing_unittest.cc @@ -0,0 +1,20 @@ +// 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 + +#include "runner.h" +#include "third_party/icu/source/i18n/unicode/timezone.h" + +namespace flutter_runner { + +// This test has not been configured with tzdata files. This test shows that +// even without the data files, the runner continues initialization. It will +// use whatever the base data exists in icudtl.dat. +TEST(RunnerTZDataTest, LoadsWithoutTZDataPresent) { + bool success = Runner::SetupICUInternal(); + ASSERT_TRUE(success) << "failed to load set up ICU data"; +} + +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/runner_tzdata_unittest.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/runner_tzdata_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..d5e3460bae1782b491607b02efdae15565b61bb7 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/runner_tzdata_unittest.cc @@ -0,0 +1,34 @@ +// 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 + +#include + +#include "runner.h" +#include "third_party/icu/source/i18n/unicode/timezone.h" + +namespace flutter_runner { + +TEST(RunnerTZDataTest, LoadsWithTZDataPresent) { + // TODO(fxbug.dev/69570): Move to cml file if env_vars gains supported for the + // gtest_runner. + setenv("ICU_TIMEZONE_FILES_DIR", "/pkg/data/tzdata", true); + + UErrorCode err = U_ZERO_ERROR; + const auto version_before = std::string(icu::TimeZone::getTZDataVersion(err)); + ASSERT_EQ(U_ZERO_ERROR, err) << "unicode error: " << u_errorName(err); + + // This loads the tzdata. In Fuchsia, we force the data from this package + // to be version 2019a, so that we can test the resource load. + bool success = Runner::SetupICUInternal(); + ASSERT_TRUE(success) << "failed to load timezone data"; + + const auto version_after = std::string(icu::TimeZone::getTZDataVersion(err)); + ASSERT_EQ(U_ZERO_ERROR, err) << "unicode error: " << u_errorName(err); + + EXPECT_EQ("2019a", version_after); +} + +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/software_surface.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/software_surface.cc new file mode 100644 index 0000000000000000000000000000000000000000..b4ad703760f54778ed659e5200c6f862775fe61f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/software_surface.cc @@ -0,0 +1,396 @@ +// 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 "software_surface.h" + +#include +#include +#include +#include + +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/trace_event.h" +#include "fuchsia/sysmem/cpp/fidl.h" +#include "include/core/SkImageInfo.h" + +#include "third_party/skia/include/core/SkColorSpace.h" +#include "third_party/skia/include/core/SkImageInfo.h" +#include "third_party/skia/include/core/SkSurface.h" + +#include "../runtime/dart/utils/inlines.h" + +namespace flutter_runner { + +namespace { + +constexpr SkColorType kSkiaColorType = kRGBA_8888_SkColorType; + +uint32_t BytesPerRow(const fuchsia::sysmem2::SingleBufferSettings& settings, + uint32_t bytes_per_pixel, + uint32_t image_width) { + const uint32_t bytes_per_row_divisor = + settings.image_format_constraints().bytes_per_row_divisor(); + const uint32_t min_bytes_per_row = + settings.image_format_constraints().min_bytes_per_row(); + const uint32_t unrounded_bytes_per_row = + std::max(image_width * bytes_per_pixel, min_bytes_per_row); + const uint32_t roundup_bytes = + unrounded_bytes_per_row % bytes_per_row_divisor; + + return unrounded_bytes_per_row + roundup_bytes; +} + +} // namespace + +SoftwareSurface::SoftwareSurface( + fuchsia::sysmem2::AllocatorSyncPtr& sysmem_allocator, + fuchsia::ui::composition::AllocatorPtr& flatland_allocator, + const SkISize& size) + : wait_for_surface_read_finished_(this) { + FML_CHECK(flatland_allocator.is_bound()); + + if (!SetupSkiaSurface(sysmem_allocator, flatland_allocator, size)) { + FML_LOG(ERROR) << "Could not create render surface."; + return; + } + + if (!CreateFences()) { + FML_LOG(ERROR) << "Could not create signal fences."; + return; + } + + wait_for_surface_read_finished_.set_object(release_event_.get()); + wait_for_surface_read_finished_.set_trigger(ZX_EVENT_SIGNALED); + Reset(); + + valid_ = true; +} + +SoftwareSurface::~SoftwareSurface() { + release_image_callback_(); + wait_for_surface_read_finished_.Cancel(); + wait_for_surface_read_finished_.set_object(ZX_HANDLE_INVALID); +} + +bool SoftwareSurface::IsValid() const { + return valid_; +} + +SkISize SoftwareSurface::GetSize() const { + if (!valid_) { + return SkISize::Make(0, 0); + } + + return SkISize::Make(sk_surface_->width(), sk_surface_->height()); +} + +bool SoftwareSurface::CreateFences() { + if (zx::event::create(0, &acquire_event_) != ZX_OK) { + FML_LOG(ERROR) << "Failed to create acquire event."; + return false; + } + + if (zx::event::create(0, &release_event_) != ZX_OK) { + FML_LOG(ERROR) << "Failed to create release event."; + return false; + } + + return true; +} + +bool SoftwareSurface::SetupSkiaSurface( + fuchsia::sysmem2::AllocatorSyncPtr& sysmem_allocator, + fuchsia::ui::composition::AllocatorPtr& flatland_allocator, + const SkISize& size) { + if (size.isEmpty()) { + FML_LOG(ERROR) << "Failed to allocate surface, size is empty."; + return false; + } + + // Allocate a "local" sysmem token to represent flutter's handle to the + // sysmem buffer. + fuchsia::sysmem2::BufferCollectionTokenSyncPtr local_token; + zx_status_t allocate_status = sysmem_allocator->AllocateSharedCollection( + std::move(fuchsia::sysmem2::AllocatorAllocateSharedCollectionRequest{} + .set_token_request(local_token.NewRequest()))); + if (allocate_status != ZX_OK) { + FML_LOG(ERROR) << "Failed to allocate collection: " + << zx_status_get_string(allocate_status); + return false; + } + + // Create a single Duplicate of the token and Sync it; the single duplicate + // token represents scenic's handle to the sysmem buffer. + fuchsia::sysmem2::BufferCollectionToken_DuplicateSync_Result duplicate_result; + zx_status_t duplicate_status = local_token->DuplicateSync( + std::move(fuchsia::sysmem2::BufferCollectionTokenDuplicateSyncRequest{} + .set_rights_attenuation_masks( + std::vector{ZX_RIGHT_SAME_RIGHTS})), + &duplicate_result); + if (duplicate_status != ZX_OK) { + FML_LOG(ERROR) << "Failed to duplicate collection token: " + << zx_status_get_string(duplicate_status); + return false; + } + auto duplicate_tokens = + std::move(*duplicate_result.response().mutable_tokens()); + if (duplicate_tokens.size() != 1u) { + FML_LOG(ERROR) << "Failed to duplicate collection token: Incorrect number " + "of tokens returned."; + return false; + } + auto scenic_token = std::move(duplicate_tokens[0]); + + // Register the sysmem token with flatland. + // + // This binds the sysmem token to a composition token, which is used later + // to associate the rendering surface with a specific flatland Image. + fuchsia::ui::composition::BufferCollectionExportToken export_token; + zx_status_t token_create_status = + zx::eventpair::create(0, &export_token.value, &import_token_.value); + if (token_create_status != ZX_OK) { + FML_LOG(ERROR) << "Failed to create flatland export token: " + << zx_status_get_string(token_create_status); + return false; + } + + fuchsia::ui::composition::RegisterBufferCollectionArgs args; + args.set_export_token(std::move(export_token)); + args.set_buffer_collection_token2(std::move(scenic_token)); + args.set_usage( + fuchsia::ui::composition::RegisterBufferCollectionUsage::DEFAULT); + flatland_allocator->RegisterBufferCollection( + std::move(args), + [](fuchsia::ui::composition::Allocator_RegisterBufferCollection_Result + result) { + if (result.is_err()) { + FML_LOG(ERROR) + << "RegisterBufferCollection call to Scenic Allocator failed."; + } + }); + + // Acquire flutter's local handle to the sysmem buffer. + fuchsia::sysmem2::BufferCollectionSyncPtr buffer_collection; + zx_status_t bind_status = sysmem_allocator->BindSharedCollection(std::move( + fuchsia::sysmem2::AllocatorBindSharedCollectionRequest{} + .set_token(std::move(local_token)) + .set_buffer_collection_request(buffer_collection.NewRequest()))); + if (bind_status != ZX_OK) { + FML_LOG(ERROR) << "Failed to bind collection token: " + << zx_status_get_string(bind_status); + return false; + } + + // Set flutter's constraints on the sysmem buffer. Software rendering only + // requires CPU access to the surface and a basic R8G8B8A8 pixel format. + fuchsia::sysmem2::BufferCollectionConstraints constraints; + constraints.set_min_buffer_count(1); + constraints.mutable_usage()->set_cpu(fuchsia::sysmem2::CPU_USAGE_WRITE | + fuchsia::sysmem2::CPU_USAGE_WRITE_OFTEN); + auto& bmc = *constraints.mutable_buffer_memory_constraints(); + bmc.set_physically_contiguous_required(false); + bmc.set_secure_required(false); + bmc.set_ram_domain_supported(true); + bmc.set_cpu_domain_supported(true); + bmc.set_inaccessible_domain_supported(false); + auto& ifc = constraints.mutable_image_format_constraints()->emplace_back(); + ifc.set_min_size(fuchsia::math::SizeU{static_cast(size.fWidth), + static_cast(size.fHeight)}); + ifc.set_min_bytes_per_row(static_cast(size.fWidth) * 4); + ifc.set_pixel_format(fuchsia::images2::PixelFormat::R8G8B8A8); + ifc.mutable_color_spaces()->emplace_back(fuchsia::images2::ColorSpace::SRGB); + ifc.set_pixel_format_modifier(fuchsia::images2::PixelFormatModifier::LINEAR); + zx_status_t set_constraints_status = buffer_collection->SetConstraints( + std::move(fuchsia::sysmem2::BufferCollectionSetConstraintsRequest{} + .set_constraints(std::move(constraints)))); + if (set_constraints_status != ZX_OK) { + FML_LOG(ERROR) << "Failed to set constraints: " + << zx_status_get_string(set_constraints_status); + return false; + } + + // Wait for sysmem to allocate, now that constraints are set. + fuchsia::sysmem2::BufferCollection_WaitForAllBuffersAllocated_Result + wait_result; + zx_status_t wait_for_allocated_status = + buffer_collection->WaitForAllBuffersAllocated(&wait_result); + if (wait_for_allocated_status != ZX_OK) { + FML_LOG(ERROR) << "Failed to wait for allocate: " + << zx_status_get_string(wait_for_allocated_status); + return false; + } + if (!wait_result.is_response()) { + if (wait_result.is_framework_err()) { + FML_LOG(ERROR) << "Failed to allocate (framework_err): " + << fidl::ToUnderlying(wait_result.framework_err()); + } else { + FML_DCHECK(wait_result.is_err()); + FML_LOG(ERROR) << "Failed to allocate (err): " + << static_cast(wait_result.err()); + } + return false; + } + auto buffer_collection_info = + std::move(*wait_result.response().mutable_buffer_collection_info()); + + // Cache the allocated surface VMO and metadata. + FML_CHECK(buffer_collection_info.settings().buffer_settings().size_bytes() != + 0); + FML_CHECK(buffer_collection_info.buffers()[0].vmo().is_valid()); + surface_vmo_ = + std::move(*buffer_collection_info.mutable_buffers()->at(0).mutable_vmo()); + surface_size_bytes_ = + buffer_collection_info.settings().buffer_settings().size_bytes(); + if (buffer_collection_info.settings().buffer_settings().coherency_domain() == + fuchsia::sysmem2::CoherencyDomain::RAM) { + // RAM coherency domain requires a cache clean when writes are finished. + needs_cache_clean_ = true; + } + + // Map the allocated buffer to the CPU. + uint8_t* vmo_base = nullptr; + zx_status_t buffer_map_status = zx::vmar::root_self()->map( + ZX_VM_PERM_WRITE | ZX_VM_PERM_READ, 0, surface_vmo_, 0, + surface_size_bytes_, reinterpret_cast(&vmo_base)); + if (buffer_map_status != ZX_OK) { + FML_LOG(ERROR) << "Failed to map buffer memory: " + << zx_status_get_string(buffer_map_status); + return false; + } + + // Now that the buffer is CPU-readable, it's safe to discard flutter's + // connection to sysmem. + zx_status_t close_status = buffer_collection->Release(); + if (close_status != ZX_OK) { + FML_LOG(ERROR) << "Failed to close buffer: " + << zx_status_get_string(close_status); + return false; + } + + // Wrap the buffer in a software-rendered Skia surface. + const uint64_t vmo_offset = + buffer_collection_info.buffers()[0].vmo_usable_start(); + const size_t vmo_stride = + BytesPerRow(buffer_collection_info.settings(), 4u, size.width()); + SkSurfaceProps sk_surface_props(0, kUnknown_SkPixelGeometry); + sk_surface_ = SkSurfaces::WrapPixels( + SkImageInfo::Make(size, kSkiaColorType, kPremul_SkAlphaType, + SkColorSpace::MakeSRGB()), + vmo_base + vmo_offset, vmo_stride, &sk_surface_props); + if (!sk_surface_ || sk_surface_->getCanvas() == nullptr) { + FML_LOG(ERROR) << "SkSurfaces::WrapPixels failed."; + return false; + } + + return true; +} + +void SoftwareSurface::SetImageId(uint32_t image_id) { + FML_CHECK(image_id_ == 0); + image_id_ = image_id; +} + +uint32_t SoftwareSurface::GetImageId() { + return image_id_; +} + +sk_sp SoftwareSurface::GetSkiaSurface() const { + return valid_ ? sk_surface_ : nullptr; +} + +fuchsia::ui::composition::BufferCollectionImportToken +SoftwareSurface::GetBufferCollectionImportToken() { + fuchsia::ui::composition::BufferCollectionImportToken import_dup; + import_token_.value.duplicate(ZX_RIGHT_SAME_RIGHTS, &import_dup.value); + return import_dup; +} + +zx::event SoftwareSurface::GetAcquireFence() { + zx::event fence; + acquire_event_.duplicate(ZX_RIGHT_SAME_RIGHTS, &fence); + return fence; +} + +zx::event SoftwareSurface::GetReleaseFence() { + zx::event fence; + release_event_.duplicate(ZX_RIGHT_SAME_RIGHTS, &fence); + return fence; +} +void SoftwareSurface::SetReleaseImageCallback( + ReleaseImageCallback release_image_callback) { + release_image_callback_ = release_image_callback; +} + +size_t SoftwareSurface::AdvanceAndGetAge() { + return ++age_; +} + +bool SoftwareSurface::FlushSessionAcquireAndReleaseEvents() { + age_ = 0; + return true; +} + +void SoftwareSurface::SignalWritesFinished( + const std::function& on_surface_read_finished) { + FML_CHECK(on_surface_read_finished); + + if (!valid_) { + on_surface_read_finished(); + return; + } + + FML_CHECK(surface_read_finished_callback_ == nullptr) + << "Attempted to signal a write on the surface when the " + "previous write has not yet been acknowledged by the " + "compositor."; + surface_read_finished_callback_ = on_surface_read_finished; + + // Sysmem *may* require the cache to be cleared after writes to the surface + // are complete. + if (needs_cache_clean_) { + surface_vmo_.op_range(ZX_VMO_OP_CACHE_CLEAN, 0, surface_size_bytes_, + /*buffer*/ nullptr, + /*buffer_size*/ 0); + } + + // Inform scenic that flutter is finished writing to the surface. + zx_status_t signal_status = acquire_event_.signal(0u, ZX_EVENT_SIGNALED); + if (signal_status != ZX_OK) { + FML_LOG(ERROR) << "Failed to signal acquire event; " + << zx_status_get_string(signal_status); + } +} + +void SoftwareSurface::Reset() { + if (acquire_event_.signal(ZX_EVENT_SIGNALED, 0u) != ZX_OK || + release_event_.signal(ZX_EVENT_SIGNALED, 0u) != ZX_OK) { + valid_ = false; + FML_LOG(ERROR) << "Could not reset fences. The surface is no longer valid."; + } + + wait_for_surface_read_finished_.Begin(async_get_default_dispatcher()); + + // It is safe for the caller to collect the surface in the callback. + auto callback = surface_read_finished_callback_; + surface_read_finished_callback_ = nullptr; + if (callback) { + callback(); + } +} + +void SoftwareSurface::OnSurfaceReadFinished(async_dispatcher_t* dispatcher, + async::WaitBase* wait, + zx_status_t status, + const zx_packet_signal_t* signal) { + if (status != ZX_OK) { + return; + } + FML_DCHECK(signal->observed & ZX_EVENT_SIGNALED); + + Reset(); +} + +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/software_surface.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/software_surface.h new file mode 100644 index 0000000000000000000000000000000000000000..e42cdfc1de99d09c658655e0d384ca1e0444e7c0 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/software_surface.h @@ -0,0 +1,122 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_SOFTWARE_SURFACE_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_SOFTWARE_SURFACE_H_ + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "flutter/fml/macros.h" +#include "third_party/skia/include/core/SkSize.h" +#include "third_party/skia/include/core/SkSurface.h" + +#include "surface_producer.h" + +namespace flutter_runner { + +class SoftwareSurface final : public SurfaceProducerSurface { + public: + SoftwareSurface(fuchsia::sysmem2::AllocatorSyncPtr& sysmem_allocator, + fuchsia::ui::composition::AllocatorPtr& flatland_allocator, + const SkISize& size); + + ~SoftwareSurface() override; + + size_t GetAllocationSize() const { return surface_size_bytes_; } + + // |SurfaceProducerSurface| + size_t AdvanceAndGetAge() override; + + // |SurfaceProducerSurface| + bool FlushSessionAcquireAndReleaseEvents() override; + + // |SurfaceProducerSurface| + bool IsValid() const override; + + // |SurfaceProducerSurface| + SkISize GetSize() const override; + + // |SurfaceProducerSurface| + void SignalWritesFinished( + const std::function& on_surface_read_finished) override; + + // |SurfaceProducerSurface| + void SetImageId(uint32_t image_id) override; + + // |SurfaceProducerSurface| + uint32_t GetImageId() override; + + // |SurfaceProducerSurface| + sk_sp GetSkiaSurface() const override; + + // |SurfaceProducerSurface| + fuchsia::ui::composition::BufferCollectionImportToken + GetBufferCollectionImportToken() override; + + // |SurfaceProducerSurface| + zx::event GetAcquireFence() override; + + // |SurfaceProducerSurface| + zx::event GetReleaseFence() override; + + // |SurfaceProducerSurface| + void SetReleaseImageCallback( + ReleaseImageCallback release_image_callback) override; + + private: + void OnSurfaceReadFinished(async_dispatcher_t* dispatcher, + async::WaitBase* wait, + zx_status_t status, + const zx_packet_signal_t* signal); + + bool SetupSkiaSurface( + fuchsia::sysmem2::AllocatorSyncPtr& sysmem_allocator, + fuchsia::ui::composition::AllocatorPtr& flatland_allocator, + const SkISize& size); + + bool CreateFences(); + + void Reset(); + uint32_t image_id_ = 0; + + sk_sp sk_surface_; + + // This is associated with `release_event_` and allows detection of when + // scenic has finished reading from the surface (and thus it is safe to re-use + // for writing). + async::WaitMethod + wait_for_surface_read_finished_; + // Called when scenic has finished reading from the surface, to allow + // `SoftwareSurfaceProducer` to re-use the surface. + std::function surface_read_finished_callback_; + // Called when the surface is destroyed, to allow + // `ExternalViewEmbedder` to release the associated Flatland image. + ReleaseImageCallback release_image_callback_; + + // Allows Flatland to associate this surface with a Flatland Image. + fuchsia::ui::composition::BufferCollectionImportToken import_token_; + zx::event acquire_event_; // Signals to scenic that writing is finished. + zx::event release_event_; // Signalled by scenic that reading is finished. + zx::vmo surface_vmo_; // VMO that is backing the surface memory. + + uint32_t surface_size_bytes_; // Size of the surface memory, in bytes. + size_t age_{0}; // Number of frames since surface was last written to. + + bool needs_cache_clean_{false}; + bool valid_{false}; + + FML_DISALLOW_COPY_AND_ASSIGN(SoftwareSurface); +}; + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_SOFTWARE_SURFACE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/software_surface_producer.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/software_surface_producer.cc new file mode 100644 index 0000000000000000000000000000000000000000..10c53ce2da460d5e8a91b3c78bbf246f68474081 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/software_surface_producer.cc @@ -0,0 +1,243 @@ +// 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 "software_surface_producer.h" + +#include +#include + +#include // For std::remove_if +#include +#include +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/trace_event.h" + +namespace flutter_runner { + +namespace { + +std::string GetCurrentProcessName() { + char name[ZX_MAX_NAME_LEN]; + zx_status_t status = + zx::process::self()->get_property(ZX_PROP_NAME, name, sizeof(name)); + if (status != ZX_OK) { + FML_LOG(ERROR) << "Failed to get process name for sysmem; using \"\"."; + return std::string(); + } + + return std::string(name); +} + +zx_koid_t GetCurrentProcessId() { + zx_info_handle_basic_t info; + zx_status_t status = zx::process::self()->get_info( + ZX_INFO_HANDLE_BASIC, &info, sizeof(info), /*actual_count*/ nullptr, + /*avail_count*/ nullptr); + if (status != ZX_OK) { + FML_LOG(ERROR) << "Failed to get process ID for sysmem; using 0."; + return ZX_KOID_INVALID; + } + + return info.koid; +} + +} // namespace + +SoftwareSurfaceProducer::SoftwareSurfaceProducer() { + zx_status_t status = fdio_service_connect( + "/svc/fuchsia.sysmem2.Allocator", + sysmem_allocator_.NewRequest().TakeChannel().release()); + sysmem_allocator_->SetDebugClientInfo( + std::move(fuchsia::sysmem2::AllocatorSetDebugClientInfoRequest{} + .set_name(GetCurrentProcessName()) + .set_id(GetCurrentProcessId()))); + FML_DCHECK(status == ZX_OK); + + status = fdio_service_connect( + "/svc/fuchsia.ui.composition.Allocator", + flatland_allocator_.NewRequest().TakeChannel().release()); + FML_DCHECK(status == ZX_OK); + + valid_ = true; +} + +SoftwareSurfaceProducer::~SoftwareSurfaceProducer() = default; + +std::unique_ptr +SoftwareSurfaceProducer::ProduceOffscreenSurface(const SkISize& size) { + FML_CHECK(valid_); + + return CreateSurface(size); +} + +std::unique_ptr SoftwareSurfaceProducer::ProduceSurface( + const SkISize& size) { + TRACE_EVENT2("flutter", "SoftwareSurfacePool::ProduceSurface", "width", + size.width(), "height", size.height()); + FML_CHECK(valid_); + + std::unique_ptr surface; + auto exact_match_it = + std::find_if(available_surfaces_.begin(), available_surfaces_.end(), + [&size](const auto& surface) { + return surface->IsValid() && surface->GetSize() == size; + }); + if (exact_match_it != available_surfaces_.end()) { + TRACE_EVENT_INSTANT0("flutter", "Exact match found"); + surface = std::move(*exact_match_it); + available_surfaces_.erase(exact_match_it); + } else { + surface = CreateSurface(size); + } + + if (surface == nullptr) { + FML_LOG(ERROR) << "Could not acquire surface."; + return nullptr; + } + + if (!surface->FlushSessionAcquireAndReleaseEvents()) { + FML_LOG(ERROR) << "Could not flush acquire/release events for buffer."; + return nullptr; + } + + return surface; +} + +void SoftwareSurfaceProducer::SubmitSurfaces( + std::vector> surfaces) { + TRACE_EVENT0("flutter", "SoftwareSurfaceProducer::SubmitSurfaces"); + + // Submit surface + for (auto& surface : surfaces) { + SubmitSurface(std::move(surface)); + } + + // Buffer management. + AgeAndCollectOldBuffers(); +} + +void SoftwareSurfaceProducer::SubmitSurface( + std::unique_ptr surface) { + TRACE_EVENT0("flutter", "SoftwareSurfacePool::SubmitSurface"); + FML_CHECK(valid_); + + // This cast is safe because |SoftwareSurface| is the only implementation of + // |SurfaceProducerSurface| for Flutter on Fuchsia. Additionally, it is + // required, because we need to access |SoftwareSurface| specific information + // of the surface (such as the amount of memory it contains). + auto software_surface = std::unique_ptr( + static_cast(surface.release())); + if (!software_surface) { + return; + } + + uintptr_t surface_key = reinterpret_cast(software_surface.get()); + auto insert_iterator = pending_surfaces_.insert(std::make_pair( + surface_key, // key + std::move(software_surface) // value + )); + if (insert_iterator.second) { + insert_iterator.first->second->SignalWritesFinished(std::bind( + &SoftwareSurfaceProducer::RecyclePendingSurface, this, surface_key)); + } +} + +std::unique_ptr SoftwareSurfaceProducer::CreateSurface( + const SkISize& size) { + TRACE_EVENT2("flutter", "SoftwareSurfacePool::CreateSurface", "width", + size.width(), "height", size.height()); + auto surface = std::make_unique(sysmem_allocator_, + flatland_allocator_, size); + if (!surface->IsValid()) { + FML_LOG(ERROR) << "Created surface is invalid."; + return nullptr; + } + trace_surfaces_created_++; + return surface; +} + +void SoftwareSurfaceProducer::RecycleSurface( + std::unique_ptr surface) { + // The surface may have become invalid (for example if the fences could + // not be reset). + if (!surface->IsValid()) { + FML_LOG(ERROR) << "Attempted to recycle invalid surface."; + return; + } + + TRACE_EVENT0("flutter", "SoftwareSurfacePool::RecycleSurface"); + // Recycle the buffer by putting it in the list of available surfaces if we + // have not reached the maximum amount of cached surfaces. + if (available_surfaces_.size() < kMaxSurfaces) { + available_surfaces_.push_back(std::move(surface)); + } else { + TRACE_EVENT_INSTANT0("flutter", "Too many surfaces in pool, dropping"); + } + TraceStats(); +} + +void SoftwareSurfaceProducer::RecyclePendingSurface(uintptr_t surface_key) { + // Before we do anything, we must clear the surface from the collection of + // pending surfaces. + auto found_in_pending = pending_surfaces_.find(surface_key); + if (found_in_pending == pending_surfaces_.end()) { + FML_LOG(ERROR) << "Attempted to recycle a surface that wasn't pending."; + return; + } + + // Grab a hold of the surface to recycle and clear the entry in the pending + // surfaces collection. + auto surface_to_recycle = std::move(found_in_pending->second); + pending_surfaces_.erase(found_in_pending); + + RecycleSurface(std::move(surface_to_recycle)); +} + +void SoftwareSurfaceProducer::AgeAndCollectOldBuffers() { + TRACE_EVENT0("flutter", "SoftwareSurfacePool::AgeAndCollectOldBuffers"); + + // Remove all surfaces that are no longer valid or are too old. + size_t size_before = available_surfaces_.size(); + available_surfaces_.erase( + std::remove_if(available_surfaces_.begin(), available_surfaces_.end(), + [&](auto& surface) { + return !surface->IsValid() || + surface->AdvanceAndGetAge() >= kMaxSurfaceAge; + }), + available_surfaces_.end()); + TRACE_EVENT1("flutter", "AgeAndCollect", "aged surfaces", + (size_before - available_surfaces_.size())); + + TraceStats(); +} + +void SoftwareSurfaceProducer::TraceStats() { + // Resources held in cached buffers. + size_t cached_surfaces_bytes = 0; + for (const auto& surface : available_surfaces_) { + cached_surfaces_bytes += surface->GetAllocationSize(); + } + + TRACE_COUNTER("flutter", "SurfacePoolCounts", 0u, "CachedCount", + available_surfaces_.size(), // + "Created", trace_surfaces_created_, // + "Reused", trace_surfaces_reused_, // + "PendingInCompositor", pending_surfaces_.size(), // + "Retained", 0 // + ); + + TRACE_COUNTER("flutter", "SurfacePoolBytes", 0u, // + "CachedBytes", cached_surfaces_bytes, // + "RetainedBytes", 0 // + ); + + // Reset per present/frame stats. + trace_surfaces_created_ = 0; + trace_surfaces_reused_ = 0; +} + +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/software_surface_producer.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/software_surface_producer.h new file mode 100644 index 0000000000000000000000000000000000000000..bcd478dac93191d0a1eea596c0a73221c31505c2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/software_surface_producer.h @@ -0,0 +1,77 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_SOFTWARE_SURFACE_PRODUCER_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_SOFTWARE_SURFACE_PRODUCER_H_ + +#include +#include + +#include + +#include "flutter/fml/macros.h" + +#include "software_surface.h" + +namespace flutter_runner { + +class SoftwareSurfaceProducer final : public SurfaceProducer { + public: + // Only keep 12 surfaces at a time. + static constexpr int kMaxSurfaces = 12; + // If a surface doesn't get used for 3 or more generations, we discard it. + static constexpr int kMaxSurfaceAge = 3; + + explicit SoftwareSurfaceProducer(); + ~SoftwareSurfaceProducer() override; + + bool IsValid() const { return valid_; } + + // |SurfaceProducer| + GrDirectContext* gr_context() const override { return nullptr; } + + // |SurfaceProducer| + std::unique_ptr ProduceOffscreenSurface( + const SkISize& size) override; + + // |SurfaceProducer| + std::unique_ptr ProduceSurface( + const SkISize& size) override; + + // |SurfaceProducer| + void SubmitSurfaces( + std::vector> surfaces) override; + + private: + void SubmitSurface(std::unique_ptr surface); + std::unique_ptr CreateSurface(const SkISize& size); + void RecycleSurface(std::unique_ptr surface); + + void RecyclePendingSurface(uintptr_t surface_key); + + void AgeAndCollectOldBuffers(); + + void TraceStats(); + + fuchsia::sysmem2::AllocatorSyncPtr sysmem_allocator_; + fuchsia::ui::composition::AllocatorPtr flatland_allocator_; + + // These surfaces are available for re-use. + std::vector> available_surfaces_; + // These surfaces have been written to, but scenic is not finished reading + // from them yet. + std::unordered_map> + pending_surfaces_; + + size_t trace_surfaces_created_ = 0; + size_t trace_surfaces_reused_ = 0; + + bool valid_ = false; + + FML_DISALLOW_COPY_AND_ASSIGN(SoftwareSurfaceProducer); +}; + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_SOFTWARE_SURFACE_PRODUCER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/surface.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/surface.cc new file mode 100644 index 0000000000000000000000000000000000000000..29381ccfef392394ec52b78e52749dd006f406db --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/surface.cc @@ -0,0 +1,56 @@ +// 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 "surface.h" + +#include +#include +#include +#include + +#include "flutter/fml/unique_fd.h" + +namespace flutter_runner { + +Surface::Surface(std::string debug_label, + std::shared_ptr view_embedder, + GrDirectContext* gr_context) + : debug_label_(std::move(debug_label)), + view_embedder_(view_embedder), + gr_context_(gr_context) {} + +Surface::~Surface() = default; + +// |flutter::Surface| +bool Surface::IsValid() { + return true; +} + +// |flutter::Surface| +std::unique_ptr Surface::AcquireFrame( + const SkISize& size) { + flutter::SurfaceFrame::FramebufferInfo framebuffer_info; + framebuffer_info.supports_readback = true; + return std::make_unique( + nullptr, std::move(framebuffer_info), + [](const flutter::SurfaceFrame& surface_frame, + flutter::DlCanvas* canvas) { return true; }, + [](const flutter::SurfaceFrame& surface_frame) { return true; }, size); +} + +// |flutter::Surface| +GrDirectContext* Surface::GetContext() { + return gr_context_; +} + +// |flutter::Surface| +SkMatrix Surface::GetRootTransformation() const { + // This backend does not support delegating to the underlying platform to + // query for root surface transformations. Just return identity. + SkMatrix matrix; + matrix.reset(); + return matrix; +} + +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/surface.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/surface.h new file mode 100644 index 0000000000000000000000000000000000000000..36dffb417c8a1d13b1bb5cd34a6a7615dd7e76e8 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/surface.h @@ -0,0 +1,48 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_SURFACE_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_SURFACE_H_ + +#include "flutter/flow/surface.h" +#include "flutter/fml/macros.h" +#include "flutter/fml/memory/weak_ptr.h" + +namespace flutter_runner { + +// The interface between the Flutter rasterizer and the underlying platform. May +// be constructed on any thread but will be used by the engine only on the +// raster thread. +class Surface final : public flutter::Surface { + public: + Surface(std::string debug_label, + std::shared_ptr view_embedder, + GrDirectContext* gr_context); + + ~Surface() override; + + private: + const std::string debug_label_; + std::shared_ptr view_embedder_; + GrDirectContext* gr_context_; + + // |flutter::Surface| + bool IsValid() override; + + // |flutter::Surface| + std::unique_ptr AcquireFrame( + const SkISize& size) override; + + // |flutter::Surface| + GrDirectContext* GetContext() override; + + // |flutter::Surface| + SkMatrix GetRootTransformation() const override; + + FML_DISALLOW_COPY_AND_ASSIGN(Surface); +}; + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_SURFACE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/surface_producer.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/surface_producer.h new file mode 100644 index 0000000000000000000000000000000000000000..1ff9e7f711b8cf00b2d20d10cc2ceeb65c5c8a86 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/surface_producer.h @@ -0,0 +1,84 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_SURFACE_PRODUCER_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_SURFACE_PRODUCER_H_ + +#include +#include +#include + +#include +#include +#include + +#include "third_party/skia/include/core/SkSize.h" +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/include/gpu/ganesh/GrDirectContext.h" + +namespace flutter_runner { + +using ReleaseImageCallback = std::function; + +// This represents an abstract notion of a "rendering surface", which is a +// destination for pixels drawn by some rendering engine. In this case, the +// rendering engine is Skia combined with one of its rendering backends. +// +// In addition to allowing Skia-based drawing via `GetSkiaSurface`, this +// rendering surface can be shared with Scenic via `SetImageId`, +// `GetBufferCollectionImportToken`, `GetAcquireFene`, and `GetReleaseFence`. +class SurfaceProducerSurface { + public: + virtual ~SurfaceProducerSurface() = default; + + virtual bool IsValid() const = 0; + + virtual SkISize GetSize() const = 0; + + virtual void SetImageId(uint32_t image_id) = 0; + + virtual uint32_t GetImageId() = 0; + + virtual sk_sp GetSkiaSurface() const = 0; + + virtual fuchsia::ui::composition::BufferCollectionImportToken + GetBufferCollectionImportToken() = 0; + + virtual zx::event GetAcquireFence() = 0; + + virtual zx::event GetReleaseFence() = 0; + + virtual void SetReleaseImageCallback( + ReleaseImageCallback release_image_callback) = 0; + + virtual size_t AdvanceAndGetAge() = 0; + + virtual bool FlushSessionAcquireAndReleaseEvents() = 0; + + virtual void SignalWritesFinished( + const std::function& on_writes_committed) = 0; +}; + +// This represents an abstract notion of "surface producer", which serves as a +// source for `SurfaceProducerSurface`s. Produces surfaces should be returned +// to this `SurfaceProducer` via `SubmitSurfaces`, at which point they will be +// shared with Scenic. +class SurfaceProducer { + public: + virtual ~SurfaceProducer() = default; + + virtual GrDirectContext* gr_context() const = 0; + + virtual std::unique_ptr ProduceOffscreenSurface( + const SkISize& size) = 0; + virtual std::unique_ptr ProduceSurface( + const SkISize& size) = 0; + + virtual void SubmitSurfaces( + std::vector> surfaces) = 0; +}; + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_SURFACE_PRODUCER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/task_runner_adapter.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/task_runner_adapter.cc new file mode 100644 index 0000000000000000000000000000000000000000..e75cc16e3914e2b611267561c11ad9d6a1b5d2cd --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/task_runner_adapter.cc @@ -0,0 +1,56 @@ +// 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 "task_runner_adapter.h" + +#include +#include +#include + +#include "flutter/fml/message_loop_impl.h" + +namespace flutter_runner { + +class CompatTaskRunner : public fml::TaskRunner { + public: + CompatTaskRunner(async_dispatcher_t* dispatcher) + : fml::TaskRunner(nullptr), forwarding_target_(dispatcher) { + FML_DCHECK(forwarding_target_); + } + + void PostTask(const fml::closure& task) override { + async::PostTask(forwarding_target_, task); + } + + void PostTaskForTime(const fml::closure& task, + fml::TimePoint target_time) override { + async::PostTaskForTime( + forwarding_target_, task, + zx::time(target_time.ToEpochDelta().ToNanoseconds())); + } + + void PostDelayedTask(const fml::closure& task, + fml::TimeDelta delay) override { + async::PostDelayedTask(forwarding_target_, task, + zx::duration(delay.ToNanoseconds())); + } + + bool RunsTasksOnCurrentThread() override { + return forwarding_target_ == async_get_default_dispatcher(); + } + + private: + async_dispatcher_t* forwarding_target_; + + FML_DISALLOW_COPY_AND_ASSIGN(CompatTaskRunner); + FML_FRIEND_MAKE_REF_COUNTED(CompatTaskRunner); + FML_FRIEND_REF_COUNTED_THREAD_SAFE(CompatTaskRunner); +}; + +fml::RefPtr CreateFMLTaskRunner( + async_dispatcher_t* dispatcher) { + return fml::MakeRefCounted(dispatcher); +} + +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/task_runner_adapter.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/task_runner_adapter.h new file mode 100644 index 0000000000000000000000000000000000000000..dbba873e0c3f44b2320de4439420892bc15c64d3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/task_runner_adapter.h @@ -0,0 +1,19 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_TASK_RUNNER_ADAPTER_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TASK_RUNNER_ADAPTER_H_ + +#include + +#include "flutter/fml/task_runner.h" + +namespace flutter_runner { + +fml::RefPtr CreateFMLTaskRunner( + async_dispatcher_t* dispatcher); + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TASK_RUNNER_ADAPTER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/engine_unittests.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/engine_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..9ae5a2b297c4a1d5b1e152c85251b67a0b242991 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/engine_unittests.cc @@ -0,0 +1,59 @@ +// Copyright 2020 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/shell/platform/fuchsia/flutter/engine.h" + +#include "flutter/shell/common/thread_host.h" + +#include "gtest/gtest.h" + +using namespace flutter; + +namespace flutter_runner { +namespace testing { +namespace { + +std::string GetCurrentTestName() { + return ::testing::UnitTest::GetInstance()->current_test_info()->name(); +} + +} // namespace + +TEST(EngineTest, ThreadNames) { + std::string prefix = GetCurrentTestName(); + flutter::ThreadHost engine_thread_host = Engine::CreateThreadHost(prefix); + + char thread_name[ZX_MAX_NAME_LEN]; + zx::thread::self()->get_property(ZX_PROP_NAME, thread_name, + sizeof(thread_name)); + EXPECT_EQ(std::string(thread_name), prefix + std::string(".platform")); + EXPECT_EQ(engine_thread_host.platform_thread, nullptr); + + engine_thread_host.raster_thread->GetTaskRunner()->PostTask([&prefix]() { + char thread_name[ZX_MAX_NAME_LEN]; + zx::thread::self()->get_property(ZX_PROP_NAME, thread_name, + sizeof(thread_name)); + EXPECT_EQ(std::string(thread_name), prefix + std::string(".raster")); + }); + engine_thread_host.raster_thread->Join(); + + engine_thread_host.ui_thread->GetTaskRunner()->PostTask([&prefix]() { + char thread_name[ZX_MAX_NAME_LEN]; + zx::thread::self()->get_property(ZX_PROP_NAME, thread_name, + sizeof(thread_name)); + EXPECT_EQ(std::string(thread_name), prefix + std::string(".ui")); + }); + engine_thread_host.ui_thread->Join(); + + engine_thread_host.io_thread->GetTaskRunner()->PostTask([&prefix]() { + char thread_name[ZX_MAX_NAME_LEN]; + zx::thread::self()->get_property(ZX_PROP_NAME, thread_name, + sizeof(thread_name)); + EXPECT_EQ(std::string(thread_name), prefix + std::string(".io")); + }); + engine_thread_host.io_thread->Join(); +} + +} // namespace testing +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/external_view_embedder_unittests.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/external_view_embedder_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..158d23697e62ccbcab7e36ae6fca31e4827d3c55 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/external_view_embedder_unittests.cc @@ -0,0 +1,1676 @@ +// 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/shell/platform/fuchsia/flutter/external_view_embedder.h" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "flutter/flow/embedded_views.h" +#include "flutter/fml/logging.h" +#include "flutter/fml/time/time_delta.h" +#include "flutter/fml/time/time_point.h" +#include "third_party/skia/include/core/SkColor.h" +#include "third_party/skia/include/core/SkSize.h" +#include "third_party/skia/include/core/SkSurface.h" + +#include "fakes/scenic/fake_flatland.h" +#include "fakes/scenic/fake_flatland_types.h" +#include "flutter/shell/platform/fuchsia/flutter/surface_producer.h" + +#include "gmock/gmock.h" // For EXPECT_THAT and matchers +#include "gtest/gtest.h" + +using flutter::DlColor; +using flutter::DlMatrix; +using flutter::DlRect; +using flutter::DlSize; +using fuchsia::scenic::scheduling::FramePresentedInfo; +using fuchsia::scenic::scheduling::FuturePresentationTimes; +using fuchsia::scenic::scheduling::PresentReceivedInfo; +using ::testing::_; +using ::testing::AllOf; +using ::testing::Contains; +using ::testing::ElementsAre; +using ::testing::Eq; +using ::testing::Field; +using ::testing::FieldsAre; +using ::testing::IsEmpty; +using ::testing::Matcher; +using ::testing::Pointee; +using ::testing::Property; +using ::testing::SizeIs; +using ::testing::VariantWith; + +namespace flutter_runner::testing { +namespace { + +constexpr static fuchsia::ui::composition::BlendMode kFirstLayerBlendMode{ + fuchsia::ui::composition::BlendMode::SRC}; +constexpr static fuchsia::ui::composition::BlendMode kUpperLayerBlendMode{ + fuchsia::ui::composition::BlendMode::SRC_OVER}; +constexpr static int64_t kImplicitViewId = 0; + +class FakeSurfaceProducerSurface : public SurfaceProducerSurface { + public: + explicit FakeSurfaceProducerSurface( + fidl::InterfaceRequest + sysmem_token_request, + fuchsia::ui::composition::BufferCollectionImportToken buffer_import_token, + const SkISize& size) + : sysmem_token_request_(std::move(sysmem_token_request)), + buffer_import_token_(std::move(buffer_import_token)), + surface_(SkSurfaces::Null(size.width(), size.height())) { + zx_status_t acquire_status = zx::event::create(0, &acquire_fence_); + if (acquire_status != ZX_OK) { + FML_LOG(ERROR) + << "FakeSurfaceProducerSurface: Failed to create acquire event"; + } + zx_status_t release_status = zx::event::create(0, &release_fence_); + if (release_status != ZX_OK) { + FML_LOG(ERROR) + << "FakeSurfaceProducerSurface: Failed to create release event"; + } + } + ~FakeSurfaceProducerSurface() override {} + + bool IsValid() const override { return true; } + + SkISize GetSize() const override { + return SkISize::Make(surface_->width(), surface_->height()); + } + + void SetImageId(uint32_t image_id) override { image_id_ = image_id; } + uint32_t GetImageId() override { return image_id_; } + + sk_sp GetSkiaSurface() const override { return surface_; } + + fuchsia::ui::composition::BufferCollectionImportToken + GetBufferCollectionImportToken() override { + return std::move(buffer_import_token_); + } + + zx::event GetAcquireFence() override { + zx::event fence; + acquire_fence_.duplicate(ZX_RIGHT_SAME_RIGHTS, &fence); + return fence; + } + + zx::event GetReleaseFence() override { + zx::event fence; + release_fence_.duplicate(ZX_RIGHT_SAME_RIGHTS, &fence); + return fence; + } + + void SetReleaseImageCallback( + ReleaseImageCallback release_image_callback) override {} + + size_t AdvanceAndGetAge() override { return 0; } + bool FlushSessionAcquireAndReleaseEvents() override { return true; } + void SignalWritesFinished( + const std::function& on_writes_committed) override {} + + private: + fidl::InterfaceRequest + sysmem_token_request_; + fuchsia::ui::composition::BufferCollectionImportToken buffer_import_token_; + zx::event acquire_fence_; + zx::event release_fence_; + + sk_sp surface_; + uint32_t image_id_{0}; +}; + +class FakeSurfaceProducer : public SurfaceProducer { + public: + explicit FakeSurfaceProducer( + fuchsia::ui::composition::AllocatorHandle flatland_allocator) + : flatland_allocator_(flatland_allocator.Bind()) {} + ~FakeSurfaceProducer() override = default; + + // |SurfaceProducer| + GrDirectContext* gr_context() const override { return nullptr; } + + // |SurfaceProducer| + std::unique_ptr ProduceOffscreenSurface( + const SkISize& size) override { + return nullptr; + } + + // |SurfaceProducer| + std::unique_ptr ProduceSurface( + const SkISize& size) override { + auto [buffer_export_token, buffer_import_token] = + BufferCollectionTokenPair::New(); + fuchsia::sysmem2::BufferCollectionTokenHandle sysmem_token; + auto sysmem_token_request = sysmem_token.NewRequest(); + + fuchsia::ui::composition::RegisterBufferCollectionArgs + buffer_collection_args; + buffer_collection_args.set_export_token(std::move(buffer_export_token)); + buffer_collection_args.set_buffer_collection_token2( + std::move(sysmem_token)); + buffer_collection_args.set_usage( + fuchsia::ui::composition::RegisterBufferCollectionUsage::DEFAULT); + flatland_allocator_->RegisterBufferCollection( + std::move(buffer_collection_args), + [](fuchsia::ui::composition::Allocator_RegisterBufferCollection_Result + result) { + if (result.is_err()) { + FAIL() + << "fuhsia::ui::composition::RegisterBufferCollection error: " + << static_cast(result.err()); + } + }); + + return std::make_unique( + std::move(sysmem_token_request), std::move(buffer_import_token), size); + } + + // |SurfaceProducer| + void SubmitSurfaces( + std::vector> surfaces) override {} + + fuchsia::ui::composition::AllocatorPtr flatland_allocator_; +}; + +Matcher IsImageProperties( + const fuchsia::math::SizeU& size) { + return AllOf( + Property("has_size", &fuchsia::ui::composition::ImageProperties::has_size, + true), + Property("size", &fuchsia::ui::composition::ImageProperties::size, size)); +} + +Matcher IsViewportProperties( + const fuchsia::math::SizeU& logical_size, + const fuchsia::math::Inset& inset) { + return AllOf( + Property("has_logical_size", + &fuchsia::ui::composition::ViewportProperties::has_logical_size, + true), + Property("logical_size", + &fuchsia::ui::composition::ViewportProperties::logical_size, + logical_size), + Property("has_inset", + &fuchsia::ui::composition::ViewportProperties::has_inset, true), + Property("inset", &fuchsia::ui::composition::ViewportProperties::inset, + inset)); +} + +Matcher IsHitRegion( + const float x, + const float y, + const float width, + const float height, + const fuchsia::ui::composition::HitTestInteraction hit_test) { + return FieldsAre(FieldsAre(x, y, width, height), hit_test); +} + +Matcher IsEmptyGraph() { + return FieldsAre(IsEmpty(), IsEmpty(), Eq(nullptr), Eq(std::nullopt)); +} + +Matcher IsFlutterGraph( + const fuchsia::ui::composition::ParentViewportWatcherPtr& + parent_viewport_watcher, + const fuchsia::ui::views::ViewportCreationToken& viewport_creation_token, + const fuchsia::ui::views::ViewRef& view_ref, + std::vector>> layer_matchers = {}, + fuchsia::math::VecF scale = FakeTransform::kDefaultScale) { + auto viewport_token_koids = GetKoids(viewport_creation_token); + auto view_ref_koids = GetKoids(view_ref); + auto watcher_koids = GetKoids(parent_viewport_watcher); + + return FieldsAre( + /*content_map*/ _, /*transform_map*/ _, + Pointee(FieldsAre( + /*id*/ _, FakeTransform::kDefaultTranslation, + /*scale*/ scale, FakeTransform::kDefaultOrientation, + /*clip_bounds*/ _, FakeTransform::kDefaultOpacity, + /*children*/ ElementsAreArray(layer_matchers), + /*content*/ Eq(nullptr), /*hit_regions*/ _)), + Eq(FakeView{ + .view_token = viewport_token_koids.second, + .view_ref = view_ref_koids.first, + .view_ref_control = view_ref_koids.second, + .view_ref_focused = ZX_KOID_INVALID, + .focuser = ZX_KOID_INVALID, + .touch_source = ZX_KOID_INVALID, + .mouse_source = ZX_KOID_INVALID, + .parent_viewport_watcher = watcher_koids.second, + })); +} + +Matcher> IsImageLayer( + const fuchsia::math::SizeU& layer_size, + fuchsia::ui::composition::BlendMode blend_mode, + std::vector> + hit_region_matchers) { + return Pointee(FieldsAre( + /*id*/ _, FakeTransform::kDefaultTranslation, + FakeTransform::kDefaultScale, FakeTransform::kDefaultOrientation, + /*clip_bounds*/ _, FakeTransform::kDefaultOpacity, + /*children*/ IsEmpty(), + /*content*/ + Pointee(VariantWith(FieldsAre( + /*id*/ _, IsImageProperties(layer_size), + FakeImage::kDefaultSampleRegion, layer_size, + FakeImage::kDefaultOpacity, blend_mode, + /*buffer_import_token*/ _, /*vmo_index*/ 0))), + /* hit_regions*/ ElementsAreArray(hit_region_matchers))); +} + +Matcher> IsViewportLayer( + const fuchsia::ui::views::ViewCreationToken& view_token, + const fuchsia::math::SizeU& view_logical_size, + const fuchsia::math::Inset& view_inset, + const fuchsia::math::Vec& view_translation, + const fuchsia::math::VecF& view_scale, + const float view_opacity) { + return Pointee(FieldsAre( + /* id */ _, view_translation, view_scale, + FakeTransform::kDefaultOrientation, /*clip_bounds*/ _, view_opacity, + /*children*/ IsEmpty(), + /*content*/ + Pointee(VariantWith(FieldsAre( + /* id */ _, IsViewportProperties(view_logical_size, view_inset), + /* viewport_token */ GetKoids(view_token).second, + /* child_view_watcher */ _))), + /*hit_regions*/ _)); +} + +Matcher> IsClipTransformLayer( + const fuchsia::math::Vec& transform_translation, + const fuchsia::math::VecF& transform_scale, + std::optional clip_bounds, + Matcher> viewport_matcher) { + return Pointee(FieldsAre( + /* id */ _, transform_translation, transform_scale, + FakeTransform::kDefaultOrientation, /*clip_bounds*/ clip_bounds, + FakeTransform::kDefaultOpacity, + /*children*/ ElementsAre(viewport_matcher), + /*content*/ _, + /*hit_regions*/ _)); +} + +Matcher> IsInputShield() { + return Pointee(AllOf( + // Must not clip the hit region. + Field("clip_bounds", &FakeTransform::clip_bounds, Eq(std::nullopt)), + // Hit region must be "infinite". + Field("hit_regions", &FakeTransform::hit_regions, + Contains(flutter_runner::testing::kInfiniteHitRegion)))); +} + +fuchsia::ui::composition::OnNextFrameBeginValues WithPresentCredits( + uint32_t additional_present_credits) { + fuchsia::ui::composition::OnNextFrameBeginValues values; + values.set_additional_present_credits(additional_present_credits); + fuchsia::scenic::scheduling::PresentationInfo info_1; + info_1.set_presentation_time(123); + std::vector infos; + infos.push_back(std::move(info_1)); + values.set_future_presentation_infos(std::move(infos)); + return values; +} + +void DrawSimpleFrame(ExternalViewEmbedder& external_view_embedder, + SkISize frame_size, + float frame_dpr, + std::function draw_callback) { + external_view_embedder.BeginFrame(nullptr, nullptr); + external_view_embedder.PrepareFlutterView(frame_size, frame_dpr); + { + flutter::DlCanvas* root_canvas = external_view_embedder.GetRootCanvas(); + external_view_embedder.PostPrerollAction(nullptr); + draw_callback(root_canvas); + } + external_view_embedder.EndFrame(false, nullptr); + flutter::SurfaceFrame::FramebufferInfo framebuffer_info; + framebuffer_info.supports_readback = true; + external_view_embedder.SubmitFlutterView( + kImplicitViewId, nullptr, nullptr, + std::make_unique( + nullptr, std::move(framebuffer_info), + [](const flutter::SurfaceFrame& surface_frame, + flutter::DlCanvas* canvas) { return true; }, + [](const flutter::SurfaceFrame& surface_frame) { return true; }, + frame_size)); +} + +void DrawFrameWithView( + ExternalViewEmbedder& external_view_embedder, + SkISize frame_size, + float frame_dpr, + int view_id, + flutter::EmbeddedViewParams& view_params, + std::function background_draw_callback, + std::function overlay_draw_callback) { + external_view_embedder.BeginFrame(nullptr, nullptr); + external_view_embedder.PrepareFlutterView(frame_size, frame_dpr); + { + flutter::DlCanvas* root_canvas = external_view_embedder.GetRootCanvas(); + external_view_embedder.PrerollCompositeEmbeddedView( + view_id, std::make_unique(view_params)); + external_view_embedder.PostPrerollAction(nullptr); + background_draw_callback(root_canvas); + flutter::DlCanvas* overlay_canvas = + external_view_embedder.CompositeEmbeddedView(view_id); + overlay_draw_callback(overlay_canvas); + } + external_view_embedder.EndFrame(false, nullptr); + flutter::SurfaceFrame::FramebufferInfo framebuffer_info; + framebuffer_info.supports_readback = true; + external_view_embedder.SubmitFlutterView( + kImplicitViewId, nullptr, nullptr, + std::make_unique( + nullptr, std::move(framebuffer_info), + [](const flutter::SurfaceFrame& surface_frame, + flutter::DlCanvas* canvas) { return true; }, + [](const flutter::SurfaceFrame& surface_frame) { return true; }, + frame_size)); +} + +}; // namespace + +class ExternalViewEmbedderTest : public ::testing::Test { + protected: + ExternalViewEmbedderTest() + : session_subloop_(loop_.StartNewLoop()), + flatland_connection_(CreateFlatlandConnection()), + fake_surface_producer_( + std::make_shared(CreateFlatlandAllocator())) {} + ~ExternalViewEmbedderTest() override = default; + + async::TestLoop& loop() { return loop_; } + + std::shared_ptr fake_surface_producer() { + return fake_surface_producer_; + } + + FakeFlatland& fake_flatland() { return fake_flatland_; } + + std::shared_ptr flatland_connection() { + return flatland_connection_; + } + + private: + fuchsia::ui::composition::AllocatorHandle CreateFlatlandAllocator() { + FML_CHECK(!fake_flatland_.is_allocator_connected()); + fuchsia::ui::composition::AllocatorHandle flatland_allocator = + fake_flatland_.ConnectAllocator(session_subloop_->dispatcher()); + + return flatland_allocator; + } + + std::shared_ptr CreateFlatlandConnection() { + FML_CHECK(!fake_flatland_.is_flatland_connected()); + fuchsia::ui::composition::FlatlandHandle flatland = + fake_flatland_.ConnectFlatland(session_subloop_->dispatcher()); + + const auto test_name = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + return std::make_shared( + std::move(test_name), std::move(flatland), + /*error_callback=*/[] { FAIL(); }, /*ofpe_callback=*/[](auto...) {}); + } + + // Primary loop and subloop for the FakeFlatland instance to process its + // messages. The subloop allocates its own zx_port_t, allowing us to use a + // separate port for each end of the message channel, rather than sharing a + // single one. Dual ports allow messages and responses to be intermingled, + // which is how production code behaves; this improves test realism. + async::TestLoop loop_; + std::unique_ptr session_subloop_; + + FakeFlatland fake_flatland_; + + std::shared_ptr flatland_connection_; + std::shared_ptr fake_surface_producer_; +}; + +TEST_F(ExternalViewEmbedderTest, RootScene) { + fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher; + fuchsia::ui::views::ViewportCreationToken viewport_creation_token; + fuchsia::ui::views::ViewCreationToken view_creation_token; + fuchsia::ui::views::ViewRef view_ref_clone; + auto view_creation_token_status = zx::channel::create( + 0u, &viewport_creation_token.value, &view_creation_token.value); + ASSERT_EQ(view_creation_token_status, ZX_OK); + + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ASSERT_EQ(status, ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + view_ref.Clone(&view_ref_clone); + + ExternalViewEmbedder external_view_embedder( + std::move(view_creation_token), + fuchsia::ui::views::ViewIdentityOnCreation{ + .view_ref = std::move(view_ref), + .view_ref_control = std::move(view_ref_control), + }, + fuchsia::ui::composition::ViewBoundProtocols{}, + parent_viewport_watcher.NewRequest(), flatland_connection(), + fake_surface_producer()); + EXPECT_THAT(fake_flatland().graph(), IsEmptyGraph()); + + // Pump the loop; the graph should still be empty because nothing called + // `Present` yet. + loop().RunUntilIdle(); + EXPECT_THAT(fake_flatland().graph(), IsEmptyGraph()); + + // Pump the loop; the contents of the initial `Present` should be processed. + flatland_connection()->Present(); + loop().RunUntilIdle(); + EXPECT_THAT(fake_flatland().graph(), + IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, + view_ref_clone)); +} + +TEST_F(ExternalViewEmbedderTest, SimpleScene) { + fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher; + fuchsia::ui::views::ViewportCreationToken viewport_creation_token; + fuchsia::ui::views::ViewCreationToken view_creation_token; + fuchsia::ui::views::ViewRef view_ref_clone; + auto view_creation_token_status = zx::channel::create( + 0u, &viewport_creation_token.value, &view_creation_token.value); + ASSERT_EQ(view_creation_token_status, ZX_OK); + + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ASSERT_EQ(status, ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + view_ref.Clone(&view_ref_clone); + + // Create the `ExternalViewEmbedder` and pump the message loop until + // the initial scene graph is setup. + ExternalViewEmbedder external_view_embedder( + std::move(view_creation_token), + fuchsia::ui::views::ViewIdentityOnCreation{ + .view_ref = std::move(view_ref), + .view_ref_control = std::move(view_ref_control), + }, + fuchsia::ui::composition::ViewBoundProtocols{}, + parent_viewport_watcher.NewRequest(), flatland_connection(), + fake_surface_producer()); + flatland_connection()->Present(); + loop().RunUntilIdle(); + fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); + loop().RunUntilIdle(); + EXPECT_THAT(fake_flatland().graph(), + IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, + view_ref_clone)); + + // Draw the scene. The scene graph shouldn't change yet. + const SkISize frame_size_signed = SkISize::Make(512, 512); + const fuchsia::math::SizeU frame_size{ + static_cast(frame_size_signed.width()), + static_cast(frame_size_signed.height())}; + DrawSimpleFrame( + external_view_embedder, frame_size_signed, 1.f, + [](flutter::DlCanvas* canvas) { + const DlSize canvas_size(canvas->GetBaseLayerDimensions()); + flutter::DlPaint rect_paint; + rect_paint.setColor(flutter::DlColor::kGreen()); + canvas->Translate(canvas_size.width / 4.f, canvas_size.height / 2.f); + canvas->DrawRect(DlRect::MakeSize(canvas_size / 32.f), rect_paint); + }); + EXPECT_THAT(fake_flatland().graph(), + IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, + view_ref_clone)); + + // Pump the message loop. The scene updates should propagate to flatland. + loop().RunUntilIdle(); + + EXPECT_THAT( + fake_flatland().graph(), + IsFlutterGraph( + parent_viewport_watcher, viewport_creation_token, view_ref_clone, + /*layers*/ + {IsImageLayer( + frame_size, kFirstLayerBlendMode, + {IsHitRegion( + /* x */ 128.f, + /* y */ 256.f, + /* width */ 16.f, + /* height */ 16.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT)})})); +} + +TEST_F(ExternalViewEmbedderTest, SceneWithOneView) { + fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher; + fuchsia::ui::views::ViewportCreationToken viewport_creation_token; + fuchsia::ui::views::ViewCreationToken view_creation_token; + fuchsia::ui::views::ViewRef view_ref_clone; + auto view_creation_token_status = zx::channel::create( + 0u, &viewport_creation_token.value, &view_creation_token.value); + ASSERT_EQ(view_creation_token_status, ZX_OK); + + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ASSERT_EQ(status, ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + view_ref.Clone(&view_ref_clone); + + // Create the `ExternalViewEmbedder` and pump the message loop until + // the initial scene graph is setup. + ExternalViewEmbedder external_view_embedder( + std::move(view_creation_token), + fuchsia::ui::views::ViewIdentityOnCreation{ + .view_ref = std::move(view_ref), + .view_ref_control = std::move(view_ref_control), + }, + fuchsia::ui::composition::ViewBoundProtocols{}, + parent_viewport_watcher.NewRequest(), flatland_connection(), + fake_surface_producer()); + flatland_connection()->Present(); + loop().RunUntilIdle(); + fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); + loop().RunUntilIdle(); + EXPECT_THAT(fake_flatland().graph(), + IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, + view_ref_clone)); + + // Create the view before drawing the scene. + const SkSize child_view_size_signed = SkSize::Make(256.f, 512.f); + const fuchsia::math::SizeU child_view_size{ + static_cast(child_view_size_signed.width()), + static_cast(child_view_size_signed.height())}; + auto [child_view_token, child_viewport_token] = ViewTokenPair::New(); + const uint32_t child_view_id = child_viewport_token.value.get(); + + const uint8_t kOpacity = 200u; + const float kOpacityFloat = DlColor::toOpacity(kOpacity); + const fuchsia::math::VecF kScale{3.0f, 4.0f}; + + DlMatrix matrix = DlMatrix::MakeScale({kScale.x, kScale.y, 1}); + + auto mutators_stack = flutter::MutatorsStack(); + mutators_stack.PushOpacity(kOpacity); + mutators_stack.PushTransform(matrix); + + flutter::EmbeddedViewParams child_view_params( + flutter::ToSkMatrix(matrix), child_view_size_signed, mutators_stack); + external_view_embedder.CreateView( + child_view_id, []() {}, + [](fuchsia::ui::composition::ContentId, + fuchsia::ui::composition::ChildViewWatcherHandle) {}); + const SkRect child_view_occlusion_hint = SkRect::MakeLTRB(1, 2, 3, 4); + const fuchsia::math::Inset child_view_inset{ + static_cast(child_view_occlusion_hint.top()), + static_cast(child_view_occlusion_hint.right()), + static_cast(child_view_occlusion_hint.bottom()), + static_cast(child_view_occlusion_hint.left())}; + external_view_embedder.SetViewProperties( + child_view_id, child_view_occlusion_hint, /*hit_testable=*/false, + /*focusable=*/false); + + // We must take into account the effect of DPR on the view scale. + const float kDPR = 2.0f; + const float kInvDPR = 1.f / kDPR; + + // Draw the scene. The scene graph shouldn't change yet. + const SkISize frame_size_signed = SkISize::Make(512, 512); + const fuchsia::math::SizeU frame_size{ + static_cast(frame_size_signed.width()), + static_cast(frame_size_signed.height())}; + DrawFrameWithView( + external_view_embedder, frame_size_signed, kDPR, child_view_id, + child_view_params, + [](flutter::DlCanvas* canvas) { + const DlSize canvas_size(canvas->GetBaseLayerDimensions()); + flutter::DlPaint rect_paint; + rect_paint.setColor(flutter::DlColor::kGreen()); + canvas->Translate(canvas_size.width / 4.f, canvas_size.height / 2.f); + canvas->DrawRect(DlRect::MakeSize(canvas_size / 32.f), rect_paint); + }, + [](flutter::DlCanvas* canvas) { + const DlSize canvas_size(canvas->GetBaseLayerDimensions()); + flutter::DlPaint rect_paint; + rect_paint.setColor(flutter::DlColor::kRed()); + canvas->Translate(canvas_size.width * 3.f / 4.f, + canvas_size.height / 2.f); + canvas->DrawRect(DlRect::MakeSize(canvas_size / 32.f), rect_paint); + }); + EXPECT_THAT(fake_flatland().graph(), + IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, + view_ref_clone)); + + // Pump the message loop. The scene updates should propagate to flatland. + loop().RunUntilIdle(); + fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); + loop().RunUntilIdle(); + + EXPECT_THAT( + fake_flatland().graph(), + IsFlutterGraph( + parent_viewport_watcher, viewport_creation_token, + view_ref_clone, /*layers*/ + {IsImageLayer( + frame_size, kFirstLayerBlendMode, + {IsHitRegion( + /* x */ 128.f, + /* y */ 256.f, + /* width */ 16.f, + /* height */ 16.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT)}), + IsViewportLayer(child_view_token, child_view_size, child_view_inset, + {0, 0}, kScale, kOpacityFloat), + IsImageLayer( + frame_size, kUpperLayerBlendMode, + {IsHitRegion( + /* x */ 384.f, + /* y */ 256.f, + /* width */ 16.f, + /* height */ 16.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT)})}, + {kInvDPR, kInvDPR})); + + // Destroy the view. The scene graph shouldn't change yet. + external_view_embedder.DestroyView( + child_view_id, [](fuchsia::ui::composition::ContentId) {}); + EXPECT_THAT( + fake_flatland().graph(), + IsFlutterGraph( + parent_viewport_watcher, viewport_creation_token, + view_ref_clone, /*layers*/ + {IsImageLayer( + frame_size, kFirstLayerBlendMode, + {IsHitRegion( + /* x */ 128.f, + /* y */ 256.f, + /* width */ 16.f, + /* height */ 16.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT)}), + IsViewportLayer(child_view_token, child_view_size, child_view_inset, + {0, 0}, kScale, kOpacityFloat), + IsImageLayer( + frame_size, kUpperLayerBlendMode, + {IsHitRegion( + /* x */ 384.f, + /* y */ 256.f, + /* width */ 16.f, + /* height */ 16.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT)})}, + {kInvDPR, kInvDPR})); + + // Draw another frame without the view. The scene graph shouldn't change yet. + DrawSimpleFrame( + external_view_embedder, frame_size_signed, 1.f, + [](flutter::DlCanvas* canvas) { + const DlSize canvas_size(canvas->GetBaseLayerDimensions()); + flutter::DlPaint rect_paint; + rect_paint.setColor(flutter::DlColor::kGreen()); + canvas->Translate(canvas_size.width / 4.f, canvas_size.height / 2.f); + canvas->DrawRect(DlRect::MakeSize(canvas_size / 32.f), rect_paint); + }); + EXPECT_THAT( + fake_flatland().graph(), + IsFlutterGraph( + parent_viewport_watcher, viewport_creation_token, + view_ref_clone, /*layers*/ + {IsImageLayer( + frame_size, kFirstLayerBlendMode, + {IsHitRegion( + /* x */ 128.f, + /* y */ 256.f, + /* width */ 16.f, + /* height */ 16.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT)}), + IsViewportLayer(child_view_token, child_view_size, child_view_inset, + {0, 0}, kScale, kOpacityFloat), + IsImageLayer( + frame_size, kUpperLayerBlendMode, + {IsHitRegion( + /* x */ 384.f, + /* y */ 256.f, + /* width */ 16.f, + /* height */ 16.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT)})}, + {kInvDPR, kInvDPR})); + + // Pump the message loop. The scene updates should propagate to flatland. + loop().RunUntilIdle(); + EXPECT_THAT( + fake_flatland().graph(), + IsFlutterGraph( + parent_viewport_watcher, viewport_creation_token, + view_ref_clone, /*layers*/ + {IsImageLayer( + frame_size, kFirstLayerBlendMode, + {IsHitRegion( + /* x */ 128.f, + /* y */ 256.f, + /* width */ 16.f, + /* height */ 16.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT)})})); +} + +TEST_F(ExternalViewEmbedderTest, SceneWithOneClippedView) { + fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher; + fuchsia::ui::views::ViewportCreationToken viewport_creation_token; + fuchsia::ui::views::ViewCreationToken view_creation_token; + fuchsia::ui::views::ViewRef view_ref_clone; + auto view_creation_token_status = zx::channel::create( + 0u, &viewport_creation_token.value, &view_creation_token.value); + ASSERT_EQ(view_creation_token_status, ZX_OK); + + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ASSERT_EQ(status, ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + view_ref.Clone(&view_ref_clone); + + // Create the `ExternalViewEmbedder` and pump the message loop until + // the initial scene graph is setup. + ExternalViewEmbedder external_view_embedder( + std::move(view_creation_token), + fuchsia::ui::views::ViewIdentityOnCreation{ + .view_ref = std::move(view_ref), + .view_ref_control = std::move(view_ref_control), + }, + fuchsia::ui::composition::ViewBoundProtocols{}, + parent_viewport_watcher.NewRequest(), flatland_connection(), + fake_surface_producer()); + flatland_connection()->Present(); + loop().RunUntilIdle(); + fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); + loop().RunUntilIdle(); + EXPECT_THAT(fake_flatland().graph(), + IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, + view_ref_clone)); + + // Create the view before drawing the scene. + const SkSize child_view_size_signed = SkSize::Make(256.f, 512.f); + const fuchsia::math::SizeU child_view_size{ + static_cast(child_view_size_signed.width()), + static_cast(child_view_size_signed.height())}; + auto [child_view_token, child_viewport_token] = ViewTokenPair::New(); + const uint32_t child_view_id = child_viewport_token.value.get(); + + const uint8_t kOpacity = 200u; + const float kOpacityFloat = DlColor::toOpacity(kOpacity); + const fuchsia::math::VecF kScale{3.0f, 4.0f}; + const int kTranslateX = 10; + const int kTranslateY = 20; + + DlMatrix matrix = DlMatrix::MakeTranslation({kTranslateX, kTranslateY}) * + DlMatrix::MakeScale({kScale.x, kScale.y, 1}); + + DlRect kClipRect = + DlRect::MakeXYWH(30, 40, child_view_size_signed.width() - 50, + child_view_size_signed.height() - 60); + fuchsia::math::Rect kClipInMathRect = { + static_cast(kClipRect.GetX()), + static_cast(kClipRect.GetY()), + static_cast(kClipRect.GetWidth()), + static_cast(kClipRect.GetHeight())}; + + auto mutators_stack = flutter::MutatorsStack(); + mutators_stack.PushOpacity(kOpacity); + mutators_stack.PushTransform(matrix); + mutators_stack.PushClipRect(kClipRect); + + flutter::EmbeddedViewParams child_view_params( + flutter::ToSkMatrix(matrix), child_view_size_signed, mutators_stack); + external_view_embedder.CreateView( + child_view_id, []() {}, + [](fuchsia::ui::composition::ContentId, + fuchsia::ui::composition::ChildViewWatcherHandle) {}); + const SkRect child_view_occlusion_hint = SkRect::MakeLTRB(1, 2, 3, 4); + const fuchsia::math::Inset child_view_inset{ + static_cast(child_view_occlusion_hint.top()), + static_cast(child_view_occlusion_hint.right()), + static_cast(child_view_occlusion_hint.bottom()), + static_cast(child_view_occlusion_hint.left())}; + external_view_embedder.SetViewProperties( + child_view_id, child_view_occlusion_hint, /*hit_testable=*/false, + /*focusable=*/false); + + // We must take into account the effect of DPR on the view scale. + const float kDPR = 2.0f; + const float kInvDPR = 1.f / kDPR; + + // Draw the scene. The scene graph shouldn't change yet. + const SkISize frame_size_signed = SkISize::Make(512, 512); + const fuchsia::math::SizeU frame_size{ + static_cast(frame_size_signed.width()), + static_cast(frame_size_signed.height())}; + DrawFrameWithView( + external_view_embedder, frame_size_signed, kDPR, child_view_id, + child_view_params, + [](flutter::DlCanvas* canvas) { + const DlSize canvas_size(canvas->GetBaseLayerDimensions()); + flutter::DlPaint rect_paint; + rect_paint.setColor(flutter::DlColor::kGreen()); + canvas->Translate(canvas_size.width / 4.f, canvas_size.height / 2.f); + canvas->DrawRect(DlRect::MakeSize(canvas_size / 32.f), rect_paint); + }, + [](flutter::DlCanvas* canvas) { + const DlSize canvas_size(canvas->GetBaseLayerDimensions()); + flutter::DlPaint rect_paint; + rect_paint.setColor(flutter::DlColor::kRed()); + canvas->Translate(canvas_size.width * 3.f / 4.f, + canvas_size.height / 2.f); + canvas->DrawRect(DlRect::MakeSize(canvas_size / 32.f), rect_paint); + }); + EXPECT_THAT(fake_flatland().graph(), + IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, + view_ref_clone)); + + // Pump the message loop. The scene updates should propagate to flatland. + loop().RunUntilIdle(); + fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); + loop().RunUntilIdle(); + + EXPECT_THAT( + fake_flatland().graph(), + IsFlutterGraph( + parent_viewport_watcher, viewport_creation_token, + view_ref_clone, /*layers*/ + {IsImageLayer( + frame_size, kFirstLayerBlendMode, + {IsHitRegion( + /* x */ 128.f, + /* y */ 256.f, + /* width */ 16.f, + /* height */ 16.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT)}), + IsClipTransformLayer( + {kTranslateX, kTranslateY}, kScale, kClipInMathRect, + IsViewportLayer(child_view_token, child_view_size, + child_view_inset, {0, 0}, + FakeTransform::kDefaultScale, kOpacityFloat)), + IsImageLayer( + frame_size, kUpperLayerBlendMode, + {IsHitRegion( + /* x */ 384.f, + /* y */ 256.f, + /* width */ 16.f, + /* height */ 16.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT)})}, + {kInvDPR, kInvDPR})); + + // Draw another frame with view, but get rid of the clips this time. This + // should remove all ClipTransformLayer instances. + DlMatrix new_matrix = DlMatrix::MakeScale({kScale.x, kScale.y, 1}); + auto new_mutators_stack = flutter::MutatorsStack(); + new_mutators_stack.PushOpacity(kOpacity); + new_mutators_stack.PushTransform(new_matrix); + flutter::EmbeddedViewParams new_child_view_params( + flutter::ToSkMatrix(new_matrix), child_view_size_signed, + new_mutators_stack); + DrawFrameWithView( + external_view_embedder, frame_size_signed, kDPR, child_view_id, + new_child_view_params, + [](flutter::DlCanvas* canvas) { + const DlSize canvas_size(canvas->GetBaseLayerDimensions()); + flutter::DlPaint rect_paint; + rect_paint.setColor(flutter::DlColor::kGreen()); + canvas->Translate(canvas_size.width / 4.f, canvas_size.height / 2.f); + canvas->DrawRect(DlRect::MakeSize(canvas_size / 32.f), rect_paint); + }, + [](flutter::DlCanvas* canvas) { + const DlSize canvas_size(canvas->GetBaseLayerDimensions()); + flutter::DlPaint rect_paint; + rect_paint.setColor(flutter::DlColor::kRed()); + canvas->Translate(canvas_size.width * 3.f / 4.f, + canvas_size.height / 2.f); + canvas->DrawRect(DlRect::MakeSize(canvas_size / 32.f), rect_paint); + }); + loop().RunUntilIdle(); + fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); + loop().RunUntilIdle(); + EXPECT_THAT( + fake_flatland().graph(), + IsFlutterGraph( + parent_viewport_watcher, viewport_creation_token, + view_ref_clone, /*layers*/ + {IsImageLayer( + frame_size, kFirstLayerBlendMode, + {IsHitRegion( + /* x */ 128.f, + /* y */ 256.f, + /* width */ 16.f, + /* height */ 16.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT)}), + IsViewportLayer(child_view_token, child_view_size, child_view_inset, + {0, 0}, kScale, kOpacityFloat), + IsImageLayer( + frame_size, kUpperLayerBlendMode, + {IsHitRegion( + /* x */ 384.f, + /* y */ 256.f, + /* width */ 16.f, + /* height */ 16.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT)})}, + {kInvDPR, kInvDPR})); + + // Destroy the view and draw another frame without the view. + external_view_embedder.DestroyView( + child_view_id, [](fuchsia::ui::composition::ContentId) {}); + DrawSimpleFrame( + external_view_embedder, frame_size_signed, 1.f, + [](flutter::DlCanvas* canvas) { + const DlSize canvas_size(canvas->GetBaseLayerDimensions()); + flutter::DlPaint rect_paint; + rect_paint.setColor(flutter::DlColor::kGreen()); + canvas->Translate(canvas_size.width / 4.f, canvas_size.height / 2.f); + canvas->DrawRect(DlRect::MakeSize(canvas_size / 32.f), rect_paint); + }); + loop().RunUntilIdle(); + EXPECT_THAT( + fake_flatland().graph(), + IsFlutterGraph( + parent_viewport_watcher, viewport_creation_token, + view_ref_clone, /*layers*/ + {IsImageLayer( + frame_size, kFirstLayerBlendMode, + {IsHitRegion( + /* x */ 128.f, + /* y */ 256.f, + /* width */ 16.f, + /* height */ 16.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT)})})); +} + +TEST_F(ExternalViewEmbedderTest, SceneWithOneView_NoOverlay) { + fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher; + fuchsia::ui::views::ViewportCreationToken viewport_creation_token; + fuchsia::ui::views::ViewCreationToken view_creation_token; + fuchsia::ui::views::ViewRef view_ref_clone; + auto view_creation_token_status = zx::channel::create( + 0u, &viewport_creation_token.value, &view_creation_token.value); + ASSERT_EQ(view_creation_token_status, ZX_OK); + + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ASSERT_EQ(status, ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + view_ref.Clone(&view_ref_clone); + + // Create the `ExternalViewEmbedder` and pump the message loop until + // the initial scene graph is setup. + ExternalViewEmbedder external_view_embedder( + std::move(view_creation_token), + fuchsia::ui::views::ViewIdentityOnCreation{ + .view_ref = std::move(view_ref), + .view_ref_control = std::move(view_ref_control), + }, + fuchsia::ui::composition::ViewBoundProtocols{}, + parent_viewport_watcher.NewRequest(), flatland_connection(), + fake_surface_producer()); + flatland_connection()->Present(); + loop().RunUntilIdle(); + fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); + loop().RunUntilIdle(); + EXPECT_THAT(fake_flatland().graph(), + IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, + view_ref_clone)); + + // Create the view before drawing the scene. + const SkSize child_view_size_signed = SkSize::Make(256.f, 512.f); + const fuchsia::math::SizeU child_view_size{ + static_cast(child_view_size_signed.width()), + static_cast(child_view_size_signed.height())}; + auto [child_view_token, child_viewport_token] = ViewTokenPair::New(); + const uint32_t child_view_id = child_viewport_token.value.get(); + + const uint8_t kOpacity = 125u; + const float kOpacityFloat = DlColor::toOpacity(kOpacity); + const fuchsia::math::VecF kScale{2.f, 3.0f}; + + DlMatrix matrix = DlMatrix::MakeScale({kScale.x, kScale.y, 1}); + + auto mutators_stack = flutter::MutatorsStack(); + mutators_stack.PushOpacity(kOpacity); + mutators_stack.PushTransform(matrix); + + flutter::EmbeddedViewParams child_view_params( + flutter::ToSkMatrix(matrix), child_view_size_signed, mutators_stack); + external_view_embedder.CreateView( + child_view_id, []() {}, + [](fuchsia::ui::composition::ContentId, + fuchsia::ui::composition::ChildViewWatcherHandle) {}); + + // Draw the scene. The scene graph shouldn't change yet. + const SkISize frame_size_signed = SkISize::Make(512, 512); + const fuchsia::math::SizeU frame_size{ + static_cast(frame_size_signed.width()), + static_cast(frame_size_signed.height())}; + DrawFrameWithView( + external_view_embedder, frame_size_signed, 1.f, child_view_id, + child_view_params, + [](flutter::DlCanvas* canvas) { + const DlSize canvas_size(canvas->GetBaseLayerDimensions()); + flutter::DlPaint rect_paint; + rect_paint.setColor(flutter::DlColor::kGreen()); + canvas->Translate(canvas_size.width / 4.f, canvas_size.height / 2.f); + canvas->DrawRect(DlRect::MakeSize(canvas_size / 32.f), rect_paint); + }, + [](flutter::DlCanvas* canvas) {}); + EXPECT_THAT(fake_flatland().graph(), + IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, + view_ref_clone)); + + // Pump the message loop. The scene updates should propagate to flatland. + loop().RunUntilIdle(); + fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); + loop().RunUntilIdle(); + EXPECT_THAT( + fake_flatland().graph(), + IsFlutterGraph( + parent_viewport_watcher, viewport_creation_token, + view_ref_clone, /*layers*/ + {IsImageLayer( + frame_size, kFirstLayerBlendMode, + {IsHitRegion( + /* x */ 128.f, + /* y */ 256.f, + /* width */ 16.f, + /* height */ 16.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT)}), + IsViewportLayer(child_view_token, child_view_size, + FakeViewport::kDefaultViewportInset, {0, 0}, kScale, + kOpacityFloat)})); + + // Destroy the view. The scene graph shouldn't change yet. + external_view_embedder.DestroyView( + child_view_id, [](fuchsia::ui::composition::ContentId) {}); + EXPECT_THAT( + fake_flatland().graph(), + IsFlutterGraph( + parent_viewport_watcher, viewport_creation_token, + view_ref_clone, /*layers*/ + {IsImageLayer( + frame_size, kFirstLayerBlendMode, + {IsHitRegion( + /* x */ 128.f, + /* y */ 256.f, + /* width */ 16.f, + /* height */ 16.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT)}), + IsViewportLayer(child_view_token, child_view_size, + FakeViewport::kDefaultViewportInset, {0, 0}, kScale, + kOpacityFloat)})); + + // Draw another frame without the view. The scene graph shouldn't change yet. + DrawSimpleFrame( + external_view_embedder, frame_size_signed, 1.f, + [](flutter::DlCanvas* canvas) { + const DlSize canvas_size(canvas->GetBaseLayerDimensions()); + flutter::DlPaint rect_paint; + rect_paint.setColor(flutter::DlColor::kGreen()); + canvas->Translate(canvas_size.width / 4.f, canvas_size.height / 2.f); + canvas->DrawRect(DlRect::MakeSize(canvas_size / 32.f), rect_paint); + }); + + EXPECT_THAT( + fake_flatland().graph(), + IsFlutterGraph( + parent_viewport_watcher, viewport_creation_token, + view_ref_clone, /*layers*/ + {IsImageLayer( + frame_size, kFirstLayerBlendMode, + {IsHitRegion( + /* x */ 128.f, + /* y */ 256.f, + /* width */ 16.f, + /* height */ 16.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT)}), + IsViewportLayer(child_view_token, child_view_size, + FakeViewport::kDefaultViewportInset, {0, 0}, kScale, + kOpacityFloat)})); + + // Pump the message loop. The scene updates should propagate to flatland. + loop().RunUntilIdle(); + EXPECT_THAT( + fake_flatland().graph(), + IsFlutterGraph( + parent_viewport_watcher, viewport_creation_token, + view_ref_clone, /*layers*/ + {IsImageLayer( + frame_size, kFirstLayerBlendMode, + {IsHitRegion( + /* x */ 128.f, + /* y */ 256.f, + /* width */ 16.f, + /* height */ 16.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT)})})); +} + +TEST_F(ExternalViewEmbedderTest, SceneWithOneView_DestroyBeforeDrawing) { + fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher; + fuchsia::ui::views::ViewportCreationToken viewport_creation_token; + fuchsia::ui::views::ViewCreationToken view_creation_token; + fuchsia::ui::views::ViewRef view_ref_clone; + auto view_creation_token_status = zx::channel::create( + 0u, &viewport_creation_token.value, &view_creation_token.value); + ASSERT_EQ(view_creation_token_status, ZX_OK); + + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ASSERT_EQ(status, ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + view_ref.Clone(&view_ref_clone); + + // Create the `ExternalViewEmbedder` and pump the message loop until + // the initial scene graph is setup. + ExternalViewEmbedder external_view_embedder( + std::move(view_creation_token), + fuchsia::ui::views::ViewIdentityOnCreation{ + .view_ref = std::move(view_ref), + .view_ref_control = std::move(view_ref_control), + }, + fuchsia::ui::composition::ViewBoundProtocols{}, + parent_viewport_watcher.NewRequest(), flatland_connection(), + fake_surface_producer()); + flatland_connection()->Present(); + loop().RunUntilIdle(); + fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); + loop().RunUntilIdle(); + EXPECT_THAT(fake_flatland().graph(), + IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, + view_ref_clone)); + + // Create the view before drawing the scene. + auto [child_view_token, child_viewport_token] = ViewTokenPair::New(); + const uint32_t child_view_id = child_viewport_token.value.get(); + external_view_embedder.CreateView( + child_view_id, []() {}, + [](fuchsia::ui::composition::ContentId, + fuchsia::ui::composition::ChildViewWatcherHandle) {}); + + // Draw the scene without the view. The scene graph shouldn't change yet. + const SkISize frame_size_signed = SkISize::Make(512, 512); + const fuchsia::math::SizeU frame_size{ + static_cast(frame_size_signed.width()), + static_cast(frame_size_signed.height())}; + DrawSimpleFrame( + external_view_embedder, frame_size_signed, 1.f, + [](flutter::DlCanvas* canvas) { + const DlSize canvas_size(canvas->GetBaseLayerDimensions()); + flutter::DlPaint rect_paint; + rect_paint.setColor(flutter::DlColor().kGreen()); + canvas->Translate(canvas_size.width / 4.f, canvas_size.height / 2.f); + canvas->DrawRect(DlRect::MakeSize(canvas_size / 32.f), rect_paint); + }); + + // Pump the message loop. The scene updates should propagate to flatland. + loop().RunUntilIdle(); + fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); + loop().RunUntilIdle(); + EXPECT_THAT( + fake_flatland().graph(), + IsFlutterGraph( + parent_viewport_watcher, viewport_creation_token, view_ref_clone, + /*layers*/ + {IsImageLayer( + frame_size, kFirstLayerBlendMode, + {IsHitRegion( + /* x */ 128.f, + /* y */ 256.f, + /* width */ 16.f, + /* height */ 16.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT)})})); + + // Destroy the view. The scene graph shouldn't change yet. + external_view_embedder.DestroyView( + child_view_id, [](fuchsia::ui::composition::ContentId) {}); + EXPECT_THAT( + fake_flatland().graph(), + IsFlutterGraph( + parent_viewport_watcher, viewport_creation_token, view_ref_clone, + /*layers*/ + {IsImageLayer( + frame_size, kFirstLayerBlendMode, + {IsHitRegion( + /* x */ 128.f, + /* y */ 256.f, + /* width */ 16.f, + /* height */ 16.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT)})})); + + // Draw another frame without the view and change the size. The scene graph + // shouldn't change yet. + const SkISize new_frame_size_signed = SkISize::Make(256, 256); + const fuchsia::math::SizeU new_frame_size{ + static_cast(new_frame_size_signed.width()), + static_cast(new_frame_size_signed.height())}; + DrawSimpleFrame( + external_view_embedder, new_frame_size_signed, 1.f, + [](flutter::DlCanvas* canvas) { + const DlSize canvas_size(canvas->GetBaseLayerDimensions()); + flutter::DlPaint rect_paint; + rect_paint.setColor(flutter::DlColor::kGreen()); + canvas->Translate(canvas_size.width / 4.f, canvas_size.height / 2.f); + canvas->DrawRect(DlRect::MakeSize(canvas_size / 32.f), rect_paint); + }); + EXPECT_THAT( + fake_flatland().graph(), + IsFlutterGraph( + parent_viewport_watcher, viewport_creation_token, view_ref_clone, + /*layers*/ + {IsImageLayer( + frame_size, kFirstLayerBlendMode, + {IsHitRegion( + /* x */ 128.f, + /* y */ 256.f, + /* width */ 16.f, + /* height */ 16.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT)})})); + + // Pump the message loop. The scene updates should propagate to flatland. + loop().RunUntilIdle(); + EXPECT_THAT( + fake_flatland().graph(), + IsFlutterGraph( + parent_viewport_watcher, viewport_creation_token, + view_ref_clone, /*layers*/ + {IsImageLayer( + new_frame_size, kFirstLayerBlendMode, + {IsHitRegion( + /* x */ 64.f, + /* y */ 128.f, + /* width */ 8.f, + /* height */ 8.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT)})})); +} + +// This test case exercises the scenario in which the view contains two disjoint +// regions with painted content; we should generate two separate hit regions +// matching the bounds of the painted regions in this case. +TEST_F(ExternalViewEmbedderTest, SimpleScene_DisjointHitRegions) { + fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher; + fuchsia::ui::views::ViewportCreationToken viewport_creation_token; + fuchsia::ui::views::ViewCreationToken view_creation_token; + fuchsia::ui::views::ViewRef view_ref_clone; + auto view_creation_token_status = zx::channel::create( + 0u, &viewport_creation_token.value, &view_creation_token.value); + ASSERT_EQ(view_creation_token_status, ZX_OK); + + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ASSERT_EQ(status, ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + view_ref.Clone(&view_ref_clone); + + // Create the `ExternalViewEmbedder` and pump the message loop until + // the initial scene graph is setup. + ExternalViewEmbedder external_view_embedder( + std::move(view_creation_token), + fuchsia::ui::views::ViewIdentityOnCreation{ + .view_ref = std::move(view_ref), + .view_ref_control = std::move(view_ref_control), + }, + fuchsia::ui::composition::ViewBoundProtocols{}, + parent_viewport_watcher.NewRequest(), flatland_connection(), + fake_surface_producer()); + flatland_connection()->Present(); + loop().RunUntilIdle(); + fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); + loop().RunUntilIdle(); + EXPECT_THAT(fake_flatland().graph(), + IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, + view_ref_clone)); + + // Draw the scene. The scene graph shouldn't change yet. + const SkISize frame_size_signed = SkISize::Make(512, 512); + const fuchsia::math::SizeU frame_size{ + static_cast(frame_size_signed.width()), + static_cast(frame_size_signed.height())}; + DrawSimpleFrame(external_view_embedder, frame_size_signed, 1.f, + [](flutter::DlCanvas* canvas) { + const DlSize canvas_size(canvas->GetBaseLayerDimensions()); + + DlRect paint_region_1, paint_region_2; + + paint_region_1 = DlRect::MakeXYWH( + canvas_size.width / 4.f, canvas_size.height / 2.f, + canvas_size.width / 32.f, canvas_size.height / 32.f); + + flutter::DlPaint rect_paint; + rect_paint.setColor(flutter::DlColor::kGreen()); + canvas->DrawRect(paint_region_1, rect_paint); + + paint_region_2 = DlRect::MakeXYWH( + canvas_size.width * 3.f / 4.f, canvas_size.height / 2.f, + canvas_size.width / 32.f, canvas_size.height / 32.f); + + rect_paint.setColor(flutter::DlColor::kRed()); + canvas->DrawRect(paint_region_2, rect_paint); + }); + EXPECT_THAT(fake_flatland().graph(), + IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, + view_ref_clone)); + + // Pump the message loop. The scene updates should propagate to flatland. + loop().RunUntilIdle(); + + EXPECT_THAT( + fake_flatland().graph(), + IsFlutterGraph( + parent_viewport_watcher, viewport_creation_token, view_ref_clone, + /*layers*/ + {IsImageLayer( + frame_size, kFirstLayerBlendMode, + {IsHitRegion( + /* x */ 128.f, + /* y */ 256.f, + /* width */ 16.f, + /* height */ 16.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT), + IsHitRegion( + /* x */ 384.f, + /* y */ 256.f, + /* width */ 16.f, + /* height */ 16.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT)})})); +} + +// This test case exercises the scenario in which the view contains two +// overlapping regions with painted content; we should generate one hit +// region matching the union of the bounds of the two painted regions in +// this case. +TEST_F(ExternalViewEmbedderTest, SimpleScene_OverlappingHitRegions) { + fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher; + fuchsia::ui::views::ViewportCreationToken viewport_creation_token; + fuchsia::ui::views::ViewCreationToken view_creation_token; + fuchsia::ui::views::ViewRef view_ref_clone; + auto view_creation_token_status = zx::channel::create( + 0u, &viewport_creation_token.value, &view_creation_token.value); + ASSERT_EQ(view_creation_token_status, ZX_OK); + + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ASSERT_EQ(status, ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + view_ref.Clone(&view_ref_clone); + + // Create the `ExternalViewEmbedder` and pump the message loop until + // the initial scene graph is setup. + ExternalViewEmbedder external_view_embedder( + std::move(view_creation_token), + fuchsia::ui::views::ViewIdentityOnCreation{ + .view_ref = std::move(view_ref), + .view_ref_control = std::move(view_ref_control), + }, + fuchsia::ui::composition::ViewBoundProtocols{}, + parent_viewport_watcher.NewRequest(), flatland_connection(), + fake_surface_producer()); + flatland_connection()->Present(); + loop().RunUntilIdle(); + fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); + loop().RunUntilIdle(); + EXPECT_THAT(fake_flatland().graph(), + IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, + view_ref_clone)); + + // Draw the scene. The scene graph shouldn't change yet. + const SkISize frame_size_signed = SkISize::Make(512, 512); + const fuchsia::math::SizeU frame_size{ + static_cast(frame_size_signed.width()), + static_cast(frame_size_signed.height())}; + DrawSimpleFrame( + external_view_embedder, frame_size_signed, 1.f, + [](flutter::DlCanvas* canvas) { + const DlSize canvas_size(canvas->GetBaseLayerDimensions()); + + DlRect paint_region_1, paint_region_2; + + paint_region_1 = DlRect::MakeXYWH( + canvas_size.width / 4.f, canvas_size.height / 2.f, + 3.f * canvas_size.width / 8.f, canvas_size.height / 4.f); + + flutter::DlPaint rect_paint; + rect_paint.setColor(flutter::DlColor::kGreen()); + canvas->DrawRect(paint_region_1, rect_paint); + + paint_region_2 = DlRect::MakeXYWH( + canvas_size.width * 3.f / 8.f, canvas_size.height / 2.f, + 3.f * canvas_size.width / 8.f, canvas_size.height / 4.f); + + rect_paint.setColor(flutter::DlColor::kRed()); + canvas->DrawRect(paint_region_2, rect_paint); + }); + EXPECT_THAT(fake_flatland().graph(), + IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, + view_ref_clone)); + + // Pump the message loop. The scene updates should propagate to flatland. + loop().RunUntilIdle(); + + EXPECT_THAT( + fake_flatland().graph(), + IsFlutterGraph( + parent_viewport_watcher, viewport_creation_token, view_ref_clone, + /*layers*/ + {IsImageLayer( + frame_size, kFirstLayerBlendMode, + {IsHitRegion( + /* x */ 128.f, + /* y */ 256.f, + /* width */ 256.f, + /* height */ 128.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT)})})); +} + +TEST_F(ExternalViewEmbedderTest, ViewportCoveredWithInputInterceptor) { + fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher; + fuchsia::ui::views::ViewportCreationToken viewport_creation_token; + fuchsia::ui::views::ViewCreationToken view_creation_token; + fuchsia::ui::views::ViewRef view_ref_clone; + auto view_creation_token_status = zx::channel::create( + 0u, &viewport_creation_token.value, &view_creation_token.value); + ASSERT_EQ(view_creation_token_status, ZX_OK); + + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ASSERT_EQ(status, ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + view_ref.Clone(&view_ref_clone); + + // Create the `ExternalViewEmbedder` and pump the message loop until + // the initial scene graph is setup. + ExternalViewEmbedder external_view_embedder( + std::move(view_creation_token), + fuchsia::ui::views::ViewIdentityOnCreation{ + .view_ref = std::move(view_ref), + .view_ref_control = std::move(view_ref_control), + }, + fuchsia::ui::composition::ViewBoundProtocols{}, + parent_viewport_watcher.NewRequest(), flatland_connection(), + fake_surface_producer(), + /*intercept_all_input=*/true // Enables the interceptor. + ); + flatland_connection()->Present(); + loop().RunUntilIdle(); + fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); + loop().RunUntilIdle(); + EXPECT_THAT(fake_flatland().graph(), + IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, + view_ref_clone, {IsInputShield()})); + + // Create the view before drawing the scene. + const SkSize child_view_size_signed = SkSize::Make(256.f, 512.f); + const fuchsia::math::SizeU child_view_size{ + static_cast(child_view_size_signed.width()), + static_cast(child_view_size_signed.height())}; + auto [child_view_token, child_viewport_token] = ViewTokenPair::New(); + const uint32_t child_view_id = child_viewport_token.value.get(); + + const uint8_t kOpacity = 200u; + const float kOpacityFloat = DlColor::toOpacity(kOpacity); + const fuchsia::math::VecF kScale{3.0f, 4.0f}; + + DlMatrix matrix = DlMatrix::MakeScale({kScale.x, kScale.y, 1}); + + auto mutators_stack = flutter::MutatorsStack(); + mutators_stack.PushOpacity(kOpacity); + mutators_stack.PushTransform(matrix); + + flutter::EmbeddedViewParams child_view_params( + flutter::ToSkMatrix(matrix), child_view_size_signed, mutators_stack); + external_view_embedder.CreateView( + child_view_id, []() {}, + [](fuchsia::ui::composition::ContentId, + fuchsia::ui::composition::ChildViewWatcherHandle) {}); + const SkRect child_view_occlusion_hint = SkRect::MakeLTRB(1, 2, 3, 4); + const fuchsia::math::Inset child_view_inset{ + static_cast(child_view_occlusion_hint.top()), + static_cast(child_view_occlusion_hint.right()), + static_cast(child_view_occlusion_hint.bottom()), + static_cast(child_view_occlusion_hint.left())}; + external_view_embedder.SetViewProperties( + child_view_id, child_view_occlusion_hint, /*hit_testable=*/false, + /*focusable=*/false); + + // We must take into account the effect of DPR on the view scale. + const float kDPR = 2.0f; + const float kInvDPR = 1.f / kDPR; + + // Draw the scene. The scene graph shouldn't change yet. + const SkISize frame_size_signed = SkISize::Make(512, 512); + const fuchsia::math::SizeU frame_size{ + static_cast(frame_size_signed.width()), + static_cast(frame_size_signed.height())}; + auto background_draw_callback = [](flutter::DlCanvas* canvas) { + const DlSize canvas_size(canvas->GetBaseLayerDimensions()); + flutter::DlPaint rect_paint; + rect_paint.setColor(flutter::DlColor::kGreen()); + canvas->Translate(canvas_size.width / 4.f, canvas_size.height / 2.f); + canvas->DrawRect(DlRect::MakeSize(canvas_size / 32.f), rect_paint); + }; + auto overlay_draw_callback = [](flutter::DlCanvas* canvas) { + const DlSize canvas_size(canvas->GetBaseLayerDimensions()); + flutter::DlPaint rect_paint; + rect_paint.setColor(flutter::DlColor::kRed()); + canvas->Translate(canvas_size.width * 3.f / 4.f, canvas_size.height / 2.f); + canvas->DrawRect(DlRect::MakeSize(canvas_size / 32.f), rect_paint); + }; + DrawFrameWithView(external_view_embedder, frame_size_signed, kDPR, + child_view_id, child_view_params, background_draw_callback, + overlay_draw_callback); + EXPECT_THAT(fake_flatland().graph(), + IsFlutterGraph(parent_viewport_watcher, viewport_creation_token, + view_ref_clone, {IsInputShield()})); + + // Pump the message loop. The scene updates should propagate to flatland. + loop().RunUntilIdle(); + fake_flatland().FireOnNextFrameBeginEvent(WithPresentCredits(1u)); + loop().RunUntilIdle(); + + EXPECT_THAT( + fake_flatland().graph(), + IsFlutterGraph( + parent_viewport_watcher, viewport_creation_token, + view_ref_clone, /*layers*/ + {IsImageLayer( + frame_size, kFirstLayerBlendMode, + {IsHitRegion( + /* x */ 128.f, + /* y */ 256.f, + /* width */ 16.f, + /* height */ 16.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT)}), + IsViewportLayer(child_view_token, child_view_size, child_view_inset, + {0, 0}, kScale, kOpacityFloat), + IsImageLayer( + frame_size, kUpperLayerBlendMode, + {IsHitRegion( + /* x */ 384.f, + /* y */ 256.f, + /* width */ 16.f, + /* height */ 16.f, + /* hit_test */ + fuchsia::ui::composition::HitTestInteraction::DEFAULT)}), + IsInputShield()}, + {kInvDPR, kInvDPR})); +} + +} // namespace flutter_runner::testing diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fake_flatland_unittests.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fake_flatland_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..0b161d10ab17829a3055f345603ddedcf2658edc --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fake_flatland_unittests.cc @@ -0,0 +1,144 @@ +// 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 "fakes/scenic/fake_flatland.h" + +#include +#include + +#include + +#include "flutter/fml/logging.h" +#include "fuchsia/ui/composition/cpp/fidl.h" +#include "gtest/gtest.h" + +namespace flutter_runner::testing { +namespace { + +std::string GetCurrentTestName() { + return ::testing::UnitTest::GetInstance()->current_test_info()->name(); +} + +} // namespace + +class FakeFlatlandTest : public ::testing::Test { + protected: + FakeFlatlandTest() : flatland_subloop_(loop_.StartNewLoop()) {} + ~FakeFlatlandTest() override = default; + + async::TestLoop& loop() { return loop_; } + + FakeFlatland& fake_flatland() { return fake_flatland_; } + + fuchsia::ui::composition::FlatlandPtr ConnectFlatland() { + FML_CHECK(!fake_flatland_.is_flatland_connected()); + + auto flatland_handle = + fake_flatland_.ConnectFlatland(flatland_subloop_->dispatcher()); + return flatland_handle.Bind(); + } + + private: + // Primary loop and subloop for the FakeFlatland instance to process its + // messages. The subloop allocates it's own zx_port_t, allowing us to use a + // separate port for each end of the message channel, rather than sharing a + // single one. Dual ports allow messages and responses to be intermingled, + // which is how production code behaves; this improves test realism. + async::TestLoop loop_; + std::unique_ptr flatland_subloop_; + + FakeFlatland fake_flatland_; +}; + +TEST_F(FakeFlatlandTest, Initialization) { + EXPECT_EQ(fake_flatland().debug_name(), ""); + + // Pump the loop one time; the flatland should retain its initial state. + loop().RunUntilIdle(); + EXPECT_EQ(fake_flatland().debug_name(), ""); +} + +TEST_F(FakeFlatlandTest, DebugLabel) { + const std::string debug_label = GetCurrentTestName(); + fuchsia::ui::composition::FlatlandPtr flatland = ConnectFlatland(); + + // Set the flatland's debug name. The `SetDebugName` hasn't been processed + // yet, so the flatland's view of the debug name is still empty. + flatland->SetDebugName(debug_label); + EXPECT_EQ(fake_flatland().debug_name(), ""); + + // Pump the loop; the contents of the initial `SetDebugName` should be + // processed. + loop().RunUntilIdle(); + EXPECT_EQ(fake_flatland().debug_name(), debug_label); +} + +TEST_F(FakeFlatlandTest, Present) { + fuchsia::ui::composition::FlatlandPtr flatland = ConnectFlatland(); + + // Fire an OnNextFrameBegin event and verify the test receives it. + constexpr uint64_t kOnNextFrameAdditionalPresentCredits = 10u; + uint64_t on_next_frame_additional_present_credits = 0u; + fuchsia::ui::composition::OnNextFrameBeginValues on_next_frame_begin_values; + on_next_frame_begin_values.set_additional_present_credits( + kOnNextFrameAdditionalPresentCredits); + flatland.events().OnNextFrameBegin = + [&on_next_frame_additional_present_credits]( + auto on_next_frame_begin_values) { + static bool called_once = false; + EXPECT_FALSE(called_once); + + on_next_frame_additional_present_credits = + on_next_frame_begin_values.additional_present_credits(); + called_once = true; + }; + fake_flatland().FireOnNextFrameBeginEvent( + std::move(on_next_frame_begin_values)); + EXPECT_EQ(on_next_frame_additional_present_credits, 0u); + loop().RunUntilIdle(); + EXPECT_EQ(on_next_frame_additional_present_credits, + kOnNextFrameAdditionalPresentCredits); + + // Fire an OnFramePresented event and verify the test receives it. + constexpr uint64_t kOnFramePresentedNumPresentsAllowed = 20u; + uint64_t frame_presented_num_presents_allowed = 0u; + flatland.events().OnFramePresented = + [&frame_presented_num_presents_allowed](auto frame_presented_info) { + static bool called_once = false; + EXPECT_FALSE(called_once); + + frame_presented_num_presents_allowed = + frame_presented_info.num_presents_allowed; + called_once = true; + }; + fake_flatland().FireOnFramePresentedEvent( + fuchsia::scenic::scheduling::FramePresentedInfo{ + .actual_presentation_time = 0, + .num_presents_allowed = kOnFramePresentedNumPresentsAllowed, + }); + EXPECT_EQ(frame_presented_num_presents_allowed, 0u); + loop().RunUntilIdle(); + EXPECT_EQ(frame_presented_num_presents_allowed, + kOnFramePresentedNumPresentsAllowed); + + // Call Present and verify the fake handled it. + constexpr int64_t kPresentRequestedTime = 42; + int64_t present_requested_time = 0; + fuchsia::ui::composition::PresentArgs present_args; + present_args.set_requested_presentation_time(kPresentRequestedTime); + fake_flatland().SetPresentHandler( + [&present_requested_time](auto present_args) { + static bool called_once = false; + EXPECT_FALSE(called_once); + + present_requested_time = present_args.requested_presentation_time(); + called_once = true; + }); + flatland->Present(std::move(present_args)); + EXPECT_EQ(present_requested_time, 0); + loop().RunUntilIdle(); + EXPECT_EQ(present_requested_time, kPresentRequestedTime); +} + +} // namespace flutter_runner::testing diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e47a8d3cbcec821e3904ac45caf512432e60d54a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/BUILD.gn @@ -0,0 +1,48 @@ +# 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. + +assert(is_fuchsia) + +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") + +group("fakes") { + testonly = true + + public_deps = [ + ":focus", + ":pointer", + "scenic", + ] +} + +source_set("focus") { + testonly = true + + sources = [ + "focuser.h", + "platform_message.h", + "touch_source.h", + "view_ref_focused.h", + ] + + deps = [ + "${fuchsia_sdk}/pkg/sys_cpp_testing", + "//flutter/lib/ui", + "//flutter/testing", + "//flutter/third_party/rapidjson", + ] +} + +source_set("pointer") { + testonly = true + + sources = [ "mock_injector_registry.h" ] + + deps = [ + "${fuchsia_sdk}/pkg/sys_cpp_testing", + "//flutter/lib/ui", + "//flutter/testing", + "//flutter/third_party/rapidjson", + ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/focuser.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/focuser.h new file mode 100644 index 0000000000000000000000000000000000000000..06e7da792ab1057505f9fee1501023229baccdbc --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/focuser.h @@ -0,0 +1,51 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_FOCUSER_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_FOCUSER_H_ + +#include +#include + +#include + +#include "flutter/fml/logging.h" + +using Focuser = fuchsia::ui::views::Focuser; + +namespace flutter_runner::testing { + +class FakeFocuser : public fuchsia::ui::views::testing::Focuser_TestBase { + public: + bool request_focus_called() const { return request_focus_called_; } + + void fail_request_focus(bool fail_request = true) { + fail_request_focus_ = fail_request; + } + + private: + void RequestFocus(fuchsia::ui::views::ViewRef view_ref, + RequestFocusCallback callback) override { + request_focus_called_ = true; + auto result = + fail_request_focus_ + ? fuchsia::ui::views::Focuser_RequestFocus_Result::WithErr( + fuchsia::ui::views::Error::DENIED) + : fuchsia::ui::views::Focuser_RequestFocus_Result::WithResponse( + fuchsia::ui::views::Focuser_RequestFocus_Response()); + callback(std::move(result)); + } + + void NotImplemented_(const std::string& name) { + FML_LOG(FATAL) << "flutter_runner::Testing::FakeFocuser does not implement " + << name; + } + + bool request_focus_called_ = false; + bool fail_request_focus_ = false; +}; + +} // namespace flutter_runner::testing + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_FOCUSER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/mock_injector_registry.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/mock_injector_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..37f7d478ed328c63d53f4750a14ed1809642642f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/mock_injector_registry.h @@ -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. + +#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_MOCK_INJECTOR_REGISTRY_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_MOCK_INJECTOR_REGISTRY_H_ + +#include +#include + +#include + +namespace flutter_runner::testing { + +// A test stub to act as the protocol server. A test can control what is sent +// back by this server implementation, via the ScheduleCallback call. +class MockInjectorRegistry : public fuchsia::ui::pointerinjector::Registry, + public fuchsia::ui::pointerinjector::Device { + public: + explicit MockInjectorRegistry( + fidl::InterfaceRequest registry) + : registry_(this, std::move(registry)) {} + + // |fuchsia.ui.pointerinjector.Registry.Register|. + void Register( + fuchsia::ui::pointerinjector::Config config, + fidl::InterfaceRequest injector, + RegisterCallback callback) override { + num_register_calls_++; + const uint32_t id = next_id_++; + + auto [it, success] = bindings_.try_emplace(id, this, std::move(injector)); + + it->second.set_error_handler( + [this, id](zx_status_t status) { bindings_.erase(id); }); + + config_ = std::move(config); + + callback(); + } + + // |fuchsia.ui.pointerinjector.Device.Inject|. + void Inject(std::vector events, + InjectCallback callback) override { + num_events_received_ += events.size(); + + for (auto& event : events) { + events_.push_back(std::move(event)); + } + + callback(); + } + + void ClearBindings() { bindings_.clear(); } + + // Returns the |fuchsia::ui::pointerinjector::Config| received in the last + // |Register(...)| call. + const fuchsia::ui::pointerinjector::Config& config() const { return config_; } + + // Returns all the |fuchsia::ui::pointerinjector::Event|s received from the + // |Inject(...)| calls. + const std::vector& events() const { + return events_; + } + + uint32_t num_register_calls() { return num_register_calls_; } + + size_t num_registered() { return bindings_.size(); } + + uint32_t num_events_received() const { return num_events_received_; } + + private: + uint32_t next_id_ = 0; + + uint32_t num_events_received_ = 0; + + uint32_t num_register_calls_ = 0; + + fuchsia::ui::pointerinjector::Config config_; + + std::vector events_; + + std::unordered_map> + bindings_; + + fidl::Binding registry_; + + FML_DISALLOW_COPY_AND_ASSIGN(MockInjectorRegistry); +}; +} // namespace flutter_runner::testing + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_MOCK_INJECTOR_REGISTRY_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/mouse_source.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/mouse_source.h new file mode 100644 index 0000000000000000000000000000000000000000..e86c7cc9eebd85c0e5494e2261f981e348491090 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/mouse_source.h @@ -0,0 +1,37 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_MOUSE_SOURCE_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_MOUSE_SOURCE_H_ + +#include + +#include "flutter/fml/logging.h" + +namespace flutter_runner::testing { + +// A test stub to act as the protocol server. A test can control what is sent +// back by this server implementation, via the ScheduleCallback call. +class FakeMouseSource : public fuchsia::ui::pointer::MouseSource { + public: + // |fuchsia.ui.pointer.MouseSource| + void Watch(MouseSource::WatchCallback callback) override { + callback_ = std::move(callback); + } + + // Have the server issue events to the client's hanging-get Watch call. + void ScheduleCallback(std::vector events) { + FML_CHECK(callback_) << "require a valid WatchCallback"; + callback_(std::move(events)); + } + + private: + // Client-side logic to invoke on Watch() call's return. A test triggers it + // with ScheduleCallback(). + MouseSource::WatchCallback callback_; +}; + +} // namespace flutter_runner::testing + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_MOUSE_SOURCE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/platform_message.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/platform_message.h new file mode 100644 index 0000000000000000000000000000000000000000..f39f3513ba81a48ce1d726cda2b652a131783d2d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/platform_message.h @@ -0,0 +1,65 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_PLATFORM_MESSAGE_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_PLATFORM_MESSAGE_H_ + +#include +#include + +#include "flutter/lib/ui/window/platform_message.h" +#include "third_party/rapidjson/include/rapidjson/document.h" + +using PlatformMessageResponse = flutter::PlatformMessageResponse; +using PlatformMessage = flutter::PlatformMessage; + +namespace flutter_runner::testing { + +class FakePlatformMessageResponse : public PlatformMessageResponse { + public: + static fml::RefPtr Create() { + return fml::AdoptRef(new FakePlatformMessageResponse()); + } + + void ExpectCompleted(std::string expected) { + EXPECT_TRUE(is_complete_); + if (is_complete_) { + EXPECT_EQ(expected, response_); + } + } + + bool IsCompleted() { return is_complete_; } + + std::unique_ptr WithMessage(std::string channel, + std::string message) { + return std::make_unique( + channel, + fml::MallocMapping::Copy(message.c_str(), + message.c_str() + message.size()), + fml::RefPtr(this)); + } + + void Complete(std::unique_ptr data) override { + response_ = + std::string(data->GetMapping(), data->GetMapping() + data->GetSize()); + FinalizeComplete(); + }; + + void CompleteEmpty() override { FinalizeComplete(); }; + + private: + // Private constructors. + FakePlatformMessageResponse() {} + + void FinalizeComplete() { + EXPECT_FALSE(std::exchange(is_complete_, true)) + << "Platform message responses can only be completed once!"; + } + + std::string response_; +}; + +} // namespace flutter_runner::testing + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_PLATFORM_MESSAGE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/scenic/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/scenic/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..d8ac33b6b0522e2d8c2e047bac206b956934de7e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/scenic/BUILD.gn @@ -0,0 +1,29 @@ +# 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. + +assert(is_fuchsia) + +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") + +source_set("scenic") { + testonly = true + + sources = [ + "fake_flatland.cc", + "fake_flatland.h", + "fake_flatland_types.cc", + "fake_flatland_types.h", + ] + + public_deps = [ + "${fuchsia_sdk}/fidl/fuchsia.images", + "${fuchsia_sdk}/fidl/fuchsia.scenic.scheduling", + "${fuchsia_sdk}/fidl/fuchsia.ui.composition", + "${fuchsia_sdk}/fidl/fuchsia.ui.views", + "${fuchsia_sdk}/pkg/async-cpp", + "${fuchsia_sdk}/pkg/async-testing", + "${fuchsia_sdk}/pkg/fidl_cpp", + "//flutter/fml", + ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_flatland.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_flatland.cc new file mode 100644 index 0000000000000000000000000000000000000000..efdd10286f72efb4d7254f0588be78a9fb7cb45a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_flatland.cc @@ -0,0 +1,965 @@ +// 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 "fake_flatland.h" + +#include + +#include // For std::remove_if +#include + +#include "flutter/fml/logging.h" + +namespace flutter_runner::testing { + +FakeFlatland::FakeFlatland() + : allocator_binding_(this), + flatland_binding_(this), + present_handler_([](auto args) {}) {} + +FakeFlatland::~FakeFlatland() = default; + +fuchsia::ui::composition::AllocatorHandle FakeFlatland::ConnectAllocator( + async_dispatcher_t* dispatcher) { + FML_CHECK(!allocator_binding_.is_bound()); + + fuchsia::ui::composition::AllocatorHandle allocator; + allocator_binding_.Bind(allocator.NewRequest(), dispatcher); + + return allocator; +} + +fuchsia::ui::composition::FlatlandHandle FakeFlatland::ConnectFlatland( + async_dispatcher_t* dispatcher) { + FML_CHECK(!flatland_binding_.is_bound()); + + fuchsia::ui::composition::FlatlandHandle flatland; + flatland_binding_.Bind(flatland.NewRequest(), dispatcher); + + return flatland; +} + +void FakeFlatland::Disconnect(fuchsia::ui::composition::FlatlandError error) { + flatland_binding_.events().OnError(error); + flatland_binding_.Unbind(); + allocator_binding_ + .Unbind(); // TODO(fxb/85619): Does the real Scenic unbind this when + // Flatland has an error? Or is it independent? +} + +void FakeFlatland::SetPresentHandler(PresentHandler present_handler) { + present_handler_ = + present_handler ? std::move(present_handler) : [](auto args) {}; +} + +void FakeFlatland::FireOnNextFrameBeginEvent( + fuchsia::ui::composition::OnNextFrameBeginValues + on_next_frame_begin_values) { + flatland_binding_.events().OnNextFrameBegin( + std::move(on_next_frame_begin_values)); +} + +void FakeFlatland::FireOnFramePresentedEvent( + fuchsia::scenic::scheduling::FramePresentedInfo frame_presented_info) { + flatland_binding_.events().OnFramePresented(std::move(frame_presented_info)); +} + +void FakeFlatland::NotImplemented_(const std::string& name) { + FML_LOG(FATAL) << "FakeFlatland does not implement " << name; +} + +void FakeFlatland::RegisterBufferCollection( + fuchsia::ui::composition::RegisterBufferCollectionArgs args, + RegisterBufferCollectionCallback callback) { + auto [export_token_koid, _] = GetKoids(args.export_token()); + + // Callers must not set both. + ZX_ASSERT(!args.has_buffer_collection_token2() || + !args.has_buffer_collection_token()); + fuchsia::sysmem2::BufferCollectionTokenHandle sysmem_token; + if (args.has_buffer_collection_token2()) { + sysmem_token = std::move(*args.mutable_buffer_collection_token2()); + } else { + sysmem_token = fuchsia::sysmem2::BufferCollectionTokenHandle( + args.mutable_buffer_collection_token()->TakeChannel()); + } + + auto [__, emplace_binding_success] = + graph_bindings_.buffer_collections.emplace( + export_token_koid, + BufferCollectionBinding{ + .export_token = std::move(*args.mutable_export_token()), + .sysmem_token = std::move(sysmem_token), + .usage = args.usage(), + }); + // TODO(fxb/85619): Disconnect the Allocator here + FML_CHECK(emplace_binding_success) + << "FakeFlatland::RegisterBufferCollection: BufferCollection already " + "exists with koid " + << export_token_koid; +} + +void FakeFlatland::Present(fuchsia::ui::composition::PresentArgs args) { + // Each FIDL call between this `Present()` and the last one mutated the + // `pending_graph_` independently of the `current_graph_`. Only the + // `current_graph_` is visible externally in the test. + // + // `Present()` updates the current graph with a deep clone of the pending one. + current_graph_ = pending_graph_.Clone(); + + present_handler_(std::move(args)); +} + +void FakeFlatland::CreateView( + fuchsia::ui::views::ViewCreationToken token, + fidl::InterfaceRequest + parent_viewport_watcher) { + CreateView2(std::move(token), fuchsia::ui::views::ViewIdentityOnCreation{}, + fuchsia::ui::composition::ViewBoundProtocols{}, + std::move(parent_viewport_watcher)); +} + +void FakeFlatland::CreateView2( + fuchsia::ui::views::ViewCreationToken token, + fuchsia::ui::views::ViewIdentityOnCreation view_identity, + fuchsia::ui::composition::ViewBoundProtocols view_protocols, + fidl::InterfaceRequest + parent_viewport_watcher) { + // TODO(fxb/85619): Handle a 2nd CreateView call + FML_CHECK(!pending_graph_.view.has_value()); + FML_CHECK(!graph_bindings_.viewport_watcher.has_value()); + + auto view_token_koids = GetKoids(token); + auto view_ref_koids = GetKoids(view_identity.view_ref); + auto view_ref_control_koids = GetKoids(view_identity.view_ref_control); + FML_CHECK(view_ref_koids.first == view_ref_control_koids.second); + FML_CHECK(view_ref_koids.second == view_ref_control_koids.first); + + pending_graph_.view.emplace(FakeView{ + .view_token = view_token_koids.first, + .view_ref = view_ref_koids.first, + .view_ref_control = view_ref_control_koids.first, + .view_ref_focused = + view_protocols.has_view_ref_focused() + ? GetKoids(view_protocols.view_ref_focused()).first + : zx_koid_t{}, + .focuser = view_protocols.has_view_focuser() + ? GetKoids(view_protocols.view_focuser()).first + : zx_koid_t{}, + .touch_source = view_protocols.has_touch_source() + ? GetKoids(view_protocols.touch_source()).first + : zx_koid_t{}, + .mouse_source = view_protocols.has_mouse_source() + ? GetKoids(view_protocols.mouse_source()).first + : zx_koid_t{}, + .parent_viewport_watcher = GetKoids(parent_viewport_watcher).first, + }); + graph_bindings_.viewport_watcher.emplace( + view_token_koids.first, + ParentViewportWatcher( + std::move(token), std::move(view_identity), std::move(view_protocols), + std::move(parent_viewport_watcher), flatland_binding_.dispatcher())); +} + +void FakeFlatland::CreateTransform( + fuchsia::ui::composition::TransformId transform_id) { + if (transform_id.value == 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) + << "FakeFlatland::CreateTransform: TransformId 0 is invalid."; + return; + } + if (pending_graph_.transform_map.count(transform_id.value) != 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::CreateTransform: TransformId " + << transform_id.value << " is already in use."; + return; + } + + auto [emplaced_transform, emplace_success] = + pending_graph_.transform_map.emplace( + transform_id.value, std::make_shared(FakeTransform{ + .id = transform_id, + })); + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(emplace_success) + << "FakeFlatland::CreateTransform: Internal error (transform_map) adding " + "transform with id: " + << transform_id.value; + + auto [_, emplace_parent_success] = parents_map_.emplace( + transform_id.value, + std::make_pair(std::weak_ptr(), + std::weak_ptr(emplaced_transform->second))); + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(emplace_parent_success) + << "FakeFlatland::CreateTransform: Internal error (parent_map) adding " + "transform with id: " + << transform_id.value; +} + +void FakeFlatland::SetTranslation( + fuchsia::ui::composition::TransformId transform_id, + fuchsia::math::Vec translation) { + if (transform_id.value == 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) + << "FakeFlatland::SetTranslation: TransformId 0 is invalid."; + return; + } + + auto found_transform = pending_graph_.transform_map.find(transform_id.value); + if (found_transform == pending_graph_.transform_map.end()) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::SetTranslation: TransformId " + << transform_id.value << " does not exist."; + return; + } + + auto& transform = found_transform->second; + FML_CHECK(transform); + transform->translation = translation; +} + +void FakeFlatland::SetScale(fuchsia::ui::composition::TransformId transform_id, + fuchsia::math::VecF scale) { + if (transform_id.value == 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::SetScale: TransformId 0 is invalid."; + return; + } + + auto found_transform = pending_graph_.transform_map.find(transform_id.value); + if (found_transform == pending_graph_.transform_map.end()) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::SetScale: TransformId " + << transform_id.value << " does not exist."; + return; + } + + if (scale.x == 0.f || scale.y == 0.f) { + FML_CHECK(false) << "SetScale failed, zero values not allowed (" << scale.x + << ", " << scale.y << " )."; + return; + } + + if (isinf(scale.x) || isinf(scale.y) || isnan(scale.x) || isnan(scale.y)) { + FML_CHECK(false) << "SetScale failed, invalid scale values (" << scale.x + << ", " << scale.y << " )."; + return; + } + + auto& transform = found_transform->second; + FML_CHECK(transform); + transform->scale = scale; +} + +void FakeFlatland::SetOrientation( + fuchsia::ui::composition::TransformId transform_id, + fuchsia::ui::composition::Orientation orientation) { + if (transform_id.value == 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) + << "FakeFlatland::SetOrientation: TransformId 0 is invalid."; + return; + } + + auto found_transform = pending_graph_.transform_map.find(transform_id.value); + if (found_transform == pending_graph_.transform_map.end()) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::SetOrientation: TransformId " + << transform_id.value << " does not exist."; + return; + } + + auto& transform = found_transform->second; + FML_CHECK(transform); + transform->orientation = orientation; +} + +void FakeFlatland::SetOpacity( + fuchsia::ui::composition::TransformId transform_id, + float value) { + if (transform_id.value == 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::SetOpacity: TransformId 0 is invalid."; + return; + } + + auto found_transform = pending_graph_.transform_map.find(transform_id.value); + if (found_transform == pending_graph_.transform_map.end()) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::SetOpacity: TransformId " + << transform_id.value << " does not exist."; + return; + } + + if (value < 0.f || value > 1.f) { + FML_CHECK(false) << "FakeFlatland::SetOpacity: Invalid opacity value."; + } + + auto& transform = found_transform->second; + FML_CHECK(transform); + transform->opacity = value; +} + +void FakeFlatland::SetClipBoundary( + fuchsia::ui::composition::TransformId transform_id, + std::unique_ptr bounds) { + if (transform_id.value == 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) + << "FakeFlatland::SetClipBoundary: TransformId 0 is invalid."; + return; + } + + auto found_transform = pending_graph_.transform_map.find(transform_id.value); + if (found_transform == pending_graph_.transform_map.end()) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::SetClipBoundary: TransformId " + << transform_id.value << " does not exist."; + return; + } + + auto& transform = found_transform->second; + FML_CHECK(transform); + if (bounds == nullptr) { + transform->clip_bounds = std::nullopt; + return; + } + + transform->clip_bounds = *bounds.get(); +} + +// TODO(fxbug.dev/89111): Re-enable once SDK rolls. +// void FakeFlatland::SetImageOpacity( +// fuchsia::ui::composition::ContentId content_id, +// float opacity) { +// if (content_id.value == 0) { +// // TODO(fxb/85619): Raise a FlatlandError here +// FML_CHECK(false) +// << "FakeFlatland::SetImageOpacity: ContentId 0 is invalid."; +// return; +// } + +// auto found_content = pending_graph_.content_map.find(image_id.value); +// if (found_content == pending_graph_.content_map.end()) { +// // TODO(fxb/85619): Raise a FlatlandError here +// FML_CHECK(false) << "FakeFlatland::SetImageOpacity: ContentId " +// << image_id.value << " does not exist."; +// return; +// } + +// auto& content = found_content->second; +// FML_CHECK(content); +// FakeImage* image = std::get_if(content.get()); +// if (image == nullptr) { +// // TODO(fxb/85619): Raise a FlatlandError here +// FML_CHECK(false) << "FakeFlatland::SetImageOpacity: ContentId " +// << image_id.value << " is not an Image."; +// return; +// } + +// image->opacity = opacity; +// } + +void FakeFlatland::AddChild( + fuchsia::ui::composition::TransformId parent_transform_id, + fuchsia::ui::composition::TransformId child_transform_id) { + if (parent_transform_id.value == 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) + << "FakeFlatland::AddChild: Parent TransformId 0 is invalid."; + return; + } + if (child_transform_id.value == 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) + << "FakeFlatland::AddChild: Child TransformId 0 is invalid."; + return; + } + + auto found_parent = + pending_graph_.transform_map.find(parent_transform_id.value); + if (found_parent == pending_graph_.transform_map.end()) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::AddChild: Parent TransformId " + << parent_transform_id.value << " does not exist."; + return; + } + auto found_child = + pending_graph_.transform_map.find(child_transform_id.value); + if (found_child == pending_graph_.transform_map.end()) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::AddChild: Child TransformId " + << child_transform_id.value << " does not exist."; + return; + } + auto found_child_old_parent = parents_map_.find(child_transform_id.value); + if (found_child_old_parent == parents_map_.end()) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) + << "FakeFlatland::AddChild: Internal error - Child TransformId " + << child_transform_id.value << " is not in parents_map."; + return; + } + if (found_child_old_parent->second.second.expired()) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) + << "FakeFlatland::AddChild: Internal error - Child TransformId " + << child_transform_id.value << " is expired in parents_map."; + return; + } + + auto& child = found_child->second; + auto& new_parent = found_parent->second; + new_parent->children.push_back(child); + if (auto old_parent = found_child_old_parent->second.first.lock()) { + old_parent->children.erase(std::remove_if( + old_parent->children.begin(), old_parent->children.end(), + [&child](const auto& transform) { return transform == child; })); + } + found_child_old_parent->second.first = std::weak_ptr(new_parent); +} + +void FakeFlatland::RemoveChild( + fuchsia::ui::composition::TransformId parent_transform_id, + fuchsia::ui::composition::TransformId child_transform_id) { + if (parent_transform_id.value == 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) + << "FakeFlatland::RemoveChild: Parent TransformId 0 is invalid."; + return; + } + if (child_transform_id.value == 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) + << "FakeFlatland::RemoveChild: Child TransformId 0 is invalid."; + return; + } + + auto found_child = + pending_graph_.transform_map.find(child_transform_id.value); + if (found_child == pending_graph_.transform_map.end()) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::RemoveChild: Child TransformId " + << child_transform_id.value << " does not exist."; + return; + } + + auto found_parent = + pending_graph_.transform_map.find(parent_transform_id.value); + if (found_parent == pending_graph_.transform_map.end()) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::RemoveChild: Parent TransformId " + << parent_transform_id.value << " does not exist."; + return; + } + + auto found_child_parent = parents_map_.find(child_transform_id.value); + if (found_child_parent == parents_map_.end()) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) + << "FakeFlatland::RemoveChild: Internal error - Child TransformId " + << child_transform_id.value << " is not in parents_map."; + return; + } + if (found_child_parent->second.second.expired()) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) + << "FakeFlatland::RemoveChild: Internal error - Child TransformId " + << child_transform_id.value << " is expired in parents_map."; + return; + } + if (found_child_parent->second.first.lock() != found_parent->second) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) + << "FakeFlatland::RemoveChild: Internal error - Child TransformId " + << child_transform_id.value << " is not a child of Parent TransformId " + << parent_transform_id.value << "."; + return; + } + + found_child_parent->second.first = std::weak_ptr(); + found_parent->second->children.erase(std::remove_if( + found_parent->second->children.begin(), + found_parent->second->children.end(), + [child_to_remove = found_child->second](const auto& child) { + return child == child_to_remove; + })); +} + +void FakeFlatland::SetContent( + fuchsia::ui::composition::TransformId transform_id, + fuchsia::ui::composition::ContentId content_id) { + if (transform_id.value == 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::SetContent: TransformId 0 is invalid."; + return; + } + + auto found_transform = pending_graph_.transform_map.find(transform_id.value); + if (found_transform == pending_graph_.transform_map.end()) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::SetContent: TransformId " + << transform_id.value << " does not exist."; + return; + } + + auto& transform = found_transform->second; + FML_CHECK(transform); + if (content_id.value == 0) { + transform->content.reset(); + return; + } + + auto found_content = pending_graph_.content_map.find(content_id.value); + if (found_content == pending_graph_.content_map.end()) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::SetContent: ContentId " + << content_id.value << " does not exist."; + return; + } + + auto& content = found_content->second; + FML_CHECK(content); + transform->content = content; +} + +void FakeFlatland::SetRootTransform( + fuchsia::ui::composition::TransformId transform_id) { + if (transform_id.value == 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) + << "FakeFlatland::SetRootTransform: TransformId 0 is invalid."; + return; + } + + auto found_new_root = pending_graph_.transform_map.find(transform_id.value); + if (found_new_root == pending_graph_.transform_map.end()) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::SetRootTransform: TransformId " + << transform_id.value << " does not exist."; + return; + } + + pending_graph_.root_transform = found_new_root->second; +} + +void FakeFlatland::CreateViewport( + fuchsia::ui::composition::ContentId viewport_id, + fuchsia::ui::views::ViewportCreationToken token, + fuchsia::ui::composition::ViewportProperties properties, + fidl::InterfaceRequest + child_view_watcher) { + if (viewport_id.value == 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::CreateViewport: ContentId 0 is invalid."; + return; + } + if (pending_graph_.content_map.count(viewport_id.value) != 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::CreateViewport: ContentId " + << viewport_id.value << " is already in use."; + return; + } + + auto viewport_token_koids = GetKoids(token.value); + auto [emplaced_viewport, emplace_success] = + pending_graph_.content_map.emplace( + viewport_id.value, + std::make_shared(FakeViewport{ + .id = viewport_id, + .viewport_properties = std::move(properties), + .viewport_token = viewport_token_koids.first, + .child_view_watcher = GetKoids(child_view_watcher).first, + })); + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(emplace_success) + << "FakeFlatland::CreateViewport: Internal error (content_map) adding " + "viewport with id: " + << viewport_id.value; + + auto [_, emplace_binding_success] = graph_bindings_.view_watchers.emplace( + viewport_token_koids.first, + ChildViewWatcher(std::move(token), std::move(child_view_watcher), + flatland_binding_.dispatcher())); + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(emplace_binding_success) + << "FakeFlatland::CreateViewport: Internal error (view_watcher) adding " + "viewport with id: " + << viewport_id.value; +} + +void FakeFlatland::CreateImage( + fuchsia::ui::composition::ContentId image_id, + fuchsia::ui::composition::BufferCollectionImportToken import_token, + uint32_t vmo_index, + fuchsia::ui::composition::ImageProperties properties) { + if (image_id.value == 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::CreateImage: ContentId 0 is invalid."; + return; + } + if (pending_graph_.content_map.count(image_id.value) != 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::CreateImage: ContentId " + << image_id.value << " is already in use."; + return; + } + + auto import_token_koids = GetKoids(import_token); + auto [emplaced_image, emplace_success] = pending_graph_.content_map.emplace( + image_id.value, std::make_shared(FakeImage{ + .id = image_id, + .image_properties = std::move(properties), + .import_token = import_token_koids.first, + .vmo_index = vmo_index, + })); + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(emplace_success) + << "FakeFlatland::CreateImage: Internal error (content_map) adding " + "image with id: " + << image_id.value; + + auto [_, emplace_binding_success] = graph_bindings_.images.emplace( + import_token_koids.first, ImageBinding{ + .import_token = std::move(import_token), + }); + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(emplace_binding_success) + << "FakeFlatland::CreateImage: Internal error (images_binding) adding " + "viewport with id: " + << image_id.value; +} + +void FakeFlatland::SetImageSampleRegion( + fuchsia::ui::composition::ContentId image_id, + fuchsia::math::RectF rect) { + if (image_id.value == 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) + << "FakeFlatland::SetImageSampleRegion: ContentId 0 is invalid."; + return; + } + + auto found_content = pending_graph_.content_map.find(image_id.value); + if (found_content == pending_graph_.content_map.end()) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::SetImageSampleRegion: ContentId " + << image_id.value << " does not exist."; + return; + } + + auto& content = found_content->second; + FML_CHECK(content); + FakeImage* image = std::get_if(content.get()); + if (image == nullptr) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::SetImageSampleRegion: ContentId " + << image_id.value << " is not an Image."; + return; + } + + image->sample_region = rect; +} + +void FakeFlatland::SetImageDestinationSize( + fuchsia::ui::composition::ContentId image_id, + fuchsia::math::SizeU size) { + if (image_id.value == 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) + << "FakeFlatland::SetImageDestinationSize: ContentId 0 is invalid."; + return; + } + + auto found_content = pending_graph_.content_map.find(image_id.value); + if (found_content == pending_graph_.content_map.end()) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::SetImageDestinationSize: ContentId " + << image_id.value << " does not exist."; + return; + } + + auto& content = found_content->second; + FML_CHECK(content); + FakeImage* image = std::get_if(content.get()); + if (image == nullptr) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::SetImageDestinationSize: ContentId " + << image_id.value << " is not an Image."; + return; + } + + image->destination_size = size; +} + +void FakeFlatland::SetImageBlendingFunction( + fuchsia::ui::composition::ContentId image_id, + fuchsia::ui::composition::BlendMode blend_mode) { + if (image_id.value == 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) + << "FakeFlatland::SetImageDestinationSize: ContentId 0 is invalid."; + return; + } + + auto found_content = pending_graph_.content_map.find(image_id.value); + if (found_content == pending_graph_.content_map.end()) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::SetImageDestinationSize: ContentId " + << image_id.value << " does not exist."; + return; + } + + auto& content = found_content->second; + FML_CHECK(content); + FakeImage* image = std::get_if(content.get()); + if (image == nullptr) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::SetImageDestinationSize: ContentId " + << image_id.value << " is not an Image."; + return; + } + + image->blend_mode = blend_mode; +} + +void FakeFlatland::SetViewportProperties( + fuchsia::ui::composition::ContentId viewport_id, + fuchsia::ui::composition::ViewportProperties properties) { + if (viewport_id.value == 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) + << "FakeFlatland::SetViewportProperties: ContentId 0 is invalid."; + return; + } + + auto found_content = pending_graph_.content_map.find(viewport_id.value); + if (found_content == pending_graph_.content_map.end()) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::SetViewportProperties: ContentId " + << viewport_id.value << " does not exist."; + return; + } + + auto& content = found_content->second; + FML_CHECK(content); + FakeViewport* viewport = std::get_if(content.get()); + if (viewport == nullptr) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::SetViewportProperties: ContentId " + << viewport_id.value << " is not a Viewport."; + return; + } + + viewport->viewport_properties = std::move(properties); +} + +void FakeFlatland::ReleaseTransform( + fuchsia::ui::composition::TransformId transform_id) { + if (transform_id.value == 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) + << "FakeFlatland::ReleaseTransform: TransformId 0 is invalid."; + return; + } + + size_t erased = pending_graph_.transform_map.erase(transform_id.value); + if (erased == 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::ReleaseTransform: TransformId " + << transform_id.value << " does not exist."; + } + + size_t parents_erased = parents_map_.erase(transform_id.value); + if (parents_erased == 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::ReleaseTransform: TransformId " + << transform_id.value << " does not exist in parents_map."; + } +} + +void FakeFlatland::ReleaseViewport( + fuchsia::ui::composition::ContentId viewport_id, + ReleaseViewportCallback callback) { + if (viewport_id.value == 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) + << "FakeFlatland::ReleaseViewport: ContentId 0 is invalid."; + return; + } + + auto found_content = pending_graph_.content_map.find(viewport_id.value); + if (found_content == pending_graph_.content_map.end()) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::ReleaseViewport: ContentId " + << viewport_id.value << " does not exist."; + return; + } + + auto& content = found_content->second; + FML_CHECK(content); + FakeViewport* viewport = std::get_if(content.get()); + if (viewport == nullptr) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::ReleaseViewport: ContentId " + << viewport_id.value << " is not a Viewport."; + return; + } + + pending_graph_.content_map.erase(found_content); +} + +void FakeFlatland::ReleaseImage(fuchsia::ui::composition::ContentId image_id) { + if (image_id.value == 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::ReleaseImage: ContentId 0 is invalid."; + return; + } + + auto found_content = pending_graph_.content_map.find(image_id.value); + if (found_content == pending_graph_.content_map.end()) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::ReleaseImage: ContentId " + << image_id.value << " does not exist."; + return; + } + + auto& content = found_content->second; + FML_CHECK(content); + FakeImage* image = std::get_if(content.get()); + if (image == nullptr) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::ReleaseImage: ContentId " + << image_id.value << " is not a Viewport."; + return; + } + + pending_graph_.content_map.erase(found_content); +} + +void FakeFlatland::SetHitRegions( + fuchsia::ui::composition::TransformId transform_id, + std::vector regions) { + if (transform_id.value == 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) + << "FakeFlatland::SetTranslation: TransformId 0 is invalid."; + return; + } + + auto found_transform = pending_graph_.transform_map.find(transform_id.value); + if (found_transform == pending_graph_.transform_map.end()) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::SetTranslation: TransformId " + << transform_id.value << " does not exist."; + return; + } + + auto& transform = found_transform->second; + FML_CHECK(transform); + transform->hit_regions = std::move(regions); +} + +void FakeFlatland::SetInfiniteHitRegion( + fuchsia::ui::composition::TransformId transform_id, + fuchsia::ui::composition::HitTestInteraction hit_test) { + if (transform_id.value == 0) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) + << "FakeFlatland::SetTranslation: TransformId 0 is invalid."; + return; + } + + auto found_transform = pending_graph_.transform_map.find(transform_id.value); + if (found_transform == pending_graph_.transform_map.end()) { + // TODO(fxb/85619): Raise a FlatlandError here + FML_CHECK(false) << "FakeFlatland::SetTranslation: TransformId " + << transform_id.value << " does not exist."; + return; + } + + auto& transform = found_transform->second; + ZX_ASSERT(transform); + transform->hit_regions = {kInfiniteHitRegion}; +} + +void FakeFlatland::Clear() { + parents_map_.clear(); + pending_graph_.Clear(); +} + +void FakeFlatland::SetDebugName(std::string debug_name) { + debug_name_ = std::move(debug_name); +} + +FakeFlatland::ParentViewportWatcher::ParentViewportWatcher( + fuchsia::ui::views::ViewCreationToken view_token, + fuchsia::ui::views::ViewIdentityOnCreation view_identity, + fuchsia::ui::composition::ViewBoundProtocols view_protocols, + fidl::InterfaceRequest + parent_viewport_watcher, + async_dispatcher_t* dispatcher) + : view_token(std::move(view_token)), + view_identity(std::move(view_identity)), + view_protocols(std::move(view_protocols)), + parent_viewport_watcher(this, + std::move(parent_viewport_watcher), + dispatcher) {} + +FakeFlatland::ParentViewportWatcher::ParentViewportWatcher( + ParentViewportWatcher&& other) + : view_token(std::move(other.view_token)), + view_identity(std::move(other.view_identity)), + view_protocols(std::move(other.view_protocols)), + parent_viewport_watcher(this, + other.parent_viewport_watcher.Unbind(), + other.parent_viewport_watcher.dispatcher()) {} + +FakeFlatland::ParentViewportWatcher::~ParentViewportWatcher() = default; + +void FakeFlatland::ParentViewportWatcher::NotImplemented_( + const std::string& name) { + FML_LOG(FATAL) << "FakeFlatland::ParentViewportWatcher does not implement " + << name; +} + +void FakeFlatland::ParentViewportWatcher::GetLayout( + GetLayoutCallback callback) { + NotImplemented_("GetLayout"); +} + +void FakeFlatland::ParentViewportWatcher::GetStatus( + GetStatusCallback callback) { + NotImplemented_("GetStatus"); +} + +FakeFlatland::ChildViewWatcher::ChildViewWatcher( + fuchsia::ui::views::ViewportCreationToken viewport_token, + fidl::InterfaceRequest + child_view_watcher, + async_dispatcher_t* dispatcher) + : viewport_token(std::move(viewport_token)), + child_view_watcher(this, std::move(child_view_watcher), dispatcher) {} + +FakeFlatland::ChildViewWatcher::ChildViewWatcher(ChildViewWatcher&& other) + : viewport_token(std::move(other.viewport_token)), + child_view_watcher(this, + other.child_view_watcher.Unbind(), + other.child_view_watcher.dispatcher()) {} + +FakeFlatland::ChildViewWatcher::~ChildViewWatcher() = default; + +void FakeFlatland::ChildViewWatcher::NotImplemented_(const std::string& name) { + FML_LOG(FATAL) << "FakeFlatland::ChildViewWatcher does not implement " + << name; +} + +void FakeFlatland::ChildViewWatcher::GetStatus(GetStatusCallback callback) { + NotImplemented_("GetStatus"); +} + +} // namespace flutter_runner::testing diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_flatland.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_flatland.h new file mode 100644 index 0000000000000000000000000000000000000000..cdc188bc213ec0748891d5da2a53117c6485f6c1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_flatland.h @@ -0,0 +1,349 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_SCENIC_FAKE_FLATLAND_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_SCENIC_FAKE_FLATLAND_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/macros.h" + +#include "fake_flatland_types.h" + +namespace flutter_runner::testing { + +// A lightweight fake implementation of the Flatland API. +// +// The fake has no side effects besides mutating its own internal state +// according to the rules of interacting with the Flatland API. It makes that +// internal state available for inspection by a test. +// +// Thus it allows tests to do a few things that would be difficult using either +// a mock implementation or the real implementation: +// + It allows the user to hook `Present` invocations and respond with +// stubbed-out `FuturePresentationTimes`, but more crucially it mimics the +// real Flatland behavior of only processing commands when a `Present` is +// invoked. +// + It allows the user to inspect a snapshot of the scene graph at any moment +// in time, via the `SceneGraph()` accessor. +// + It stores the various Flatland transforms and content generated by +// commands into a std::unordered_map, and also correctly manages the +// transform and content lifetimes via reference counting. This allows a +// given transform or content to stay alive if its parent still holds a +// reference to it, in the same way the real Flatland implementation would. +// + The resources returned by `SceneGraph()` that the test uses for +// inspection are decoupled from the resources managed internally by the +// `FakeFlatland` itself -- they are a snapshot of the scene graph at that +// moment in time, with all snapshot state being cloned from the underlying +// scene graph state. This allows the `FakeFlatland` and test to naturally +// use `shared_ptr` for reference counting and mimic the real Flatland +// behavior exactly, instead of an awkward index-based API. +// + TODO(fxb/85619): Allow injecting {touch,mouse,focus,views} events using +// the ViewBoundProtocols and {ParentViewport,ChildView}Watcher. +// + TODO(fxb/85619): Error handling / flatland disconnection is still WIP. +// FakeFlatland will likely generate a CHECK in any place where the real +// Flatland would disconnect or send a FlatlandError. +// +// The fake deliberately does not attempt to handle certain aspects of the real +// Flatland implemntation which are complex or burdensome to implement: +// +Rendering/interacting with Vulkan in any way +// +Cross-flatland links between Views and Viewports. +class FakeFlatland + : public fuchsia::ui::composition::testing::Allocator_TestBase, + public fuchsia::ui::composition::testing::Flatland_TestBase { + public: + using PresentHandler = + std::function; + + FakeFlatland(); + ~FakeFlatland() override; + + bool is_allocator_connected() const { return allocator_binding_.is_bound(); } + + bool is_flatland_connected() const { return flatland_binding_.is_bound(); } + + const std::string& debug_name() const { return debug_name_; } + + const FakeGraph& graph() { return current_graph_; } + + // Bind this instance's Flatland FIDL channel to the `dispatcher` and allow + // processing of incoming FIDL requests. + // + // This can only be called once. + fuchsia::ui::composition::AllocatorHandle ConnectAllocator( + async_dispatcher_t* dispatcher = nullptr); + + // Bind this instance's Allocator FIDL channel to the `dispatcher` and allow + // processing of incoming FIDL requests. + // + // This can only be called once. + fuchsia::ui::composition::FlatlandHandle ConnectFlatland( + async_dispatcher_t* dispatcher = nullptr); + + // Disconnect the Flatland's FIDL channel with an error. + // TODO(fxb/85619): Call this internally upon command error, instead of + // CHECK'ing. + void Disconnect(fuchsia::ui::composition::FlatlandError error); + + // Set a handler for `Present`-related FIDL calls' return values. + void SetPresentHandler(PresentHandler present_handler); + + // Fire an `OnNextFrameBegin` event. Call this first after a `Present` in + // order to give additional present tokens to the client and simulate scenic's + // normal event flow. + void FireOnNextFrameBeginEvent( + fuchsia::ui::composition::OnNextFrameBeginValues + on_next_frame_begin_values); + + // Fire an `OnFramePresented` event. Call this second after a `Present` in + // order to inform the client of retured frames and simulate scenic's normal + // event flow. + void FireOnFramePresentedEvent( + fuchsia::scenic::scheduling::FramePresentedInfo frame_presented_info); + + private: + struct ParentViewportWatcher : public fuchsia::ui::composition::testing:: + ParentViewportWatcher_TestBase { + public: + ParentViewportWatcher( + fuchsia::ui::views::ViewCreationToken view_token, + fuchsia::ui::views::ViewIdentityOnCreation view_identity, + fuchsia::ui::composition::ViewBoundProtocols view_protocols, + fidl::InterfaceRequest + parent_viewport_watcher, + async_dispatcher_t* dispatcher); + ParentViewportWatcher(ParentViewportWatcher&& other); + ~ParentViewportWatcher() override; + + // |fuchsia::ui::composition::testing::ParentViewportWatcher_TestBase| + void NotImplemented_(const std::string& name) override; + + // |fuchsia::ui::composition::ParentViewportWatcher| + void GetLayout(GetLayoutCallback callback) override; + + // |fuchsia::ui::composition::ParentViewportWatcher| + void GetStatus(GetStatusCallback callback) override; + + fuchsia::ui::views::ViewCreationToken view_token; + fuchsia::ui::views::ViewIdentityOnCreation view_identity; + fuchsia::ui::composition::ViewBoundProtocols view_protocols; + fidl::Binding + parent_viewport_watcher; + }; + + struct ChildViewWatcher + : public fuchsia::ui::composition::testing::ChildViewWatcher_TestBase { + public: + ChildViewWatcher( + fuchsia::ui::views::ViewportCreationToken viewport_token, + fidl::InterfaceRequest + child_view_watcher, + async_dispatcher_t* dispatcher); + ChildViewWatcher(ChildViewWatcher&& other); + ~ChildViewWatcher() override; + + // |fuchsia::ui::composition::testing::ChildViewWatcher_TestBase| + void NotImplemented_(const std::string& name) override; + + // |fuchsia::ui::composition::ChildViewWatcher| + void GetStatus(GetStatusCallback callback) override; + + fuchsia::ui::views::ViewportCreationToken viewport_token; + fidl::Binding + child_view_watcher; + }; + + struct ImageBinding { + fuchsia::ui::composition::BufferCollectionImportToken import_token; + }; + + struct BufferCollectionBinding { + fuchsia::ui::composition::BufferCollectionExportToken export_token; + fuchsia::sysmem2::BufferCollectionTokenHandle sysmem_token; + + fuchsia::ui::composition::RegisterBufferCollectionUsage usage; + }; + + struct GraphBindings { + std::optional> viewport_watcher; + std::unordered_map view_watchers; + std::unordered_map images; + std::unordered_map buffer_collections; + }; + + // |fuchsia::ui::composition::testing::Allocator_TestBase| + // |fuchsia::ui::composition::testing::Flatland_TestBase| + void NotImplemented_(const std::string& name) override; + + // |fuchsia::ui::composition::testing::Allocator| + void RegisterBufferCollection( + fuchsia::ui::composition::RegisterBufferCollectionArgs args, + RegisterBufferCollectionCallback callback) override; + + // |fuchsia::ui::composition::Flatland| + void Present(fuchsia::ui::composition::PresentArgs args) override; + + // |fuchsia::ui::composition::Flatland| + void CreateView( + fuchsia::ui::views::ViewCreationToken token, + fidl::InterfaceRequest + parent_viewport_watcher) override; + + // |fuchsia::ui::composition::Flatland| + void CreateView2( + fuchsia::ui::views::ViewCreationToken token, + fuchsia::ui::views::ViewIdentityOnCreation view_identity, + fuchsia::ui::composition::ViewBoundProtocols view_protocols, + fidl::InterfaceRequest + parent_viewport_watcher) override; + + // |fuchsia::ui::composition::Flatland| + void CreateTransform( + fuchsia::ui::composition::TransformId transform_id) override; + + // |fuchsia::ui::composition::Flatland| + void SetTranslation(fuchsia::ui::composition::TransformId transform_id, + fuchsia::math::Vec translation) override; + + // |fuchsia::ui::composition::Flatland| + void SetScale(fuchsia::ui::composition::TransformId transform_id, + fuchsia::math::VecF scale) override; + + // |fuchsia::ui::composition::Flatland| + void SetOrientation( + fuchsia::ui::composition::TransformId transform_id, + fuchsia::ui::composition::Orientation orientation) override; + + // |fuchsia::ui::composition::Flatland| + void SetOpacity(fuchsia::ui::composition::TransformId transform_id, + float value) override; + + // |fuchsia::ui::composition::Flatland| + void SetClipBoundary(fuchsia::ui::composition::TransformId transform_id, + std::unique_ptr bounds) override; + + // TODO(fxbug.dev/89111): Re-enable once SDK rolls. + // // |fuchsia::ui::composition::Flatland| + // void SetImageOpacity(fuchsia::ui::composition::ContentId image_id, + // float opacity) override; + + // |fuchsia::ui::composition::Flatland| + void AddChild( + fuchsia::ui::composition::TransformId parent_transform_id, + fuchsia::ui::composition::TransformId child_transform_id) override; + + // |fuchsia::ui::composition::Flatland| + void RemoveChild( + fuchsia::ui::composition::TransformId parent_transform_id, + fuchsia::ui::composition::TransformId child_transform_id) override; + + // |fuchsia::ui::composition::Flatland| + void SetContent(fuchsia::ui::composition::TransformId transform_id, + fuchsia::ui::composition::ContentId content_id) override; + + // |fuchsia::ui::composition::Flatland| + void SetRootTransform( + fuchsia::ui::composition::TransformId transform_id) override; + + // |fuchsia::ui::composition::Flatland| + void CreateViewport( + fuchsia::ui::composition::ContentId viewport_id, + fuchsia::ui::views::ViewportCreationToken token, + fuchsia::ui::composition::ViewportProperties properties, + fidl::InterfaceRequest + child_view_watcher) override; + + // |fuchsia::ui::composition::Flatland| + void CreateImage( + fuchsia::ui::composition::ContentId image_id, + fuchsia::ui::composition::BufferCollectionImportToken import_token, + uint32_t vmo_index, + fuchsia::ui::composition::ImageProperties properties) override; + + // |fuchsia::ui::composition::Flatland| + void SetImageSampleRegion(fuchsia::ui::composition::ContentId image_id, + fuchsia::math::RectF rect) override; + + // |fuchsia::ui::composition::Flatland| + void SetImageDestinationSize(fuchsia::ui::composition::ContentId image_id, + fuchsia::math::SizeU size) override; + + // |fuchsia::ui::composition::Flatland| + void SetImageBlendingFunction( + fuchsia::ui::composition::ContentId image_id, + fuchsia::ui::composition::BlendMode blend_mode) override; + + // |fuchsia::ui::composition::Flatland| + void SetViewportProperties( + fuchsia::ui::composition::ContentId viewport_id, + fuchsia::ui::composition::ViewportProperties properties) override; + + // |fuchsia::ui::composition::Flatland| + void ReleaseTransform( + fuchsia::ui::composition::TransformId transform_id) override; + + // |fuchsia::ui::composition::Flatland| + void ReleaseViewport(fuchsia::ui::composition::ContentId viewport_id, + ReleaseViewportCallback callback) override; + + // |fuchsia::ui::composition::Flatland| + void ReleaseImage(fuchsia::ui::composition::ContentId image_id) override; + + // |fuchsia::ui::composition::Flatland| + void SetHitRegions( + fuchsia::ui::composition::TransformId transform_id, + std::vector regions) override; + + // |fuchsia::ui::composition::Flatland| + void SetInfiniteHitRegion( + fuchsia::ui::composition::TransformId transform_id, + fuchsia::ui::composition::HitTestInteraction hit_test) override; + + // |fuchsia::ui::composition::Flatland| + void Clear() override; + + // |fuchsia::ui::composition::Flatland| + void SetDebugName(std::string debug_name) override; + + fidl::Binding allocator_binding_; + fidl::Binding flatland_binding_; + GraphBindings graph_bindings_; + PresentHandler present_handler_; + + FakeGraph pending_graph_; + FakeGraph current_graph_; + + // This map is used to cache parent refs for `AddChild` and `RemoveChild`. + // + // Ideally we would like to map weak(child) -> weak(parent), but std::weak_ptr + // cannot be the Key for an associative container. Instead we key on the raw + // parent pointer and store pair(weak(parent), weak(child)) in the map. + std::unordered_map< + FakeGraph::TransformIdKey, + std::pair, std::weak_ptr>> + parents_map_; + + std::string debug_name_; + + FML_DISALLOW_COPY_AND_ASSIGN(FakeFlatland); +}; + +} // namespace flutter_runner::testing + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_SCENIC_FAKE_FLATLAND_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_flatland_types.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_flatland_types.cc new file mode 100644 index 0000000000000000000000000000000000000000..777344a36f5df4234d68b426d995de5cfce3650e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_flatland_types.cc @@ -0,0 +1,180 @@ +// 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 "fake_flatland_types.h" + +#include +#include +#include + +#include "flutter/fml/logging.h" + +namespace flutter_runner::testing { +namespace { + +using FakeTransformCache = + std::unordered_map>; + +std::vector> CloneFakeTransformVector( + const std::vector>& transforms, + FakeTransformCache& transform_cache); + +std::shared_ptr CloneFakeContent( + const std::shared_ptr& content) { + if (content == nullptr) { + return nullptr; + } + + if (FakeViewport* viewport = std::get_if(content.get())) { + return std::make_shared(FakeViewport{ + .id = viewport->id, + .viewport_properties = fidl::Clone(viewport->viewport_properties), + .viewport_token = viewport->viewport_token, + .child_view_watcher = viewport->child_view_watcher, + }); + } else if (FakeImage* image = std::get_if(content.get())) { + return std::make_shared(FakeImage{ + .id = image->id, + .image_properties = fidl::Clone(image->image_properties), + .sample_region = image->sample_region, + .destination_size = image->destination_size, + .opacity = image->opacity, + .blend_mode = image->blend_mode, + .import_token = image->import_token, + .vmo_index = image->vmo_index, + }); + } else { + FML_UNREACHABLE(); + } +} + +std::shared_ptr CloneFakeTransform( + const std::shared_ptr& transform, + FakeTransformCache& transform_cache) { + if (transform == nullptr) { + return nullptr; + } + + auto found_transform = transform_cache.find(transform.get()); + if (found_transform != transform_cache.end()) { + return found_transform->second; + } + + auto [emplaced_transform, success] = transform_cache.emplace( + transform.get(), std::make_shared(FakeTransform{ + .id = transform->id, + .translation = transform->translation, + .scale = transform->scale, + .orientation = transform->orientation, + .clip_bounds = transform->clip_bounds, + .opacity = transform->opacity, + .children = CloneFakeTransformVector( + transform->children, transform_cache), + .content = CloneFakeContent(transform->content), + .hit_regions = transform->hit_regions, + })); + FML_CHECK(success); + + return emplaced_transform->second; +} + +std::vector> CloneFakeTransformVector( + const std::vector>& transforms, + FakeTransformCache& transform_cache) { + std::vector> clones; + for (auto& transform : transforms) { + clones.emplace_back(CloneFakeTransform(transform, transform_cache)); + } + return clones; +} + +} // namespace + +ViewTokenPair ViewTokenPair::New() { + ViewTokenPair token_pair; + auto status = zx::channel::create(0u, &token_pair.view_token.value, + &token_pair.viewport_token.value); + FML_CHECK(status == ZX_OK); + + return token_pair; +} + +BufferCollectionTokenPair BufferCollectionTokenPair::New() { + BufferCollectionTokenPair token_pair; + auto status = zx::eventpair::create(0u, &token_pair.export_token.value, + &token_pair.import_token.value); + FML_CHECK(status == ZX_OK); + + return token_pair; +} + +bool FakeView::operator==(const FakeView& other) const { + return view_token == other.view_token && view_ref == other.view_ref && + view_ref_control == other.view_ref_control && + view_ref_focused == other.view_ref_focused && + focuser == other.focuser && touch_source == other.touch_source && + mouse_source == other.mouse_source && + parent_viewport_watcher == other.parent_viewport_watcher; +} + +bool FakeViewport::operator==(const FakeViewport& other) const { + return id == other.id && viewport_properties == other.viewport_properties && + viewport_token == other.viewport_token && + child_view_watcher == other.child_view_watcher; +} + +bool FakeImage::operator==(const FakeImage& other) const { + return id == other.id && image_properties == other.image_properties && + sample_region == other.sample_region && + destination_size == other.destination_size && + opacity == other.opacity && blend_mode == other.blend_mode && + import_token == other.import_token && vmo_index == other.vmo_index; +} + +bool FakeTransform::operator==(const FakeTransform& other) const { + return id == other.id && translation == other.translation && + *clip_bounds == *other.clip_bounds && + orientation == other.orientation && children == other.children && + content == other.content && hit_regions == other.hit_regions; +} + +bool FakeGraph::operator==(const FakeGraph& other) const { + return transform_map == other.transform_map && + content_map == other.content_map && + root_transform == other.root_transform && view == other.view; +} + +void FakeGraph::Clear() { + view.reset(); + root_transform.reset(); + transform_map.clear(); + content_map.clear(); +} + +FakeGraph FakeGraph::Clone() const { + FakeGraph clone; + FakeTransformCache transform_cache; + + for (const auto& [transform_id, transform] : transform_map) { + FML_CHECK(transform); + clone.transform_map.emplace(transform_id, + CloneFakeTransform(transform, transform_cache)); + } + for (const auto& [content_id, content] : content_map) { + FML_CHECK(content); + clone.content_map.emplace(content_id, CloneFakeContent(content)); + } + if (root_transform) { + auto found_transform = transform_cache.find(root_transform.get()); + FML_CHECK(found_transform != transform_cache.end()); + clone.root_transform = found_transform->second; + } + if (view.has_value()) { + clone.view.emplace(view.value()); + } + + return clone; +} + +} // namespace flutter_runner::testing diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_flatland_types.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_flatland_types.h new file mode 100644 index 0000000000000000000000000000000000000000..2dbd8b5e8e90d015025d1de2062073126efbe999 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_flatland_types.h @@ -0,0 +1,333 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_SCENIC_FAKE_FLATLAND_TYPES_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_SCENIC_FAKE_FLATLAND_TYPES_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "flutter/fml/macros.h" + +namespace fuchsia { +namespace math { + +inline bool operator==(const fuchsia::math::SizeU& a, + const fuchsia::math::SizeU& b) { + return a.width == b.width && a.height == b.height; +} + +inline bool operator==(const fuchsia::math::Inset& a, + const fuchsia::math::Inset& b) { + return a.top == b.top && a.left == b.left && a.right == b.right && + a.bottom == b.bottom; +} + +inline bool operator==(const fuchsia::math::Vec& a, + const fuchsia::math::Vec& b) { + return a.x == b.x && a.y == b.y; +} + +inline bool operator==(const fuchsia::math::VecF& a, + const fuchsia::math::VecF& b) { + return a.x == b.x && a.y == b.y; +} + +inline bool operator==(const fuchsia::math::Rect& a, + const fuchsia::math::Rect& b) { + return a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height; +} + +inline bool operator==(const fuchsia::math::RectF& a, + const fuchsia::math::RectF& b) { + return a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height; +} + +inline bool operator==(const std::optional& a, + const std::optional& b) { + if (a.has_value() != b.has_value()) { + return false; + } + if (!a.has_value()) { + } + return a.value() == b.value(); +} + +} // namespace math + +namespace ui::composition { + +inline bool operator==(const fuchsia::ui::composition::ContentId& a, + const fuchsia::ui::composition::ContentId& b) { + return a.value == b.value; +} + +inline bool operator==(const fuchsia::ui::composition::TransformId& a, + const fuchsia::ui::composition::TransformId& b) { + return a.value == b.value; +} + +inline bool operator==(const fuchsia::ui::composition::ViewportProperties& a, + const fuchsia::ui::composition::ViewportProperties& b) { + if (a.has_logical_size() != b.has_logical_size()) { + return false; + } + + bool logical_size_equal = true; + if (a.has_logical_size()) { + const fuchsia::math::SizeU& a_logical_size = a.logical_size(); + const fuchsia::math::SizeU& b_logical_size = b.logical_size(); + logical_size_equal = (a_logical_size.width == b_logical_size.width && + a_logical_size.height == b_logical_size.height); + } + + return logical_size_equal; +} + +inline bool operator==(const fuchsia::ui::composition::ImageProperties& a, + const fuchsia::ui::composition::ImageProperties& b) { + if (a.has_size() != b.has_size()) { + return false; + } + + bool size_equal = true; + if (a.has_size()) { + const fuchsia::math::SizeU& a_size = a.size(); + const fuchsia::math::SizeU& b_size = b.size(); + size_equal = + (a_size.width == b_size.width && a_size.height == b_size.height); + } + + return size_equal; +} + +inline bool operator==(const fuchsia::ui::composition::HitRegion& a, + const fuchsia::ui::composition::HitRegion& b) { + return a.region == b.region && a.hit_test == b.hit_test; +} + +inline bool operator!=(const fuchsia::ui::composition::HitRegion& a, + const fuchsia::ui::composition::HitRegion& b) { + return !(a == b); +} + +inline bool operator==( + const std::vector& a, + const std::vector& b) { + if (a.size() != b.size()) + return false; + + for (size_t i = 0; i < a.size(); ++i) { + if (a[i] != b[i]) { + return false; + } + } + + return true; +} + +} // namespace ui::composition +} // namespace fuchsia + +namespace flutter_runner::testing { + +constexpr static fuchsia::ui::composition::TransformId kInvalidTransformId{0}; +constexpr static fuchsia::ui::composition::ContentId kInvalidContentId{0}; +constexpr static fuchsia::ui::composition::HitRegion kInfiniteHitRegion = { + .region = {-FLT_MAX, -FLT_MAX, FLT_MAX, FLT_MAX}}; + +// Convenience structure which allows clients to easily create a valid +// `ViewCreationToken` / `ViewportCreationToken` pair for use with Flatland +// `CreateView` and `CreateViewport`. +struct ViewTokenPair { + static ViewTokenPair New(); + + fuchsia::ui::views::ViewCreationToken view_token; + fuchsia::ui::views::ViewportCreationToken viewport_token; +}; + +// Convenience structure which allows clients to easily create a valid +// `BufferCollectionExportToken` / `BufferCollectionImportToken` pair for use +// with Flatland `RegisterBufferCollection` and `CreateImage`. +struct BufferCollectionTokenPair { + static BufferCollectionTokenPair New(); + + fuchsia::ui::composition::BufferCollectionExportToken export_token; + fuchsia::ui::composition::BufferCollectionImportToken import_token; +}; + +struct FakeView { + bool operator==(const FakeView& other) const; + + zx_koid_t view_token{}; + zx_koid_t view_ref{}; + zx_koid_t view_ref_control{}; + zx_koid_t view_ref_focused{}; + zx_koid_t focuser{}; + zx_koid_t touch_source{}; + zx_koid_t mouse_source{}; + zx_koid_t parent_viewport_watcher{}; +}; + +struct FakeViewport { + bool operator==(const FakeViewport& other) const; + + constexpr static fuchsia::math::SizeU kDefaultViewportLogicalSize{}; + constexpr static fuchsia::math::Inset kDefaultViewportInset{}; + + fuchsia::ui::composition::ContentId id{kInvalidContentId}; + + fuchsia::ui::composition::ViewportProperties viewport_properties{}; + zx_koid_t viewport_token{}; + zx_koid_t child_view_watcher{}; +}; + +struct FakeImage { + bool operator==(const FakeImage& other) const; + + constexpr static fuchsia::math::SizeU kDefaultImageSize{}; + constexpr static fuchsia::math::RectF kDefaultSampleRegion{}; + constexpr static fuchsia::math::SizeU kDefaultDestinationSize{}; + constexpr static float kDefaultOpacity{1.f}; + constexpr static fuchsia::ui::composition::BlendMode kDefaultBlendMode{ + fuchsia::ui::composition::BlendMode::SRC_OVER}; + + fuchsia::ui::composition::ContentId id{kInvalidContentId}; + + fuchsia::ui::composition::ImageProperties image_properties{}; + fuchsia::math::RectF sample_region{kDefaultSampleRegion}; + fuchsia::math::SizeU destination_size{kDefaultDestinationSize}; + float opacity{kDefaultOpacity}; + fuchsia::ui::composition::BlendMode blend_mode{kDefaultBlendMode}; + + zx_koid_t import_token{}; + uint32_t vmo_index{0}; +}; + +using FakeContent = std::variant; + +struct FakeTransform { + bool operator==(const FakeTransform& other) const; + + constexpr static fuchsia::math::Vec kDefaultTranslation{.x = 0, .y = 0}; + constexpr static fuchsia::math::VecF kDefaultScale{.x = 1.0f, .y = 1.0f}; + constexpr static fuchsia::ui::composition::Orientation kDefaultOrientation{ + fuchsia::ui::composition::Orientation::CCW_0_DEGREES}; + constexpr static float kDefaultOpacity = 1.0f; + + fuchsia::ui::composition::TransformId id{kInvalidTransformId}; + + fuchsia::math::Vec translation{kDefaultTranslation}; + fuchsia::math::VecF scale{kDefaultScale}; + fuchsia::ui::composition::Orientation orientation{kDefaultOrientation}; + + std::optional clip_bounds = std::nullopt; + + float opacity = kDefaultOpacity; + + std::vector> children; + std::shared_ptr content; + std::vector hit_regions; +}; + +struct FakeGraph { + using ContentIdKey = decltype(fuchsia::ui::composition::ContentId::value); + using TransformIdKey = decltype(fuchsia::ui::composition::TransformId::value); + + bool operator==(const FakeGraph& other) const; + + void Clear(); + FakeGraph Clone() const; + + std::unordered_map> content_map; + std::unordered_map> + transform_map; + std::shared_ptr root_transform; + std::optional view; +}; + +template +std::pair GetKoids(const ZX& kobj) { + zx_info_handle_basic_t info; + zx_status_t status = + kobj.get_info(ZX_INFO_HANDLE_BASIC, &info, sizeof(info), + /*actual_records*/ nullptr, /*avail_records*/ nullptr); + return status == ZX_OK ? std::make_pair(info.koid, info.related_koid) + : std::make_pair(zx_koid_t{}, zx_koid_t{}); +} + +template +std::pair GetKoids( + const fidl::InterfaceHandle& interface_handle) { + return GetKoids(interface_handle.channel()); +} + +template +std::pair GetKoids( + const fidl::InterfaceRequest& interface_request) { + return GetKoids(interface_request.channel()); +} + +template +std::pair GetKoids( + const fidl::InterfacePtr& interface_ptr) { + return GetKoids(interface_ptr.channel()); +} + +template +std::pair GetKoids( + const fidl::Binding& interface_binding) { + return GetKoids(interface_binding.channel()); +} + +inline std::pair GetKoids( + const fuchsia::ui::views::ViewCreationToken& view_token) { + return GetKoids(view_token.value); +} + +inline std::pair GetKoids( + const fuchsia::ui::views::ViewportCreationToken& viewport_token) { + return GetKoids(viewport_token.value); +} + +inline std::pair GetKoids( + const fuchsia::ui::views::ViewRef& view_ref) { + return GetKoids(view_ref.reference); +} + +inline std::pair GetKoids( + const fuchsia::ui::views::ViewRefControl& view_ref_control) { + return GetKoids(view_ref_control.reference); +} + +inline std::pair GetKoids( + const fuchsia::ui::composition::BufferCollectionExportToken& + buffer_collection_token) { + return GetKoids(buffer_collection_token.value); +} + +inline std::pair GetKoids( + const fuchsia::ui::composition::BufferCollectionImportToken& + buffer_collection_token) { + return GetKoids(buffer_collection_token.value); +} + +}; // namespace flutter_runner::testing + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_SCENIC_FAKE_FLATLAND_TYPES_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/touch_source.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/touch_source.h new file mode 100644 index 0000000000000000000000000000000000000000..31bc4e7c67dd5cb9099a07a505146d65158e02ad --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/touch_source.h @@ -0,0 +1,60 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_TOUCH_SOURCE_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_TOUCH_SOURCE_H_ + +#include + +#include +#include + +#include "flutter/fml/logging.h" + +namespace flutter_runner::testing { + +// A test stub to act as the protocol server. A test can control what is sent +// back by this server implementation, via the ScheduleCallback call. +class FakeTouchSource : public fuchsia::ui::pointer::TouchSource { + public: + // |fuchsia.ui.pointer.TouchSource| + void Watch(std::vector responses, + TouchSource::WatchCallback callback) override { + responses_ = std::move(responses); + callback_ = std::move(callback); + } + + // Have the server issue events to the client's hanging-get Watch call. + void ScheduleCallback(std::vector events) { + FML_CHECK(callback_) << "require a valid WatchCallback"; + callback_(std::move(events)); + } + + // Allow the test to observe what the client uploaded on the next Watch call. + std::optional> + UploadedResponses() { + auto responses = std::move(responses_); + responses_.reset(); + return responses; + } + + private: + // |fuchsia.ui.pointer.TouchSource| + void UpdateResponse(fuchsia::ui::pointer::TouchInteractionId ixn, + fuchsia::ui::pointer::TouchResponse response, + TouchSource::UpdateResponseCallback callback) override { + FML_UNREACHABLE(); + } + + // Client uploads responses to server. + std::optional> responses_; + + // Client-side logic to invoke on Watch() call's return. A test triggers it + // with ScheduleCallback(). + TouchSource::WatchCallback callback_; +}; + +} // namespace flutter_runner::testing + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_TOUCH_SOURCE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/view_ref_focused.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/view_ref_focused.h new file mode 100644 index 0000000000000000000000000000000000000000..f6789a874dff9bc25d156dcf50fd38cd6637f7d5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/view_ref_focused.h @@ -0,0 +1,36 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_VIEW_REF_FOCUSED_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_VIEW_REF_FOCUSED_H_ + +#include + +using ViewRefFocused = fuchsia::ui::views::ViewRefFocused; + +namespace flutter_runner::testing { + +class FakeViewRefFocused : public ViewRefFocused { + public: + using WatchCallback = ViewRefFocused::WatchCallback; + std::size_t times_watched = 0; + + void Watch(WatchCallback callback) override { + callback_ = std::move(callback); + ++times_watched; + } + + void ScheduleCallback(bool focused) { + fuchsia::ui::views::FocusState focus_state; + focus_state.set_focused(focused); + callback_(std::move(focus_state)); + } + + private: + WatchCallback callback_; +}; + +} // namespace flutter_runner::testing + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_VIEW_REF_FOCUSED_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/flatland_connection_unittests.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/flatland_connection_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..affbf45f180e07c3a73d534a67cbcee9bae7d181 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/flatland_connection_unittests.cc @@ -0,0 +1,649 @@ +// 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/shell/platform/fuchsia/flutter/flatland_connection.h" + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/time/time_delta.h" +#include "flutter/fml/time/time_point.h" +#include "gtest/gtest.h" + +#include "fakes/scenic/fake_flatland.h" + +namespace flutter_runner::testing { + +namespace { + +std::string GetCurrentTestName() { + return ::testing::UnitTest::GetInstance()->current_test_info()->name(); +} + +void AwaitVsyncChecked(FlatlandConnection& flatland_connection, + bool& condition_variable, + fml::TimeDelta expected_frame_delta) { + flatland_connection.AwaitVsync( + [&condition_variable, expected_frame_delta](fml::TimePoint frame_start, + fml::TimePoint frame_end) { + EXPECT_EQ(frame_end.ToEpochDelta() - frame_start.ToEpochDelta(), + expected_frame_delta); + condition_variable = true; + }); +} + +void AwaitVsyncChecked(FlatlandConnection& flatland_connection, + bool& condition_variable, + fml::TimePoint expected_frame_end) { + flatland_connection.AwaitVsync( + [&condition_variable, expected_frame_end](fml::TimePoint frame_start, + fml::TimePoint frame_end) { + EXPECT_EQ(frame_end, expected_frame_end); + condition_variable = true; + }); +} + +std::vector +CreateFuturePresentationInfos(const fml::TimePoint& presentation_time_1, + const fml::TimePoint& presentation_time_2) { + fuchsia::scenic::scheduling::PresentationInfo info_1; + info_1.set_presentation_time( + presentation_time_1.ToEpochDelta().ToNanoseconds()); + std::vector infos; + infos.push_back(std::move(info_1)); + fuchsia::scenic::scheduling::PresentationInfo info_2; + info_2.set_presentation_time( + presentation_time_2.ToEpochDelta().ToNanoseconds()); + infos.push_back(std::move(info_2)); + return infos; +} + +} // namespace + +class FlatlandConnectionTest : public ::testing::Test { + protected: + FlatlandConnectionTest() + : session_subloop_(loop_.StartNewLoop()), + flatland_handle_( + fake_flatland_.ConnectFlatland(session_subloop_->dispatcher())) {} + ~FlatlandConnectionTest() override = default; + + async::TestLoop& loop() { return loop_; } + + async_dispatcher_t* subloop_dispatcher() { + return session_subloop_->dispatcher(); + } + + FakeFlatland& fake_flatland() { return fake_flatland_; } + + fidl::InterfaceHandle + TakeFlatlandHandle() { + FML_CHECK(flatland_handle_.is_valid()); + return std::move(flatland_handle_); + } + + // Syntactic sugar for OnNextFrameBegin + void OnNextFrameBegin(int num_present_credits, + const fml::TimePoint& presentation_time_1, + const fml::TimePoint& presentation_time_2) { + fuchsia::ui::composition::OnNextFrameBeginValues on_next_frame_begin_values; + on_next_frame_begin_values.set_additional_present_credits( + num_present_credits); + on_next_frame_begin_values.set_future_presentation_infos( + CreateFuturePresentationInfos(presentation_time_1, + presentation_time_2)); + fake_flatland().FireOnNextFrameBeginEvent( + std::move(on_next_frame_begin_values)); + } + void OnNextFrameBegin(int num_present_credits) { + const auto now = fml::TimePoint::Now(); + const auto kPresentationTime1 = now + fml::TimeDelta::FromSeconds(100); + const auto kPresentationTime2 = now + fml::TimeDelta::FromSeconds(200); + OnNextFrameBegin(num_present_credits, kPresentationTime1, + kPresentationTime2); + } + + private: + async::TestLoop loop_; + std::unique_ptr session_subloop_; + + FakeFlatland fake_flatland_; + + fidl::InterfaceHandle flatland_handle_; +}; + +TEST_F(FlatlandConnectionTest, Initialization) { + // Create the FlatlandConnection but don't pump the loop. No FIDL calls are + // completed yet. + const std::string debug_name = GetCurrentTestName(); + flutter_runner::FlatlandConnection flatland_connection( + debug_name, TakeFlatlandHandle(), []() { FAIL(); }, + [](auto...) { FAIL(); }, loop().dispatcher()); + EXPECT_EQ(fake_flatland().debug_name(), ""); + + // Simulate an AwaitVsync that returns immediately. + bool await_vsync_fired = false; + AwaitVsyncChecked(flatland_connection, await_vsync_fired, + kInitialFlatlandVsyncOffset); + EXPECT_TRUE(await_vsync_fired); + + // Ensure the debug name is set. + loop().RunUntilIdle(); + EXPECT_EQ(fake_flatland().debug_name(), debug_name); +} + +TEST_F(FlatlandConnectionTest, FlatlandDisconnect) { + // Set up a callback which allows sensing of the error state. + bool error_fired = false; + fml::closure on_session_error = [&error_fired]() { error_fired = true; }; + + // Create the FlatlandConnection but don't pump the loop. No FIDL calls are + // completed yet. + flutter_runner::FlatlandConnection flatland_connection( + GetCurrentTestName(), TakeFlatlandHandle(), std::move(on_session_error), + [](auto...) { FAIL(); }, loop().dispatcher()); + EXPECT_FALSE(error_fired); + + // Simulate a flatland disconnection, then Pump the loop. The error callback + // will fire. + fake_flatland().Disconnect( + fuchsia::ui::composition::FlatlandError::BAD_OPERATION); + loop().RunUntilIdle(); + EXPECT_TRUE(error_fired); +} + +TEST_F(FlatlandConnectionTest, BasicPresent) { + // Set up callbacks which allow sensing of how many presents were handled. + size_t presents_called = 0u; + zx_handle_t release_fence_handle; + fake_flatland().SetPresentHandler([&presents_called, + &release_fence_handle](auto present_args) { + presents_called++; + release_fence_handle = present_args.release_fences().empty() + ? ZX_HANDLE_INVALID + : present_args.release_fences().front().get(); + }); + + // Set up a callback which allows sensing of how many vsync's + // (`OnFramePresented` events) were handled. + size_t vsyncs_handled = 0u; + on_frame_presented_event on_frame_presented = [&vsyncs_handled](auto...) { + vsyncs_handled++; + }; + + // Create the FlatlandConnection but don't pump the loop. No FIDL calls are + // completed yet. + flutter_runner::FlatlandConnection flatland_connection( + GetCurrentTestName(), TakeFlatlandHandle(), []() { FAIL(); }, + std::move(on_frame_presented), loop().dispatcher()); + EXPECT_EQ(presents_called, 0u); + EXPECT_EQ(vsyncs_handled, 0u); + + // Pump the loop. Nothing is called. + loop().RunUntilIdle(); + EXPECT_EQ(presents_called, 0u); + EXPECT_EQ(vsyncs_handled, 0u); + + // Simulate an AwaitVsync that comes after the first call. + bool await_vsync_fired = false; + AwaitVsyncChecked(flatland_connection, await_vsync_fired, + kInitialFlatlandVsyncOffset); + EXPECT_TRUE(await_vsync_fired); + + // Call Present and Pump the loop; `Present` and its callback is called. No + // release fence should be queued. + await_vsync_fired = false; + zx::event first_release_fence; + zx::event::create(0u, &first_release_fence); + const zx_handle_t first_release_fence_handle = first_release_fence.get(); + flatland_connection.EnqueueReleaseFence(std::move(first_release_fence)); + flatland_connection.Present(); + loop().RunUntilIdle(); + EXPECT_EQ(presents_called, 1u); + EXPECT_EQ(release_fence_handle, ZX_HANDLE_INVALID); + EXPECT_EQ(vsyncs_handled, 0u); + EXPECT_FALSE(await_vsync_fired); + + // Fire the `OnNextFrameBegin` event. AwaitVsync should be fired. + const auto now = fml::TimePoint::Now(); + const auto kPresentationTime1 = now + fml::TimeDelta::FromSeconds(100); + const auto kPresentationTime2 = now + fml::TimeDelta::FromSeconds(200); + fuchsia::ui::composition::OnNextFrameBeginValues on_next_frame_begin_values; + on_next_frame_begin_values.set_additional_present_credits(3); + on_next_frame_begin_values.set_future_presentation_infos( + CreateFuturePresentationInfos(kPresentationTime1, kPresentationTime2)); + fake_flatland().FireOnNextFrameBeginEvent( + std::move(on_next_frame_begin_values)); + loop().RunUntilIdle(); + AwaitVsyncChecked(flatland_connection, await_vsync_fired, kPresentationTime1); + EXPECT_TRUE(await_vsync_fired); + + // Fire the `OnFramePresented` event associated with the first `Present`, + fake_flatland().FireOnFramePresentedEvent( + fuchsia::scenic::scheduling::FramePresentedInfo()); + loop().RunUntilIdle(); + EXPECT_EQ(vsyncs_handled, 1u); + + // Call Present for a second time and Pump the loop; `Present` and its + // callback is called. Release fences for the earlier present is used. + await_vsync_fired = false; + flatland_connection.Present(); + loop().RunUntilIdle(); + EXPECT_EQ(presents_called, 2u); + EXPECT_EQ(release_fence_handle, first_release_fence_handle); + + // AwaitVsync should be fired with the second present. + await_vsync_fired = false; + AwaitVsyncChecked(flatland_connection, await_vsync_fired, kPresentationTime2); + EXPECT_TRUE(await_vsync_fired); +} + +TEST_F(FlatlandConnectionTest, AwaitVsyncsBeforeOnNextFrameBegin) { + // Set up callbacks which allow sensing of how many presents were handled. + size_t presents_called = 0u; + fake_flatland().SetPresentHandler( + [&presents_called](auto present_args) { presents_called++; }); + + // Create the FlatlandConnection but don't pump the loop. No FIDL calls are + // completed yet. + flutter_runner::FlatlandConnection flatland_connection( + GetCurrentTestName(), TakeFlatlandHandle(), []() { FAIL(); }, + [](auto...) {}, loop().dispatcher()); + EXPECT_EQ(presents_called, 0u); + + // Pump the loop. Nothing is called. + loop().RunUntilIdle(); + EXPECT_EQ(presents_called, 0u); + + // Simulate an AwaitVsync that comes before the first Present. + bool await_vsync_callback_fired = false; + AwaitVsyncChecked(flatland_connection, await_vsync_callback_fired, + kInitialFlatlandVsyncOffset); + EXPECT_TRUE(await_vsync_callback_fired); + + // AwaitVsync that comes before the first Present. + bool await_vsync_secondary_callback_fired = false; + flatland_connection.AwaitVsyncForSecondaryCallback( + [&await_vsync_secondary_callback_fired](fml::TimePoint frame_start, + fml::TimePoint frame_end) { + await_vsync_secondary_callback_fired = true; + }); + EXPECT_TRUE(await_vsync_secondary_callback_fired); +} + +TEST_F(FlatlandConnectionTest, RunsOutOfFuturePresentationInfos) { + // Set up callbacks which allow sensing of how many presents were handled. + size_t presents_called = 0u; + fake_flatland().SetPresentHandler( + [&presents_called](auto present_args) { presents_called++; }); + + // Set up a callback which allows sensing of how many vsync's + // (`OnFramePresented` events) were handled. + size_t vsyncs_handled = 0u; + on_frame_presented_event on_frame_presented = [&vsyncs_handled](auto...) { + vsyncs_handled++; + }; + + // Create the FlatlandConnection but don't pump the loop. No FIDL calls are + // completed yet. + flutter_runner::FlatlandConnection flatland_connection( + GetCurrentTestName(), TakeFlatlandHandle(), []() { FAIL(); }, + std::move(on_frame_presented), loop().dispatcher()); + EXPECT_EQ(presents_called, 0u); + EXPECT_EQ(vsyncs_handled, 0u); + + // Pump the loop. Nothing is called. + loop().RunUntilIdle(); + EXPECT_EQ(presents_called, 0u); + EXPECT_EQ(vsyncs_handled, 0u); + + // Simulate an AwaitVsync that comes before the first Present. + bool await_vsync_callback_fired = false; + AwaitVsyncChecked(flatland_connection, await_vsync_callback_fired, + kInitialFlatlandVsyncOffset); + EXPECT_TRUE(await_vsync_callback_fired); + + // Queue Present. + flatland_connection.Present(); + loop().RunUntilIdle(); + EXPECT_EQ(presents_called, 1u); + + // Fire the `OnNextFrameBegin` event. AwaitVsync callback should be fired with + // the first presentation time. + await_vsync_callback_fired = false; + const auto kPresentationTime1 = + fml::TimePoint::Now() + fml::TimeDelta::FromSeconds(123); + const auto kVsyncInterval = fml::TimeDelta::FromSeconds(234); + const auto kPresentationTime2 = kPresentationTime1 + kVsyncInterval; + OnNextFrameBegin(1, kPresentationTime1, kPresentationTime2); + loop().RunUntilIdle(); + AwaitVsyncChecked(flatland_connection, await_vsync_callback_fired, + kPresentationTime1); + EXPECT_TRUE(await_vsync_callback_fired); + + // Second consecutive AwaitVsync callback should be fired with + // the second presentation time. + await_vsync_callback_fired = false; + AwaitVsyncChecked(flatland_connection, await_vsync_callback_fired, + kPresentationTime2); + EXPECT_TRUE(await_vsync_callback_fired); + + // Another AwaitVsync callback should be fired with vsync_interval. + await_vsync_callback_fired = false; + AwaitVsyncChecked(flatland_connection, await_vsync_callback_fired, + kPresentationTime2 + kVsyncInterval); + EXPECT_TRUE(await_vsync_callback_fired); +} + +TEST_F(FlatlandConnectionTest, PresentCreditExhaustion) { + // Set up callbacks which allow sensing of how many presents were handled. + size_t num_presents_called = 0u; + size_t num_release_fences = 0u; + size_t num_acquire_fences = 0u; + + auto reset_test_counters = [&num_presents_called, &num_acquire_fences, + &num_release_fences]() { + num_presents_called = 0u; + num_release_fences = 0u; + num_acquire_fences = 0u; + }; + + fake_flatland().SetPresentHandler( + [&num_presents_called, &num_acquire_fences, &num_release_fences]( + fuchsia::ui::composition::PresentArgs present_args) { + num_presents_called++; + num_acquire_fences = present_args.acquire_fences().size(); + num_release_fences = present_args.release_fences().size(); + }); + + // Create the FlatlandConnection but don't pump the loop. No FIDL calls are + // completed yet. + on_frame_presented_event on_frame_presented = [](auto...) {}; + flutter_runner::FlatlandConnection flatland_connection( + GetCurrentTestName(), TakeFlatlandHandle(), []() { FAIL(); }, + std::move(on_frame_presented), loop().dispatcher()); + EXPECT_EQ(num_presents_called, 0u); + + // Pump the loop. Nothing is called. + loop().RunUntilIdle(); + EXPECT_EQ(num_presents_called, 0u); + + // Simulate an AwaitVsync that comes before the first Present. + flatland_connection.AwaitVsync([](fml::TimePoint, fml::TimePoint) {}); + loop().RunUntilIdle(); + EXPECT_EQ(num_presents_called, 0u); + + // This test uses a fire callback that triggers Present() with a single + // acquire and release fence in order to approximate the behavior of the real + // flutter fire callback and let us drive presents with ONFBs + auto fire_callback = [dispatcher = loop().dispatcher(), &flatland_connection]( + fml::TimePoint frame_start, + fml::TimePoint frame_end) { + async::PostTask(dispatcher, [&flatland_connection]() { + zx::event acquire_fence; + zx::event::create(0u, &acquire_fence); + zx::event release_fence; + zx::event::create(0u, &release_fence); + flatland_connection.EnqueueAcquireFence(std::move(acquire_fence)); + flatland_connection.EnqueueReleaseFence(std::move(release_fence)); + flatland_connection.Present(); + }); + }; + + // Call Await Vsync with a callback that triggers Present and consumes the one + // and only present credit we start with. + reset_test_counters(); + flatland_connection.AwaitVsync(fire_callback); + loop().RunUntilIdle(); + EXPECT_EQ(num_presents_called, 1u); + EXPECT_EQ(num_acquire_fences, 1u); + EXPECT_EQ(num_release_fences, 0u); + + // Do it again, but this time we should not get a present because the client + // has exhausted its present credits. + reset_test_counters(); + flatland_connection.AwaitVsync(fire_callback); + OnNextFrameBegin(0); + loop().RunUntilIdle(); + EXPECT_EQ(num_presents_called, 0u); + + // Supply a present credit but dont set a new fire callback. Fire callback + // from previous ONFB should fire and trigger a Present() + reset_test_counters(); + OnNextFrameBegin(1); + loop().RunUntilIdle(); + EXPECT_EQ(num_presents_called, 1u); + EXPECT_EQ(num_acquire_fences, 1u); + EXPECT_EQ(num_release_fences, 1u); + + // From here on we are testing handling of a race condition where a fire + // callback is fired but another ONFB arrives before the present from the + // first fire callback comes in, causing present_credits to be negative + // within Present(). + + uint num_onfb = 5; + uint num_deferred_callbacks = 0; + // This callback will accumulate num_onfb+1 calls before firing all + // of their presents at once. + auto accumulating_fire_callback = [&](fml::TimePoint frame_start, + fml::TimePoint frame_end) { + num_deferred_callbacks++; + if (num_deferred_callbacks > num_onfb) { + fml::TimePoint now = fml::TimePoint::Now(); + for (uint i = 0; i < num_onfb + 1; i++) { + fire_callback(now, now); + num_deferred_callbacks--; + } + } + }; + + reset_test_counters(); + for (uint i = 0; i < num_onfb; i++) { + flatland_connection.AwaitVsync(accumulating_fire_callback); + // only supply a present credit on the first call. Since Presents are being + // deferred this credit will not be used up, but we need a credit to call + // the accumulating_fire_callback + OnNextFrameBegin(i == 0 ? 1 : 0); + loop().RunUntilIdle(); + EXPECT_EQ(num_presents_called, 0u); + } + + // This is the num_onfb+1 call to accumulating_fire_callback which triggers + // all of the "racing" presents to fire. the first one should be fired, + // but the other num_onfb Presents should be deferred. + flatland_connection.AwaitVsync(accumulating_fire_callback); + OnNextFrameBegin(0); + loop().RunUntilIdle(); + EXPECT_EQ(num_presents_called, 1u); + EXPECT_EQ(num_acquire_fences, 1u); + EXPECT_EQ(num_release_fences, 1u); + + // Supply a present credit, but pass an empty lambda to AwaitVsync so + // that it doesnt call Present(). Should get a deferred present with + // all the accumulate acuire fences + reset_test_counters(); + flatland_connection.AwaitVsync([](fml::TimePoint, fml::TimePoint) {}); + OnNextFrameBegin(1); + loop().RunUntilIdle(); + EXPECT_EQ(num_presents_called, 1u); + EXPECT_EQ(num_acquire_fences, num_onfb); + EXPECT_EQ(num_release_fences, 1u); + + // Pump another frame to check that release fences accumulate as expected + reset_test_counters(); + flatland_connection.AwaitVsync(fire_callback); + OnNextFrameBegin(1); + loop().RunUntilIdle(); + EXPECT_EQ(num_presents_called, 1u); + EXPECT_EQ(num_acquire_fences, 1u); + EXPECT_EQ(num_release_fences, num_onfb); +} + +typedef struct { + std::shared_ptr> fences; + std::shared_ptr> fences_dup; +} FencesPair; + +// Create two vectors of paired fences. +FencesPair GetFencesPair(size_t num_fences) { + auto fences = std::make_shared>(); + auto fences_dup = std::make_shared>(); + for (size_t i = 0; i < num_fences; i++) { + zx::event fence; + auto status = zx::event::create(0u, &fence); + EXPECT_EQ(status, ZX_OK); + + zx::event fence_dup; + status = fence.duplicate(ZX_RIGHT_SAME_RIGHTS, &fence_dup); + EXPECT_EQ(status, ZX_OK); + + fences->push_back(std::move(fence)); + fences_dup->push_back(std::move(fence_dup)); + } + return FencesPair{ + .fences = fences, + .fences_dup = fences_dup, + }; +} + +void SignalAll(std::vector* fences) { + for (auto& fence : *fences) { + const auto status = fence.signal(0, ZX_EVENT_SIGNALED); + ASSERT_EQ(status, ZX_OK); + } +} + +void WaitAll(std::vector* fences) { + for (auto& fence : *fences) { + zx_signals_t ignored; + // Maybe the timeout here should be finite. + const auto status = + fence.wait_one(ZX_EVENT_SIGNALED, zx::time::infinite(), &ignored); + ASSERT_EQ(status, ZX_OK); + } +} + +TEST_F(FlatlandConnectionTest, FenceStuffing) { + // Set up callbacks which allow sensing of how many presents were handled. + size_t num_presents_called = 0u; + size_t num_release_fences = 0u; + size_t num_acquire_fences = 0u; + + auto reset_test_counters = [&num_presents_called, &num_acquire_fences, + &num_release_fences]() { + num_presents_called = 0u; + num_release_fences = 0u; + num_acquire_fences = 0u; + }; + + fuchsia::ui::composition::PresentArgs last_present_args; + fake_flatland().SetPresentHandler( + [&num_presents_called, &num_acquire_fences, &num_release_fences, + &last_present_args](fuchsia::ui::composition::PresentArgs present_args) { + num_presents_called++; + num_acquire_fences = present_args.acquire_fences().size(); + num_release_fences = present_args.release_fences().size(); + + last_present_args = std::move(present_args); + }); + + // Create the FlatlandConnection but don't pump the loop. No FIDL calls are + // completed yet. + on_frame_presented_event on_frame_presented = [](auto...) {}; + flutter_runner::FlatlandConnection flatland_connection( + GetCurrentTestName(), TakeFlatlandHandle(), []() { FAIL(); }, + std::move(on_frame_presented), subloop_dispatcher()); + EXPECT_EQ(num_presents_called, 0u); + + // Pump the loop. Nothing is called. + loop().RunUntilIdle(); + EXPECT_EQ(num_presents_called, 0u); + + // Simulate an AwaitVsync that comes before the first Present. + flatland_connection.AwaitVsync([](fml::TimePoint, fml::TimePoint) {}); + loop().RunUntilIdle(); + EXPECT_EQ(num_presents_called, 0u); + + constexpr size_t kMaxFences = 16; + + // We must signal these. + FencesPair acquire = GetFencesPair(kMaxFences + 1); + // Flatland will signal these. + FencesPair release = GetFencesPair(kMaxFences + 1); + + auto fire_callback = [dispatcher = loop().dispatcher(), &flatland_connection, + rfd = release.fences_dup, afd = acquire.fences_dup]( + fml::TimePoint frame_start, + fml::TimePoint frame_end) mutable { + async::PostTask(dispatcher, [&flatland_connection, rf = rfd, af = afd]() { + for (auto& fence : *rf) { + zx::event fence_dup; + const auto status = fence.duplicate(ZX_RIGHT_SAME_RIGHTS, &fence_dup); + ASSERT_EQ(status, ZX_OK); + flatland_connection.EnqueueReleaseFence(std::move(fence_dup)); + } + for (auto& fence : *af) { + zx::event fence_dup; + const auto status = fence.duplicate(ZX_RIGHT_SAME_RIGHTS, &fence_dup); + ASSERT_EQ(status, ZX_OK); + flatland_connection.EnqueueAcquireFence(std::move(fence_dup)); + } + flatland_connection.Present(); + }); + }; + + SignalAll(acquire.fences.get()); + + // Call Await Vsync with a callback that triggers Present and consumes the one + // and only present credit we start with. + reset_test_counters(); + flatland_connection.AwaitVsync(fire_callback); + + loop().RunUntilIdle(); + + EXPECT_EQ(num_presents_called, 1u); + EXPECT_EQ(num_acquire_fences, 16u); + EXPECT_EQ(num_release_fences, 0u); + + // Move on to next present call. Reset all the expectations and callbacks. + reset_test_counters(); + OnNextFrameBegin(1); + // Replenish present credits. + loop().RunUntilIdle(); + + flatland_connection.AwaitVsync([dispatcher = subloop_dispatcher(), + &flatland_connection](fml::TimePoint, + fml::TimePoint) { + async::PostTask(dispatcher, + [&flatland_connection] { flatland_connection.Present(); }); + }); + loop().RunUntilIdle(); + + // Simulate Flatland signaling all release fences. Note that the set of + // release fences here is only the first ~15 of the fences, the rest are + // released indirectly via the overflow mechanism. + SignalAll(last_present_args.mutable_release_fences()); + + loop().RunUntilIdle(); + + // At this point all release fences from prior frame should have been released + // by Flatland. + EXPECT_EQ(num_presents_called, 1u); + EXPECT_EQ(num_acquire_fences, 0u); + EXPECT_EQ(num_release_fences, 16u); + + // Prove that all release fences have been signaled. If not, this will block + // forever. + WaitAll(release.fences.get()); +} + +} // namespace flutter_runner::testing diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/flutter_runner_product_configuration_unittests.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/flutter_runner_product_configuration_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..51fa2a1a3816aaa5d63ebdf027df4326f917a2c2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/flutter_runner_product_configuration_unittests.cc @@ -0,0 +1,57 @@ +// 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 + +#include "flutter/shell/platform/fuchsia/flutter/flutter_runner_product_configuration.h" + +using namespace flutter_runner; + +namespace flutter_runner_test { + +class FlutterRunnerProductConfigurationTest : public testing::Test {}; + +TEST_F(FlutterRunnerProductConfigurationTest, InvalidJsonString) { + const std::string json_string = "{ \"invalid json string\" }}} "; + const uint64_t expected_intercept_all_input = false; + + FlutterRunnerProductConfiguration product_config = + FlutterRunnerProductConfiguration(json_string); + EXPECT_EQ(expected_intercept_all_input, + product_config.get_intercept_all_input()); +} + +TEST_F(FlutterRunnerProductConfigurationTest, EmptyJsonString) { + const std::string json_string = ""; + const uint64_t expected_intercept_all_input = false; + + FlutterRunnerProductConfiguration product_config = + FlutterRunnerProductConfiguration(json_string); + EXPECT_EQ(expected_intercept_all_input, + product_config.get_intercept_all_input()); +} + +TEST_F(FlutterRunnerProductConfigurationTest, ValidInterceptAllInput) { + const std::string json_string = "{ \"intercept_all_input\" : true } "; + const uint64_t expected_intercept_all_input = true; + + FlutterRunnerProductConfiguration product_config = + FlutterRunnerProductConfiguration(json_string); + + EXPECT_EQ(expected_intercept_all_input, + product_config.get_intercept_all_input()); +} + +TEST_F(FlutterRunnerProductConfigurationTest, MissingInterceptAllInput) { + const std::string json_string = "{ \"intercept_all_input\" : } "; + const uint64_t expected_intercept_all_input = false; + + FlutterRunnerProductConfiguration product_config = + FlutterRunnerProductConfiguration(json_string); + + EXPECT_EQ(expected_intercept_all_input, + product_config.get_intercept_all_input()); +} + +} // namespace flutter_runner_test diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..2117b86aa4e62d8db742e073013e02cc9fa536f6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/BUILD.gn @@ -0,0 +1,17 @@ +# 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. + +assert(is_fuchsia) + +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") + +group("integration") { + testonly = true + deps = [ + "embedder:tests", + "mouse-input:tests", + "text-input:tests", + "touch-input:tests", + ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/README.md b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fe7c0847abf2f50d8826fe8b3835fdb11cf68db4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/README.md @@ -0,0 +1,45 @@ +# Flutter runner integration tests + +To run the Flutter runner integration tests locally, +first start a Fuchsia package server: + +```shell +cd "$FUCHSIA_DIR" +fx serve +``` + +Then run the integration test: + +```shell +$ENGINE_DIR/flutter/tools/fuchsia/devshell/run_integration_test.sh --no-lto +``` + +For example, to run the `embedder` integration test: + +```shell +$ENGINE_DIR/flutter/tools/fuchsia/devshell/run_integration_test.sh embedder --no-lto +``` + +Command-line options: + +* Pass `--unoptimized` to disable C++ compiler optimizations. +* Add `--fuchsia-cpu x64` or `--fuchsia-cpu arm64` to target a particular architecture. + The default is x64. +* Add `--runtime-mode debug` or `--runtime-mode profile` to switch between JIT and AOT + builds. These correspond to a vanilla Fuchsia build and a `--release` Fuchsia build + respectively. The default is debug/JIT builds. +* Remove `--no-lto` if you care about performance or binary size; unfortunately it results + in a *much* slower build. + +## Iterating on tests + +By default, `run_integration_test.sh` will build Fuchsia and start up a Fuchsia emulator +to ensure that the test runs on the correct environment. + +However, this is slow for iterating on tests. Once you've run `run_integration_tests.sh` +once, you don't need to build Fuchsia or start the emulator anymore, and can pass +`--skip-fuchsia-build` and `--skip-fuchsia-emu` to skip those steps. + +```shell +$ENGINE_DIR/flutter/tools/fuchsia/devshell/run_integration_test.sh embedder --no-lto --skip-fuchsia-build --skip-fuchsia-emu +``` diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4267976a7bbc87482130dec867e5c2eb8e6a34d3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/BUILD.gn @@ -0,0 +1,62 @@ +# 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. + +assert(is_fuchsia) + +import("//flutter/tools/fuchsia/fuchsia_archive.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") + +group("tests") { + testonly = true + deps = [ ":flutter-embedder-test" ] +} + +executable("flutter-embedder-test-bin") { + testonly = true + + output_name = "flutter-embedder-test" + + sources = [ "flutter-embedder-test.cc" ] + + # This is needed for //flutter/third_party/googletest for linking zircon + # symbols. + libs = [ "${fuchsia_arch_root}/sysroot/lib/libzircon.so" ] + + deps = [ + "${fuchsia_sdk}/fidl/fuchsia.inspect", + "${fuchsia_sdk}/fidl/fuchsia.logger", + "${fuchsia_sdk}/fidl/fuchsia.sysmem", + "${fuchsia_sdk}/fidl/fuchsia.sysmem2", + "${fuchsia_sdk}/fidl/fuchsia.tracing.provider", + "${fuchsia_sdk}/fidl/fuchsia.ui.app", + "${fuchsia_sdk}/fidl/fuchsia.ui.composition", + "${fuchsia_sdk}/fidl/fuchsia.ui.display.singleton", + "${fuchsia_sdk}/fidl/fuchsia.ui.observation.geometry", + "${fuchsia_sdk}/fidl/fuchsia.ui.test.input", + "${fuchsia_sdk}/fidl/fuchsia.ui.test.scene", + "${fuchsia_sdk}/pkg/async", + "${fuchsia_sdk}/pkg/async-loop-testing", + "${fuchsia_sdk}/pkg/fidl_cpp", + "${fuchsia_sdk}/pkg/sys_component_cpp_testing", + "${fuchsia_sdk}/pkg/zx", + "//flutter/fml", + "//flutter/shell/platform/fuchsia/flutter/tests/integration/utils:check_view", + "//flutter/shell/platform/fuchsia/flutter/tests/integration/utils:screenshot", + "//flutter/third_party/googletest:gtest", + "//flutter/third_party/googletest:gtest_main", + ] +} + +fuchsia_test_archive("flutter-embedder-test") { + deps = [ + ":flutter-embedder-test-bin", + "child-view:package", + "parent-view:package", + + # "OOT" copies of the runners used by tests, to avoid conflicting with the + # runners in the base fuchsia image. + # TODO(fxbug.dev/106575): Fix this with subpackages. + "//flutter/shell/platform/fuchsia/flutter:oot_flutter_jit_runner", + ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/child-view/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/child-view/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..08cb1bd9588a0666b5ad9b1104717474e9db6d8a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/child-view/BUILD.gn @@ -0,0 +1,26 @@ +# 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. + +import("//flutter/tools/fuchsia/dart/dart_library.gni") +import("//flutter/tools/fuchsia/flutter/flutter_component.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/package.gni") + +dart_library("lib") { + package_name = "child-view" + sources = [ "child_view.dart" ] +} + +flutter_component("component") { + main_package = "child-view" + component_name = "child-view" + main_dart = "child_view.dart" + manifest = rebase_path("meta/child-view.cml") + deps = [ ":lib" ] +} + +fuchsia_package("package") { + package_name = "child-view" + deps = [ ":component" ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/child-view/lib/child_view.dart b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/child-view/lib/child_view.dart new file mode 100644 index 0000000000000000000000000000000000000000..0bd2156e7789db698954971fce60ad75a40365d4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/child-view/lib/child_view.dart @@ -0,0 +1,60 @@ +// 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. + +import 'dart:ui'; + +void main(List args) { + print('child-view: starting'); + + TestApp app = TestApp(); + app.run(); +} + +class TestApp { + static const _yellow = Color.fromARGB(255, 255, 255, 0); + static const _pink = Color.fromARGB(255, 255, 0, 255); + + Color _backgroundColor = _pink; + + void run() { + window.onPointerDataPacket = (PointerDataPacket packet) { + this.pointerDataPacket(packet); + }; + window.onMetricsChanged = () { + window.scheduleFrame(); + }; + window.onBeginFrame = (Duration duration) { + this.beginFrame(duration); + }; + + window.scheduleFrame(); + } + + void beginFrame(Duration duration) { + final pixelRatio = window.devicePixelRatio; + final size = window.physicalSize / pixelRatio; + final physicalBounds = Offset.zero & size * pixelRatio; + final recorder = PictureRecorder(); + final canvas = Canvas(recorder, physicalBounds); + canvas.scale(pixelRatio, pixelRatio); + final paint = Paint()..color = this._backgroundColor; + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint); + final picture = recorder.endRecording(); + final sceneBuilder = + SceneBuilder() + ..pushClipRect(physicalBounds) + ..addPicture(Offset.zero, picture) + ..pop(); + window.render(sceneBuilder.build()); + } + + void pointerDataPacket(PointerDataPacket packet) { + for (final data in packet.data) { + if (data.change == PointerChange.down) { + this._backgroundColor = _yellow; + } + } + window.scheduleFrame(); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/child-view/meta/child-view.cml b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/child-view/meta/child-view.cml new file mode 100644 index 0000000000000000000000000000000000000000..c1aab3a83d0631715b538a941f7f6ddacd90eb7d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/child-view/meta/child-view.cml @@ -0,0 +1,24 @@ +// 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: [ "syslog/client.shard.cml" ], + program: { + data: "data/child-view", + + // Always use the jit runner for now. + // TODO(fxbug.dev/106577): Implement manifest merging build rules for V2 components. + runner: "flutter_jit_runner", + }, + capabilities: [ + { + protocol: [ "fuchsia.ui.app.ViewProvider" ], + }, + ], + expose: [ + { + protocol: [ "fuchsia.ui.app.ViewProvider" ], + from: "self", + }, + ], +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/child-view/pubspec.yaml b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/child-view/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..999c2898734e2f615dfbbd6938a27b6ccb18f52d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/child-view/pubspec.yaml @@ -0,0 +1,8 @@ +# 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. + +name: child_view2 + +environment: + sdk: ^3.7.0-0 diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/flutter-embedder-test.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/flutter-embedder-test.cc new file mode 100644 index 0000000000000000000000000000000000000000..26464422abfd44b9088bad988de555b9f14ba612 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/flutter-embedder-test.cc @@ -0,0 +1,451 @@ +// 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "flutter/fml/logging.h" +#include "gtest/gtest.h" + +#include "flutter/shell/platform/fuchsia/flutter/tests/integration/utils/check_view.h" +#include "flutter/shell/platform/fuchsia/flutter/tests/integration/utils/screenshot.h" + +namespace flutter_embedder_test { +namespace { + +// Types imported for the realm_builder library. +using component_testing::ChildOptions; +using component_testing::ChildRef; +using component_testing::DirectoryContents; +using component_testing::ParentRef; +using component_testing::Protocol; +using component_testing::RealmRoot; +using component_testing::Route; +using component_testing::StartupMode; + +using fuchsia_test_utils::CheckViewExistsInUpdates; + +// The FIDL bindings for this service are not exposed in the Fuchsia SDK, so we +// must encode the name manually here. +constexpr auto kVulkanLoaderServiceName = "fuchsia.vulkan.loader.Loader"; + +constexpr auto kFlutterJitRunnerUrl = + "fuchsia-pkg://fuchsia.com/oot_flutter_jit_runner#meta/" + "flutter_jit_runner.cm"; +constexpr auto kFlutterJitProductRunnerUrl = + "fuchsia-pkg://fuchsia.com/oot_flutter_jit_product_runner#meta/" + "flutter_jit_product_runner.cm"; +constexpr auto kFlutterAotRunnerUrl = + "fuchsia-pkg://fuchsia.com/oot_flutter_aot_runner#meta/" + "flutter_aot_runner.cm"; +constexpr auto kFlutterAotProductRunnerUrl = + "fuchsia-pkg://fuchsia.com/oot_flutter_aot_product_runner#meta/" + "flutter_aot_product_runner.cm"; +constexpr char kChildViewUrl[] = + "fuchsia-pkg://fuchsia.com/child-view#meta/child-view.cm"; +constexpr char kParentViewUrl[] = + "fuchsia-pkg://fuchsia.com/parent-view#meta/parent-view.cm"; +static constexpr auto kTestUiStackUrl = + "fuchsia-pkg://fuchsia.com/flatland-scene-manager-test-ui-stack#meta/" + "test-ui-stack.cm"; + +constexpr auto kFlutterRunnerEnvironment = "flutter_runner_env"; +constexpr auto kFlutterJitRunner = "flutter_jit_runner"; +constexpr auto kFlutterJitRunnerRef = ChildRef{kFlutterJitRunner}; +constexpr auto kFlutterJitProductRunner = "flutter_jit_product_runner"; +constexpr auto kFlutterJitProductRunnerRef = ChildRef{kFlutterJitProductRunner}; +constexpr auto kFlutterAotRunner = "flutter_aot_runner"; +constexpr auto kFlutterAotRunnerRef = ChildRef{kFlutterAotRunner}; +constexpr auto kFlutterAotProductRunner = "flutter_aot_product_runner"; +constexpr auto kFlutterAotProductRunnerRef = ChildRef{kFlutterAotProductRunner}; +constexpr auto kChildView = "child_view"; +constexpr auto kChildViewRef = ChildRef{kChildView}; +constexpr auto kParentView = "parent_view"; +constexpr auto kParentViewRef = ChildRef{kParentView}; +constexpr auto kTestUiStack = "ui"; +constexpr auto kTestUiStackRef = ChildRef{kTestUiStack}; + +// Background and foreground color values. +const fuchsia_test_utils::Pixel kParentBackgroundColor(0xFF, + 0x00, + 0x00, + 0xFF); // Blue +const fuchsia_test_utils::Pixel kChildBackgroundColor(0xFF, + 0x00, + 0xFF, + 0xFF); // Pink +const fuchsia_test_utils::Pixel kFlatlandOverlayColor(0x00, + 0xFF, + 0x00, + 0xFF); // Green + +static uint32_t OverlayPixelCount( + std::map& histogram) { + return histogram[kFlatlandOverlayColor]; +} + +// Timeout for |TakeScreenshot| FIDL call. +constexpr zx::duration kScreenshotTimeout = zx::sec(10); +// Timeout to fail the test if it goes beyond this duration. +constexpr zx::duration kTestTimeout = zx::min(1); + +} // namespace + +class FlutterEmbedderTest : public ::loop_fixture::RealLoop, + public ::testing::Test { + public: + FlutterEmbedderTest() + : realm_builder_(component_testing::RealmBuilder::Create()) { + FML_VLOG(1) << "Setting up base realm"; + SetUpRealmBase(); + + // Post a "just in case" quit task, if the test hangs. + async::PostDelayedTask( + dispatcher(), + [] { + FML_LOG(FATAL) + << "\n\n>> Test did not complete in time, terminating. <<\n\n"; + }, + kTestTimeout); + } + + bool HasViewConnected( + const fuchsia::ui::observation::geometry::ViewTreeWatcherPtr& + view_tree_watcher, + std::optional& + watch_response, + zx_koid_t view_ref_koid); + + void LaunchParentViewInRealm( + const std::vector& component_args = {}); + + fuchsia_test_utils::Screenshot TakeScreenshot(); + + bool TakeScreenshotUntil( + fuchsia_test_utils::Pixel color, + fit::function)> + callback = nullptr, + zx::duration timeout = kTestTimeout); + + private: + void SetUpRealmBase(); + + fuchsia::ui::test::scene::ControllerPtr scene_provider_; + fuchsia::ui::observation::geometry::ViewTreeWatcherPtr view_tree_watcher_; + fuchsia::ui::composition::ScreenshotPtr screenshot_; + + // Wrapped in optional since the view is not created until the middle of SetUp + component_testing::RealmBuilder realm_builder_; + std::unique_ptr realm_; + + uint64_t display_width_ = 0; + uint64_t display_height_ = 0; +}; + +void FlutterEmbedderTest::SetUpRealmBase() { + FML_LOG(INFO) << "Setting up realm base."; + + // First, add the flutter runner(s) as children. + realm_builder_.AddChild(kFlutterJitRunner, kFlutterJitRunnerUrl); + realm_builder_.AddChild(kFlutterJitProductRunner, + kFlutterJitProductRunnerUrl); + realm_builder_.AddChild(kFlutterAotRunner, kFlutterAotRunnerUrl); + realm_builder_.AddChild(kFlutterAotProductRunner, + kFlutterAotProductRunnerUrl); + + // Then, add an environment providing them. + fuchsia::component::decl::Environment flutter_runner_environment; + flutter_runner_environment.set_name(kFlutterRunnerEnvironment); + flutter_runner_environment.set_extends( + fuchsia::component::decl::EnvironmentExtends::REALM); + flutter_runner_environment.set_runners({}); + auto environment_runners = flutter_runner_environment.mutable_runners(); + fuchsia::component::decl::RunnerRegistration flutter_jit_runner_reg; + flutter_jit_runner_reg.set_source(fuchsia::component::decl::Ref::WithChild( + fuchsia::component::decl::ChildRef{.name = kFlutterJitRunner})); + flutter_jit_runner_reg.set_source_name(kFlutterJitRunner); + flutter_jit_runner_reg.set_target_name(kFlutterJitRunner); + environment_runners->push_back(std::move(flutter_jit_runner_reg)); + fuchsia::component::decl::RunnerRegistration flutter_jit_product_runner_reg; + flutter_jit_product_runner_reg.set_source( + fuchsia::component::decl::Ref::WithChild( + fuchsia::component::decl::ChildRef{.name = + kFlutterJitProductRunner})); + flutter_jit_product_runner_reg.set_source_name(kFlutterJitProductRunner); + flutter_jit_product_runner_reg.set_target_name(kFlutterJitProductRunner); + environment_runners->push_back(std::move(flutter_jit_product_runner_reg)); + fuchsia::component::decl::RunnerRegistration flutter_aot_runner_reg; + flutter_aot_runner_reg.set_source(fuchsia::component::decl::Ref::WithChild( + fuchsia::component::decl::ChildRef{.name = kFlutterAotRunner})); + flutter_aot_runner_reg.set_source_name(kFlutterAotRunner); + flutter_aot_runner_reg.set_target_name(kFlutterAotRunner); + environment_runners->push_back(std::move(flutter_aot_runner_reg)); + fuchsia::component::decl::RunnerRegistration flutter_aot_product_runner_reg; + flutter_aot_product_runner_reg.set_source( + fuchsia::component::decl::Ref::WithChild( + fuchsia::component::decl::ChildRef{.name = + kFlutterAotProductRunner})); + flutter_aot_product_runner_reg.set_source_name(kFlutterAotProductRunner); + flutter_aot_product_runner_reg.set_target_name(kFlutterAotProductRunner); + environment_runners->push_back(std::move(flutter_aot_product_runner_reg)); + auto realm_decl = realm_builder_.GetRealmDecl(); + if (!realm_decl.has_environments()) { + realm_decl.set_environments({}); + } + auto realm_environments = realm_decl.mutable_environments(); + realm_environments->push_back(std::move(flutter_runner_environment)); + realm_builder_.ReplaceRealmDecl(std::move(realm_decl)); + + // Add test UI stack component. + realm_builder_.AddChild(kTestUiStack, kTestUiStackUrl); + + // Add embedded parent and child components. + realm_builder_.AddChild(kChildView, kChildViewUrl, + ChildOptions{ + .environment = kFlutterRunnerEnvironment, + }); + realm_builder_.AddChild(kParentView, kParentViewUrl, + ChildOptions{ + .environment = kFlutterRunnerEnvironment, + }); + + // Route base system services to flutter runners. + realm_builder_.AddRoute( + Route{.capabilities = + { + Protocol{fuchsia::logger::LogSink::Name_}, + Protocol{fuchsia::inspect::InspectSink::Name_}, + Protocol{fuchsia::sysmem::Allocator::Name_}, + Protocol{fuchsia::sysmem2::Allocator::Name_}, + Protocol{fuchsia::tracing::provider::Registry::Name_}, + Protocol{kVulkanLoaderServiceName}, + }, + .source = ParentRef{}, + .targets = {kFlutterJitRunnerRef, kFlutterJitProductRunnerRef, + kFlutterAotRunnerRef, kFlutterAotProductRunnerRef}}); + + // Route base system services to the test UI stack. + realm_builder_.AddRoute(Route{ + .capabilities = {Protocol{fuchsia::logger::LogSink::Name_}, + Protocol{fuchsia::inspect::InspectSink::Name_}, + Protocol{fuchsia::sysmem::Allocator::Name_}, + Protocol{fuchsia::sysmem2::Allocator::Name_}, + Protocol{fuchsia::tracing::provider::Registry::Name_}, + Protocol{kVulkanLoaderServiceName}}, + .source = ParentRef{}, + .targets = {kTestUiStackRef}}); + + // Route UI capabilities from test UI stack to flutter runners. + realm_builder_.AddRoute(Route{ + .capabilities = {Protocol{fuchsia::ui::composition::Allocator::Name_}, + Protocol{fuchsia::ui::composition::Flatland::Name_}}, + .source = kTestUiStackRef, + .targets = {kFlutterJitRunnerRef, kFlutterJitProductRunnerRef, + kFlutterAotRunnerRef, kFlutterAotProductRunnerRef}}); + + // Route test capabilities from test UI stack to test driver. + realm_builder_.AddRoute(Route{ + .capabilities = {Protocol{fuchsia::ui::composition::Screenshot::Name_}, + Protocol{fuchsia::ui::test::input::Registry::Name_}, + Protocol{fuchsia::ui::test::scene::Controller::Name_}, + Protocol{fuchsia::ui::display::singleton::Info::Name_}}, + .source = kTestUiStackRef, + .targets = {ParentRef()}}); + + // Route ViewProvider from child to parent, and parent to test. + realm_builder_.AddRoute( + Route{.capabilities = {Protocol{fuchsia::ui::app::ViewProvider::Name_}}, + .source = kParentViewRef, + .targets = {ParentRef()}}); + realm_builder_.AddRoute( + Route{.capabilities = {Protocol{fuchsia::ui::app::ViewProvider::Name_}}, + .source = kChildViewRef, + .targets = {kParentViewRef}}); +} + +// Checks whether the view with |view_ref_koid| has connected to the view tree. +// The response of a f.u.o.g.Provider.Watch call is stored in |watch_response| +// if it contains |view_ref_koid|. +bool FlutterEmbedderTest::HasViewConnected( + const fuchsia::ui::observation::geometry::ViewTreeWatcherPtr& + view_tree_watcher, + std::optional& + watch_response, + zx_koid_t view_ref_koid) { + std::optional watch_result; + view_tree_watcher->Watch( + [&watch_result](auto response) { watch_result = std::move(response); }); + FML_LOG(INFO) << "Waiting for view tree watch result"; + RunLoopUntil([&watch_result] { return watch_result.has_value(); }); + FML_LOG(INFO) << "Received for view tree watch result"; + if (CheckViewExistsInUpdates(watch_result->updates(), view_ref_koid)) { + watch_response = std::move(watch_result); + }; + return watch_response.has_value(); +} + +void FlutterEmbedderTest::LaunchParentViewInRealm( + const std::vector& component_args) { + FML_LOG(INFO) << "Launching parent-view"; + + if (!component_args.empty()) { + // Construct a args.csv file containing the specified comma-separated + // component args. + std::string csv; + for (const auto& arg : component_args) { + csv += arg + ','; + } + // Remove last comma. + csv.pop_back(); + + auto config_directory_contents = DirectoryContents(); + config_directory_contents.AddFile("args.csv", csv); + realm_builder_.RouteReadOnlyDirectory("config-data", {kParentViewRef}, + std::move(config_directory_contents)); + } + realm_ = std::make_unique(realm_builder_.Build()); + + // Get the display information using the |fuchsia.ui.display.singleton.Info|. + std::optional display_metrics_obtained; + fuchsia::ui::display::singleton::InfoPtr display_info = + realm_->component().Connect(); + display_info->GetMetrics([this, &display_metrics_obtained](auto info) { + display_width_ = info.extent_in_px().width; + display_height_ = info.extent_in_px().height; + display_metrics_obtained = true; + }); + RunLoopUntil([&display_metrics_obtained] { + return display_metrics_obtained.has_value(); + }); + FML_LOG(INFO) << "Got display_width " << display_width_ << " display_height " + << display_height_; + + // Instruct Test UI Stack to present parent-view's View. + std::optional view_ref_koid; + scene_provider_ = + realm_->component().Connect(); + scene_provider_.set_error_handler( + [](auto) { FML_LOG(ERROR) << "Error from test scene provider"; }); + fuchsia::ui::test::scene::ControllerAttachClientViewRequest request; + request.set_view_provider( + realm_->component().Connect()); + scene_provider_->RegisterViewTreeWatcher(view_tree_watcher_.NewRequest(), + []() {}); + scene_provider_->AttachClientView( + std::move(request), [&view_ref_koid](auto client_view_ref_koid) { + view_ref_koid = client_view_ref_koid; + }); + + FML_LOG(INFO) << "Waiting for client view ref koid"; + RunLoopUntil([&view_ref_koid] { return view_ref_koid.has_value(); }); + + // Wait for the client view to get attached to the view tree. + std::optional + watch_response; + FML_LOG(INFO) << "Waiting for client view to render; koid is " + << (view_ref_koid.has_value() ? view_ref_koid.value() : 0); + RunLoopUntil([this, &watch_response, &view_ref_koid] { + return HasViewConnected(view_tree_watcher_, watch_response, *view_ref_koid); + }); + FML_LOG(INFO) << "Client view has rendered"; + + screenshot_ = + realm_->component().Connect(); + FML_LOG(INFO) << "Launched parent-view"; +} + +fuchsia_test_utils::Screenshot FlutterEmbedderTest::TakeScreenshot() { + FML_LOG(INFO) << "Taking screenshot... "; + + fuchsia::ui::composition::ScreenshotTakeRequest request; + request.set_format(fuchsia::ui::composition::ScreenshotFormat::BGRA_RAW); + + std::optional response; + screenshot_->Take(std::move(request), [this, &response](auto screenshot) { + response = std::move(screenshot); + QuitLoop(); + }); + + EXPECT_FALSE(RunLoopWithTimeout(kScreenshotTimeout)) + << "Timed out waiting for screenshot."; + FML_LOG(INFO) << "Screenshot captured."; + + return fuchsia_test_utils::Screenshot( + response->vmo(), display_width_, display_height_, /*display_rotation*/ 0); +} + +bool FlutterEmbedderTest::TakeScreenshotUntil( + fuchsia_test_utils::Pixel color, + fit::function)> callback, + zx::duration timeout) { + return RunLoopWithTimeoutOrUntil( + [this, &callback, &color] { + auto screenshot = TakeScreenshot(); + auto histogram = screenshot.Histogram(); + + bool color_found = histogram[color] > 0; + if (color_found && callback != nullptr) { + callback(std::move(histogram)); + } + return color_found; + }, + timeout); +} + +TEST_F(FlutterEmbedderTest, Embedding) { + LaunchParentViewInRealm(); + + // Take screenshot until we see the child-view's embedded color. + ASSERT_TRUE(TakeScreenshotUntil( + kChildBackgroundColor, + [](std::map histogram) { + // Expect parent and child background colors, with parent color > child + // color. + EXPECT_GT(histogram[kParentBackgroundColor], 0u); + EXPECT_GT(histogram[kChildBackgroundColor], 0u); + EXPECT_GT(histogram[kParentBackgroundColor], + histogram[kChildBackgroundColor]); + })); +} + +TEST_F(FlutterEmbedderTest, EmbeddingWithOverlay) { + LaunchParentViewInRealm({"--showOverlay"}); + + // Take screenshot until we see the child-view's embedded color. + ASSERT_TRUE(TakeScreenshotUntil( + kChildBackgroundColor, + [](std::map histogram) { + // Expect parent, overlay and child background colors. + // With parent color > child color and overlay color > child color. + const uint32_t overlay_pixel_count = OverlayPixelCount(histogram); + EXPECT_GT(histogram[kParentBackgroundColor], 0u); + EXPECT_GT(overlay_pixel_count, 0u); + EXPECT_GT(histogram[kChildBackgroundColor], 0u); + EXPECT_GT(histogram[kParentBackgroundColor], + histogram[kChildBackgroundColor]); + EXPECT_GT(overlay_pixel_count, histogram[kChildBackgroundColor]); + })); +} + +} // namespace flutter_embedder_test diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/meta/flutter-embedder-test.cml b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/meta/flutter-embedder-test.cml new file mode 100644 index 0000000000000000000000000000000000000000..28e1a19c526e6cfd697b9bc3dd4161bceb47a5a1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/meta/flutter-embedder-test.cml @@ -0,0 +1,50 @@ +// 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: [ + "sys/testing/gtest_runner.shard.cml", + "sys/component/realm_builder_absolute.shard.cml", + + // This test needs both the vulkan facet and the hermetic-tier-2 facet, + // so we are forced to make it a system test. + "sys/testing/system-test.shard.cml", + // TODO(https://fxbug.dev/404543928): Remove this shard usage when possible + // and replace with explicit routes. + "syslog/client.shard.cml", + "inspect/client.shard.cml", + ], + program: { + binary: "bin/app", + }, + offer: [ + { + // Offer capabilities needed by components in this test realm. + // Keep it minimal, describe only what's actually needed. + protocol: [ + "fuchsia.sysmem.Allocator", + "fuchsia.sysmem2.Allocator", + "fuchsia.tracing.provider.Registry", + "fuchsia.vulkan.loader.Loader", + ], + from: "parent", + to: "#realm_builder", + }, + ], + // TODO(https://fxbug.dev/114584): Figure out how to bring these in as deps (if possible oot). + facets: { + "fuchsia.test": { + "deprecated-allowed-packages": [ + "child-view", + "flatland-scene-manager-test-ui-stack", + "oot_flutter_aot_runner", + "oot_flutter_jit_runner", + "oot_flutter_jit_product_runner", + "oot_flutter_aot_product_runner", + "parent-view", + "test-ui-stack", + "test_manager", + ], + }, + }, +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/parent-view/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/parent-view/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..0407e790c75ba57af26eec718ec905619fc7ab56 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/parent-view/BUILD.gn @@ -0,0 +1,31 @@ +# 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. + +import("//flutter/tools/fuchsia/dart/dart_library.gni") +import("//flutter/tools/fuchsia/flutter/flutter_component.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/package.gni") + +dart_library("lib") { + package_name = "parent-view" + sources = [ "parent_view.dart" ] + + deps = [ + "//flutter/shell/platform/fuchsia/dart:args", + "//flutter/shell/platform/fuchsia/dart:vector_math", + ] +} + +flutter_component("component") { + main_package = "parent-view" + component_name = "parent-view" + main_dart = "parent_view.dart" + manifest = rebase_path("meta/parent-view.cml") + deps = [ ":lib" ] +} + +fuchsia_package("package") { + package_name = "parent-view" + deps = [ ":component" ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/parent-view/lib/parent_view.dart b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/parent-view/lib/parent_view.dart new file mode 100644 index 0000000000000000000000000000000000000000..cf937836c2e9c78a8baea20d4ea8ee08b06ee59d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/parent-view/lib/parent_view.dart @@ -0,0 +1,209 @@ +// 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. + +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; +import 'dart:io'; +import 'dart:ui'; + +import 'package:args/args.dart'; +import 'package:vector_math/vector_math_64.dart' as vector_math_64; + +final _argsCsvFilePath = '/config/data/args.csv'; + +void main(List args) async { + print('parent-view: starting'); + + args = args + _GetArgsFromConfigFile(); + final parser = + ArgParser() + ..addFlag('showOverlay', defaultsTo: false) + ..addFlag('focusable', defaultsTo: true); + final arguments = parser.parse(args); + for (final option in arguments.options) { + print('parent-view: $option: ${arguments[option]}'); + } + + TestApp app; + app = TestApp( + ChildView(await _launchChildView()), + showOverlay: arguments['showOverlay'], + focusable: arguments['focusable'], + ); + + app.run(); +} + +class TestApp { + static const _black = Color.fromARGB(255, 0, 0, 0); + static const _blue = Color.fromARGB(255, 0, 0, 255); + + final ChildView childView; + final bool showOverlay; + final bool focusable; + + Color _backgroundColor = _blue; + + TestApp(this.childView, {this.showOverlay = false, this.focusable = true}) {} + + void run() { + childView.create(focusable, (ByteData? reply) { + // Set up window allbacks. + window.onPointerDataPacket = (PointerDataPacket packet) { + for (final data in packet.data) { + if (data.change == PointerChange.down) { + this._backgroundColor = _black; + } + } + window.scheduleFrame(); + }; + window.onMetricsChanged = () { + window.scheduleFrame(); + }; + window.onBeginFrame = (Duration duration) { + this.beginFrame(duration); + }; + + // The child view should be attached to Scenic now. + // Ready to build the scene. + window.scheduleFrame(); + }); + } + + void beginFrame(Duration duration) { + final windowPhysicalBounds = Offset.zero & window.physicalSize; + final pixelRatio = window.devicePixelRatio; + final windowSize = window.physicalSize / pixelRatio; + final windowBounds = Offset.zero & windowSize; + + final recorder = PictureRecorder(); + final canvas = Canvas(recorder, windowPhysicalBounds); + canvas.scale(pixelRatio); + final paint = Paint()..color = this._backgroundColor; + canvas.drawRect(windowBounds, paint); + final picture = recorder.endRecording(); + + final sceneBuilder = + SceneBuilder() + ..pushClipRect(windowPhysicalBounds) + ..addPicture(Offset.zero, picture); + + final childPhysicalSize = window.physicalSize * 0.33; + // Alignment.center + final windowCenter = windowSize.center(Offset.zero); + final windowPhysicalCenter = window.physicalSize.center(Offset.zero); + final childPhysicalOffset = windowPhysicalCenter - childPhysicalSize.center(Offset.zero); + + sceneBuilder + ..pushTransform( + vector_math_64.Matrix4.translationValues( + childPhysicalOffset.dx, + childPhysicalOffset.dy, + 0.0, + ).storage, + ) + ..addPlatformView( + childView.viewId, + width: childPhysicalSize.width, + height: childPhysicalSize.height, + ) + ..pop(); + + if (showOverlay) { + final containerSize = windowSize * .66; + // Alignment.center + final containerOffset = windowCenter - containerSize.center(Offset.zero); + + final overlaySize = containerSize * 0.5; + // Alignment.topRight + final overlayOffset = Offset( + containerOffset.dx + containerSize.width - overlaySize.width, + containerOffset.dy, + ); + + final overlayPhysicalSize = overlaySize * pixelRatio; + final overlayPhysicalOffset = overlayOffset * pixelRatio; + final overlayPhysicalBounds = overlayPhysicalOffset & overlayPhysicalSize; + + final recorder = PictureRecorder(); + final overlayCullRect = Offset.zero & overlayPhysicalSize; // in canvas physical coordinates + final canvas = Canvas(recorder, overlayCullRect); + canvas.scale(pixelRatio); + final paint = Paint()..color = Color.fromARGB(255, 0, 255, 0); + canvas.drawRect(Offset.zero & overlaySize, paint); + final overlayPicture = recorder.endRecording(); + sceneBuilder + ..pushClipRect(overlayPhysicalBounds) // in window physical coordinates + ..addPicture(overlayPhysicalOffset, overlayPicture) + ..pop(); + } + sceneBuilder.pop(); + + window.render(sceneBuilder.build()); + } +} + +class ChildView { + final int viewId; + + ChildView(this.viewId); + + void create(bool focusable, PlatformMessageResponseCallback callback) { + // Construct the dart:ui platform message to create the view, and when the + // return callback is invoked, build the scene. At that point, it is safe + // to embed the child-view2 in the scene. + final viewOcclusionHint = Rect.zero; + + final Map args = { + 'viewId': viewId, + // Flatland doesn't support disabling hit testing. + 'hitTestable': true, + 'focusable': focusable, + 'viewOcclusionHintLTRB': [ + viewOcclusionHint.left, + viewOcclusionHint.top, + viewOcclusionHint.right, + viewOcclusionHint.bottom, + ], + }; + + final ByteData createViewMessage = ByteData.sublistView( + utf8.encode(json.encode({'method': 'View.create', 'args': args})), + ); + + final platformViewsChannel = 'flutter/platform_views'; + + PlatformDispatcher.instance.sendPlatformMessage( + platformViewsChannel, + createViewMessage, + callback, + ); + } +} + +Future _launchChildView() async { + final message = Int8List.fromList([0x31]); + final completer = new Completer(); + PlatformDispatcher.instance.sendPlatformMessage( + 'fuchsia/child_view', + ByteData.sublistView(message), + (ByteData? reply) { + completer.complete(reply!); + }, + ); + + return int.parse(ascii.decode(((await completer.future).buffer.asUint8List()))); +} + +List _GetArgsFromConfigFile() { + List args; + final f = File(_argsCsvFilePath); + if (!f.existsSync()) { + return List.empty(); + } + final fileContentCsv = f.readAsStringSync(); + args = fileContentCsv.split('\n'); + return args; +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/parent-view/meta/parent-view.cml b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/parent-view/meta/parent-view.cml new file mode 100644 index 0000000000000000000000000000000000000000..a285bb4a55ad85fa07326372c82dc102f736a0f5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/parent-view/meta/parent-view.cml @@ -0,0 +1,42 @@ +// 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: [ "syslog/client.shard.cml" ], + program: { + data: "data/parent-view", + + // Always use the jit runner for now. + // TODO(fxbug.dev/106577): Implement manifest merging build rules for V2 components. + runner: "flutter_jit_runner", + }, + capabilities: [ + { + protocol: [ "fuchsia.ui.app.ViewProvider" ], + }, + ], + use: [ + { + protocol: [ + "fuchsia.ui.app.ViewProvider", + ], + }, + { + directory: "config-data", + rights: [ "r*" ], + path: "/config/data", + }, + // See common.shard.cml. + { + directory: "tzdata-icu", + rights: [ "r*" ], + path: "/config/tzdata/icu", + }, + ], + expose: [ + { + protocol: [ "fuchsia.ui.app.ViewProvider" ], + from: "self", + }, + ], +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/parent-view/pubspec.yaml b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/parent-view/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..418f4a5f0179a756e4867f790fc8433741f4dc0d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/embedder/parent-view/pubspec.yaml @@ -0,0 +1,8 @@ +# 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. + +name: parent-view2 + +environment: + sdk: ^3.7.0-0 diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..62697f2cc10042ad8e859543e6ccdd437f15f872 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/BUILD.gn @@ -0,0 +1,65 @@ +# 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. + +assert(is_fuchsia) + +import("//flutter/tools/fuchsia/fuchsia_archive.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/package.gni") + +group("tests") { + testonly = true + deps = [ ":mouse-input-test" ] +} + +executable("mouse-input-test-bin") { + testonly = true + output_name = "mouse-input-test" + sources = [ "mouse-input-test.cc" ] + + # This is needed for //flutter/third_party/googletest for linking zircon + # symbols. + libs = [ "${fuchsia_arch_root}/sysroot/lib/libzircon.so" ] + + deps = [ + "${fuchsia_sdk}/fidl/fuchsia.accessibility.semantics", + "${fuchsia_sdk}/fidl/fuchsia.buildinfo", + "${fuchsia_sdk}/fidl/fuchsia.component", + "${fuchsia_sdk}/fidl/fuchsia.fonts", + "${fuchsia_sdk}/fidl/fuchsia.intl", + "${fuchsia_sdk}/fidl/fuchsia.kernel", + "${fuchsia_sdk}/fidl/fuchsia.memorypressure", + "${fuchsia_sdk}/fidl/fuchsia.metrics", + "${fuchsia_sdk}/fidl/fuchsia.net.interfaces", + "${fuchsia_sdk}/fidl/fuchsia.tracing.provider", + "${fuchsia_sdk}/fidl/fuchsia.ui.app", + "${fuchsia_sdk}/fidl/fuchsia.ui.display.singleton", + "${fuchsia_sdk}/fidl/fuchsia.ui.input", + "${fuchsia_sdk}/fidl/fuchsia.ui.pointerinjector", + "${fuchsia_sdk}/fidl/fuchsia.ui.test.input", + "${fuchsia_sdk}/fidl/fuchsia.ui.test.scene", + "${fuchsia_sdk}/fidl/fuchsia.web", + "${fuchsia_sdk}/pkg/async", + "${fuchsia_sdk}/pkg/async-loop-testing", + "${fuchsia_sdk}/pkg/fidl_cpp", + "${fuchsia_sdk}/pkg/sys_component_cpp_testing", + "${fuchsia_sdk}/pkg/zx", + "mouse-input-view:package", + "//flutter/fml", + "//flutter/shell/platform/fuchsia/flutter/tests/integration/utils:portable_ui_test", + "//flutter/third_party/googletest:gtest", + "//flutter/third_party/googletest:gtest_main", + ] +} + +fuchsia_test_archive("mouse-input-test") { + deps = [ + ":mouse-input-test-bin", + + # "OOT" copies of the runners used by tests, to avoid conflicting with the + # runners in the base fuchsia image. + # TODO(fxbug.dev/106575): Fix this with subpackages. + "//flutter/shell/platform/fuchsia/flutter:oot_flutter_jit_runner", + ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/README.md b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5755445724ab7b28d036c1f0de2b71fae28d40a9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/README.md @@ -0,0 +1,58 @@ +# mouse-input + +`mouse-input-test` exercises mouse input through a child view (in this case, the `mouse-input-view` Dart component) and +asserting the location as well as what button was used (mouse down, mouse up, wheel, etc) during the event. We do this by +attaching the child view, injecting mouse input, and validating that the view reports the event back with the expected +payload. + +```shell +Injecting the mouse input +[mouse-input-test.cm] INFO: [portable_ui_test.cc(227)] Injecting mouse input + +View receives the event +[flutter_jit_runner] INFO: mouse-input-view.cm(flutter): mouse-input-view received input: PointerData(embedderId: 0, timeStamp: 23:18:05.031003, change: PointerChange.add, kind: PointerDeviceKind.mouse, signalKind: PointerSignalKind.none, device: 4294967295, pointerIdentifier: 0, physicalX: 641.4656372070312, physicalY: 402.9313049316406, physicalDeltaX: 0.0, physicalDeltaY: 0.0, buttons: 0, synthesized: true, pressure: 0.0, pressureMin: 0.0, pressureMax: 0.0, distance: 0.0, distanceMax: 0.0, size: 0.0, radiusMajor: 0.0, radiusMinor: 0.0, radiusMin: 0.0, radiusMax: 0.0, orientation: 0.0, tilt: 0.0, platformData: 0, scrollDeltaX: 0.0, scrollDeltaY: 0.0, panX: 0.0, panY: 0.0, panDeltaX: 0.0, panDeltaY: 0.0, scale: 0.0, rotation: 0.0) + +Successfully received response from view +[mouse-input-test.cm] INFO: [mouse-input-test.cc(120)] Received MouseInput event +[mouse-input-test.cm] INFO: [mouse-input-test.cc(207)] Client received mouse change at (641.466, 402.931) with buttons 0. +[mouse-input-test.cm] INFO: [mouse-input-test.cc(211)] Expected mouse change is at approximately (641, 402) with buttons 0. +``` + +## Running the Test + +Reference the Flutter integration test [documentation](https://github.com/flutter/engine/blob/main/shell/platform/fuchsia/flutter/tests/integration/README.md) at `//flutter/shell/platform/fuchsia/flutter/tests/integration/README.md` + +## Playing around with `mouse-input-view` + +Build Fuchsia with `terminal.qemu-x64` +```shell +fx set terminal.qemu-x64 && fx build +``` + +Build flutter/engine +```shell +$ENGINE_DIR/flutter/tools/gn --fuchsia --no-lto && ninja -C $ENGINE_DIR/out/fuchsia_debug_x64 flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input:tests +``` + +Start a Fuchsia package server +```shell +cd "$FUCHSIA_DIR" +fx serve +``` + +Publish `mouse-input-view` +```shell +$FUCHSIA_DIR/.jiri_root/bin/fx pm publish -a -repo $FUCHSIA_DIR/$(cat $FUCHSIA_DIR/.fx-build-dir)/amber-files -f $ENGINE_DIR/out/fuchsia_debug_x64/gen/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-view/mouse-input-view/mouse-input-view.far +``` + +Launch Fuchsia emulator in a graphical environment +```shell +ffx emu start +``` + +**Before proceeding, make sure you have successfully completed the "Set a Password" screen** + +Add `mouse-input-view` +```shell +ffx session add fuchsia-pkg://fuchsia.com/mouse-input-view#meta/mouse-input-view.cm +``` diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/meta/mouse-input-test.cml b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/meta/mouse-input-test.cml new file mode 100644 index 0000000000000000000000000000000000000000..a95f67901ef45fdf3db95bcd0e52f475e22121de --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/meta/mouse-input-test.cml @@ -0,0 +1,82 @@ +// 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: [ + "sys/testing/gtest_runner.shard.cml", + "sys/component/realm_builder_absolute.shard.cml", + + // This test needs both the vulkan facet and the hermetic-tier-2 facet, + // so we are forced to make it a system test. + "sys/testing/system-test.shard.cml", + + // TODO(https://fxbug.dev/404543928): Remove this shard usage when possible + // and replace with explicit routes. + "syslog/client.shard.cml", + "inspect/client.shard.cml", + ], + program: { + binary: "bin/app", + }, + use: [ + { + protocol: [ + "fuchsia.ui.test.input.MouseInputListener", + ] + } + ], + offer: [ + { + // Offer capabilities needed by components in this test realm. + // Keep it minimal, describe only what's actually needed. + protocol: [ + "fuchsia.kernel.RootJobForInspect", + "fuchsia.kernel.Stats", + "fuchsia.scheduler.ProfileProvider", + "fuchsia.sysmem.Allocator", + "fuchsia.sysmem2.Allocator", + "fuchsia.tracing.provider.Registry", + "fuchsia.ui.input.ImeService", + "fuchsia.vulkan.loader.Loader", + "fuchsia.ui.composition.Allocator", + "fuchsia.ui.composition.Flatland", + "fuchsia.ui.test.input.MouseInputListener", + "fuchsia.intl.PropertyProvider", + "fuchsia.posix.socket.Provider", + "fuchsia.ui.pointerinjector.Registry", + ], + from: "parent", + to: "#realm_builder", + }, + { + directory: "pkg", + subdir: "config", + as: "config-data", + from: "framework", + to: "#realm_builder", + }, + // See common.shard.cml. + { + directory: "tzdata-icu", + from: "framework", + to: "#realm_builder", + }, + ], + // TODO(https://fxbug.dev/114584): Figure out how to bring these in as deps (if possible oot). + facets: { + "fuchsia.test": { + "deprecated-allowed-packages": [ + "child-view", + "cursor", + "flatland-scene-manager-test-ui-stack", + "mouse-input-view", + "oot_flutter_aot_runner", + "oot_flutter_jit_runner", + "oot_flutter_jit_product_runner", + "oot_flutter_aot_product_runner", + "test_manager", + "test-ui-stack", + ], + }, + }, +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-test.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-test.cc new file mode 100644 index 0000000000000000000000000000000000000000..bbce8eed34db256b7f5d37be213215c936b8049e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-test.cc @@ -0,0 +1,616 @@ +// Copyright 2022 The Fuchsia 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "flutter/fml/logging.h" +#include "flutter/shell/platform/fuchsia/flutter/tests/integration/utils/portable_ui_test.h" +#include "lib/fidl/cpp/interface_ptr.h" + +namespace mouse_input_test::testing { +namespace { +// Types imported for the realm_builder library. +using component_testing::ChildRef; +using component_testing::ConfigValue; +using component_testing::LocalComponentImpl; +using component_testing::ParentRef; +using component_testing::Protocol; +using component_testing::Realm; +using component_testing::Route; + +using fuchsia_test_utils::PortableUITest; +using RealmBuilder = component_testing::RealmBuilder; + +// Alias for Component child name as provided to Realm Builder. +using ChildName = std::string; + +// Alias for Component Legacy URL as provided to Realm Builder. +using LegacyUrl = std::string; + +// Maximum pointer movement during a clickpad press for the gesture to +// be guaranteed to be interpreted as a click. For movement greater than +// this value, upper layers may, e.g., interpret the gesture as a drag. +// +// This value corresponds to the one used to instantiate the ClickDragHandler +// registered by Input Pipeline in Scene Manager. +constexpr int64_t kClickToDragThreshold = 16.0; + +constexpr auto kMouseInputListener = "mouse_input_listener"; +constexpr auto kMouseInputListenerRef = ChildRef{kMouseInputListener}; +constexpr auto kMouseInputView = "mouse-input-view"; +constexpr auto kMouseInputViewRef = ChildRef{kMouseInputView}; +constexpr auto kMouseInputViewUrl = + "fuchsia-pkg://fuchsia.com/mouse-input-view#meta/mouse-input-view.cm"; + +struct Position { + double x = 0.0; + double y = 0.0; +}; + +// Combines all vectors in `vecs` into one. +template +std::vector merge(std::initializer_list> vecs) { + std::vector result; + for (auto v : vecs) { + result.insert(result.end(), v.begin(), v.end()); + } + return result; +} + +int ButtonsToInt( + const std::vector& buttons) { + int result = 0; + for (const auto& button : buttons) { + result |= (0x1 >> button); + } + + return result; +} + +// `MouseInputListener` is a local test protocol that our test apps use to let +// us know what position and button press state the mouse cursor has. +class MouseInputListenerServer + : public fuchsia::ui::test::input::MouseInputListener, + public LocalComponentImpl { + public: + explicit MouseInputListenerServer(async_dispatcher_t* dispatcher) + : dispatcher_(dispatcher) {} + + void ReportMouseInput( + fuchsia::ui::test::input::MouseInputListenerReportMouseInputRequest + request) override { + FML_LOG(INFO) << "Received MouseInput event"; + events_.push(std::move(request)); + } + + // |MockComponent::OnStart| + // When the component framework requests for this component to start, this + // method will be invoked by the realm_builder library. + void OnStart() override { + FML_LOG(INFO) << "Starting MouseInputServer"; + ASSERT_EQ(ZX_OK, outgoing()->AddPublicService( + fidl::InterfaceRequestHandler< + fuchsia::ui::test::input::MouseInputListener>( + [this](auto request) { + bindings_.AddBinding(this, std::move(request), + dispatcher_); + }))); + } + + size_t SizeOfEvents() const { return events_.size(); } + + fuchsia::ui::test::input::MouseInputListenerReportMouseInputRequest + PopEvent() { + auto e = std::move(events_.front()); + events_.pop(); + return e; + } + + const fuchsia::ui::test::input::MouseInputListenerReportMouseInputRequest& + LastEvent() const { + return events_.back(); + } + + void ClearEvents() { events_ = {}; } + + private: + // Not owned. + async_dispatcher_t* dispatcher_ = nullptr; + fidl::BindingSet bindings_; + std::queue< + fuchsia::ui::test::input::MouseInputListenerReportMouseInputRequest> + events_; +}; + +class MouseInputTest : public PortableUITest, + public ::testing::Test, + public ::testing::WithParamInterface { + protected: + void SetUp() override { + PortableUITest::SetUp(); + + // Register fake mouse device. + RegisterMouse(); + + // Get the display dimensions. + FML_LOG(INFO) + << "Waiting for display info from fuchsia.ui.display.singleton.Info"; + fuchsia::ui::display::singleton::InfoPtr display_info = + realm_root() + ->component() + .Connect(); + display_info->GetMetrics( + [this](fuchsia::ui::display::singleton::Metrics metrics) { + display_width_ = metrics.extent_in_px().width; + display_height_ = metrics.extent_in_px().height; + FML_LOG(INFO) << "Got display_width = " << display_width_ + << " and display_height = " << display_height_; + }); + RunLoopUntil( + [this] { return display_width_ != 0 && display_height_ != 0; }); + } + + void TearDown() override { + // at the end of test, ensure event queue is empty. + ASSERT_EQ(mouse_input_listener_->SizeOfEvents(), 0u); + } + + MouseInputListenerServer* mouse_input_listener() { + return mouse_input_listener_; + } + + // Helper method for checking the test.mouse.MouseInputListener response from + // the client app. + void VerifyEvent( + fuchsia::ui::test::input::MouseInputListenerReportMouseInputRequest& + pointer_data, + double expected_x, + double expected_y, + std::vector expected_buttons, + const fuchsia::ui::test::input::MouseEventPhase expected_phase, + const std::string& component_name) { + FML_LOG(INFO) << "Client received mouse change at (" + << pointer_data.local_x() << ", " << pointer_data.local_y() + << ") with buttons " << ButtonsToInt(pointer_data.buttons()) + << "."; + FML_LOG(INFO) << "Expected mouse change is at approximately (" << expected_x + << ", " << expected_y << ") with buttons " + << ButtonsToInt(expected_buttons) << "."; + + // Allow for minor rounding differences in coordinates. + // Note: These approximations don't account for + // `PointerMotionDisplayScaleHandler` or `PointerMotionSensorScaleHandler`. + // We will need to do so in order to validate larger motion or different + // sized displays. + EXPECT_NEAR(pointer_data.local_x(), expected_x, 1); + EXPECT_NEAR(pointer_data.local_y(), expected_y, 1); + EXPECT_EQ(pointer_data.buttons(), expected_buttons); + EXPECT_EQ(pointer_data.phase(), expected_phase); + EXPECT_EQ(pointer_data.component_name(), component_name); + } + + void VerifyEventLocationOnTheRightOfExpectation( + fuchsia::ui::test::input::MouseInputListenerReportMouseInputRequest& + pointer_data, + double expected_x_min, + double expected_y, + std::vector expected_buttons, + const fuchsia::ui::test::input::MouseEventPhase expected_phase, + const std::string& component_name) { + FML_LOG(INFO) << "Client received mouse change at (" + << pointer_data.local_x() << ", " << pointer_data.local_y() + << ") with buttons " << ButtonsToInt(pointer_data.buttons()) + << "."; + FML_LOG(INFO) << "Expected mouse change is at approximately (>" + << expected_x_min << ", " << expected_y << ") with buttons " + << ButtonsToInt(expected_buttons) << "."; + + EXPECT_GT(pointer_data.local_x(), expected_x_min); + EXPECT_NEAR(pointer_data.local_y(), expected_y, 1); + EXPECT_EQ(pointer_data.buttons(), expected_buttons); + EXPECT_EQ(pointer_data.phase(), expected_phase); + EXPECT_EQ(pointer_data.component_name(), component_name); + } + + // Guaranteed to be initialized after SetUp(). + uint32_t display_width() const { return display_width_; } + uint32_t display_height() const { return display_height_; } + + private: + void ExtendRealm() override { + FML_LOG(INFO) << "Extending realm"; + + // Key part of service setup: have this test component vend the + // |MouseInputListener| service in the constructed realm. + auto mouse_input_listener = + std::make_unique(dispatcher()); + mouse_input_listener_ = mouse_input_listener.get(); + realm_builder()->AddLocalChild( + kMouseInputListener, + [mouse_input_listener = std::move(mouse_input_listener)]() mutable { + return std::move(mouse_input_listener); + }); + + realm_builder()->AddChild(kMouseInputView, kMouseInputViewUrl, + component_testing::ChildOptions{ + .environment = kFlutterRunnerEnvironment, + }); + + realm_builder()->AddRoute( + Route{.capabilities = {Protocol{ + fuchsia::ui::test::input::MouseInputListener::Name_}}, + .source = kMouseInputListenerRef, + .targets = {kFlutterJitRunnerRef, kMouseInputViewRef}}); + + realm_builder()->AddRoute( + Route{.capabilities = {Protocol{fuchsia::ui::app::ViewProvider::Name_}}, + .source = kMouseInputViewRef, + .targets = {ParentRef()}}); + } + + ParamType GetTestUIStackUrl() override { return GetParam(); }; + + MouseInputListenerServer* mouse_input_listener_; + + uint32_t display_width_ = 0; + uint32_t display_height_ = 0; +}; + +// Makes use of gtest's parameterized testing, allowing us +// to test different combinations of test-ui-stack + runners. Currently, there +// is just one combination. Documentation: +// http://go/gunitadvanced#value-parameterized-tests +INSTANTIATE_TEST_SUITE_P( + MouseInputTestParameterized, + MouseInputTest, + ::testing::Values( + "fuchsia-pkg://fuchsia.com/flatland-scene-manager-test-ui-stack#meta/" + "test-ui-stack.cm")); + +TEST_P(MouseInputTest, DISABLED_FlutterMouseMove) { + LaunchClient(); + + SimulateMouseEvent(/* pressed_buttons = */ {}, /* movement_x = */ 1, + /* movement_y = */ 2); + RunLoopUntil( + [this] { return this->mouse_input_listener()->SizeOfEvents() == 1; }); + + ASSERT_EQ(mouse_input_listener()->SizeOfEvents(), 1u); + + auto e = mouse_input_listener()->PopEvent(); + + // If the first mouse event is cursor movement, Flutter first sends an ADD + // event with updated location. + VerifyEvent(e, + /*expected_x=*/static_cast(display_width()) / 2.f + 1, + /*expected_y=*/static_cast(display_height()) / 2.f + 2, + /*expected_buttons=*/{}, + /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::ADD, + /*component_name=*/"mouse-input-view"); +} + +TEST_P(MouseInputTest, DISABLED_FlutterMouseDown) { + LaunchClient(); + + SimulateMouseEvent( + /* pressed_buttons = */ {fuchsia::ui::test::input::MouseButton::FIRST}, + /* movement_x = */ 0, /* movement_y = */ 0); + RunLoopUntil( + [this] { return this->mouse_input_listener()->SizeOfEvents() == 3; }); + + ASSERT_EQ(mouse_input_listener()->SizeOfEvents(), 3u); + + auto event_add = mouse_input_listener()->PopEvent(); + auto event_down = mouse_input_listener()->PopEvent(); + auto event_noop_move = mouse_input_listener()->PopEvent(); + + // If the first mouse event is a button press, Flutter first sends an ADD + // event with no buttons. + VerifyEvent(event_add, + /*expected_x=*/static_cast(display_width()) / 2.f, + /*expected_y=*/static_cast(display_height()) / 2.f, + /*expected_buttons=*/{}, + /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::ADD, + /*component_name=*/"mouse-input-view"); + + // Then Flutter sends a DOWN pointer event with the buttons we care about. + VerifyEvent( + event_down, + /*expected_x=*/static_cast(display_width()) / 2.f, + /*expected_y=*/static_cast(display_height()) / 2.f, + /*expected_buttons=*/{fuchsia::ui::test::input::MouseButton::FIRST}, + /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::DOWN, + /*component_name=*/"mouse-input-view"); + + // Then Flutter sends a MOVE pointer event with no new information. + VerifyEvent( + event_noop_move, + /*expected_x=*/static_cast(display_width()) / 2.f, + /*expected_y=*/static_cast(display_height()) / 2.f, + /*expected_buttons=*/{fuchsia::ui::test::input::MouseButton::FIRST}, + /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::MOVE, + /*component_name=*/"mouse-input-view"); +} + +TEST_P(MouseInputTest, DISABLED_FlutterMouseDownUp) { + LaunchClient(); + + SimulateMouseEvent( + /* pressed_buttons = */ {fuchsia::ui::test::input::MouseButton::FIRST}, + /* movement_x = */ 0, /* movement_y = */ 0); + RunLoopUntil( + [this] { return this->mouse_input_listener()->SizeOfEvents() == 3; }); + + ASSERT_EQ(mouse_input_listener()->SizeOfEvents(), 3u); + + auto event_add = mouse_input_listener()->PopEvent(); + auto event_down = mouse_input_listener()->PopEvent(); + auto event_noop_move = mouse_input_listener()->PopEvent(); + + // If the first mouse event is a button press, Flutter first sends an ADD + // event with no buttons. + VerifyEvent(event_add, + /*expected_x=*/static_cast(display_width()) / 2.f, + /*expected_y=*/static_cast(display_height()) / 2.f, + /*expected_buttons=*/{}, + /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::ADD, + /*component_name=*/"mouse-input-view"); + + // Then Flutter sends a DOWN pointer event with the buttons we care about. + VerifyEvent( + event_down, + /*expected_x=*/static_cast(display_width()) / 2.f, + /*expected_y=*/static_cast(display_height()) / 2.f, + /*expected_buttons=*/{fuchsia::ui::test::input::MouseButton::FIRST}, + /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::DOWN, + /*component_name=*/"mouse-input-view"); + + // Then Flutter sends a MOVE pointer event with no new information. + VerifyEvent( + event_noop_move, + /*expected_x=*/static_cast(display_width()) / 2.f, + /*expected_y=*/static_cast(display_height()) / 2.f, + /*expected_buttons=*/{fuchsia::ui::test::input::MouseButton::FIRST}, + /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::MOVE, + /*component_name=*/"mouse-input-view"); + + SimulateMouseEvent(/* pressed_buttons = */ {}, /* movement_x = */ 0, + /* movement_y = */ 0); + RunLoopUntil( + [this] { return this->mouse_input_listener()->SizeOfEvents() == 1; }); + + ASSERT_EQ(mouse_input_listener()->SizeOfEvents(), 1u); + + auto event_up = mouse_input_listener()->PopEvent(); + VerifyEvent(event_up, + /*expected_x=*/static_cast(display_width()) / 2.f, + /*expected_y=*/static_cast(display_height()) / 2.f, + /*expected_buttons=*/{}, + /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::UP, + /*component_name=*/"mouse-input-view"); +} + +TEST_P(MouseInputTest, DISABLED_FlutterMouseDownMoveUp) { + LaunchClient(); + + SimulateMouseEvent( + /* pressed_buttons = */ {fuchsia::ui::test::input::MouseButton::FIRST}, + /* movement_x = */ 0, /* movement_y = */ 0); + RunLoopUntil( + [this] { return this->mouse_input_listener()->SizeOfEvents() == 3; }); + + ASSERT_EQ(mouse_input_listener()->SizeOfEvents(), 3u); + + auto event_add = mouse_input_listener()->PopEvent(); + auto event_down = mouse_input_listener()->PopEvent(); + auto event_noop_move = mouse_input_listener()->PopEvent(); + + // If the first mouse event is a button press, Flutter first sends an ADD + // event with no buttons. + VerifyEvent(event_add, + /*expected_x=*/static_cast(display_width()) / 2.f, + /*expected_y=*/static_cast(display_height()) / 2.f, + /*expected_buttons=*/{}, + /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::ADD, + /*component_name=*/"mouse-input-view"); + + // Then Flutter sends a DOWN pointer event with the buttons we care about. + VerifyEvent( + event_down, + /*expected_x=*/static_cast(display_width()) / 2.f, + /*expected_y=*/static_cast(display_height()) / 2.f, + /*expected_buttons=*/{fuchsia::ui::test::input::MouseButton::FIRST}, + /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::DOWN, + /*component_name=*/"mouse-input-view"); + + // Then Flutter sends a MOVE pointer event with no new information. + VerifyEvent( + event_noop_move, + /*expected_x=*/static_cast(display_width()) / 2.f, + /*expected_y=*/static_cast(display_height()) / 2.f, + /*expected_buttons=*/{fuchsia::ui::test::input::MouseButton::FIRST}, + /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::MOVE, + /*component_name=*/"mouse-input-view"); + + SimulateMouseEvent( + /* pressed_buttons = */ {fuchsia::ui::test::input::MouseButton::FIRST}, + /* movement_x = */ kClickToDragThreshold, /* movement_y = */ 0); + RunLoopUntil( + [this] { return this->mouse_input_listener()->SizeOfEvents() == 1; }); + + ASSERT_EQ(mouse_input_listener()->SizeOfEvents(), 1u); + + auto event_move = mouse_input_listener()->PopEvent(); + + VerifyEventLocationOnTheRightOfExpectation( + event_move, + /*expected_x_min=*/static_cast(display_width()) / 2.f + 1, + /*expected_y=*/static_cast(display_height()) / 2.f, + /*expected_buttons=*/{fuchsia::ui::test::input::MouseButton::FIRST}, + /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::MOVE, + /*component_name=*/"mouse-input-view"); + + SimulateMouseEvent(/* pressed_buttons = */ {}, /* movement_x = */ 0, + /* movement_y = */ 0); + RunLoopUntil( + [this] { return this->mouse_input_listener()->SizeOfEvents() == 1; }); + + ASSERT_EQ(mouse_input_listener()->SizeOfEvents(), 1u); + + auto event_up = mouse_input_listener()->PopEvent(); + + VerifyEventLocationOnTheRightOfExpectation( + event_up, + /*expected_x_min=*/static_cast(display_width()) / 2.f + 1, + /*expected_y=*/static_cast(display_height()) / 2.f, + /*expected_buttons=*/{}, + /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::UP, + /*component_name=*/"mouse-input-view"); +} + +// TODO(fxbug.dev/103098): This test shows the issue when sending mouse wheel as +// the first event to Flutter. +// 1. expect Flutter app receive 2 events: ADD - Scroll, but got 3 events: Move +// - Scroll - Scroll. +// 2. the first event flutter app received has random value in buttons field +// Disabled until flutter rolls, since it changes the behavior of this issue. +TEST_P(MouseInputTest, DISABLED_FlutterMouseWheelIssue103098) { + LaunchClient(); + + SimulateMouseScroll(/* pressed_buttons = */ {}, /* scroll_x = */ 1, + /* scroll_y = */ 0); + // Here we expected 2 events, ADD - Scroll, but got 3, Move - Scroll - Scroll. + RunLoopUntil( + [this] { return this->mouse_input_listener()->SizeOfEvents() == 3; }); + + double initial_x = static_cast(display_width()) / 2.f; + double initial_y = static_cast(display_height()) / 2.f; + + auto event_1 = mouse_input_listener()->PopEvent(); + EXPECT_NEAR(event_1.local_x(), initial_x, 1); + EXPECT_NEAR(event_1.local_y(), initial_y, 1); + // Flutter will scale the count of ticks to pixel. + EXPECT_GT(event_1.wheel_x_physical_pixel(), 0); + EXPECT_EQ(event_1.wheel_y_physical_pixel(), 0); + EXPECT_EQ(event_1.phase(), fuchsia::ui::test::input::MouseEventPhase::MOVE); + + auto event_2 = mouse_input_listener()->PopEvent(); + VerifyEvent( + event_2, + /*expected_x=*/initial_x, + /*expected_y=*/initial_y, + /*expected_buttons=*/{}, + /*expected_phase=*/fuchsia::ui::test::input::MouseEventPhase::HOVER, + /*component_name=*/"mouse-input-view"); + // Flutter will scale the count of ticks to pixel. + EXPECT_GT(event_2.wheel_x_physical_pixel(), 0); + EXPECT_EQ(event_2.wheel_y_physical_pixel(), 0); + + auto event_3 = mouse_input_listener()->PopEvent(); + VerifyEvent( + event_3, + /*expected_x=*/initial_x, + /*expected_y=*/initial_y, + /*expected_buttons=*/{}, + /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::HOVER, + /*component_name=*/"mouse-input-view"); + // Flutter will scale the count of ticks to pixel. + EXPECT_GT(event_3.wheel_x_physical_pixel(), 0); + EXPECT_EQ(event_3.wheel_y_physical_pixel(), 0); +} + +TEST_P(MouseInputTest, DISABLED_FlutterMouseWheel) { + LaunchClient(); + + double initial_x = static_cast(display_width()) / 2.f + 1; + double initial_y = static_cast(display_height()) / 2.f + 2; + + // TODO(fxbug.dev/103098): Send a mouse move as the first event to workaround. + SimulateMouseEvent(/* pressed_buttons = */ {}, + /* movement_x = */ 1, /* movement_y = */ 2); + RunLoopUntil( + [this] { return this->mouse_input_listener()->SizeOfEvents() == 1; }); + + auto event_add = mouse_input_listener()->PopEvent(); + VerifyEvent(event_add, + /*expected_x=*/initial_x, + /*expected_y=*/initial_y, + /*expected_buttons=*/{}, + /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::ADD, + /*component_name=*/"mouse-input-view"); + + SimulateMouseScroll(/* pressed_buttons = */ {}, /* scroll_x = */ 1, + /* scroll_y = */ 0); + RunLoopUntil( + [this] { return this->mouse_input_listener()->SizeOfEvents() == 1; }); + + auto event_wheel_h = mouse_input_listener()->PopEvent(); + + VerifyEvent( + event_wheel_h, + /*expected_x=*/initial_x, + /*expected_y=*/initial_y, + /*expected_buttons=*/{}, + /*expected_phase=*/fuchsia::ui::test::input::MouseEventPhase::HOVER, + /*component_name=*/"mouse-input-view"); + // Flutter will scale the count of ticks to pixel. + EXPECT_GT(event_wheel_h.wheel_x_physical_pixel(), 0); + EXPECT_EQ(event_wheel_h.wheel_y_physical_pixel(), 0); + + SimulateMouseScroll(/* pressed_buttons = */ {}, /* scroll_x = */ 0, + /* scroll_y = */ 1); + RunLoopUntil( + [this] { return this->mouse_input_listener()->SizeOfEvents() == 1; }); + + auto event_wheel_v = mouse_input_listener()->PopEvent(); + + VerifyEvent( + event_wheel_v, + /*expected_x=*/initial_x, + /*expected_y=*/initial_y, + /*expected_buttons=*/{}, + /*expected_type=*/fuchsia::ui::test::input::MouseEventPhase::HOVER, + /*component_name=*/"mouse-input-view"); + // Flutter will scale the count of ticks to pixel. + EXPECT_LT(event_wheel_v.wheel_y_physical_pixel(), 0); + EXPECT_EQ(event_wheel_v.wheel_x_physical_pixel(), 0); +} + +} // namespace +} // namespace mouse_input_test::testing diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-view/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-view/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..1e59eeafe42a5539ff908f7a8be81263e6d0f70b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-view/BUILD.gn @@ -0,0 +1,33 @@ +# 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. + +import("//flutter/tools/fuchsia/dart/dart_library.gni") +import("//flutter/tools/fuchsia/flutter/flutter_component.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/component.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/package.gni") + +dart_library("lib") { + package_name = "mouse-input-view" + sources = [ "mouse-input-view.dart" ] + + deps = [ "//flutter/shell/platform/fuchsia/dart:args" ] +} + +flutter_component("component") { + testonly = true + component_name = "mouse-input-view" + manifest = rebase_path("meta/mouse-input-view.cml") + main_package = "mouse-input-view" + main_dart = "mouse-input-view.dart" + + deps = [ ":lib" ] +} + +fuchsia_package("package") { + testonly = true + package_name = "mouse-input-view" + + deps = [ ":component" ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-view/lib/mouse-input-view.dart b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-view/lib/mouse-input-view.dart new file mode 100644 index 0000000000000000000000000000000000000000..e1b92eb00e333ff220d0bb6384838f18719a005e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-view/lib/mouse-input-view.dart @@ -0,0 +1,123 @@ +// Copyright 2020 The Fuchsia Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:convert'; +import 'dart:typed_data'; +import 'dart:ui'; +import 'dart:zircon'; + +void main() { + print('Launching mouse-input-view'); + MyApp app = MyApp(); + app.run(); +} + +class MyApp { + static const _red = Color.fromARGB(255, 244, 67, 54); + static const _orange = Color.fromARGB(255, 255, 152, 0); + static const _yellow = Color.fromARGB(255, 255, 235, 59); + static const _green = Color.fromARGB(255, 76, 175, 80); + static const _blue = Color.fromARGB(255, 33, 150, 143); + static const _purple = Color.fromARGB(255, 156, 39, 176); + + final List _colors = [_red, _orange, _yellow, _green, _blue, _purple]; + + // Each tap will increment the counter, we then determine what color to choose + int _touchCounter = 0; + + void run() { + // Set up window callbacks. + window.onPointerDataPacket = (PointerDataPacket packet) { + this.pointerDataPacket(packet); + }; + window.onMetricsChanged = () { + window.scheduleFrame(); + }; + window.onBeginFrame = (Duration duration) { + this.beginFrame(duration); + }; + + // The child view should be attached to Scenic now. + // Ready to build the scene. + window.scheduleFrame(); + } + + void beginFrame(Duration duration) { + // Convert physical screen size of device to values + final pixelRatio = window.devicePixelRatio; + final size = window.physicalSize / pixelRatio; + final physicalBounds = Offset.zero & size * pixelRatio; + // Set up Canvas that uses the screen size + final recorder = PictureRecorder(); + final canvas = Canvas(recorder, physicalBounds); + canvas.scale(pixelRatio, pixelRatio); + // Draw something + // Color of the screen is set initially to the first value in _colors + // Incrementing _touchCounter will change screen color + final paint = Paint()..color = _colors[_touchCounter % _colors.length]; + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint); + // Build the scene + final picture = recorder.endRecording(); + final sceneBuilder = + SceneBuilder() + ..pushClipRect(physicalBounds) + ..addPicture(Offset.zero, picture) + ..pop(); + window.render(sceneBuilder.build()); + } + + void pointerDataPacket(PointerDataPacket packet) async { + int nowNanos = System.clockGetMonotonic(); + + for (PointerData data in packet.data) { + print('mouse-input-view received input: ${data.toStringFull()}'); + + if (data.kind == PointerDeviceKind.mouse) { + if (data.change == PointerChange.down) { + _touchCounter++; + } + + _reportMouseInput( + localX: data.physicalX, + localY: data.physicalY, + buttons: data.buttons, + phase: data.change.name, + timeReceived: nowNanos, + wheelXPhysicalPixel: data.scrollDeltaX, + wheelYPhysicalPixel: data.scrollDeltaY, + ); + } + } + + window.scheduleFrame(); + } + + void _reportMouseInput({ + required double localX, + required double localY, + required int timeReceived, + required int buttons, + required String phase, + required double wheelXPhysicalPixel, + required double wheelYPhysicalPixel, + }) { + print('mouse-input-view reporting mouse input to MouseInputListener'); + final message = ByteData.sublistView( + utf8.encode( + json.encode({ + 'method': 'MouseInputListener.ReportMouseInput', + 'local_x': localX, + 'local_y': localY, + 'time_received': timeReceived, + 'component_name': 'touch-input-view', + 'buttons': buttons, + 'phase': phase, + 'wheel_x_physical_pixel': wheelXPhysicalPixel, + 'wheel_y_physical_pixel': wheelYPhysicalPixel, + }), + ), + ); + PlatformDispatcher.instance.sendPlatformMessage('fuchsia/input_test', message, null); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-view/meta/mouse-input-view.cml b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-view/meta/mouse-input-view.cml new file mode 100644 index 0000000000000000000000000000000000000000..f2e6bbcfc3f5d3656af2a378741fec50020f0978 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-view/meta/mouse-input-view.cml @@ -0,0 +1,36 @@ +// 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: [ "syslog/client.shard.cml" ], + program: { + data: "data/mouse-input-view", + + // Always use the jit runner for now. + // TODO(fxbug.dev/106577): Implement manifest merging build rules for V2 components. + runner: "flutter_jit_runner", + }, + capabilities: [ + { + protocol: [ "fuchsia.ui.app.ViewProvider" ], + }, + ], + expose: [ + { + protocol: [ "fuchsia.ui.app.ViewProvider" ], + from: "self", + }, + ], + use: [ + { + protocol: [ + "fuchsia.sysmem.Allocator", + "fuchsia.sysmem2.Allocator", + "fuchsia.tracing.provider.Registry", + "fuchsia.ui.composition.Flatland", + "fuchsia.ui.test.input.MouseInputListener", + "fuchsia.vulkan.loader.Loader", + ] + } + ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-view/pubspec.yaml b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-view/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1b4c748f4ed7c9d4e4b398ed7d400cafed0efc81 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-view/pubspec.yaml @@ -0,0 +1,8 @@ +# 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. + +name: mouse-input-view + +environment: + sdk: ^3.7.0-0 diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/text-input/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/text-input/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..64d5c21062aee5d22a54309d75cf419828e9d858 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/text-input/BUILD.gn @@ -0,0 +1,62 @@ +# 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. + +assert(is_fuchsia) + +import("//flutter/tools/fuchsia/fuchsia_archive.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/package.gni") + +group("tests") { + testonly = true + deps = [ ":text-input-test" ] +} + +executable("text-input-test-bin") { + testonly = true + output_name = "text-input-test" + sources = [ "text-input-test.cc" ] + + # This is needed for //flutter/third_party/googletest for linking zircon + # symbols. + libs = [ "${fuchsia_arch_root}/sysroot/lib/libzircon.so" ] + + deps = [ + "${fuchsia_sdk}/fidl/fuchsia.accessibility.semantics", + "${fuchsia_sdk}/fidl/fuchsia.component", + "${fuchsia_sdk}/fidl/fuchsia.feedback", + "${fuchsia_sdk}/fidl/fuchsia.intl", + "${fuchsia_sdk}/fidl/fuchsia.kernel", + "${fuchsia_sdk}/fidl/fuchsia.logger", + "${fuchsia_sdk}/fidl/fuchsia.tracing.provider", + "${fuchsia_sdk}/fidl/fuchsia.ui.app", + "${fuchsia_sdk}/fidl/fuchsia.ui.display.singleton", + "${fuchsia_sdk}/fidl/fuchsia.ui.input", + "${fuchsia_sdk}/fidl/fuchsia.ui.pointerinjector", + "${fuchsia_sdk}/fidl/fuchsia.ui.test.input", + "${fuchsia_sdk}/fidl/fuchsia.ui.test.scene", + "${fuchsia_sdk}/pkg/async", + "${fuchsia_sdk}/pkg/async-loop-testing", + "${fuchsia_sdk}/pkg/fidl_cpp", + "${fuchsia_sdk}/pkg/sys_component_cpp_testing", + "${fuchsia_sdk}/pkg/zx", + "text-input-view:package", + "//flutter/fml", + "//flutter/shell/platform/fuchsia/flutter/tests/integration/utils:check_view", + "//flutter/shell/platform/fuchsia/flutter/tests/integration/utils:portable_ui_test", + "//flutter/third_party/googletest:gtest", + "//flutter/third_party/googletest:gtest_main", + ] +} + +fuchsia_test_archive("text-input-test") { + deps = [ + ":text-input-test-bin", + + # "OOT" copies of the runners used by tests, to avoid conflicting with the + # runners in the base fuchsia image. + # TODO(fxbug.dev/106575): Fix this with subpackages. + "//flutter/shell/platform/fuchsia/flutter:oot_flutter_jit_runner", + ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/text-input/meta/text-input-test.cml b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/text-input/meta/text-input-test.cml new file mode 100644 index 0000000000000000000000000000000000000000..e6339ed20616384107f382e940a2a75f29f786de --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/text-input/meta/text-input-test.cml @@ -0,0 +1,82 @@ +// 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: [ + "sys/testing/gtest_runner.shard.cml", + "sys/component/realm_builder_absolute.shard.cml", + + // This test needs both the vulkan facet and the hermetic-tier-2 facet, + // so we are forced to make it a system test. + "sys/testing/system-test.shard.cml", + + // TODO(https://fxbug.dev/404543928): Remove this shard usage when possible + // and replace with explicit routes. + "syslog/client.shard.cml", + "inspect/client.shard.cml", + ], + program: { + binary: "bin/app", + }, + use: [ + { + protocol: [ + "fuchsia.ui.test.input.KeyboardInputListener", + ] + } + ], + offer: [ + { + protocol: [ + "fuchsia.kernel.RootJobForInspect", + "fuchsia.kernel.Stats", + "fuchsia.scheduler.ProfileProvider", + "fuchsia.sysmem.Allocator", + "fuchsia.sysmem2.Allocator", + "fuchsia.tracing.provider.Registry", + "fuchsia.ui.input.ImeService", + "fuchsia.vulkan.loader.Loader", + "fuchsia.ui.test.input.KeyboardInputListener", + "fuchsia.ui.input3.Keyboard", + "fuchsia.intl.PropertyProvider", + "fuchsia.posix.socket.Provider", + "fuchsia.ui.pointerinjector.Registry", + "fuchsia.fonts.Provider", + "fuchsia.feedback.CrashReportingProductRegister", + "fuchsia.settings.Keyboard", + "fuchsia.accessibility.semantics.SemanticsManager", + ], + from: "parent", + to: "#realm_builder", + }, + { + directory: "pkg", + subdir: "config", + as: "config-data", + from: "framework", + to: "#realm_builder", + }, + // See common.shard.cml. + { + directory: "tzdata-icu", + from: "framework", + to: "#realm_builder", + }, + ], + // TODO(https://fxbug.dev/114584): Figure out how to bring these in as deps (if possible oot). + facets: { + "fuchsia.test": { + "deprecated-allowed-packages": [ + "cursor", + "flatland-scene-manager-test-ui-stack", + "test-ui-stack", + "oot_flutter_aot_runner", + "oot_flutter_jit_runner", + "oot_flutter_jit_product_runner", + "oot_flutter_aot_product_runner", + "test_manager", + "text-input-view", + ], + }, + }, +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/text-input/text-input-test.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/text-input/text-input-test.cc new file mode 100644 index 0000000000000000000000000000000000000000..345f9763ce36f5e3daaf07a9a31d897e44550831 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/text-input/text-input-test.cc @@ -0,0 +1,237 @@ +// 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "flutter/fml/logging.h" +#include "flutter/shell/platform/fuchsia/flutter/tests/integration/utils/check_view.h" +#include "flutter/shell/platform/fuchsia/flutter/tests/integration/utils/portable_ui_test.h" + +namespace { + +// Types imported for the realm_builder library. +using component_testing::ChildRef; +using component_testing::LocalComponentImpl; +using component_testing::ParentRef; +using component_testing::Protocol; +using component_testing::RealmBuilder; +using component_testing::RealmRoot; +using component_testing::Route; + +using fuchsia_test_utils::CheckViewExistsInUpdates; +using fuchsia_test_utils::PortableUITest; + +/// Max timeout in failure cases. +/// Set this as low as you can that still works across all test platforms. +constexpr zx::duration kTimeout = zx::min(5); + +constexpr auto kKeyboardInputListener = "keyboard_input_listener"; +constexpr auto kKeyboardInputListenerRef = ChildRef{kKeyboardInputListener}; + +constexpr auto kTextInputView = "text-input-view"; +constexpr auto kTextInputViewRef = ChildRef{kTextInputView}; +static constexpr auto kTextInputViewUrl = + "fuchsia-pkg://fuchsia.com/text-input-view#meta/text-input-view.cm"; + +constexpr auto kTestUIStackUrl = + "fuchsia-pkg://fuchsia.com/flatland-scene-manager-test-ui-stack#meta/" + "test-ui-stack.cm"; + +/// |KeyboardInputListener| is a local test protocol that our test Flutter app +/// uses to let us know what text is being entered into its only text field. +/// +/// The text field contents are reported on almost every change, so if you are +/// entering a long text, you will see calls corresponding to successive +/// additions of characters, not just the end result. +class KeyboardInputListenerServer + : public fuchsia::ui::test::input::KeyboardInputListener, + public LocalComponentImpl { + public: + explicit KeyboardInputListenerServer(async_dispatcher_t* dispatcher) + : dispatcher_(dispatcher) {} + + // |fuchsia::ui::test::input::KeyboardInputListener| + void ReportTextInput( + fuchsia::ui::test::input::KeyboardInputListenerReportTextInputRequest + request) override { + FML_LOG(INFO) << "Flutter app sent: '" << request.text() << "'"; + response_list_.push_back(request.text()); + } + + /// Starts this server. + void OnStart() override { + FML_LOG(INFO) << "Starting KeyboardInputListenerServer"; + ASSERT_EQ(ZX_OK, outgoing()->AddPublicService( + bindings_.GetHandler(this, dispatcher_))); + } + + /// Returns true if the response vector values matches `expected` + bool HasResponse(const std::vector& expected) { + if (response_list_.size() != expected.size()) { + return false; + } + + // Iterate through the expected vector + // Corresponding indices for response_list and expected should contain the + // same values + for (size_t i = 0; i < expected.size(); ++i) { + if (response_list_[i] != expected[i]) { + return false; + } + } + + return true; + } + + // KeyboardInputListener override + void ReportReady(ReportReadyCallback callback) override { + FML_LOG(INFO) << "ReportReady callback ready"; + ready_ = true; + callback(); + } + + private: + async_dispatcher_t* dispatcher_ = nullptr; + fidl::BindingSet bindings_; + std::vector response_list_; + bool ready_ = false; +}; + +class TextInputTest : public PortableUITest, + public ::testing::Test, + public ::testing::WithParamInterface { + protected: + void SetUp() override { + PortableUITest::SetUp(); + + // Post a "just in case" quit task, if the test hangs. + async::PostDelayedTask( + dispatcher(), + [] { + FML_LOG(FATAL) + << "\n\n>> Test did not complete in time, terminating. <<\n\n"; + }, + kTimeout); + + // Get the display dimensions. + FML_LOG(INFO) + << "Waiting for display info from fuchsia.ui.display.singleton.Info"; + fuchsia::ui::display::singleton::InfoPtr display_info = + realm_root() + ->component() + .Connect(); + display_info->GetMetrics( + [this](fuchsia::ui::display::singleton::Metrics metrics) { + display_width_ = metrics.extent_in_px().width; + display_height_ = metrics.extent_in_px().height; + FML_LOG(INFO) << "Got display_width = " << display_width_ + << " and display_height = " << display_height_; + }); + RunLoopUntil( + [this] { return display_width_ != 0 && display_height_ != 0; }); + + // Register input injection device. + FML_LOG(INFO) << "Registering input injection device"; + RegisterKeyboard(); + } + + // Guaranteed to be initialized after SetUp(). + uint32_t display_width() const { return display_width_; } + uint32_t display_height() const { return display_height_; } + + std::string GetTestUIStackUrl() override { return GetParam(); }; + + KeyboardInputListenerServer* keyboard_input_listener_server_; + + private: + void ExtendRealm() override { + FML_LOG(INFO) << "Extending realm"; + // Key part of service setup: have this test component vend the + // |KeyboardInputListener| service in the constructed realm. + auto keyboard_input_listener_server = + std::make_unique(dispatcher()); + keyboard_input_listener_server_ = keyboard_input_listener_server.get(); + realm_builder()->AddLocalChild( + kKeyboardInputListener, + [keyboard_input_listener_server = + std::move(keyboard_input_listener_server)]() mutable { + return std::move(keyboard_input_listener_server); + }); + + // Add text-input-view to the Realm + realm_builder()->AddChild(kTextInputView, kTextInputViewUrl, + component_testing::ChildOptions{ + .environment = kFlutterRunnerEnvironment, + }); + + // Route KeyboardInputListener to the runner and Flutter app + realm_builder()->AddRoute( + Route{.capabilities = {Protocol{ + fuchsia::ui::test::input::KeyboardInputListener::Name_}}, + .source = kKeyboardInputListenerRef, + .targets = {kFlutterJitRunnerRef, kTextInputViewRef}}); + + // Expose fuchsia.ui.app.ViewProvider from the flutter app. + realm_builder()->AddRoute( + Route{.capabilities = {Protocol{fuchsia::ui::app::ViewProvider::Name_}}, + .source = kTextInputViewRef, + .targets = {ParentRef()}}); + + realm_builder()->AddRoute(Route{ + .capabilities = + {Protocol{fuchsia::ui::input3::Keyboard::Name_}, + Protocol{"fuchsia.accessibility.semantics.SemanticsManager"}}, + .source = kTestUIStackRef, + .targets = {ParentRef(), kFlutterJitRunnerRef}}); + } +}; + +INSTANTIATE_TEST_SUITE_P(TextInputTestParameterized, + TextInputTest, + ::testing::Values(kTestUIStackUrl)); + +TEST_P(TextInputTest, TextInput) { + // Launch view + FML_LOG(INFO) << "Initializing scene"; + LaunchClient(); + FML_LOG(INFO) << "Client launched"; + + SimulateTextEntry("Hello\nworld!"); + std::vector expected = {"LEFT_SHIFT", "H", "E", "L", "L", "O", + "ENTER", "W", "O", "R", "L", "D", + "LEFT_SHIFT", "KEY_1"}; + + RunLoopUntil( + [&] { return keyboard_input_listener_server_->HasResponse(expected); }); +} + +} // namespace diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/text-input/text-input-view/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/text-input/text-input-view/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..5ec7ed603cc21e8a231dbc791e8ffe634bdd8006 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/text-input/text-input-view/BUILD.gn @@ -0,0 +1,31 @@ +# 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. + +import("//flutter/tools/fuchsia/dart/dart_library.gni") +import("//flutter/tools/fuchsia/flutter/flutter_component.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/component.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/package.gni") + +dart_library("lib") { + testonly = true + package_name = "text-input-view" + sources = [ "text_input_view.dart" ] + deps = [ "//flutter/shell/platform/fuchsia/dart:args" ] +} + +flutter_component("component") { + testonly = true + component_name = "text-input-view" + manifest = rebase_path("meta/text-input-view.cml") + main_package = "text-input-view" + main_dart = "text_input_view.dart" + deps = [ ":lib" ] +} + +fuchsia_package("package") { + testonly = true + package_name = "text-input-view" + deps = [ ":component" ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/text-input/text-input-view/lib/text_input_view.dart b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/text-input/text-input-view/lib/text_input_view.dart new file mode 100644 index 0000000000000000000000000000000000000000..f3e8b38d12ebb01c32471e5ec2477dd07c439252 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/text-input/text-input-view/lib/text_input_view.dart @@ -0,0 +1,108 @@ +// 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. + +// This is an instrumented test application. It has a single field, is +// able to receive keyboard input from the test fixture, and is able to report +// back the contents of its text field to the test fixture. + +import 'dart:convert'; +import 'dart:typed_data'; +import 'dart:ui'; + +// Corresponds to the USB HID values provided in fidl.fuchsia.input +// https://fuchsia.dev/reference/fidl/fuchsia.input +final Map hidToKey = { + 458977: 'LEFT_SHIFT', // Keyboard Left Shift + 458792: 'ENTER', // Keyboard Enter (Return) + 458782: 'KEY_1', // Keyboard 1 and ! + 458763: 'H', // Keyboard h and H + 458760: 'E', // Keyboard e and E + 458767: 'L', // Keyboard l and L + 458770: 'O', // Keyboard o and O + 458778: 'W', // Keyboard w and W + 458773: 'R', // Keyboard r and R + 458759: 'D', // Keyboard d and D +}; + +int main() { + final bool soundNullSafety = [null] is! List; + print('Launching text-input-view. Sound null safety: $soundNullSafety'); + TestApp app = TestApp(); + app.run(); + return 0; +} + +class TestApp { + static const _yellow = Color.fromARGB(255, 255, 255, 0); + Color _backgroundColor = _yellow; + + void run() { + // Set up window callbacks + window.onPlatformMessage = ( + String name, + ByteData? data, + PlatformMessageResponseCallback? callback, + ) { + this.decodeAndReportPlatformMessage(name, data!); + }; + window.onMetricsChanged = () { + window.scheduleFrame(); + }; + window.onBeginFrame = (Duration duration) { + this.beginFrame(duration); + }; + + window.scheduleFrame(); + } + + void beginFrame(Duration duration) { + // Convert physical screen size of device to values + final pixelRatio = window.devicePixelRatio; + final size = window.physicalSize / pixelRatio; + final physicalBounds = Offset.zero & size * pixelRatio; + final windowBounds = Offset.zero & size; + // Set up a Canvas that uses the screen size + final recorder = PictureRecorder(); + final canvas = Canvas(recorder, physicalBounds); + canvas.scale(pixelRatio, pixelRatio); + // Draw something + final paint = Paint()..color = this._backgroundColor; + canvas.drawRect(windowBounds, paint); + // Build the scene + final picture = recorder.endRecording(); + final sceneBuilder = + SceneBuilder() + ..pushClipRect(physicalBounds) + ..addPicture(Offset.zero, picture) + ..pop(); + window.render(sceneBuilder.build()); + } + + void decodeAndReportPlatformMessage(String name, ByteData data) async { + final buffer = data.buffer; + var list = buffer.asUint8List(data.offsetInBytes, data.lengthInBytes); + var decoded = utf8.decode(list); + var decodedJson = json.decode(decoded); + print('received ${name} platform message: ${decodedJson}'); + + if (name == "flutter/keyevent" && decodedJson["type"] == "keydown") { + if (hidToKey[decodedJson["hidUsage"]] != null) { + _reportTextInput(hidToKey[decodedJson["hidUsage"]!]!); + } + } + + window.scheduleFrame(); + } + + void _reportTextInput(String text) { + print('text-input-view reporting keyboard input to KeyboardInputListener'); + + final message = + utf8 + .encode(json.encode({'method': 'KeyboardInputListener.ReportTextInput', 'text': text})) + .buffer + .asByteData(); + PlatformDispatcher.instance.sendPlatformMessage('fuchsia/input_test', message, null); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/text-input/text-input-view/meta/text-input-view.cml b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/text-input/text-input-view/meta/text-input-view.cml new file mode 100644 index 0000000000000000000000000000000000000000..901c136829f40de3f84cf78ec68bd49a42320436 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/text-input/text-input-view/meta/text-input-view.cml @@ -0,0 +1,29 @@ +// 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: [ "syslog/client.shard.cml" ], + program: { + data: "data/text-input-view", + + // Always use the jit runner for now. + // TODO(fxbug.dev/106577): Implement manifest merging build rules for V2 components. + runner: "flutter_jit_runner", + }, + capabilities: [ + { + protocol: [ "fuchsia.ui.app.ViewProvider", "fuchsia.settings.Keyboard" ], + }, + ], + use: [ + { + protocol: [ "fuchsia.ui.test.input.KeyboardInputListener", "fuchsia.settings.Keyboard" ], + }, + ], + expose: [ + { + protocol: [ "fuchsia.ui.app.ViewProvider", "fuchsia.settings.Keyboard" ], + from: "self", + }, + ], +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/text-input/text-input-view/pubspec.yaml b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/text-input/text-input-view/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1c7aebb632d2387640b510fbaefe2ea30b6fadb4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/text-input/text-input-view/pubspec.yaml @@ -0,0 +1,8 @@ +# 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. + +name: text-input-view + +environment: + sdk: ^3.7.0-0 diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..51aaae45e4bae70b3c1dc6ba3023452f2d10a7b7 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/BUILD.gn @@ -0,0 +1,66 @@ +# 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. + +assert(is_fuchsia) + +import("//flutter/tools/fuchsia/fuchsia_archive.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/package.gni") + +group("tests") { + testonly = true + deps = [ ":touch-input-test" ] +} + +executable("touch-input-test-bin") { + testonly = true + output_name = "touch-input-test" + sources = [ "touch-input-test.cc" ] + + # This is needed for //flutter/third_party/googletest for linking zircon + # symbols. + libs = [ "${fuchsia_arch_root}/sysroot/lib/libzircon.so" ] + + deps = [ + "${fuchsia_sdk}/fidl/fuchsia.accessibility.semantics", + "${fuchsia_sdk}/fidl/fuchsia.buildinfo", + "${fuchsia_sdk}/fidl/fuchsia.component", + "${fuchsia_sdk}/fidl/fuchsia.fonts", + "${fuchsia_sdk}/fidl/fuchsia.intl", + "${fuchsia_sdk}/fidl/fuchsia.kernel", + "${fuchsia_sdk}/fidl/fuchsia.memorypressure", + "${fuchsia_sdk}/fidl/fuchsia.metrics", + "${fuchsia_sdk}/fidl/fuchsia.net.interfaces", + "${fuchsia_sdk}/fidl/fuchsia.tracing.provider", + "${fuchsia_sdk}/fidl/fuchsia.ui.app", + "${fuchsia_sdk}/fidl/fuchsia.ui.display.singleton", + "${fuchsia_sdk}/fidl/fuchsia.ui.input", + "${fuchsia_sdk}/fidl/fuchsia.ui.pointerinjector", + "${fuchsia_sdk}/fidl/fuchsia.ui.test.input", + "${fuchsia_sdk}/fidl/fuchsia.ui.test.scene", + "${fuchsia_sdk}/fidl/fuchsia.web", + "${fuchsia_sdk}/pkg/async", + "${fuchsia_sdk}/pkg/async-loop-testing", + "${fuchsia_sdk}/pkg/fidl_cpp", + "${fuchsia_sdk}/pkg/sys_component_cpp_testing", + "${fuchsia_sdk}/pkg/zx", + "embedding-flutter-view:package", + "touch-input-view:package", + "//flutter/fml", + "//flutter/shell/platform/fuchsia/flutter/tests/integration/utils:portable_ui_test", + "//flutter/third_party/googletest:gtest", + "//flutter/third_party/googletest:gtest_main", + ] +} + +fuchsia_test_archive("touch-input-test") { + deps = [ + ":touch-input-test-bin", + + # "OOT" copies of the runners used by tests, to avoid conflicting with the + # runners in the base fuchsia image. + # TODO(fxbug.dev/106575): Fix this with subpackages. + "//flutter/shell/platform/fuchsia/flutter:oot_flutter_jit_runner", + ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/README.md b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/README.md new file mode 100644 index 0000000000000000000000000000000000000000..61c23e9aa5b8c67f942dc0108fd27932f084f89f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/README.md @@ -0,0 +1,77 @@ +# touch-input + +`touch-input-test` exercises touch through a child view (in this case, the `touch-input-view` Dart component) and asserting +the precise location of the touch event. We validate a touch event as valid through two ways: +- By attaching the child view, injecting touch, and validating that the view reports the touch event back with the correct coordinates. +- By embedding a child view into a parent view, injecting touch into both views, and validating that each view reports its touch event back with the correct coordinates. + +```shell +Injecting the tap event +[touch-input-test.cm] INFO: [portable_ui_test.cc(193)] Injecting tap at (-500, -500) + +View receives the event +[flutter_jit_runner] INFO: touch-input-view.cm(flutter): touch-input-view received tap: PointerData(embedderId: 0, timeStamp: 0:01:03.623259, +change: PointerChange.add, kind: PointerDeviceKind.touch, signalKind: PointerSignalKind.none, device: -4294967295, pointerIdentifier: 0, +physicalX: 319.99998331069946, physicalY: 199.99999284744263, physicalDeltaX: 0.0, physicalDeltaY: 0.0, buttons: 0, synthesized: false, +pressure: 0.0, pressureMin: 0.0, pressureMax: 0.0, distance: 0.0, distanceMax: 0.0, size: 0.0, radiusMajor: 0.0, radiusMinor: 0.0, +radiusMin: 0.0, radiusMax: 0.0, orientation: 0.0, tilt: 0.0, platformData: 0, scrollDeltaX: 0.0, scrollDeltaY: 0.0, panX: 0.0, panY: 0.0, +panDeltaX: 0.0, panDeltaY: 0.0, scale: 0.0, rotation: 0.0) + +Successfully received response from view +[touch-input-test.cm] INFO: [touch-input-test.cc(162)] Received ReportTouchInput event +[touch-input-test.cm] INFO: [touch-input-test.cc(255)] Expecting event for component touch-input-view at (320, 200) +[touch-input-test.cm] INFO: [touch-input-test.cc(257)] Received event for component touch-input-view at (320, 200), accounting for pixel scale of 1 +``` + +Some interesting details (thanks to abrusher@): + +There exists two coordinate spaces within our testing realm. The first is `touch-input-view`'s "logical" coordinate space. This +is determined based on `touch-input-view`'s size and is the space in which it sees incoming events. The second is the "injector" +coordinate space, which spans [-1000, 1000] on both axes. + +The size/position of a view doesn't always match the bounds of a display exactly. As a result, Scenic has a separate coordinate space +to specify the location at which to inject a touch event. This is always fixed to the display bounds. Scenic knows how to map this +coordinate space onto the client view's space. + +For example, if we inject at (-500, -500) `touch-input-view` will see a touch event at the middle of the upper-left quadrant of the screen. + +## Running the Test + +Reference the Flutter integration test [documentation](https://github.com/flutter/engine/blob/main/shell/platform/fuchsia/flutter/tests/integration/README.md) at //flutter/shell/platform/fuchsia/flutter/tests/integration/README.md + +## Playing around with `touch-input-view` + +Build Fuchsia with `terminal.qemu-x64` +```shell +fx set terminal.qemu-x64 && fx build +``` + +Build flutter/engine +```shell +$ENGINE_DIR/flutter/tools/gn --fuchsia --no-lto && ninja -C $ENGINE_DIR/out/fuchsia_debug_x64 flutter/shell/platform/fuchsia/flutter/tests/ +integration/touch_input:tests +``` + +Start a Fuchsia package server +```shell +cd "$FUCHSIA_DIR" +fx serve +``` + +Publish `touch-input-view` +```shell +$FUCHSIA_DIR/.jiri_root/bin/fx pm publish -a -repo $FUCHSIA_DIR/$(cat $FUCHSIA_DIR/.fx-build-dir)/amber-files -f $ENGINE_DIR/out/ +fuchsia_debug_x64/gen/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/touch-input-view/touch-input-view/touch-input-view.far +``` + +Launch Fuchsia emulator in a graphical environment +```shell +ffx emu start +``` + +**Before proceeding, make sure you have successfully completed the "Set a Password" screen** + +Add `touch-input-view` +```shell +ffx session add fuchsia-pkg://fuchsia.com/touch-input-view#meta/touch-input-view.cm +``` diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/embedding-flutter-view/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/embedding-flutter-view/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e532a158c8749220a10fe26029f66eb039c6eafb --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/embedding-flutter-view/BUILD.gn @@ -0,0 +1,36 @@ +# 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. + +import("//flutter/tools/fuchsia/dart/dart_library.gni") +import("//flutter/tools/fuchsia/flutter/flutter_component.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/component.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/package.gni") + +dart_library("lib") { + package_name = "embedding-flutter-view" + sources = [ "embedding-flutter-view.dart" ] + + deps = [ + "//flutter/shell/platform/fuchsia/dart:args", + "//flutter/shell/platform/fuchsia/dart:vector_math", + ] +} + +flutter_component("component") { + testonly = true + component_name = "embedding-flutter-view" + manifest = rebase_path("meta/embedding-flutter-view.cml") + main_package = "embedding-flutter-view" + main_dart = "embedding-flutter-view.dart" + + deps = [ ":lib" ] +} + +fuchsia_package("package") { + testonly = true + package_name = "embedding-flutter-view" + + deps = [ ":component" ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/embedding-flutter-view/lib/embedding-flutter-view.dart b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/embedding-flutter-view/lib/embedding-flutter-view.dart new file mode 100644 index 0000000000000000000000000000000000000000..ac0448c3aa6a4f34fed2d20acebfab22e5f2d5cc --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/embedding-flutter-view/lib/embedding-flutter-view.dart @@ -0,0 +1,249 @@ +// 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. + +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; +import 'dart:io'; +import 'dart:ui'; +import 'dart:zircon'; + +import 'package:args/args.dart'; +import 'package:vector_math/vector_math_64.dart' as vector_math_64; + +final _argsCsvFilePath = '/config/data/args.csv'; + +void main(List args) async { + print('Launching embedding-flutter-view'); + + args = args + _GetArgsFromConfigFile(); + final parser = + ArgParser() + ..addFlag('showOverlay', defaultsTo: false) + ..addFlag('focusable', defaultsTo: true); + + final arguments = parser.parse(args); + for (final option in arguments.options) { + print('embedding-flutter-view args: $option: ${arguments[option]}'); + } + + TestApp app = TestApp( + ChildView(await _launchChildView()), + showOverlay: arguments['showOverlay'], + focusable: arguments['focusable'], + ); + + app.run(); +} + +class TestApp { + static const _black = Color.fromARGB(255, 0, 0, 0); + static const _blue = Color.fromARGB(255, 0, 0, 255); + + final ChildView childView; + final bool showOverlay; + final bool focusable; + + Color _backgroundColor = _blue; + + TestApp(this.childView, {this.showOverlay = false, this.focusable = true}) {} + + void run() { + childView.create(focusable, (ByteData? reply) { + // Set up window callbacks. + window.onPointerDataPacket = (PointerDataPacket packet) { + this.pointerDataPacket(packet); + }; + window.onMetricsChanged = () { + window.scheduleFrame(); + }; + window.onBeginFrame = (Duration duration) { + this.beginFrame(duration); + }; + + // The child view should be attached to Scenic now. + // Ready to build the scene. + window.scheduleFrame(); + }); + } + + void beginFrame(Duration duration) { + // Convert physical screen size of device to values + final pixelRatio = window.devicePixelRatio; + final size = window.physicalSize / pixelRatio; + final physicalBounds = Offset.zero & window.physicalSize; + final windowBounds = Offset.zero & size; + // Set up a Canvas that uses the screen size + final recorder = PictureRecorder(); + final canvas = Canvas(recorder, physicalBounds); + canvas.scale(pixelRatio); + // Draw something + final paint = Paint()..color = this._backgroundColor; + canvas.drawRect(windowBounds, paint); + final picture = recorder.endRecording(); + // Build the scene + final sceneBuilder = + SceneBuilder() + ..pushClipRect(physicalBounds) + ..addPicture(Offset.zero, picture); + + final childPhysicalSize = window.physicalSize * 0.25; + // Alignment.center + final windowCenter = size.center(Offset.zero); + final windowPhysicalCenter = window.physicalSize.center(Offset.zero); + final childPhysicalOffset = windowPhysicalCenter - childPhysicalSize.center(Offset.zero); + + sceneBuilder + ..pushTransform( + vector_math_64.Matrix4.translationValues( + childPhysicalOffset.dx, + childPhysicalOffset.dy, + 0.0, + ).storage, + ) + ..addPlatformView( + childView.viewId, + width: childPhysicalSize.width, + height: childPhysicalSize.height, + ) + ..pop(); + + if (showOverlay) { + final containerSize = size * 0.5; + // Alignment.center + final containerOffset = windowCenter - containerSize.center(Offset.zero); + + final overlaySize = containerSize * 0.5; + // Alignment.topRight + final overlayOffset = Offset( + containerOffset.dx + containerSize.width - overlaySize.width, + containerOffset.dy, + ); + final overlayPhysicalSize = overlaySize * pixelRatio; + final overlayPhysicalOffset = overlayOffset * pixelRatio; + final overlayPhysicalBounds = overlayPhysicalOffset & overlayPhysicalSize; + + final recorder = PictureRecorder(); + final overlayCullRect = Offset.zero & overlayPhysicalSize; // in canvas physical coordinates + final canvas = Canvas(recorder, overlayCullRect); + canvas.scale(pixelRatio); + + final paint = Paint()..color = Color.fromARGB(255, 0, 255, 0); + canvas.drawRect(Offset.zero & overlaySize, paint); + + final overlayPicture = recorder.endRecording(); + sceneBuilder + ..pushClipRect(overlayPhysicalBounds) // in window physical coordinates + ..addPicture(overlayPhysicalOffset, overlayPicture) + ..pop(); + } + + sceneBuilder.pop(); + window.render(sceneBuilder.build()); + } + + void pointerDataPacket(PointerDataPacket packet) async { + int nowNanos = System.clockGetMonotonic(); + + for (PointerData data in packet.data) { + print('embedding-flutter-view received tap: ${data.toStringFull()}'); + + if (data.change == PointerChange.down) { + this._backgroundColor = _black; + } + + if (data.change == PointerChange.down || data.change == PointerChange.move) { + _reportTouchInput(localX: data.physicalX, localY: data.physicalY, timeReceived: nowNanos); + } + } + + window.scheduleFrame(); + } + + void _reportTouchInput({ + required double localX, + required double localY, + required int timeReceived, + }) { + print('embedding-flutter-view reporting touch input to TouchInputListener'); + final message = + utf8 + .encode( + json.encode({ + 'method': 'TouchInputListener.ReportTouchInput', + 'local_x': localX, + 'local_y': localY, + 'time_received': timeReceived, + 'component_name': 'embedding-flutter-view', + }), + ) + .buffer + .asByteData(); + PlatformDispatcher.instance.sendPlatformMessage('fuchsia/input_test', message, null); + } +} + +class ChildView { + final int viewId; + + ChildView(this.viewId); + + void create(bool focusable, PlatformMessageResponseCallback callback) { + // Construct the dart:ui platform message to create the view, and when the + // return callback is invoked, build the scene. At that point, it is safe + // to embed the child view in the scene. + final viewOcclusionHint = Rect.zero; + final Map args = { + 'viewId': viewId, + // Flatland doesn't support disabling hit testing. + 'hitTestable': true, + 'focusable': focusable, + 'viewOcclusionHintLTRB': [ + viewOcclusionHint.left, + viewOcclusionHint.top, + viewOcclusionHint.right, + viewOcclusionHint.bottom, + ], + }; + + final ByteData createViewMessage = + utf8 + .encode(json.encode({'method': 'View.create', 'args': args})) + .buffer + .asByteData(); + + final platformViewsChannel = 'flutter/platform_views'; + + PlatformDispatcher.instance.sendPlatformMessage( + platformViewsChannel, + createViewMessage, + callback, + ); + } +} + +Future _launchChildView() async { + final message = Int8List.fromList([0x31]); + final completer = new Completer(); + PlatformDispatcher.instance.sendPlatformMessage( + 'fuchsia/child_view', + ByteData.sublistView(message), + (ByteData? reply) { + completer.complete(reply!); + }, + ); + + return int.parse(ascii.decode(((await completer.future).buffer.asUint8List()))); +} + +List _GetArgsFromConfigFile() { + List args; + final f = File(_argsCsvFilePath); + if (!f.existsSync()) { + return List.empty(); + } + final fileContentCsv = f.readAsStringSync(); + args = fileContentCsv.split('\n'); + return args; +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/embedding-flutter-view/meta/embedding-flutter-view.cml b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/embedding-flutter-view/meta/embedding-flutter-view.cml new file mode 100644 index 0000000000000000000000000000000000000000..ead254908f27961fef7e6780e7cfff4ff3af67fb --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/embedding-flutter-view/meta/embedding-flutter-view.cml @@ -0,0 +1,37 @@ +// 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: [ "syslog/client.shard.cml" ], + program: { + data: "data/embedding-flutter-view", + + // Always use the jit runner for now. + // TODO(fxbug.dev/106577): Implement manifest merging build rules for V2 components. + runner: "flutter_jit_runner", + }, + capabilities: [ + { + protocol: [ "fuchsia.ui.app.ViewProvider" ], + }, + ], + expose: [ + { + protocol: [ "fuchsia.ui.app.ViewProvider" ], + from: "self", + }, + ], + use: [ + { + protocol: [ + "fuchsia.ui.app.ViewProvider", + "fuchsia.ui.test.input.TouchInputListener", + ] + }, + { + directory: "config-data", + rights: [ "r*" ], + path: "/config/data", + }, + ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/embedding-flutter-view/pubspec.yaml b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/embedding-flutter-view/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..88d86708587c5378bf5c46251c914cc5b88cf239 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/embedding-flutter-view/pubspec.yaml @@ -0,0 +1,8 @@ +# 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. + +name: embedding-flutter-view + +environment: + sdk: ^3.7.0-0 diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/meta/touch-input-test.cml b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/meta/touch-input-test.cml new file mode 100644 index 0000000000000000000000000000000000000000..fd510d5da1c5b6358232f6414ecc12ea6487ae1a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/meta/touch-input-test.cml @@ -0,0 +1,72 @@ +// 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: [ + "sys/testing/gtest_runner.shard.cml", + "sys/component/realm_builder_absolute.shard.cml", + + // This test needs both the vulkan facet and the hermetic-tier-2 facet, + // so we are forced to make it a system test. + "sys/testing/system-test.shard.cml", + + // TODO(https://fxbug.dev/404543928): Remove this shard usage when possible + // and replace with explicit routes. + "syslog/client.shard.cml", + "inspect/client.shard.cml", + ], + program: { + binary: "bin/app", + }, + use: [ + { + protocol: [ + "fuchsia.ui.test.input.TouchInputListener", + ] + } + ], + offer: [ + { + // Offer capabilities needed by components in this test realm. + // Keep it minimal, describe only what's actually needed. + protocol: [ + "fuchsia.kernel.RootJobForInspect", + "fuchsia.kernel.Stats", + "fuchsia.scheduler.ProfileProvider", + "fuchsia.sysmem.Allocator", + "fuchsia.sysmem2.Allocator", + "fuchsia.tracing.provider.Registry", + "fuchsia.ui.input.ImeService", + "fuchsia.vulkan.loader.Loader", + "fuchsia.ui.test.input.TouchInputListener", + "fuchsia.intl.PropertyProvider", + "fuchsia.posix.socket.Provider", + "fuchsia.ui.pointerinjector.Registry", + ], + from: "parent", + to: "#realm_builder", + }, + { + directory: "pkg", + subdir: "config", + as: "config-data", + from: "framework", + to: "#realm_builder", + }, + ], + // TODO(https://fxbug.dev/114584): Figure out how to bring these in as deps (if possible oot). + facets: { + "fuchsia.test": { + "deprecated-allowed-packages": [ + "embedding-flutter-view", + "flatland-scene-manager-test-ui-stack", + "oot_flutter_aot_runner", + "oot_flutter_jit_runner", + "oot_flutter_jit_product_runner", + "oot_flutter_aot_product_runner", + "test_manager", + "touch-input-view", + ], + }, + }, +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/touch-input-test.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/touch-input-test.cc new file mode 100644 index 0000000000000000000000000000000000000000..913ce128b5876abd9333f98a228ca9179d033ec5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/touch-input-test.cc @@ -0,0 +1,525 @@ +// 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "flutter/fml/logging.h" +#include "flutter/shell/platform/fuchsia/flutter/tests/integration/utils/portable_ui_test.h" + +// This test exercises the touch input dispatch path from Input Pipeline to a +// Scenic client. It is a multi-component test, and carefully avoids sleeping or +// polling for component coordination. +// - It runs real Scene Manager and Scenic components. +// - It uses a fake display controller; the physical device is unused. +// +// Components involved +// - This test program +// - Scene Manager +// - Scenic +// - Child view, a Scenic client +// +// Touch dispatch path +// - Test program's injection -> Input Pipeline -> Scenic -> Child view +// +// Setup sequence +// - The test sets up this view hierarchy: +// - Top level scene, owned by Scene Manager. +// - Child view, owned by the ui client. +// - The test waits for a Scenic event that verifies the child has UI content in +// the scene graph. +// - The test injects input into Input Pipeline, emulating a display's touch +// report. +// - Input Pipeline dispatches the touch event to Scenic, which in turn +// dispatches it to the child. +// - The child receives the touch event and reports back to the test over a +// custom test-only FIDL. +// - Test waits for the child to report a touch; when the test receives the +// report, the test quits +// successfully. +// +// This test uses the realm_builder library to construct the topology of +// components and routes services between them. For v2 components, every test +// driver component sits as a child of test_manager in the topology. Thus, the +// topology of a test driver component such as this one looks like this: +// +// test_manager +// | +// touch-input-test.cml (this component) +// +// With the usage of the realm_builder library, we construct a realm during +// runtime and then extend the topology to look like: +// +// test_manager +// | +// touch-input-test.cml (this component) +// | +// +// / \ +// scenic input-pipeline +// +// For more information about testing v2 components and realm_builder, +// visit the following links: +// +// Testing: https://fuchsia.dev/fuchsia-src/concepts/testing/v2 +// Realm Builder: +// https://fuchsia.dev/fuchsia-src/development/components/v2/realm_builder + +namespace touch_input_test::testing { +namespace { +// Types imported for the realm_builder library. +using component_testing::ChildRef; +using component_testing::ConfigValue; +using component_testing::DirectoryContents; +using component_testing::LocalComponentImpl; +using component_testing::ParentRef; +using component_testing::Protocol; +using component_testing::Realm; +using component_testing::RealmRoot; +using component_testing::Route; + +using fuchsia_test_utils::PortableUITest; + +using RealmBuilder = component_testing::RealmBuilder; + +// Max timeout in failure cases. +// Set this as low as you can that still works across all test platforms. +constexpr zx::duration kTimeout = zx::min(1); + +constexpr auto kTestUIStackUrl = + "fuchsia-pkg://fuchsia.com/flatland-scene-manager-test-ui-stack#meta/" + "test-ui-stack.cm"; + +constexpr auto kMockTouchInputListener = "touch_input_listener"; +constexpr auto kMockTouchInputListenerRef = ChildRef{kMockTouchInputListener}; + +constexpr auto kTouchInputView = "touch-input-view"; +constexpr auto kTouchInputViewRef = ChildRef{kTouchInputView}; +constexpr auto kTouchInputViewUrl = + "fuchsia-pkg://fuchsia.com/touch-input-view#meta/touch-input-view.cm"; +constexpr auto kEmbeddingFlutterView = "embedding-flutter-view"; +constexpr auto kEmbeddingFlutterViewRef = ChildRef{kEmbeddingFlutterView}; +constexpr auto kEmbeddingFlutterViewUrl = + "fuchsia-pkg://fuchsia.com/embedding-flutter-view#meta/" + "embedding-flutter-view.cm"; + +bool CompareDouble(double f0, double f1, double epsilon) { + return std::abs(f0 - f1) <= epsilon; +} + +// This component implements the TouchInput protocol +// and the interface for a RealmBuilder LocalComponentImpl. A LocalComponentImpl +// is a component that is implemented here in the test, as opposed to +// elsewhere in the system. When it's inserted to the realm, it will act +// like a proper component. This is accomplished, in part, because the +// realm_builder library creates the necessary plumbing. It creates a manifest +// for the component and routes all capabilities to and from it. +// LocalComponentImpl: +// https://fuchsia.dev/fuchsia-src/development/testing/components/realm_builder#mock-components +class TouchInputListenerServer + : public fuchsia::ui::test::input::TouchInputListener, + public LocalComponentImpl { + public: + explicit TouchInputListenerServer(async_dispatcher_t* dispatcher) + : dispatcher_(dispatcher) {} + + // |fuchsia::ui::test::input::TouchInputListener| + void ReportTouchInput( + fuchsia::ui::test::input::TouchInputListenerReportTouchInputRequest + request) override { + FML_LOG(INFO) << "Received ReportTouchInput event"; + events_received_.push_back(std::move(request)); + } + + // |LocalComponentImpl::OnStart| + // When the component framework requests for this component to start, this + // method will be invoked by the realm_builder library. + void OnStart() override { + FML_LOG(INFO) << "Starting TouchInputListenerServer"; + // When this component starts, add a binding to the + // protocol to this component's outgoing directory. + ASSERT_EQ(ZX_OK, outgoing()->AddPublicService( + fidl::InterfaceRequestHandler< + fuchsia::ui::test::input::TouchInputListener>( + [this](auto request) { + bindings_.AddBinding(this, std::move(request), + dispatcher_); + }))); + } + + const std::vector< + fuchsia::ui::test::input::TouchInputListenerReportTouchInputRequest>& + events_received() { + return events_received_; + } + + private: + async_dispatcher_t* dispatcher_ = nullptr; + fidl::BindingSet bindings_; + std::vector< + fuchsia::ui::test::input::TouchInputListenerReportTouchInputRequest> + events_received_; +}; + +class FlutterTapTestBase : public PortableUITest, public ::testing::Test { + protected: + ~FlutterTapTestBase() override { + FML_CHECK(touch_injection_request_count() > 0) + << "Injection expected but didn't happen."; + } + + void SetUp() override { + PortableUITest::SetUp(); + + // Post a "just in case" quit task, if the test hangs. + async::PostDelayedTask( + dispatcher(), + [] { + FML_LOG(FATAL) + << "\n\n>> Test did not complete in time, terminating. <<\n\n"; + }, + kTimeout); + + // Get the display information using the + // |fuchsia.ui.display.singleton.Info|. + FML_LOG(INFO) + << "Waiting for display info from fuchsia.ui.display.singleton.Info"; + std::optional display_metrics_obtained; + fuchsia::ui::display::singleton::InfoPtr display_info = + realm_root() + ->component() + .Connect(); + display_info->GetMetrics([this, &display_metrics_obtained](auto info) { + display_width_ = info.extent_in_px().width; + display_height_ = info.extent_in_px().height; + display_metrics_obtained = true; + }); + RunLoopUntil([&display_metrics_obtained] { + return display_metrics_obtained.has_value(); + }); + + // Register input injection device. + FML_LOG(INFO) << "Registering input injection device"; + RegisterTouchScreen(); + } + + bool LastEventReceivedMatches(float expected_x, + float expected_y, + std::string component_name) { + const auto& events_received = + touch_input_listener_server_->events_received(); + + if (events_received.empty()) { + return false; + } + + const auto& last_event = events_received.back(); + + auto pixel_scale = last_event.has_device_pixel_ratio() + ? last_event.device_pixel_ratio() + : 1; + + auto actual_x = pixel_scale * last_event.local_x(); + auto actual_y = pixel_scale * last_event.local_y(); + auto actual_component = last_event.component_name(); + + bool last_event_matches = + CompareDouble(actual_x, expected_x, pixel_scale) && + CompareDouble(actual_y, expected_y, pixel_scale) && + last_event.component_name() == component_name; + + if (last_event_matches) { + FML_LOG(INFO) << "Received event for component " << component_name + << " at (" << expected_x << ", " << expected_y << ")"; + } else { + FML_LOG(WARNING) << "Expecting event for component " << component_name + << " at (" << expected_x << ", " << expected_y << "). " + << "Instead received event for component " + << actual_component << " at (" << actual_x << ", " + << actual_y << "), accounting for pixel scale of " + << pixel_scale; + } + + return last_event_matches; + } + + // Guaranteed to be initialized after SetUp(). + uint32_t display_width() const { return display_width_; } + uint32_t display_height() const { return display_height_; } + + std::string GetTestUIStackUrl() override { return kTestUIStackUrl; }; + + TouchInputListenerServer* touch_input_listener_server_; +}; + +class FlutterTapTest : public FlutterTapTestBase { + private: + void ExtendRealm() override { + FML_LOG(INFO) << "Extending realm"; + // Key part of service setup: have this test component vend the + // |TouchInputListener| service in the constructed realm. + auto touch_input_listener_server = + std::make_unique(dispatcher()); + touch_input_listener_server_ = touch_input_listener_server.get(); + realm_builder()->AddLocalChild( + kMockTouchInputListener, [touch_input_listener_server = std::move( + touch_input_listener_server)]() mutable { + return std::move(touch_input_listener_server); + }); + + // Add touch-input-view to the Realm + realm_builder()->AddChild(kTouchInputView, kTouchInputViewUrl, + component_testing::ChildOptions{ + .environment = kFlutterRunnerEnvironment, + }); + + // Route the TouchInput protocol capability to the Dart component + realm_builder()->AddRoute( + Route{.capabilities = {Protocol{ + fuchsia::ui::test::input::TouchInputListener::Name_}}, + .source = kMockTouchInputListenerRef, + .targets = {kFlutterJitRunnerRef, kTouchInputViewRef}}); + + realm_builder()->AddRoute( + Route{.capabilities = {Protocol{fuchsia::ui::app::ViewProvider::Name_}}, + .source = kTouchInputViewRef, + .targets = {ParentRef()}}); + } +}; + +class FlutterEmbedTapTest : public FlutterTapTestBase { + protected: + void SetUp() override { + PortableUITest::SetUp(false); + + // Post a "just in case" quit task, if the test hangs. + async::PostDelayedTask( + dispatcher(), + [] { + FML_LOG(FATAL) + << "\n\n>> Test did not complete in time, terminating. <<\n\n"; + }, + kTimeout); + } + + void LaunchClientWithEmbeddedView() { + BuildRealm(); + + // Get the display information using the + // |fuchsia.ui.display.singleton.Info|. + FML_LOG(INFO) + << "Waiting for display info from fuchsia.ui.display.singleton.Info"; + std::optional display_metrics_obtained; + fuchsia::ui::display::singleton::InfoPtr display_info = + realm_root() + ->component() + .Connect(); + display_info->GetMetrics([this, &display_metrics_obtained](auto info) { + display_width_ = info.extent_in_px().width; + display_height_ = info.extent_in_px().height; + display_metrics_obtained = true; + }); + RunLoopUntil([&display_metrics_obtained] { + return display_metrics_obtained.has_value(); + }); + + // Register input injection device. + FML_LOG(INFO) << "Registering input injection device"; + RegisterTouchScreen(); + + PortableUITest::LaunchClientWithEmbeddedView(); + } + + // Helper method to add a component argument + // This will be written into an args.csv file that can be parsed and read + // by embedding-flutter-view.dart + // + // Note: You must call this method before LaunchClientWithEmbeddedView() + // Realm Builder will not allow you to create a new directory / file in a + // realm that's already been built + void AddComponentArgument(std::string component_arg) { + auto config_directory_contents = DirectoryContents(); + config_directory_contents.AddFile("args.csv", component_arg); + realm_builder()->RouteReadOnlyDirectory( + "config-data", {kEmbeddingFlutterViewRef}, + std::move(config_directory_contents)); + } + + private: + void ExtendRealm() override { + FML_LOG(INFO) << "Extending realm"; + // Key part of service setup: have this test component vend the + // |TouchInputListener| service in the constructed realm. + auto touch_input_listener_server = + std::make_unique(dispatcher()); + touch_input_listener_server_ = touch_input_listener_server.get(); + realm_builder()->AddLocalChild( + kMockTouchInputListener, [touch_input_listener_server = std::move( + touch_input_listener_server)]() mutable { + return std::move(touch_input_listener_server); + }); + + // Add touch-input-view to the Realm + realm_builder()->AddChild(kTouchInputView, kTouchInputViewUrl, + component_testing::ChildOptions{ + .environment = kFlutterRunnerEnvironment, + }); + // Add embedding-flutter-view to the Realm + // This component will embed touch-input-view as a child view + realm_builder()->AddChild(kEmbeddingFlutterView, kEmbeddingFlutterViewUrl, + component_testing::ChildOptions{ + .environment = kFlutterRunnerEnvironment, + }); + + // Route the TouchInput protocol capability to the Dart component + realm_builder()->AddRoute( + Route{.capabilities = {Protocol{ + fuchsia::ui::test::input::TouchInputListener::Name_}}, + .source = kMockTouchInputListenerRef, + .targets = {kFlutterJitRunnerRef, kTouchInputViewRef, + kEmbeddingFlutterViewRef}}); + + realm_builder()->AddRoute( + Route{.capabilities = {Protocol{fuchsia::ui::app::ViewProvider::Name_}}, + .source = kEmbeddingFlutterViewRef, + .targets = {ParentRef()}}); + realm_builder()->AddRoute( + Route{.capabilities = {Protocol{fuchsia::ui::app::ViewProvider::Name_}}, + .source = kTouchInputViewRef, + .targets = {kEmbeddingFlutterViewRef}}); + } +}; + +TEST_F(FlutterTapTest, FlutterTap) { + // Launch client view, and wait until it's rendering to proceed with the test. + FML_LOG(INFO) << "Initializing scene"; + LaunchClient(); + FML_LOG(INFO) << "Client launched"; + + // touch-input-view logical coordinate space doesn't match the fake touch + // screen injector's coordinate space, which spans [-1000, 1000] on both axes. + // Scenic handles figuring out where in the coordinate space + // to inject a touch event (this is fixed to a display's bounds). + InjectTap(-500, -500); + // For a (-500 [x], -500 [y]) tap, we expect a touch event in the middle of + // the upper-left quadrant of the screen. + RunLoopUntil([this] { + return LastEventReceivedMatches( + /*expected_x=*/static_cast(display_width() / 4.0f), + /*expected_y=*/static_cast(display_height() / 4.0f), + /*component_name=*/"touch-input-view"); + }); + + // There should be 1 injected tap + ASSERT_EQ(touch_injection_request_count(), 1); +} + +TEST_F(FlutterEmbedTapTest, FlutterEmbedTap) { + // Launch view + FML_LOG(INFO) << "Initializing scene"; + LaunchClientWithEmbeddedView(); + FML_LOG(INFO) << "Client launched"; + + { + // Embedded child view takes up the center of the screen + // Expect a response from the child view if we inject a tap there + InjectTap(0, 0); + RunLoopUntil([this] { + return LastEventReceivedMatches( + /*expected_x=*/static_cast(display_width() / 8.0f), + /*expected_y=*/static_cast(display_height() / 8.0f), + /*component_name=*/"touch-input-view"); + }); + } + + { + // Parent view takes up the rest of the screen + // Validate that parent can still receive taps + InjectTap(500, 500); + RunLoopUntil([this] { + return LastEventReceivedMatches( + /*expected_x=*/static_cast(display_width() / (4.0f / 3.0f)), + /*expected_y=*/static_cast(display_height() / (4.0f / 3.0f)), + /*component_name=*/"embedding-flutter-view"); + }); + } + + // There should be 2 injected taps + ASSERT_EQ(touch_injection_request_count(), 2); +} + +TEST_F(FlutterEmbedTapTest, FlutterEmbedOverlayEnabled) { + FML_LOG(INFO) << "Initializing scene"; + AddComponentArgument("--showOverlay"); + LaunchClientWithEmbeddedView(); + FML_LOG(INFO) << "Client launched"; + + { + // The bottom-left corner of the overlay is at the center of the screen + // Expect the overlay / parent view to respond if we inject a tap there + // and not the embedded child view + InjectTap(0, 0); + RunLoopUntil([this] { + return LastEventReceivedMatches( + /*expected_x=*/static_cast(display_width() / 2.0f), + /*expected_y=*/static_cast(display_height() / 2.0f), + /*component_name=*/"embedding-flutter-view"); + }); + } + + { + // The embedded child view is just outside of the bottom-left corner of the + // overlay + // Expect the embedded child view to still receive taps + InjectTap(-1, -1); + RunLoopUntil([this] { + return LastEventReceivedMatches( + /*expected_x=*/static_cast(display_width() / 8.0f), + /*expected_y=*/static_cast(display_height() / 8.0f), + /*component_name=*/"touch-input-view"); + }); + } + + // There should be 2 injected taps + ASSERT_EQ(touch_injection_request_count(), 2); +} + +} // namespace +} // namespace touch_input_test::testing diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/touch-input-view/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/touch-input-view/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..2ba2fa5a7373a3c1a0f5f2baba010eeed131df12 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/touch-input-view/BUILD.gn @@ -0,0 +1,33 @@ +# 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. + +import("//flutter/tools/fuchsia/dart/dart_library.gni") +import("//flutter/tools/fuchsia/flutter/flutter_component.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/component.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/package.gni") + +dart_library("lib") { + package_name = "touch-input-view" + sources = [ "touch-input-view.dart" ] + + deps = [ "//flutter/shell/platform/fuchsia/dart:args" ] +} + +flutter_component("component") { + testonly = true + component_name = "touch-input-view" + manifest = rebase_path("meta/touch-input-view.cml") + main_package = "touch-input-view" + main_dart = "touch-input-view.dart" + + deps = [ ":lib" ] +} + +fuchsia_package("package") { + testonly = true + package_name = "touch-input-view" + + deps = [ ":component" ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/touch-input-view/lib/touch-input-view.dart b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/touch-input-view/lib/touch-input-view.dart new file mode 100644 index 0000000000000000000000000000000000000000..ced8882ace8b1e3d35709711ccd3b1464f6e4779 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/touch-input-view/lib/touch-input-view.dart @@ -0,0 +1,101 @@ +// Copyright 2020 The Fuchsia Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:convert'; +import 'dart:typed_data'; +import 'dart:ui'; +import 'dart:zircon'; + +void main() { + print('Launching touch-input-view'); + TestApp app = TestApp(); + app.run(); +} + +class TestApp { + static const _yellow = Color.fromARGB(255, 255, 255, 0); + static const _pink = Color.fromARGB(255, 255, 0, 255); + + Color _backgroundColor = _pink; + + void run() { + // Set up window callbacks. + window.onPointerDataPacket = (PointerDataPacket packet) { + this.pointerDataPacket(packet); + }; + window.onMetricsChanged = () { + window.scheduleFrame(); + }; + window.onBeginFrame = (Duration duration) { + this.beginFrame(duration); + }; + + // The child view should be attached to Scenic now. + // Ready to build the scene. + window.scheduleFrame(); + } + + void beginFrame(Duration duration) { + // Convert physical screen size of device to values + final pixelRatio = window.devicePixelRatio; + final size = window.physicalSize / pixelRatio; + final physicalBounds = Offset.zero & size * pixelRatio; + final windowBounds = Offset.zero & size; + // Set up a Canvas that uses the screen size + final recorder = PictureRecorder(); + final canvas = Canvas(recorder, physicalBounds); + canvas.scale(pixelRatio, pixelRatio); + // Draw something + final paint = Paint()..color = this._backgroundColor; + canvas.drawRect(windowBounds, paint); + // Build the scene + final picture = recorder.endRecording(); + final sceneBuilder = + SceneBuilder() + ..pushClipRect(physicalBounds) + ..addPicture(Offset.zero, picture) + ..pop(); + window.render(sceneBuilder.build()); + } + + void pointerDataPacket(PointerDataPacket packet) async { + int nowNanos = System.clockGetMonotonic(); + + for (PointerData data in packet.data) { + print('touch-input-view received tap: ${data.toStringFull()}'); + + if (data.change == PointerChange.down) { + this._backgroundColor = _yellow; + } + + if (data.change == PointerChange.down || data.change == PointerChange.move) { + _reportTouchInput(localX: data.physicalX, localY: data.physicalY, timeReceived: nowNanos); + } + } + + window.scheduleFrame(); + } + + void _reportTouchInput({ + required double localX, + required double localY, + required int timeReceived, + }) { + print('touch-input-view reporting touch input to TouchInputListener'); + final message = + utf8 + .encode( + json.encode({ + 'method': 'TouchInputListener.ReportTouchInput', + 'local_x': localX, + 'local_y': localY, + 'time_received': timeReceived, + 'component_name': 'touch-input-view', + }), + ) + .buffer + .asByteData(); + PlatformDispatcher.instance.sendPlatformMessage('fuchsia/input_test', message, null); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/touch-input-view/meta/touch-input-view.cml b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/touch-input-view/meta/touch-input-view.cml new file mode 100644 index 0000000000000000000000000000000000000000..0210fbd527a5542fa5829e983f47c46dbcaead69 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/touch-input-view/meta/touch-input-view.cml @@ -0,0 +1,31 @@ +// 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: [ "syslog/client.shard.cml" ], + program: { + data: "data/touch-input-view", + + // Always use the jit runner for now. + // TODO(fxbug.dev/106577): Implement manifest merging build rules for V2 components. + runner: "flutter_jit_runner", + }, + capabilities: [ + { + protocol: [ "fuchsia.ui.app.ViewProvider" ], + }, + ], + expose: [ + { + protocol: [ "fuchsia.ui.app.ViewProvider" ], + from: "self", + }, + ], + use: [ + { + protocol: [ + "fuchsia.ui.test.input.TouchInputListener", + ] + } + ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/touch-input-view/pubspec.yaml b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/touch-input-view/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4ba22fab5b13439aff3c20e2fb8d20aa09d19674 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/touch-input-view/pubspec.yaml @@ -0,0 +1,8 @@ +# 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. + +name: touch-input-view + +environment: + sdk: ^3.7.0-0 diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/utils/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/utils/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..3767ffa01800f772eb4e0351a893ac983eafdb5f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/utils/BUILD.gn @@ -0,0 +1,60 @@ +# 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. + +assert(is_fuchsia) + +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") + +source_set("check_view") { + sources = [ + "check_view.cc", + "check_view.h", + ] + + deps = [ + "${fuchsia_sdk}/fidl/fuchsia.ui.observation.geometry", + "${fuchsia_sdk}/pkg/zx", + "//flutter/fml", + ] +} + +source_set("screenshot") { + sources = [ + "screenshot.cc", + "screenshot.h", + ] + + deps = [ + "${fuchsia_sdk}/fidl/fuchsia.logger", + "${fuchsia_sdk}/pkg/zx", + "//flutter/fml", + ] +} + +source_set("portable_ui_test") { + testonly = true + sources = [ + "portable_ui_test.cc", + "portable_ui_test.h", + ] + + deps = [ + ":check_view", + "${fuchsia_sdk}/fidl/fuchsia.inspect", + "${fuchsia_sdk}/fidl/fuchsia.logger", + "${fuchsia_sdk}/fidl/fuchsia.sysmem", + "${fuchsia_sdk}/fidl/fuchsia.sysmem2", + "${fuchsia_sdk}/fidl/fuchsia.tracing.provider", + "${fuchsia_sdk}/fidl/fuchsia.ui.app", + "${fuchsia_sdk}/fidl/fuchsia.ui.composition", + "${fuchsia_sdk}/fidl/fuchsia.ui.display.singleton", + "${fuchsia_sdk}/fidl/fuchsia.ui.input", + "${fuchsia_sdk}/fidl/fuchsia.ui.observation.geometry", + "${fuchsia_sdk}/fidl/fuchsia.ui.test.input", + "${fuchsia_sdk}/fidl/fuchsia.ui.test.scene", + "${fuchsia_sdk}/pkg/async-loop-testing", + "${fuchsia_sdk}/pkg/sys_component_cpp_testing", + "//flutter/fml", + ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/utils/check_view.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/utils/check_view.cc new file mode 100644 index 0000000000000000000000000000000000000000..6b35f1e831bd6e342a0b1499b5c18eb3868d7de7 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/utils/check_view.cc @@ -0,0 +1,39 @@ +// 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 "check_view.h" + +#include "flutter/fml/logging.h" + +namespace fuchsia_test_utils { + +bool CheckViewExistsInSnapshot( + const fuchsia::ui::observation::geometry::ViewTreeSnapshot& snapshot, + zx_koid_t view_ref_koid) { + if (!snapshot.has_views()) { + return false; + } + + auto snapshot_count = + std::count_if(snapshot.views().begin(), snapshot.views().end(), + [view_ref_koid](const auto& view) { + return view.view_ref_koid() == view_ref_koid; + }); + + return snapshot_count > 0; +} + +bool CheckViewExistsInUpdates( + const std::vector& + updates, + zx_koid_t view_ref_koid) { + auto update_count = std::count_if( + updates.begin(), updates.end(), [view_ref_koid](auto& snapshot) { + return CheckViewExistsInSnapshot(snapshot, view_ref_koid); + }); + + return update_count > 0; +} + +} // namespace fuchsia_test_utils diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/utils/check_view.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/utils/check_view.h new file mode 100644 index 0000000000000000000000000000000000000000..662de84d59f3cccaeb91a15cfa76fb38a537f71b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/utils/check_view.h @@ -0,0 +1,30 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_INTEGRATION_UTILS_CHECK_VIEW_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_INTEGRATION_UTILS_CHECK_VIEW_H_ + +#include + +#include +#include + +namespace fuchsia_test_utils { + +/// Returns true if a view with the given |view_ref_koid| exists in a |snapshot| +/// of the view tree, false otherwise. +bool CheckViewExistsInSnapshot( + const fuchsia::ui::observation::geometry::ViewTreeSnapshot& snapshot, + zx_koid_t view_ref_koid); + +/// Returns true if any of the snapshots of the view tree in |updates| contain a +/// view with the given |view_ref_koid|, false otherwise. +bool CheckViewExistsInUpdates( + const std::vector& + updates, + zx_koid_t view_ref_koid); + +} // namespace fuchsia_test_utils + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_INTEGRATION_UTILS_CHECK_VIEW_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/utils/portable_ui_test.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/utils/portable_ui_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..45b2f3c759913fd28de4664f9ffcf93fe6732500 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/utils/portable_ui_test.cc @@ -0,0 +1,340 @@ +// 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 "portable_ui_test.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "check_view.h" +#include "flutter/fml/logging.h" + +namespace fuchsia_test_utils { +namespace { + +// Types imported for the realm_builder library. +using component_testing::ChildOptions; +using component_testing::ChildRef; +using component_testing::ParentRef; +using component_testing::Protocol; +using component_testing::RealmRoot; +using component_testing::Route; + +using fuchsia_test_utils::CheckViewExistsInSnapshot; + +} // namespace + +void PortableUITest::SetUp(bool build_realm) { + SetUpRealmBase(); + ExtendRealm(); + + if (build_realm) { + BuildRealm(); + } +} + +void PortableUITest::BuildRealm() { + realm_ = std::make_unique(realm_builder_.Build()); +} + +void PortableUITest::SetUpRealmBase() { + FML_LOG(INFO) << "Setting up realm base"; + + // Add Flutter JIT runner as a child of the RealmBuilder + realm_builder_.AddChild(kFlutterJitRunner, kFlutterJitRunnerUrl); + + // Add environment providing the Flutter JIT runner + fuchsia::component::decl::Environment flutter_runner_environment; + flutter_runner_environment.set_name(kFlutterRunnerEnvironment); + flutter_runner_environment.set_extends( + fuchsia::component::decl::EnvironmentExtends::REALM); + flutter_runner_environment.set_runners({}); + auto environment_runners = flutter_runner_environment.mutable_runners(); + + // Add Flutter JIT runner to the environment + fuchsia::component::decl::RunnerRegistration flutter_jit_runner_reg; + flutter_jit_runner_reg.set_source(fuchsia::component::decl::Ref::WithChild( + fuchsia::component::decl::ChildRef{.name = kFlutterJitRunner})); + flutter_jit_runner_reg.set_source_name(kFlutterJitRunner); + flutter_jit_runner_reg.set_target_name(kFlutterJitRunner); + environment_runners->push_back(std::move(flutter_jit_runner_reg)); + auto realm_decl = realm_builder_.GetRealmDecl(); + if (!realm_decl.has_environments()) { + realm_decl.set_environments({}); + } + auto realm_environments = realm_decl.mutable_environments(); + realm_environments->push_back(std::move(flutter_runner_environment)); + realm_builder_.ReplaceRealmDecl(std::move(realm_decl)); + + // Add test UI stack component. + realm_builder_.AddChild(kTestUIStack, GetTestUIStackUrl()); + + // // Route base system services to flutter and the test UI stack. + realm_builder_.AddRoute(Route{ + .capabilities = {Protocol{fuchsia::logger::LogSink::Name_}, + Protocol{fuchsia::inspect::InspectSink::Name_}, + Protocol{fuchsia::sysmem::Allocator::Name_}, + Protocol{fuchsia::sysmem2::Allocator::Name_}, + Protocol{fuchsia::tracing::provider::Registry::Name_}, + Protocol{fuchsia::ui::input::ImeService::Name_}, + Protocol{kPosixSocketProviderName}, + Protocol{kVulkanLoaderServiceName}, + component_testing::Directory{"config-data"}}, + .source = ParentRef(), + .targets = {kFlutterJitRunnerRef, kTestUIStackRef}}); + + // Route UI capabilities to test driver and Flutter runner + realm_builder_.AddRoute(Route{ + .capabilities = {Protocol{fuchsia::ui::composition::Allocator::Name_}, + Protocol{fuchsia::ui::composition::Flatland::Name_}, + Protocol{fuchsia::ui::test::input::Registry::Name_}, + Protocol{fuchsia::ui::test::scene::Controller::Name_}, + Protocol{fuchsia::ui::display::singleton::Info::Name_}, + Protocol{kPointerInjectorRegistryName}}, + .source = kTestUIStackRef, + .targets = {ParentRef(), kFlutterJitRunnerRef}}); +} + +void PortableUITest::ProcessViewGeometryResponse( + fuchsia::ui::observation::geometry::WatchResponse response) { + // Process update if no error + if (!response.has_error()) { + std::vector* updates = + response.mutable_updates(); + if (updates && !updates->empty()) { + last_view_tree_snapshot_ = std::move(updates->back()); + } + } else { + // Otherwise process error + const auto& error = response.error(); + if (error | fuchsia::ui::observation::geometry::Error::CHANNEL_OVERFLOW) { + FML_LOG(INFO) << "View Tree watcher channel overflowed"; + } else if (error | + fuchsia::ui::observation::geometry::Error::BUFFER_OVERFLOW) { + FML_LOG(INFO) << "View Tree watcher buffer overflowed"; + } else if (error | + fuchsia::ui::observation::geometry::Error::VIEWS_OVERFLOW) { + // This one indicates some possible data loss, so we log with a high + // severity + FML_LOG(WARNING) + << "View Tree watcher attempted to report too many views"; + } + } +} + +void PortableUITest::WatchViewGeometry() { + FML_CHECK(view_tree_watcher_) + << "View Tree watcher must be registered before calling Watch()"; + + view_tree_watcher_->Watch([this](auto response) { + ProcessViewGeometryResponse(std::move(response)); + WatchViewGeometry(); + }); +} + +bool PortableUITest::HasViewConnected(zx_koid_t view_ref_koid) { + return last_view_tree_snapshot_.has_value() && + CheckViewExistsInSnapshot(*last_view_tree_snapshot_, view_ref_koid); +} + +void PortableUITest::LaunchClient() { + scene_provider_ = + realm_->component().Connect(); + scene_provider_.set_error_handler([](auto) { + FML_LOG(ERROR) << "Error from test scene provider: " + << &zx_status_get_string; + }); + + fuchsia::ui::test::scene::ControllerAttachClientViewRequest request; + request.set_view_provider( + realm_->component().Connect()); + scene_provider_->RegisterViewTreeWatcher(view_tree_watcher_.NewRequest(), + []() {}); + scene_provider_->AttachClientView( + std::move(request), [this](auto client_view_ref_koid) { + client_root_view_ref_koid_ = client_view_ref_koid; + }); + + FML_LOG(INFO) << "Waiting for client view ref koid"; + RunLoopUntil([this] { return client_root_view_ref_koid_.has_value(); }); + + WatchViewGeometry(); + + FML_LOG(INFO) << "Waiting for client view to connect"; + // Wait for the client view to get attached to the view tree. + RunLoopUntil( + [this] { return HasViewConnected(*client_root_view_ref_koid_); }); + FML_LOG(INFO) << "Client view has rendered"; +} + +void PortableUITest::LaunchClientWithEmbeddedView() { + LaunchClient(); + // At this point, the parent view must have rendered, so we just need to wait + // for the embedded view. + RunLoopUntil([this] { + if (!last_view_tree_snapshot_.has_value() || + !last_view_tree_snapshot_->has_views()) { + return false; + } + + if (!client_root_view_ref_koid_.has_value()) { + return false; + } + + for (const auto& view : last_view_tree_snapshot_->views()) { + if (!view.has_view_ref_koid() || + view.view_ref_koid() != *client_root_view_ref_koid_) { + continue; + } + + if (view.children().empty()) { + return false; + } + + // NOTE: We can't rely on the presence of the child view in + // `view.children()` to guarantee that it has rendered. The child view + // also needs to be present in `last_view_tree_snapshot_->views`. + return std::count_if( + last_view_tree_snapshot_->views().begin(), + last_view_tree_snapshot_->views().end(), + [view_to_find = + view.children().back()](const auto& view_to_check) { + return view_to_check.has_view_ref_koid() && + view_to_check.view_ref_koid() == view_to_find; + }) > 0; + } + + return false; + }); + + FML_LOG(INFO) << "Embedded view has rendered"; +} + +void PortableUITest::RegisterTouchScreen() { + FML_LOG(INFO) << "Registering fake touch screen"; + input_registry_ = + realm_->component().Connect(); + input_registry_.set_error_handler([](auto) { + FML_LOG(ERROR) << "Error from input helper: " << &zx_status_get_string; + }); + + bool touchscreen_registered = false; + fuchsia::ui::test::input::RegistryRegisterTouchScreenRequest request; + request.set_device(fake_touchscreen_.NewRequest()); + input_registry_->RegisterTouchScreen( + std::move(request), + [&touchscreen_registered]() { touchscreen_registered = true; }); + + RunLoopUntil([&touchscreen_registered] { return touchscreen_registered; }); + FML_LOG(INFO) << "Touchscreen registered"; +} + +void PortableUITest::RegisterMouse() { + FML_LOG(INFO) << "Registering fake mouse"; + input_registry_ = + realm_->component().Connect(); + input_registry_.set_error_handler([](auto) { + FML_LOG(ERROR) << "Error from input helper: " << &zx_status_get_string; + }); + + bool mouse_registered = false; + fuchsia::ui::test::input::RegistryRegisterMouseRequest request; + request.set_device(fake_mouse_.NewRequest()); + input_registry_->RegisterMouse( + std::move(request), [&mouse_registered]() { mouse_registered = true; }); + + RunLoopUntil([&mouse_registered] { return mouse_registered; }); + FML_LOG(INFO) << "Mouse registered"; +} + +void PortableUITest::RegisterKeyboard() { + FML_LOG(INFO) << "Registering fake keyboard"; + input_registry_ = + realm_->component().Connect(); + input_registry_.set_error_handler([](auto) { + FML_LOG(ERROR) << "Error from input helper: " << &zx_status_get_string; + }); + + bool keyboard_registered = false; + fuchsia::ui::test::input::RegistryRegisterKeyboardRequest request; + request.set_device(fake_keyboard_.NewRequest()); + input_registry_->RegisterKeyboard( + std::move(request), + [&keyboard_registered]() { keyboard_registered = true; }); + + RunLoopUntil([&keyboard_registered] { return keyboard_registered; }); + FML_LOG(INFO) << "Keyboard registered"; +} + +void PortableUITest::InjectTap(int32_t x, int32_t y) { + fuchsia::ui::test::input::TouchScreenSimulateTapRequest tap_request; + tap_request.mutable_tap_location()->x = x; + tap_request.mutable_tap_location()->y = y; + + FML_LOG(INFO) << "Injecting tap at (" << tap_request.tap_location().x << ", " + << tap_request.tap_location().y << ")"; + fake_touchscreen_->SimulateTap(std::move(tap_request), [this]() { + ++touch_injection_request_count_; + FML_LOG(INFO) << "*** Tap injected, count: " + << touch_injection_request_count_; + }); +} + +void PortableUITest::SimulateMouseEvent( + std::vector pressed_buttons, + int movement_x, + int movement_y) { + fuchsia::ui::test::input::MouseSimulateMouseEventRequest request; + request.set_pressed_buttons(std::move(pressed_buttons)); + request.set_movement_x(movement_x); + request.set_movement_y(movement_y); + + FML_LOG(INFO) << "Injecting mouse input"; + + fake_mouse_->SimulateMouseEvent( + std::move(request), [] { FML_LOG(INFO) << "Mouse event injected"; }); +} + +void PortableUITest::SimulateMouseScroll( + std::vector pressed_buttons, + int scroll_x, + int scroll_y, + bool use_physical_units) { + FML_LOG(INFO) << "Requesting mouse scroll"; + fuchsia::ui::test::input::MouseSimulateMouseEventRequest request; + request.set_pressed_buttons(std::move(pressed_buttons)); + if (use_physical_units) { + request.set_scroll_h_physical_pixel(scroll_x); + request.set_scroll_v_physical_pixel(scroll_y); + } else { + request.set_scroll_h_detent(scroll_x); + request.set_scroll_v_detent(scroll_y); + } + + fake_mouse_->SimulateMouseEvent(std::move(request), [] { + FML_LOG(INFO) << "Mouse scroll event injected"; + }); +} + +void PortableUITest::SimulateTextEntry(std::string text) { + FML_LOG(INFO) << "Sending text request"; + bool done = false; + + fuchsia::ui::test::input::KeyboardSimulateUsAsciiTextEntryRequest request; + request.set_text(text); + fake_keyboard_->SimulateUsAsciiTextEntry(std::move(request), + [&done]() { done = true; }); + + RunLoopUntil([&] { return done; }); + FML_LOG(INFO) << "Text request sent"; +} + +} // namespace fuchsia_test_utils diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/utils/portable_ui_test.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/utils/portable_ui_test.h new file mode 100644 index 0000000000000000000000000000000000000000..62b5417a5b500d925537f65105e9637932b27a79 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/utils/portable_ui_test.h @@ -0,0 +1,155 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_INTEGRATION_UTILS_PORTABLE_UI_TEST_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_INTEGRATION_UTILS_PORTABLE_UI_TEST_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace fuchsia_test_utils { +class PortableUITest : public ::loop_fixture::RealLoop { + public: + // The FIDL bindings for these services are not exposed in the Fuchsia SDK so + // we must encode the names manually here. + static constexpr auto kVulkanLoaderServiceName = + "fuchsia.vulkan.loader.Loader"; + static constexpr auto kPosixSocketProviderName = + "fuchsia.posix.socket.Provider"; + static constexpr auto kPointerInjectorRegistryName = + "fuchsia.ui.pointerinjector.Registry"; + + // The naming and references used by Realm Builder + static constexpr auto kTestUIStack = "ui"; + static constexpr auto kTestUIStackRef = + component_testing::ChildRef{kTestUIStack}; + static constexpr auto kFlutterJitRunner = "flutter_jit_runner"; + static constexpr auto kFlutterJitRunnerRef = + component_testing::ChildRef{kFlutterJitRunner}; + static constexpr auto kFlutterJitRunnerUrl = + "fuchsia-pkg://fuchsia.com/oot_flutter_jit_runner#meta/" + "flutter_jit_runner.cm"; + static constexpr auto kFlutterRunnerEnvironment = "flutter_runner_env"; + + void SetUp(bool build_realm = true); + + // Calls the Build method for Realm Builder to build the realm + // Can only be called once, panics otherwise + void BuildRealm(); + + // Attaches a client view to the scene, and waits for it to render. + void LaunchClient(); + // Attaches a view with an embedded child view to the scene, and waits for it + // to render. + void LaunchClientWithEmbeddedView(); + + // Returns true when the specified view is fully connected to the scene AND + // has presented at least one frame of content. + bool HasViewConnected(zx_koid_t view_ref_koid); + + // Registers a fake touch screen device with an injection coordinate space + // spanning [-1000, 1000] on both axes. + void RegisterTouchScreen(); + + // Registers a fake mouse device, for which mouse movement is measured on a + // scale of [-1000, 1000] on both axes and scroll is measured from [-100, 100] + // on both axes. + void RegisterMouse(); + + // Register a fake keyboard + void RegisterKeyboard(); + + // Simulates a tap at location (x, y). + void InjectTap(int32_t x, int32_t y); + + // Helper method to simulate combinations of button presses/releases and/or + // mouse movements. + void SimulateMouseEvent( + std::vector pressed_buttons, + int movement_x, + int movement_y); + + // Helper method to simulate a mouse scroll event. + // + // Set `use_physical_units` to true to specify scroll in physical pixels and + // false to specify scroll in detents. + void SimulateMouseScroll( + std::vector pressed_buttons, + int scroll_x, + int scroll_y, + bool use_physical_units = false); + + // Helper method to simluate text input + void SimulateTextEntry(std::string text); + + protected: + component_testing::RealmBuilder* realm_builder() { return &realm_builder_; } + component_testing::RealmRoot* realm_root() { return realm_.get(); } + + uint32_t display_width_ = 0; + uint32_t display_height_ = 0; + + int touch_injection_request_count() const { + return touch_injection_request_count_; + } + + private: + void SetUpRealmBase(); + + // Configures the test-specific component topology. + virtual void ExtendRealm() = 0; + + // Returns the test-specific test-ui-stack component url to use. + // Usually overridden to return a value from gtest GetParam() + virtual std::string GetTestUIStackUrl() = 0; + + // Helper method to watch for view geometry updates. + void WatchViewGeometry(); + + // Helper method to process a view geometry update. + void ProcessViewGeometryResponse( + fuchsia::ui::observation::geometry::WatchResponse response); + + fuchsia::ui::test::input::RegistryPtr input_registry_; + fuchsia::ui::test::input::TouchScreenPtr fake_touchscreen_; + fuchsia::ui::test::input::MousePtr fake_mouse_; + fuchsia::ui::test::input::KeyboardPtr fake_keyboard_; + fuchsia::ui::test::scene::ControllerPtr scene_provider_; + fuchsia::ui::observation::geometry::ViewTreeWatcherPtr view_tree_watcher_; + + component_testing::RealmBuilder realm_builder_ = + component_testing::RealmBuilder::Create(); + std::unique_ptr realm_; + + // Counts the number of completed requests to inject touch reports into input + // pipeline. + int touch_injection_request_count_ = 0; + + // The KOID of the client root view's `ViewRef`. + std::optional client_root_view_ref_koid_; + + // Holds the most recent view tree snapshot received from the view tree + // watcher. + // + // From this snapshot, we can retrieve relevant view tree state on demand, + // e.g. if the client view is rendering content. + std::optional + last_view_tree_snapshot_; +}; + +} // namespace fuchsia_test_utils + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_INTEGRATION_UTILS_PORTABLE_UI_TEST_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/utils/screenshot.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/utils/screenshot.cc new file mode 100644 index 0000000000000000000000000000000000000000..9f7e33764a7ee744121cab964b927fdb05755d4f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/utils/screenshot.cc @@ -0,0 +1,104 @@ +// 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 "screenshot.h" + +#include + +#include +#include +#include +#include + +#include "flutter/fml/logging.h" + +namespace fuchsia_test_utils { +namespace { +constexpr uint64_t kBytesPerPixel = 4; +} // namespace + +Screenshot::Screenshot(const zx::vmo& screenshot_vmo, + uint64_t width, + uint64_t height, + int rotation) + : width_(width), height_(height) { + FML_CHECK(rotation == 0 || rotation == 90 || rotation == 270); + if (rotation == 90 || rotation == 270) { + std::swap(width_, height_); + } + // Populate |screenshot_| from |screenshot_vmo|. + uint64_t vmo_size; + screenshot_vmo.get_prop_content_size(&vmo_size); + FML_CHECK(vmo_size == kBytesPerPixel * width_ * height_); + uint8_t* vmo_host = nullptr; + auto status = zx::vmar::root_self()->map( + ZX_VM_PERM_READ, /*vmar_offset*/ 0, screenshot_vmo, + /*vmo_offset*/ 0, vmo_size, reinterpret_cast(&vmo_host)); + FML_CHECK(status == ZX_OK); + ExtractScreenshotFromVMO(vmo_host); + // map the pointer. + uintptr_t address = reinterpret_cast(vmo_host); + status = zx::vmar::root_self()->unmap(address, vmo_size); + FML_CHECK(status == ZX_OK); +} + +std::ostream& operator<<(std::ostream& stream, const Pixel& pixel) { + return stream << "{Pixel:" << " r:" << static_cast(pixel.red) + << " g:" << static_cast(pixel.green) + << " b:" << static_cast(pixel.blue) + << " a:" << static_cast(pixel.alpha) << "}"; +} + +Pixel Screenshot::GetPixelAt(uint64_t x, uint64_t y) const { + FML_CHECK(x >= 0 && x < width_ && y >= 0 && y < height_) + << "Index out of bounds"; + return screenshot_[y][x]; +} + +std::map Screenshot::Histogram() const { + std::map histogram; + FML_CHECK(screenshot_.size() == height_ && screenshot_[0].size() == width_); + for (size_t i = 0; i < height_; i++) { + for (size_t j = 0; j < width_; j++) { + histogram[screenshot_[i][j]]++; + } + } + return histogram; +} + +void Screenshot::ExtractScreenshotFromVMO(uint8_t* screenshot_vmo) { + FML_CHECK(screenshot_vmo); + for (size_t i = 0; i < height_; i++) { + // The head index of the ith row in the screenshot is |i* width_* + // KbytesPerPixel|. + screenshot_.push_back(GetPixelsInRow(screenshot_vmo, i)); + } +} + +std::vector Screenshot::GetPixelsInRow(uint8_t* screenshot_vmo, + size_t row_index) { + std::vector row; + for (size_t col_idx = 0; + col_idx < static_cast(width_ * kBytesPerPixel); + col_idx += kBytesPerPixel) { + // Each row in the screenshot has |kBytesPerPixel * width_| elements. + // Therefore in order to reach the first pixel of the |row_index| row, we + // have to jump |row_index * width_ * kBytesPerPixel| positions. + auto pixel_start_index = row_index * width_ * kBytesPerPixel; + // Every |kBytesPerPixel| bytes represents the BGRA values of a pixel. Skip + // |kBytesPerPixel| bytes to get to the BGRA values of the next pixel. Each + // row in a screenshot has |kBytesPerPixel * width_| bytes of data. + // Example:- + // auto data = TakeScreenshot(); + // data[0-3] -> RGBA of pixel 0. + // data[4-7] -> RGBA pf pixel 1. + row.emplace_back(screenshot_vmo[pixel_start_index + col_idx], + screenshot_vmo[pixel_start_index + col_idx + 1], + screenshot_vmo[pixel_start_index + col_idx + 2], + screenshot_vmo[pixel_start_index + col_idx + 3]); + } + return row; +} + +} // namespace fuchsia_test_utils diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/utils/screenshot.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/utils/screenshot.h new file mode 100644 index 0000000000000000000000000000000000000000..717089d9d9840c47a3dda1b13dd85a806878a641 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/integration/utils/screenshot.h @@ -0,0 +1,112 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_INTEGRATION_UTILS_SCREENSHOT_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_INTEGRATION_UTILS_SCREENSHOT_H_ + +#include +#include + +#include +#include +#include +#include +#include + +namespace fuchsia_test_utils { +// Represents a Pixel in BGRA format. +// Uses the sRGB color space. +struct Pixel { + uint8_t blue = 0; + uint8_t green = 0; + uint8_t red = 0; + uint8_t alpha = 0; + + Pixel(uint8_t blue, uint8_t green, uint8_t red, uint8_t alpha) + : blue(blue), green(green), red(red), alpha(alpha) {} + + bool operator==(const Pixel& rhs) const { + return blue == rhs.blue && green == rhs.green && red == rhs.red && + alpha == rhs.alpha; + } + + inline bool operator!=(const Pixel& rhs) const { return !(*this == rhs); } + + bool operator<(const Pixel& other) const { + return std::tie(blue, green, red, alpha) < + std::tie(other.blue, other.green, other.red, other.alpha); + } +}; + +std::ostream& operator<<(std::ostream& stream, const Pixel& pixel); + +// Helper class to get information about a screenshot returned by +// |fuchsia.ui.composition.Screenshot| protocol. +class Screenshot { + public: + // BGRA format. + inline static const Pixel kBlack = Pixel(0, 0, 0, 255); + inline static const Pixel kBlue = Pixel(255, 0, 0, 255); + inline static const Pixel kRed = Pixel(0, 0, 255, 255); + inline static const Pixel kMagenta = Pixel(255, 0, 255, 255); + inline static const Pixel kGreen = Pixel(0, 255, 0, 255); + + // Params:- + // |screenshot_vmo| - The VMO returned by + // fuchsia.ui.composition.Screenshot.Take representing the screenshot data. + // |width|, |height| - Width and height of the physical display in pixels as + // returned by |fuchsia.ui.display.singleton.Info|. + // |rotation| - The display rotation value in degrees. The width and the + // height of the screenshot are flipped if this value is 90 or 270 degrees, + // as the screenshot shows how content is seen by the user. + Screenshot(const zx::vmo& screenshot_vmo, + uint64_t width, + uint64_t height, + int rotation); + + // Returns the |Pixel| located at (x,y) coordinates. |x| and |y| should range + // from [0,width_) and [0,height_) respectively. + // + // (0,0)________________width_____________(w-1,0) + // | | | + // | | y |h + // | x | |e + // |-----------------------X |i + // | |g + // | |h + // | |t + // |_________________________________| + // (0,h-1) screenshot (w-1,h-1) + // + // Clients should only use this function to get the pixel data. + Pixel GetPixelAt(uint64_t x, uint64_t y) const; + + // Counts the frequencies of each color in a screenshot. + std::map Histogram() const; + + // Returns a 2D vector of size |height_ * width_|. Each value in the vector + // corresponds to a pixel in the screenshot. + std::vector> screenshot() const { return screenshot_; } + + uint64_t width() const { return width_; } + + uint64_t height() const { return height_; } + + private: + // Populates |screenshot_| by converting the linear array of bytes in + // |screenshot_vmo| of size |kBytesPerPixel * width_ * height_| to a 2D vector + // of |Pixel|s of size |height_ * width_|. + void ExtractScreenshotFromVMO(uint8_t* screenshot_vmo); + + // Returns the |Pixel|s in the |row_index| row of the screenshot. + std::vector GetPixelsInRow(uint8_t* screenshot_vmo, size_t row_index); + + uint64_t width_ = 0; + uint64_t height_ = 0; + std::vector> screenshot_; +}; + +} // namespace fuchsia_test_utils + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_INTEGRATION_UTILS_SCREENSHOT_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/platform_view_unittest.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/platform_view_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..fc010ed923d632af8a5b2c40089d03a3b117b07a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/platform_view_unittest.cc @@ -0,0 +1,1539 @@ +// 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "flutter/flow/embedded_views.h" +#include "flutter/lib/ui/window/platform_message.h" +#include "flutter/lib/ui/window/pointer_data.h" +#include "flutter/lib/ui/window/viewport_metrics.h" +#include "flutter/shell/common/context_options.h" +#include "flutter/shell/platform/fuchsia/flutter/platform_view.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +#include "fakes/focuser.h" +#include "fakes/platform_message.h" +#include "fakes/touch_source.h" +#include "fakes/view_ref_focused.h" +#include "flutter/shell/platform/fuchsia/flutter/surface.h" +#include "flutter/shell/platform/fuchsia/flutter/task_runner_adapter.h" +#include "platform/assert.h" +#include "pointer_event_utility.h" + +namespace flutter_runner::testing { +namespace { + +class MockExternalViewEmbedder : public flutter::ExternalViewEmbedder { + public: + flutter::DlCanvas* GetRootCanvas() override { return nullptr; } + + void CancelFrame() override {} + void BeginFrame(GrDirectContext* context, + const fml::RefPtr& + raster_thread_merger) override {} + + void PrepareFlutterView(SkISize frame_size, + double device_pixel_ratio) override {} + + void SubmitFlutterView( + int64_t flutter_view_id, + GrDirectContext* context, + const std::shared_ptr& aiks_context, + std::unique_ptr frame) override {} + + void PrerollCompositeEmbeddedView( + int64_t view_id, + std::unique_ptr params) override {} + + flutter::DlCanvas* CompositeEmbeddedView(int64_t view_id) override { + return nullptr; + } +}; + +class MockPlatformViewDelegate : public flutter::PlatformView::Delegate { + public: + void Reset() { + message_ = nullptr; + metrics_ = flutter::ViewportMetrics{}; + semantics_features_ = 0; + semantics_enabled_ = false; + pointer_packets_.clear(); + } + + // |flutter::PlatformView::Delegate| + void OnPlatformViewCreated(std::unique_ptr surface) { + ASSERT_EQ(surface_.get(), nullptr); + + surface_ = std::move(surface); + } + // |flutter::PlatformView::Delegate| + void OnPlatformViewDestroyed() {} + // |flutter::PlatformView::Delegate| + void OnPlatformViewScheduleFrame() {} + // |flutter::PlatformView::Delegate| + void OnPlatformViewAddView(int64_t view_id, + const flutter::ViewportMetrics& viewport_metrics, + AddViewCallback callback) override {} + // |flutter::PlatformView::Delegate| + void OnPlatformViewRemoveView(int64_t view_id, + RemoveViewCallback callback) override {} + // |flutter::PlatformView::Delegate| + void OnPlatformViewSetNextFrameCallback(const fml::closure& closure) {} + // |flutter::PlatformView::Delegate| + void OnPlatformViewSetViewportMetrics( + int64_t view_id, + const flutter::ViewportMetrics& metrics) { + metrics_ = metrics; + } + // |flutter::PlatformView::Delegate| + const flutter::Settings& OnPlatformViewGetSettings() const { + return settings_; + } + // |flutter::PlatformView::Delegate| + void OnPlatformViewDispatchPlatformMessage( + std::unique_ptr message) { + message_ = std::move(message); + } + // |flutter::PlatformView::Delegate| + void OnPlatformViewDispatchPointerDataPacket( + std::unique_ptr packet) { + pointer_packets_.push_back(std::move(packet)); + } + // |flutter::PlatformView::Delegate| + void OnPlatformViewDispatchKeyDataPacket( + std::unique_ptr packet, + std::function callback) {} + // |flutter::PlatformView::Delegate| + void OnPlatformViewDispatchSemanticsAction(int64_t view_id, + int32_t node_id, + flutter::SemanticsAction action, + fml::MallocMapping args) {} + // |flutter::PlatformView::Delegate| + void OnPlatformViewSetSemanticsEnabled(bool enabled) { + semantics_enabled_ = enabled; + } + // |flutter::PlatformView::Delegate| + void OnPlatformViewSetAccessibilityFeatures(int32_t flags) { + semantics_features_ = flags; + } + // |flutter::PlatformView::Delegate| + void OnPlatformViewRegisterTexture( + std::shared_ptr texture) {} + // |flutter::PlatformView::Delegate| + void OnPlatformViewUnregisterTexture(int64_t texture_id) {} + // |flutter::PlatformView::Delegate| + void OnPlatformViewMarkTextureFrameAvailable(int64_t texture_id) {} + // |flutter::PlatformView::Delegate| + std::unique_ptr> ComputePlatformViewResolvedLocale( + const std::vector& supported_locale_data) { + return nullptr; + } + // |flutter::PlatformView::Delegate| + void LoadDartDeferredLibrary( + intptr_t loading_unit_id, + std::unique_ptr snapshot_data, + std::unique_ptr snapshot_instructions) {} + // |flutter::PlatformView::Delegate| + void LoadDartDeferredLibraryError(intptr_t loading_unit_id, + const std::string error_message, + bool transient) {} + // |flutter::PlatformView::Delegate| + void UpdateAssetResolverByType( + std::unique_ptr updated_asset_resolver, + flutter::AssetResolver::AssetResolverType type) {} + // |flutter::PlatformView::Delegate| + void OnPlatformViewSendViewFocusEvent(const flutter::ViewFocusEvent& event) { + }; + + flutter::Surface* surface() const { return surface_.get(); } + flutter::PlatformMessage* message() const { return message_.get(); } + const flutter::ViewportMetrics& metrics() const { return metrics_; } + int32_t semantics_features() const { return semantics_features_; } + bool semantics_enabled() const { return semantics_enabled_; } + const std::vector>& + pointer_packets() const { + return pointer_packets_; + } + std::vector> + TakePointerDataPackets() { + auto tmp = std::move(pointer_packets_); + pointer_packets_.clear(); + return tmp; + } + + private: + std::unique_ptr surface_; + std::unique_ptr message_; + flutter::ViewportMetrics metrics_; + std::vector> pointer_packets_; + int32_t semantics_features_ = 0; + bool semantics_enabled_ = false; + flutter::Settings settings_; +}; + +class MockResponse : public flutter::PlatformMessageResponse { + public: + MOCK_METHOD(void, Complete, (std::unique_ptr data), (override)); + MOCK_METHOD(void, CompleteEmpty, (), (override)); +}; + +class TestPlatformMessageResponse : public flutter::PlatformMessageResponse { + public: + TestPlatformMessageResponse() {} + void Complete(std::unique_ptr data) override { + result_string = std::string( + reinterpret_cast(data->GetMapping()), data->GetSize()); + is_complete_ = true; + } + void CompleteEmpty() override { is_complete_ = true; } + std::string result_string; + FML_DISALLOW_COPY_AND_ASSIGN(TestPlatformMessageResponse); +}; + +class MockKeyboard : public fuchsia::ui::input3::testing::Keyboard_TestBase { + public: + explicit MockKeyboard( + fidl::InterfaceRequest keyboard) + : keyboard_(this, std::move(keyboard)) {} + ~MockKeyboard() = default; + + void AddListener(fuchsia::ui::views::ViewRef view_ref, + fuchsia::ui::input3::KeyboardListenerHandle listener, + AddListenerCallback callback) override { + FML_CHECK(!listener_.is_bound()); + + listener_ = listener.Bind(); + view_ref_ = std::move(view_ref); + + callback(); + } + + void NotImplemented_(const std::string& name) override { FAIL(); } + + fidl::Binding keyboard_; + fuchsia::ui::input3::KeyboardListenerPtr listener_{}; + fuchsia::ui::views::ViewRef view_ref_{}; + + FML_DISALLOW_COPY_AND_ASSIGN(MockKeyboard); +}; + +class MockChildViewWatcher + : public fuchsia::ui::composition::testing::ChildViewWatcher_TestBase { + public: + explicit MockChildViewWatcher( + fidl::InterfaceRequest + request) + : binding_(this, std::move(request)) {} + ~MockChildViewWatcher() = default; + + // |fuchsia::ui::composition::ChildViewWatcher| + void GetStatus(GetStatusCallback callback) override { + // GetStatus only returns once as per flatland.fidl comments + if (get_status_returned_) { + return; + } + callback(fuchsia::ui::composition::ChildViewStatus::CONTENT_HAS_PRESENTED); + get_status_returned_ = true; + } + + // |fuchsia::ui::composition::ChildViewWatcher| + void GetViewRef(GetViewRefCallback callback) override { + // GetViewRef only returns once as per flatland.fidl comments + ASSERT_FALSE(control_ref_.reference); + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ZX_ASSERT(status == ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + control_ref_ = std::move(view_ref_control); + callback(std::move(view_ref)); + } + + void NotImplemented_(const std::string& name) override { FAIL(); } + + fidl::Binding binding_; + fuchsia::ui::views::ViewRefControl control_ref_; + bool get_status_returned_ = false; + + FML_DISALLOW_COPY_AND_ASSIGN(MockChildViewWatcher); +}; + +class MockParentViewportWatcher + : public fuchsia::ui::composition::testing::ParentViewportWatcher_TestBase { + public: + explicit MockParentViewportWatcher() : binding_(this, handle_.NewRequest()) {} + ~MockParentViewportWatcher() = default; + + // |fuchsia::ui::composition::ParentViewportWatcher| + void GetStatus(GetStatusCallback callback) override { + // GetStatus only returns once as per flatland.fidl comments + if (get_status_returned_) { + return; + } + callback( + fuchsia::ui::composition::ParentViewportStatus::CONNECTED_TO_DISPLAY); + get_status_returned_ = true; + } + + // |fuchsia::ui::composition::ParentViewportWatcher| + void GetLayout(GetLayoutCallback callback) override { + if (layout_changed_) { + callback(std::move(layout_)); + } else { + FML_CHECK(!pending_callback_valid_); + pending_layout_callback_ = std::move(callback); + pending_callback_valid_ = true; + } + } + + void SetLayout(uint32_t logical_size_x, + uint32_t logical_size_y, + float DPR = 1.0) { + ::fuchsia::math::SizeU logical_size; + logical_size.width = logical_size_x; + logical_size.height = logical_size_y; + layout_.set_logical_size(logical_size); + layout_.set_device_pixel_ratio({DPR, DPR}); + + if (pending_callback_valid_) { + pending_layout_callback_(std::move(layout_)); + pending_callback_valid_ = false; + } else { + layout_changed_ = true; + } + } + + fuchsia::ui::composition::ParentViewportWatcherHandle GetHandle() { + FML_CHECK(handle_); // You can only get the handle once. + return std::move(handle_); + } + + void NotImplemented_(const std::string& name) override { FAIL(); } + + fuchsia::ui::composition::ParentViewportWatcherHandle handle_; + fidl::Binding binding_; + + fuchsia::ui::composition::LayoutInfo layout_; + bool layout_changed_ = false; + GetLayoutCallback pending_layout_callback_; + bool pending_callback_valid_ = false; + + bool get_status_returned_ = false; + + FML_DISALLOW_COPY_AND_ASSIGN(MockParentViewportWatcher); +}; + +// Used to construct partial instances of PlatformView for testing. The +// PlatformView constructor has many parameters, not all of which need to +// be filled out for each test. The builder allows you to initialize only +// those that matter to your specific test. Not all builder methods are +// provided: if you find some that are missing, feel free to add them. +class PlatformViewBuilder { + public: + PlatformViewBuilder(flutter::PlatformView::Delegate& delegate, + flutter::TaskRunners task_runners) + : delegate_(delegate), task_runners_(task_runners) { + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ZX_ASSERT(status == ZX_OK); + view_ref_control.reference.replace( + ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE), + &view_ref_control.reference); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + auto view_ref_pair = + std::make_pair(std::move(view_ref_control), std::move(view_ref)); + view_ref_pair_ = std::move(view_ref_pair); + } + + PlatformViewBuilder& SetExternalViewEmbedder( + std::shared_ptr embedder) { + external_external_view_embedder_ = embedder; + return *this; + } + + PlatformViewBuilder& SetImeService( + fuchsia::ui::input::ImeServiceHandle ime_service) { + ime_service_ = std::move(ime_service); + return *this; + } + + PlatformViewBuilder& SetKeyboard( + fuchsia::ui::input3::KeyboardHandle keyboard) { + keyboard_ = std::move(keyboard); + return *this; + } + + PlatformViewBuilder& SetTouchSource( + fuchsia::ui::pointer::TouchSourceHandle touch_source) { + touch_source_ = std::move(touch_source); + return *this; + } + + PlatformViewBuilder& SetMouseSource( + fuchsia::ui::pointer::MouseSourceHandle mouse_source) { + mouse_source_ = std::move(mouse_source); + return *this; + } + + PlatformViewBuilder& SetFocuser(fuchsia::ui::views::FocuserHandle focuser) { + focuser_ = std::move(focuser); + return *this; + } + + PlatformViewBuilder& SetViewRefFocused( + fuchsia::ui::views::ViewRefFocusedHandle view_ref_focused) { + view_ref_focused_ = std::move(view_ref_focused); + return *this; + } + + PlatformViewBuilder& SetPointerInjectorRegistry( + fuchsia::ui::pointerinjector::RegistryHandle pointerinjector_registry) { + pointerinjector_registry_ = std::move(pointerinjector_registry); + return *this; + } + + PlatformViewBuilder& SetEnableWireframeCallback( + OnEnableWireframeCallback callback) { + wireframe_enabled_callback_ = std::move(callback); + return *this; + } + + PlatformViewBuilder& SetParentViewportWatcher( + fuchsia::ui::composition::ParentViewportWatcherHandle + parent_viewport_watcher) { + parent_viewport_watcher_ = std::move(parent_viewport_watcher); + return *this; + } + + PlatformViewBuilder& SetCreateViewCallback(OnCreateViewCallback callback) { + on_create_view_callback_ = std::move(callback); + return *this; + } + + PlatformViewBuilder& SetDestroyViewCallback(OnDestroyViewCallback callback) { + on_destroy_view_callback_ = std::move(callback); + return *this; + } + + PlatformViewBuilder& SetUpdateViewCallback(OnUpdateViewCallback callback) { + on_update_view_callback_ = std::move(callback); + return *this; + } + + PlatformViewBuilder& SetCreateSurfaceCallback( + OnCreateSurfaceCallback callback) { + on_create_surface_callback_ = std::move(callback); + return *this; + } + + PlatformViewBuilder& SetShaderWarmupCallback( + OnShaderWarmupCallback callback) { + on_shader_warmup_callback_ = std::move(callback); + return *this; + } + + // Once Build is called, the instance is no longer usable. + PlatformView Build() { + EXPECT_FALSE(std::exchange(built_, true)) + << "Build() was already called, this builder is good for one use only."; + return PlatformView( + delegate_, task_runners_, std::move(view_ref_pair_.second), + external_external_view_embedder_, std::move(ime_service_), + std::move(keyboard_), std::move(touch_source_), + std::move(mouse_source_), std::move(focuser_), + std::move(view_ref_focused_), std::move(parent_viewport_watcher_), + std::move(pointerinjector_registry_), + std::move(wireframe_enabled_callback_), + std::move(on_create_view_callback_), + std::move(on_update_view_callback_), + std::move(on_destroy_view_callback_), + std::move(on_create_surface_callback_), + std::move(on_semantics_node_update_callback_), + std::move(on_request_announce_callback_), + std::move(on_shader_warmup_callback_), [](auto...) {}, [](auto...) {}, + nullptr); + } + + private: + PlatformViewBuilder() = delete; + + flutter::PlatformView::Delegate& delegate_; + flutter::TaskRunners task_runners_; + std::pair + view_ref_pair_; + + std::shared_ptr + external_external_view_embedder_; + fuchsia::ui::input::ImeServiceHandle ime_service_; + fuchsia::ui::input3::KeyboardHandle keyboard_; + fuchsia::ui::pointer::TouchSourceHandle touch_source_; + fuchsia::ui::pointer::MouseSourceHandle mouse_source_; + fuchsia::ui::views::ViewRefFocusedHandle view_ref_focused_; + fuchsia::ui::views::FocuserHandle focuser_; + fuchsia::ui::pointerinjector::RegistryHandle pointerinjector_registry_; + fit::closure on_session_listener_error_callback_; + OnEnableWireframeCallback wireframe_enabled_callback_; + fuchsia::ui::composition::ParentViewportWatcherHandle + parent_viewport_watcher_; + OnCreateViewCallback on_create_view_callback_; + OnDestroyViewCallback on_destroy_view_callback_; + OnUpdateViewCallback on_update_view_callback_; + OnCreateSurfaceCallback on_create_surface_callback_; + OnSemanticsNodeUpdateCallback on_semantics_node_update_callback_; + OnRequestAnnounceCallback on_request_announce_callback_; + OnShaderWarmupCallback on_shader_warmup_callback_; + + bool built_{false}; +}; + +std::string ToString(const fml::Mapping& mapping) { + return std::string(mapping.GetMapping(), + mapping.GetMapping() + mapping.GetSize()); +} + +// Stolen from pointer_data_packet_converter_unittests.cc. +void UnpackPointerPacket(std::vector& output, // NOLINT + std::unique_ptr packet) { + for (size_t i = 0; i < packet->GetLength(); i++) { + flutter::PointerData pointer_data = packet->GetPointerData(i); + output.push_back(pointer_data); + } + packet.reset(); +} + +} // namespace + +class PlatformViewTests : public ::testing::Test { + protected: + PlatformViewTests() : loop_(&kAsyncLoopConfigAttachToCurrentThread) {} + + async_dispatcher_t* dispatcher() { return loop_.dispatcher(); } + + void RunLoopUntilIdle() { + loop_.RunUntilIdle(); + loop_.ResetQuit(); + } + + void RunLoopOnce() { + loop_.Run(zx::time::infinite(), true); + loop_.ResetQuit(); + } + + fuchsia::ui::input3::KeyEvent MakeEvent( + fuchsia::ui::input3::KeyEventType event_type, + std::optional modifiers, + fuchsia::input::Key key) { + fuchsia::ui::input3::KeyEvent event; + event.set_timestamp(++event_timestamp_); + event.set_type(event_type); + if (modifiers.has_value()) { + event.set_modifiers(modifiers.value()); + } + event.set_key(key); + return event; + } + + fuchsia::ui::composition::ChildViewWatcherPtr MakeChildViewWatcher() { + fuchsia::ui::composition::ChildViewWatcherPtr ptr; + auto watcher = std::make_unique( + ptr.NewRequest(loop_.dispatcher())); + child_view_watchers_.push_back(std::move(watcher)); + return ptr; + } + + private: + async::Loop loop_; + + uint64_t event_timestamp_{42}; + + std::vector> child_view_watchers_; + + FML_DISALLOW_COPY_AND_ASSIGN(PlatformViewTests); +}; + +// This test makes sure that the PlatformView always completes a platform +// message request, even for error conditions or if the request is malformed. +TEST_F(PlatformViewTests, InvalidPlatformMessageRequest) { + MockPlatformViewDelegate delegate; + flutter::TaskRunners task_runners = + flutter::TaskRunners("test_runners", nullptr, nullptr, nullptr, nullptr); + + FakeViewRefFocused vrf; + fidl::BindingSet vrf_bindings; + auto vrf_handle = vrf_bindings.AddBinding(&vrf); + + auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners)) + .SetViewRefFocused(std::move(vrf_handle)) + .Build(); + + // Cast platform_view to its base view so we can have access to the public + // "HandlePlatformMessage" function. + auto base_view = static_cast(&platform_view); + EXPECT_TRUE(base_view); + + // Invalid platform channel. + auto response1 = FakePlatformMessageResponse::Create(); + base_view->HandlePlatformMessage(response1->WithMessage( + "flutter/invalid", "{\"method\":\"Invalid.invalidMethod\"}")); + + // Invalid json. + auto response2 = FakePlatformMessageResponse::Create(); + base_view->HandlePlatformMessage( + response2->WithMessage("flutter/platform_views", "{Invalid JSON")); + + // Invalid method. + auto response3 = FakePlatformMessageResponse::Create(); + base_view->HandlePlatformMessage(response3->WithMessage( + "flutter/platform_views", "{\"method\":\"View.focus.invalidMethod\"}")); + + // Missing arguments. + auto response4 = FakePlatformMessageResponse::Create(); + base_view->HandlePlatformMessage(response4->WithMessage( + "flutter/platform_views", "{\"method\":\"View.update\"}")); + auto response5 = FakePlatformMessageResponse::Create(); + base_view->HandlePlatformMessage( + response5->WithMessage("flutter/platform_views", + "{\"method\":\"View.update\",\"args\":{" + "\"irrelevantField\":\"irrelevantValue\"}}")); + + // Wrong argument types. + auto response6 = FakePlatformMessageResponse::Create(); + base_view->HandlePlatformMessage(response6->WithMessage( + "flutter/platform_views", + "{\"method\":\"View.update\",\"args\":{\"viewId\":false,\"hitTestable\":" + "123,\"focusable\":\"yes\"}}")); + + // Run the event loop and check our responses. + RunLoopUntilIdle(); + response1->ExpectCompleted(""); + response2->ExpectCompleted(""); + response3->ExpectCompleted(""); + response4->ExpectCompleted(""); + response5->ExpectCompleted(""); + response6->ExpectCompleted(""); +} + +// This test makes sure that the PlatformView correctly returns a Surface +// instance that can surface the provided gr_context and external_view_embedder. +TEST_F(PlatformViewTests, CreateSurfaceTest) { + MockPlatformViewDelegate delegate; + + flutter::TaskRunners task_runners = + flutter::TaskRunners("test_runners", // label + nullptr, // platform + flutter_runner::CreateFMLTaskRunner( + async_get_default_dispatcher()), // raster + nullptr, // ui + nullptr // io + ); + + // Test create surface callback function. + sk_sp gr_context = GrDirectContext::MakeMock( + nullptr, + flutter::MakeDefaultContextOptions(flutter::ContextType::kRender)); + std::shared_ptr external_view_embedder = + std::make_shared(); + auto CreateSurfaceCallback = [&external_view_embedder, gr_context]() { + return std::make_unique( + "PlatformViewTest", external_view_embedder, gr_context.get()); + }; + + auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners)) + .SetCreateSurfaceCallback(CreateSurfaceCallback) + .SetExternalViewEmbedder(external_view_embedder) + .Build(); + platform_view.NotifyCreated(); + + RunLoopUntilIdle(); + + EXPECT_EQ(gr_context.get(), delegate.surface()->GetContext()); + EXPECT_EQ(external_view_embedder.get(), + platform_view.CreateExternalViewEmbedder().get()); +} + +// This test makes sure that the PlatformView correctly registers Scenic +// MetricsEvents sent to it via FIDL, correctly parses the metrics it receives, +// and calls the SetViewportMetrics callback with the appropriate parameters. +TEST_F(PlatformViewTests, SetViewportMetrics) { + constexpr float kDPR = 2; + constexpr uint32_t width = 640; + constexpr uint32_t height = 480; + + MockPlatformViewDelegate delegate; + EXPECT_EQ(delegate.metrics(), flutter::ViewportMetrics()); + + MockParentViewportWatcher watcher; + flutter::TaskRunners task_runners("test_runners", nullptr, nullptr, nullptr, + nullptr); + auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners)) + .SetParentViewportWatcher(watcher.GetHandle()) + .Build(); + RunLoopUntilIdle(); + EXPECT_EQ(delegate.metrics(), flutter::ViewportMetrics()); + + watcher.SetLayout(width, height, kDPR); + RunLoopUntilIdle(); + EXPECT_EQ(delegate.metrics(), + flutter::ViewportMetrics(kDPR, std::round(width * kDPR), + std::round(height * kDPR), -1.0, 0)); +} + +// This test makes sure that the PlatformView correctly registers semantics +// settings changes applied to it and calls the SetSemanticsEnabled / +// SetAccessibilityFeatures callbacks with the appropriate parameters. +TEST_F(PlatformViewTests, ChangesAccessibilitySettings) { + MockPlatformViewDelegate delegate; + flutter::TaskRunners task_runners = + flutter::TaskRunners("test_runners", nullptr, nullptr, nullptr, nullptr); + + EXPECT_FALSE(delegate.semantics_enabled()); + EXPECT_EQ(delegate.semantics_features(), 0); + + auto platform_view = + PlatformViewBuilder(delegate, std::move(task_runners)).Build(); + + RunLoopUntilIdle(); + + platform_view.SetSemanticsEnabled(true); + + EXPECT_TRUE(delegate.semantics_enabled()); + EXPECT_EQ(delegate.semantics_features(), + static_cast( + flutter::AccessibilityFeatureFlag::kAccessibleNavigation)); + + platform_view.SetSemanticsEnabled(false); + + EXPECT_FALSE(delegate.semantics_enabled()); + EXPECT_EQ(delegate.semantics_features(), 0); +} + +// This test makes sure that the PlatformView forwards messages on the +// "flutter/platform_views" channel for EnableWireframe. +TEST_F(PlatformViewTests, EnableWireframeTest) { + MockPlatformViewDelegate delegate; + flutter::TaskRunners task_runners = + flutter::TaskRunners("test_runners", nullptr, nullptr, nullptr, nullptr); + + // Test wireframe callback function. If the message sent to the platform + // view was properly handled and parsed, this function should be called, + // setting |wireframe_enabled| to true. + bool wireframe_enabled = false; + auto EnableWireframeCallback = [&wireframe_enabled](bool should_enable) { + wireframe_enabled = should_enable; + }; + + auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners)) + .SetEnableWireframeCallback(EnableWireframeCallback) + .Build(); + + // Cast platform_view to its base view so we can have access to the public + // "HandlePlatformMessage" function. + auto base_view = static_cast(&platform_view); + EXPECT_TRUE(base_view); + + // JSON for the message to be passed into the PlatformView. + const uint8_t txt[] = + "{" + " \"method\":\"View.enableWireframe\"," + " \"args\": {" + " \"enable\":true" + " }" + "}"; + + std::unique_ptr message = + std::make_unique( + "flutter/platform_views", fml::MallocMapping::Copy(txt, sizeof(txt)), + fml::RefPtr()); + base_view->HandlePlatformMessage(std::move(message)); + + RunLoopUntilIdle(); + + EXPECT_TRUE(wireframe_enabled); +} + +// This test makes sure that the PlatformView forwards messages on the +// "flutter/platform_views" channel for Createview. +TEST_F(PlatformViewTests, CreateViewTest) { + MockPlatformViewDelegate delegate; + const uint64_t view_id = 42; + flutter::TaskRunners task_runners = + flutter::TaskRunners("test_runners", // label + flutter_runner::CreateFMLTaskRunner( + async_get_default_dispatcher()), // platform + nullptr, // raster + nullptr, // ui + nullptr // io + ); + + // Test wireframe callback function. If the message sent to the platform + // view was properly handled and parsed, this function should be called, + // setting |wireframe_enabled| to true. + bool create_view_called = false; + auto CreateViewCallback = + [&create_view_called, this]( + int64_t view_id, flutter_runner::ViewCallback on_view_created, + flutter_runner::ViewCreatedCallback on_view_bound, bool hit_testable, + bool focusable) { + create_view_called = true; + on_view_created(); + fuchsia::ui::composition::ContentId content_id; + on_view_bound(std::move(content_id), MakeChildViewWatcher()); + }; + + auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners)) + .SetCreateViewCallback(CreateViewCallback) + .Build(); + + // Cast platform_view to its base view so we can have access to the public + // "HandlePlatformMessage" function. + auto base_view = static_cast(&platform_view); + EXPECT_TRUE(base_view); + + // JSON for the message to be passed into the PlatformView. + std::ostringstream create_view_message; + create_view_message << "{" << " \"method\":\"View.create\"," + << " \"args\":{" << " \"viewId\":" << view_id << "," + << " \"hitTestable\":true," << " \"focusable\":true" + << " }" << "}"; + + std::string create_view_call = create_view_message.str(); + std::unique_ptr message = + std::make_unique( + "flutter/platform_views", + fml::MallocMapping::Copy(create_view_call.c_str(), + create_view_call.size()), + fml::RefPtr()); + base_view->HandlePlatformMessage(std::move(message)); + + RunLoopUntilIdle(); + + EXPECT_TRUE(create_view_called); + + // Platform view forwards the 'View.viewConnected' message on the + // 'flutter/platform_views' channel when a view gets created. + std::ostringstream view_connected_expected_out; + view_connected_expected_out << "{" << "\"method\":\"View.viewConnected\"," + << "\"args\":{" << " \"viewId\":" << view_id + << " }" << "}"; + + ASSERT_NE(delegate.message(), nullptr); + EXPECT_EQ(view_connected_expected_out.str(), + ToString(delegate.message()->data())); +} + +// This test makes sure that the PlatformView forwards messages on the +// "flutter/platform_views" channel for UpdateView. +TEST_F(PlatformViewTests, UpdateViewTest) { + MockPlatformViewDelegate delegate; + flutter::TaskRunners task_runners = + flutter::TaskRunners("test_runners", nullptr, nullptr, nullptr, nullptr); + + std::optional occlusion_hint_for_test; + std::optional hit_testable_for_test; + std::optional focusable_for_test; + auto UpdateViewCallback = [&occlusion_hint_for_test, &hit_testable_for_test, + &focusable_for_test]( + int64_t view_id, SkRect occlusion_hint, + bool hit_testable, bool focusable) { + occlusion_hint_for_test = occlusion_hint; + hit_testable_for_test = hit_testable; + focusable_for_test = focusable; + }; + + auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners)) + .SetUpdateViewCallback(UpdateViewCallback) + .Build(); + + // Cast platform_view to its base view so we can have access to the public + // "HandlePlatformMessage" function. + auto base_view = static_cast(&platform_view); + EXPECT_TRUE(base_view); + + // Send a basic message. + const uint8_t json[] = + "{" + " \"method\":\"View.update\"," + " \"args\": {" + " \"viewId\":42," + " \"hitTestable\":true," + " \"focusable\":true" + " }" + "}"; + std::unique_ptr message = + std::make_unique( + "flutter/platform_views", + fml::MallocMapping::Copy(json, sizeof(json)), + fml::RefPtr()); + base_view->HandlePlatformMessage(std::move(message)); + + RunLoopUntilIdle(); + ASSERT_TRUE(occlusion_hint_for_test.has_value()); + ASSERT_TRUE(hit_testable_for_test.has_value()); + ASSERT_TRUE(focusable_for_test.has_value()); + EXPECT_EQ(occlusion_hint_for_test.value(), SkRect::MakeEmpty()); + EXPECT_EQ(hit_testable_for_test.value(), true); + EXPECT_EQ(focusable_for_test.value(), true); + + // Reset for the next message. + occlusion_hint_for_test.reset(); + hit_testable_for_test.reset(); + focusable_for_test.reset(); + + // Send another basic message. + const uint8_t json_false[] = + "{" + " \"method\":\"View.update\"," + " \"args\": {" + " \"viewId\":42," + " \"hitTestable\":false," + " \"focusable\":false" + " }" + "}"; + std::unique_ptr message_false = + std::make_unique( + "flutter/platform_views", + fml::MallocMapping::Copy(json_false, sizeof(json_false)), + fml::RefPtr()); + base_view->HandlePlatformMessage(std::move(message_false)); + RunLoopUntilIdle(); + ASSERT_TRUE(occlusion_hint_for_test.has_value()); + ASSERT_TRUE(hit_testable_for_test.has_value()); + ASSERT_TRUE(focusable_for_test.has_value()); + EXPECT_EQ(occlusion_hint_for_test.value(), SkRect::MakeEmpty()); + EXPECT_EQ(hit_testable_for_test.value(), false); + EXPECT_EQ(focusable_for_test.value(), false); + + // Reset for the next message. + occlusion_hint_for_test.reset(); + hit_testable_for_test.reset(); + focusable_for_test.reset(); + + // Send a message including an occlusion hint. + const uint8_t json_occlusion_hint[] = + "{" + " \"method\":\"View.update\"," + " \"args\": {" + " \"viewId\":42," + " \"hitTestable\":true," + " \"focusable\":true," + " \"viewOcclusionHintLTRB\":[0.1,0.2,0.3,0.4]" + " }" + "}"; + std::unique_ptr message_occlusion_hint = + std::make_unique( + "flutter/platform_views", + fml::MallocMapping::Copy(json_occlusion_hint, + sizeof(json_occlusion_hint)), + fml::RefPtr()); + base_view->HandlePlatformMessage(std::move(message_occlusion_hint)); + RunLoopUntilIdle(); + ASSERT_TRUE(occlusion_hint_for_test.has_value()); + ASSERT_TRUE(hit_testable_for_test.has_value()); + ASSERT_TRUE(focusable_for_test.has_value()); + EXPECT_EQ(occlusion_hint_for_test.value(), + SkRect::MakeLTRB(0.1, 0.2, 0.3, 0.4)); + EXPECT_EQ(hit_testable_for_test.value(), true); + EXPECT_EQ(focusable_for_test.value(), true); +} + +// This test makes sure that the PlatformView forwards messages on the +// "flutter/platform_views" channel for DestroyView. +TEST_F(PlatformViewTests, DestroyViewTest) { + MockPlatformViewDelegate delegate; + const uint64_t view_id = 42; + + flutter::TaskRunners task_runners = + flutter::TaskRunners("test_runners", // label + flutter_runner::CreateFMLTaskRunner( + async_get_default_dispatcher()), // platform + nullptr, // raster + nullptr, // ui + nullptr // io + ); + + bool destroy_view_called = false; + + auto on_destroy_view = [&destroy_view_called]( + int64_t view_id, + flutter_runner::ViewIdCallback on_view_unbound) { + destroy_view_called = true; + fuchsia::ui::composition::ContentId content_id; + on_view_unbound(std::move(content_id)); + }; + + bool create_view_called = false; + auto on_create_view = [&create_view_called, this]( + int64_t view_id, + flutter_runner::ViewCallback on_view_created, + flutter_runner::ViewCreatedCallback on_view_bound, + bool hit_testable, bool focusable) { + create_view_called = true; + on_view_created(); + fuchsia::ui::composition::ContentId content_id; + on_view_bound(std::move(content_id), MakeChildViewWatcher()); + }; + + auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners)) + .SetCreateViewCallback(on_create_view) + .SetDestroyViewCallback(on_destroy_view) + .Build(); + + // Cast platform_view to its base view so we can have access to the public + // "HandlePlatformMessage" function. + auto base_view = static_cast(&platform_view); + EXPECT_TRUE(base_view); + + std::ostringstream create_message; + create_message << "{" << " \"method\":\"View.create\"," + << " \"args\": {" << " \"viewId\":" << view_id << "," + << " \"hitTestable\":true," + << " \"focusable\":true" << " }" << "}"; + + auto create_response = FakePlatformMessageResponse::Create(); + base_view->HandlePlatformMessage(create_response->WithMessage( + "flutter/platform_views", create_message.str())); + RunLoopUntilIdle(); + + delegate.Reset(); + + // JSON for the message to be passed into the PlatformView. + std::ostringstream dispose_message; + dispose_message << "{" << " \"method\":\"View.dispose\"," + << " \"args\": {" << " \"viewId\":" << view_id + << " }" << "}"; + + std::string dispose_view_call = dispose_message.str(); + std::unique_ptr message = + std::make_unique( + "flutter/platform_views", + fml::MallocMapping::Copy(dispose_view_call.c_str(), + dispose_view_call.size()), + fml::RefPtr()); + base_view->HandlePlatformMessage(std::move(message)); + + RunLoopUntilIdle(); + + EXPECT_TRUE(destroy_view_called); + + // Platform view forwards the 'View.viewDisconnected' message on the + // 'flutter/platform_views' channel when a view gets destroyed. + std::ostringstream view_disconnected_expected_out; + view_disconnected_expected_out + << "{" << "\"method\":\"View.viewDisconnected\"," << "\"args\":{" + << " \"viewId\":" << view_id << " }" << "}"; + + ASSERT_NE(delegate.message(), nullptr); + EXPECT_EQ(view_disconnected_expected_out.str(), + ToString(delegate.message()->data())); +} + +// This test makes sure that the PlatformView forwards messages on the +// "flutter/platform_views" channel for View.focus.getCurrent and +// View.focus.getNext. +TEST_F(PlatformViewTests, GetFocusStatesTest) { + MockPlatformViewDelegate delegate; + flutter::TaskRunners task_runners = + flutter::TaskRunners("test_runners", nullptr, nullptr, nullptr, nullptr); + + FakeViewRefFocused vrf; + fidl::BindingSet vrf_bindings; + auto vrf_handle = vrf_bindings.AddBinding(&vrf); + + auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners)) + .SetViewRefFocused(std::move(vrf_handle)) + .Build(); + + // Cast platform_view to its base view so we can have access to the public + // "HandlePlatformMessage" function. + auto base_view = static_cast(&platform_view); + EXPECT_TRUE(base_view); + + std::vector vrf_states{false, true, true, false, + true, false, true, true}; + + for (std::size_t i = 0; i < vrf_states.size(); ++i) { + // View.focus.getNext should complete with the next focus state. + auto response1 = FakePlatformMessageResponse::Create(); + base_view->HandlePlatformMessage(response1->WithMessage( + "flutter/platform_views", "{\"method\":\"View.focus.getNext\"}")); + // Duplicate View.focus.getNext requests should complete empty. + auto response2 = FakePlatformMessageResponse::Create(); + base_view->HandlePlatformMessage(response2->WithMessage( + "flutter/platform_views", "{\"method\":\"View.focus.getNext\"}")); + + // Post watch events and make sure the hanging get is invoked each time. + RunLoopUntilIdle(); + EXPECT_EQ(vrf.times_watched, i + 1); + + // Dispatch the next vrf event. + vrf.ScheduleCallback(vrf_states[i]); + RunLoopUntilIdle(); + + // Make sure View.focus.getCurrent completes with the current focus state. + auto response3 = FakePlatformMessageResponse::Create(); + base_view->HandlePlatformMessage(response3->WithMessage( + "flutter/platform_views", "{\"method\":\"View.focus.getCurrent\"}")); + // Duplicate View.focus.getCurrent are allowed. + auto response4 = FakePlatformMessageResponse::Create(); + base_view->HandlePlatformMessage(response4->WithMessage( + "flutter/platform_views", "{\"method\":\"View.focus.getCurrent\"}")); + + // Run event loop and check our results. + RunLoopUntilIdle(); + response1->ExpectCompleted(vrf_states[i] ? "[true]" : "[false]"); + response2->ExpectCompleted("[null]"); + response3->ExpectCompleted(vrf_states[i] ? "[true]" : "[false]"); + response4->ExpectCompleted(vrf_states[i] ? "[true]" : "[false]"); + } +} + +// This test makes sure that the PlatformView forwards messages on the +// "flutter/platform_views" channel for View.focus.request. +TEST_F(PlatformViewTests, RequestFocusTest) { + MockPlatformViewDelegate delegate; + flutter::TaskRunners task_runners = + flutter::TaskRunners("test_runners", // label + flutter_runner::CreateFMLTaskRunner( + async_get_default_dispatcher()), // platform + nullptr, // raster + nullptr, // ui + nullptr // io + ); + + FakeFocuser focuser; + fidl::BindingSet focuser_bindings; + auto focuser_handle = focuser_bindings.AddBinding(&focuser); + + bool create_view_called = false; + auto on_create_view = [&create_view_called, this]( + int64_t view_id, + flutter_runner::ViewCallback on_view_created, + flutter_runner::ViewCreatedCallback on_view_bound, + bool hit_testable, bool focusable) { + create_view_called = true; + on_view_created(); + fuchsia::ui::composition::ContentId content_id; + on_view_bound(std::move(content_id), MakeChildViewWatcher()); + }; + + auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners)) + .SetFocuser(std::move(focuser_handle)) + .SetCreateViewCallback(on_create_view) + .Build(); + + // Cast platform_view to its base view so we can have access to the public + // "HandlePlatformMessage" function. + auto base_view = static_cast(&platform_view); + EXPECT_TRUE(base_view); + + uint64_t view_id = 42; + + std::ostringstream create_message; + create_message << "{" << " \"method\":\"View.create\"," + << " \"args\": {" << " \"viewId\":" << view_id << "," + << " \"hitTestable\":true," + << " \"focusable\":true" << " }" << "}"; + + // Dispatch the plaform message request. + auto create_response = FakePlatformMessageResponse::Create(); + base_view->HandlePlatformMessage(create_response->WithMessage( + "flutter/platform_views", create_message.str())); + + RunLoopUntilIdle(); + + // JSON for the message to be passed into the PlatformView. + std::ostringstream focus_message; + focus_message << "{" << " \"method\":\"View.focus.requestById\"," + << " \"args\": {" << " \"viewId\":" << view_id + << " }" << "}"; + + // Dispatch the plaform message request. + auto focus_response = FakePlatformMessageResponse::Create(); + base_view->HandlePlatformMessage(focus_response->WithMessage( + "flutter/platform_views", focus_message.str())); + RunLoopUntilIdle(); + + focus_response->ExpectCompleted("[0]"); + EXPECT_TRUE(focuser.request_focus_called()); +} + +// This test tries to set focus on a view without creating it first +TEST_F(PlatformViewTests, RequestFocusNeverCreatedTest) { + MockPlatformViewDelegate delegate; + flutter::TaskRunners task_runners = + flutter::TaskRunners("test_runners", // label + flutter_runner::CreateFMLTaskRunner( + async_get_default_dispatcher()), // platform + nullptr, // raster + nullptr, // ui + nullptr // io + ); + + FakeFocuser focuser; + fidl::BindingSet focuser_bindings; + auto focuser_handle = focuser_bindings.AddBinding(&focuser); + + bool create_view_called = false; + auto on_create_view = [&create_view_called, this]( + int64_t view_id, + flutter_runner::ViewCallback on_view_created, + flutter_runner::ViewCreatedCallback on_view_bound, + bool hit_testable, bool focusable) { + create_view_called = true; + on_view_created(); + fuchsia::ui::composition::ContentId content_id; + on_view_bound(std::move(content_id), MakeChildViewWatcher()); + }; + + auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners)) + .SetFocuser(std::move(focuser_handle)) + .SetCreateViewCallback(on_create_view) + .Build(); + + auto base_view = static_cast(&platform_view); + EXPECT_TRUE(base_view); + + uint64_t view_id = 42; + + std::ostringstream focus_message; + focus_message << "{" << " \"method\":\"View.focus.requestById\"," + << " \"args\": {" << " \"viewId\":" << view_id + << " }" << "}"; + + // Dispatch the plaform message request. + auto focus_response = FakePlatformMessageResponse::Create(); + base_view->HandlePlatformMessage(focus_response->WithMessage( + "flutter/platform_views", focus_message.str())); + RunLoopUntilIdle(); + + focus_response->ExpectCompleted("[1]"); + EXPECT_FALSE(focuser.request_focus_called()); +} + +TEST_F(PlatformViewTests, RequestFocusDisposedTest) { + MockPlatformViewDelegate delegate; + flutter::TaskRunners task_runners = + flutter::TaskRunners("test_runners", // label + flutter_runner::CreateFMLTaskRunner( + async_get_default_dispatcher()), // platform + nullptr, // raster + nullptr, // ui + nullptr // io + ); + + FakeFocuser focuser; + fidl::BindingSet focuser_bindings; + auto focuser_handle = focuser_bindings.AddBinding(&focuser); + + bool create_view_called = false; + auto on_create_view = [&create_view_called, this]( + int64_t view_id, + flutter_runner::ViewCallback on_view_created, + flutter_runner::ViewCreatedCallback on_view_bound, + bool hit_testable, bool focusable) { + create_view_called = true; + on_view_created(); + fuchsia::ui::composition::ContentId content_id; + on_view_bound(std::move(content_id), MakeChildViewWatcher()); + }; + + bool destroy_view_called = false; + + auto on_destroy_view = [&destroy_view_called]( + int64_t view_id, + flutter_runner::ViewIdCallback on_view_unbound) { + destroy_view_called = true; + fuchsia::ui::composition::ContentId content_id; + on_view_unbound(std::move(content_id)); + }; + + auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners)) + .SetFocuser(std::move(focuser_handle)) + .SetCreateViewCallback(on_create_view) + .SetDestroyViewCallback(on_destroy_view) + .Build(); + + auto base_view = static_cast(&platform_view); + EXPECT_TRUE(base_view); + + uint64_t view_id = 42; + + // Create a new view + std::ostringstream create_message; + create_message << "{" << " \"method\":\"View.create\"," + << " \"args\": {" << " \"viewId\":" << view_id << "," + << " \"hitTestable\":true," + << " \"focusable\":true" << " }" << "}"; + + auto create_response = FakePlatformMessageResponse::Create(); + base_view->HandlePlatformMessage(create_response->WithMessage( + "flutter/platform_views", create_message.str())); + RunLoopUntilIdle(); + + EXPECT_FALSE(destroy_view_called); + // Dispose of the view + std::ostringstream dispose_message; + dispose_message << "{" << " \"method\":\"View.dispose\"," + << " \"args\": {" << " \"viewId\":" << view_id + << " }" << "}"; + + auto dispose_response = FakePlatformMessageResponse::Create(); + base_view->HandlePlatformMessage(dispose_response->WithMessage( + "flutter/platform_views", dispose_message.str())); + RunLoopUntilIdle(); + EXPECT_TRUE(destroy_view_called); + + // Request focus on newly disposed view + std::ostringstream focus_message; + focus_message << "{" << " \"method\":\"View.focus.requestById\"," + << " \"args\": {" << " \"viewId\":" << view_id + << " }" << "}"; + + auto focus_response = FakePlatformMessageResponse::Create(); + base_view->HandlePlatformMessage(focus_response->WithMessage( + "flutter/platform_views", focus_message.str())); + RunLoopUntilIdle(); + + // Expect it to fail + focus_response->ExpectCompleted("[1]"); + EXPECT_FALSE(focuser.request_focus_called()); +} + +// Makes sure that OnKeyEvent is dispatched as a platform message. +TEST_F(PlatformViewTests, OnKeyEvent) { + struct EventFlow { + fuchsia::ui::input3::KeyEvent event; + fuchsia::ui::input3::KeyEventStatus expected_key_event_status; + std::string expected_platform_message; + }; + + MockPlatformViewDelegate delegate; + flutter::TaskRunners task_runners = + flutter::TaskRunners("test_runners", nullptr, nullptr, nullptr, nullptr); + + fuchsia::ui::input3::KeyboardHandle keyboard_service; + MockKeyboard keyboard(keyboard_service.NewRequest()); + + auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners)) + .SetKeyboard(std::move(keyboard_service)) + .Build(); + RunLoopUntilIdle(); + + std::vector events; + // Press A. Get 'a'. + // The HID usage for the key A is 0x70004, or 458756. + events.emplace_back(EventFlow{ + MakeEvent(fuchsia::ui::input3::KeyEventType::PRESSED, std::nullopt, + fuchsia::input::Key::A), + fuchsia::ui::input3::KeyEventStatus::HANDLED, + R"({"type":"keydown","keymap":"fuchsia","hidUsage":458756,"codePoint":97,"modifiers":0})", + }); + // Release A. Get 'a' release. + events.emplace_back(EventFlow{ + MakeEvent(fuchsia::ui::input3::KeyEventType::RELEASED, std::nullopt, + fuchsia::input::Key::A), + fuchsia::ui::input3::KeyEventStatus::HANDLED, + R"({"type":"keyup","keymap":"fuchsia","hidUsage":458756,"codePoint":97,"modifiers":0})", + }); + // Press CAPS_LOCK. Modifier now active. + events.emplace_back(EventFlow{ + MakeEvent(fuchsia::ui::input3::KeyEventType::PRESSED, + fuchsia::ui::input3::Modifiers::CAPS_LOCK, + fuchsia::input::Key::CAPS_LOCK), + fuchsia::ui::input3::KeyEventStatus::HANDLED, + R"({"type":"keydown","keymap":"fuchsia","hidUsage":458809,"codePoint":0,"modifiers":1})", + }); + // Press A. Get 'A'. + events.emplace_back(EventFlow{ + MakeEvent(fuchsia::ui::input3::KeyEventType::PRESSED, std::nullopt, + fuchsia::input::Key::A), + fuchsia::ui::input3::KeyEventStatus::HANDLED, + R"({"type":"keydown","keymap":"fuchsia","hidUsage":458756,"codePoint":65,"modifiers":1})", + }); + // Release CAPS_LOCK. + events.emplace_back(EventFlow{ + MakeEvent(fuchsia::ui::input3::KeyEventType::RELEASED, + fuchsia::ui::input3::Modifiers::CAPS_LOCK, + fuchsia::input::Key::CAPS_LOCK), + fuchsia::ui::input3::KeyEventStatus::HANDLED, + R"({"type":"keyup","keymap":"fuchsia","hidUsage":458809,"codePoint":0,"modifiers":1})", + }); + // Press A again. This time get 'A'. + // CAPS_LOCK is latched active even if it was just released. + events.emplace_back(EventFlow{ + MakeEvent(fuchsia::ui::input3::KeyEventType::PRESSED, std::nullopt, + fuchsia::input::Key::A), + fuchsia::ui::input3::KeyEventStatus::HANDLED, + R"({"type":"keydown","keymap":"fuchsia","hidUsage":458756,"codePoint":65,"modifiers":1})", + }); + + for (const auto& event : events) { + fuchsia::ui::input3::KeyEvent e; + event.event.Clone(&e); + fuchsia::ui::input3::KeyEventStatus key_event_status{0u}; + keyboard.listener_->OnKeyEvent( + std::move(e), + [&key_event_status](fuchsia::ui::input3::KeyEventStatus status) { + key_event_status = status; + }); + RunLoopUntilIdle(); + + ASSERT_NOTNULL(delegate.message()); + EXPECT_EQ(event.expected_platform_message, + ToString(delegate.message()->data())); + EXPECT_EQ(event.expected_key_event_status, key_event_status); + } +} + +TEST_F(PlatformViewTests, OnShaderWarmup) { + MockPlatformViewDelegate delegate; + flutter::TaskRunners task_runners = + flutter::TaskRunners("test_runners", nullptr, nullptr, nullptr, nullptr); + + uint64_t width = 200; + uint64_t height = 100; + std::vector shaders = {"foo.skp", "bar.skp", "baz.skp"}; + + OnShaderWarmupCallback on_shader_warmup_callback = + [&](const std::vector& shaders_in, + std::function completion_callback, uint64_t width_in, + uint64_t height_in) { + ASSERT_EQ(shaders.size(), shaders_in.size()); + for (size_t i = 0; i < shaders_in.size(); i++) { + ASSERT_EQ(shaders[i], shaders_in[i]); + } + ASSERT_EQ(width, width_in); + ASSERT_EQ(height, height_in); + + completion_callback(shaders_in.size()); + }; + + auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners)) + .SetShaderWarmupCallback(on_shader_warmup_callback) + .Build(); + + std::ostringstream shaders_array_ostream; + shaders_array_ostream << "[ "; + for (auto it = shaders.begin(); it != shaders.end(); ++it) { + shaders_array_ostream << "\"" << *it << "\""; + if (std::next(it) != shaders.end()) { + shaders_array_ostream << ", "; + } + } + shaders_array_ostream << "]"; + + std::string shaders_array_string = shaders_array_ostream.str(); + + // Create initial view for testing. + std::ostringstream warmup_shaders_ostream; + warmup_shaders_ostream << "{" << " \"method\":\"WarmupSkps\"," + << " \"args\":{" + << " \"shaders\":" << shaders_array_string << "," + << " \"width\":" << width << "," + << " \"height\":" << height << " }" << "}\n"; + std::string warmup_shaders_string = warmup_shaders_ostream.str(); + + fml::RefPtr response( + new TestPlatformMessageResponse); + static_cast(&platform_view) + ->HandlePlatformMessage(std::make_unique( + "fuchsia/shader_warmup", + fml::MallocMapping::Copy(warmup_shaders_string.c_str(), + warmup_shaders_string.size()), + response)); + RunLoopUntilIdle(); + ASSERT_TRUE(response->is_complete()); + + std::ostringstream expected_result_ostream; + expected_result_ostream << "[" << shaders.size() << "]"; + std::string expected_result_string = expected_result_ostream.str(); + EXPECT_EQ(expected_result_string, response->result_string); +} + +TEST_F(PlatformViewTests, TouchSourceLogicalToPhysicalConversion) { + constexpr uint32_t width = 640; + constexpr uint32_t height = 480; + constexpr std::array, 2> kRect = { + {{0, 0}, {width, height}}}; + constexpr std::array kIdentity = {1, 0, 0, 0, 1, 0, 0, 0, 1}; + constexpr fuchsia::ui::pointer::TouchInteractionId kIxnOne = { + .device_id = 0u, .pointer_id = 1u, .interaction_id = 2u}; + + MockPlatformViewDelegate delegate; + flutter::TaskRunners task_runners("test_runners", nullptr, nullptr, nullptr, + nullptr); + + MockParentViewportWatcher viewport_watcher; + FakeTouchSource touch_server; + fidl::BindingSet touch_bindings; + auto touch_handle = touch_bindings.AddBinding(&touch_server); + auto platform_view = + PlatformViewBuilder(delegate, std::move(task_runners)) + .SetParentViewportWatcher(viewport_watcher.GetHandle()) + .SetTouchSource(std::move(touch_handle)) + .Build(); + RunLoopUntilIdle(); + EXPECT_EQ(delegate.pointer_packets().size(), 0u); + + viewport_watcher.SetLayout(width, height); + RunLoopUntilIdle(); + EXPECT_EQ(delegate.metrics(), + flutter::ViewportMetrics(1, width, height, -1, 0)); + + // Inject + std::vector events = + TouchEventBuilder::New() + .AddTime(/* in nanoseconds */ 1111789u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kIxnOne, fuchsia::ui::pointer::EventPhase::ADD, + {width / 2, height / 2}) + .AddResult( + {.interaction = kIxnOne, + .status = fuchsia::ui::pointer::TouchInteractionStatus::GRANTED}) + .BuildAsVector(); + touch_server.ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + // Unpack + std::vector> packets = + delegate.TakePointerDataPackets(); + ASSERT_EQ(packets.size(), 1u); + std::vector flutter_events; + UnpackPointerPacket(flutter_events, std::move(packets[0])); + + // Examine phases + ASSERT_EQ(flutter_events.size(), 2u); + EXPECT_EQ(flutter_events[0].change, flutter::PointerData::Change::kAdd); + EXPECT_EQ(flutter_events[1].change, flutter::PointerData::Change::kDown); + + // Examine coordinates + EXPECT_EQ(flutter_events[0].physical_x, width / 2); + EXPECT_EQ(flutter_events[0].physical_y, height / 2); + EXPECT_EQ(flutter_events[1].physical_x, width / 2); + EXPECT_EQ(flutter_events[1].physical_y, height / 2); +} + +} // namespace flutter_runner::testing diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/pointer_event_utility.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/pointer_event_utility.cc new file mode 100644 index 0000000000000000000000000000000000000000..a1e30231130897e5a66062ee90d33166967b6dec --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/pointer_event_utility.cc @@ -0,0 +1,176 @@ +// 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 "pointer_event_utility.h" + +namespace flutter_runner::testing { + +using fup_EventPhase = fuchsia::ui::pointer::EventPhase; +using fup_TouchEvent = fuchsia::ui::pointer::TouchEvent; +using fup_TouchIxnId = fuchsia::ui::pointer::TouchInteractionId; +using fup_TouchIxnResult = fuchsia::ui::pointer::TouchInteractionResult; +using fup_TouchPointerSample = fuchsia::ui::pointer::TouchPointerSample; +using fup_ViewParameters = fuchsia::ui::pointer::ViewParameters; +using fup_MouseEvent = fuchsia::ui::pointer::MouseEvent; +using fup_MousePointerSample = fuchsia::ui::pointer::MousePointerSample; +using fup_MouseDeviceInfo = fuchsia::ui::pointer::MouseDeviceInfo; + +namespace { + +fup_ViewParameters CreateViewParameters( + std::array, 2> view, + std::array, 2> viewport, + std::array transform) { + fup_ViewParameters params; + fuchsia::ui::pointer::Rectangle view_rect; + view_rect.min = view[0]; + view_rect.max = view[1]; + params.view = view_rect; + fuchsia::ui::pointer::Rectangle viewport_rect; + viewport_rect.min = viewport[0]; + viewport_rect.max = viewport[1]; + params.viewport = viewport_rect; + params.viewport_to_view_transform = transform; + return params; +} + +} // namespace + +TouchEventBuilder TouchEventBuilder::New() { + return TouchEventBuilder(); +} + +TouchEventBuilder& TouchEventBuilder::AddTime(zx_time_t time) { + time_ = time; + return *this; +} + +TouchEventBuilder& TouchEventBuilder::AddSample(fup_TouchIxnId id, + fup_EventPhase phase, + std::array position) { + sample_ = std::make_optional(); + sample_->set_interaction(id); + sample_->set_phase(phase); + sample_->set_position_in_viewport(position); + return *this; +} + +TouchEventBuilder& TouchEventBuilder::AddViewParameters( + std::array, 2> view, + std::array, 2> viewport, + std::array transform) { + params_ = CreateViewParameters(std::move(view), std::move(viewport), + std::move(transform)); + return *this; +} + +TouchEventBuilder& TouchEventBuilder::AddResult(fup_TouchIxnResult result) { + result_ = result; + return *this; +} + +fup_TouchEvent TouchEventBuilder::Build() { + fup_TouchEvent event; + if (time_) { + event.set_timestamp(time_.value()); + } + if (params_) { + event.set_view_parameters(std::move(params_.value())); + } + if (sample_) { + event.set_pointer_sample(std::move(sample_.value())); + } + if (result_) { + event.set_interaction_result(std::move(result_.value())); + } + return event; +} + +std::vector TouchEventBuilder::BuildAsVector() { + std::vector events; + events.emplace_back(Build()); + return events; +} + +MouseEventBuilder MouseEventBuilder::New() { + return MouseEventBuilder(); +} + +MouseEventBuilder& MouseEventBuilder::AddTime(zx_time_t time) { + time_ = time; + return *this; +} + +MouseEventBuilder& MouseEventBuilder::AddSample( + uint32_t id, + std::array position, + std::vector pressed_buttons, + std::array scroll, + std::array scroll_in_physical_pixel, + bool is_precision_scroll) { + sample_ = std::make_optional(); + sample_->set_device_id(id); + if (!pressed_buttons.empty()) { + sample_->set_pressed_buttons(pressed_buttons); + } + sample_->set_position_in_viewport(position); + if (scroll[0] != 0) { + sample_->set_scroll_h(scroll[0]); + } + if (scroll[1] != 0) { + sample_->set_scroll_v(scroll[1]); + } + if (scroll_in_physical_pixel[0] != 0) { + sample_->set_scroll_h_physical_pixel(scroll_in_physical_pixel[0]); + } + if (scroll_in_physical_pixel[1] != 0) { + sample_->set_scroll_v_physical_pixel(scroll_in_physical_pixel[1]); + } + sample_->set_is_precision_scroll(is_precision_scroll); + return *this; +} + +MouseEventBuilder& MouseEventBuilder::AddViewParameters( + std::array, 2> view, + std::array, 2> viewport, + std::array transform) { + params_ = CreateViewParameters(std::move(view), std::move(viewport), + std::move(transform)); + return *this; +} + +MouseEventBuilder& MouseEventBuilder::AddMouseDeviceInfo( + uint32_t id, + std::vector buttons) { + device_info_ = std::make_optional(); + device_info_->set_id(id); + device_info_->set_buttons(buttons); + return *this; +} + +fup_MouseEvent MouseEventBuilder::Build() { + fup_MouseEvent event; + if (time_) { + event.set_timestamp(time_.value()); + } + if (params_) { + event.set_view_parameters(std::move(params_.value())); + } + if (sample_) { + event.set_pointer_sample(std::move(sample_.value())); + } + if (device_info_) { + event.set_device_info(std::move(device_info_.value())); + } + event.set_trace_flow_id(123); + return event; +} + +std::vector MouseEventBuilder::BuildAsVector() { + std::vector events; + events.emplace_back(Build()); + return events; +} + +} // namespace flutter_runner::testing diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/pointer_event_utility.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/pointer_event_utility.h new file mode 100644 index 0000000000000000000000000000000000000000..1e3ce9fc6b56cf3e4945488ae767d0e54b327f36 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/pointer_event_utility.h @@ -0,0 +1,73 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_POINTER_EVENT_UTILITY_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_POINTER_EVENT_UTILITY_H_ + +#include +#include + +#include +#include +#include + +namespace flutter_runner::testing { + +// A helper class for crafting a fuchsia.ui.pointer.TouchEvent table. +class TouchEventBuilder { + public: + static TouchEventBuilder New(); + + TouchEventBuilder& AddTime(zx_time_t time); + TouchEventBuilder& AddSample(fuchsia::ui::pointer::TouchInteractionId id, + fuchsia::ui::pointer::EventPhase phase, + std::array position); + TouchEventBuilder& AddViewParameters( + std::array, 2> view, + std::array, 2> viewport, + std::array transform); + TouchEventBuilder& AddResult( + fuchsia::ui::pointer::TouchInteractionResult result); + + fuchsia::ui::pointer::TouchEvent Build(); + std::vector BuildAsVector(); + + private: + std::optional time_; + std::optional params_; + std::optional sample_; + std::optional result_; +}; + +// A helper class for crafting a fuchsia.ui.pointer.MouseEventBuilder table. +class MouseEventBuilder { + public: + static MouseEventBuilder New(); + + MouseEventBuilder& AddTime(zx_time_t time); + MouseEventBuilder& AddSample(uint32_t id, + std::array position, + std::vector pressed_buttons, + std::array scroll, + std::array scroll_in_physical_pixel, + bool is_precision_scroll); + MouseEventBuilder& AddViewParameters( + std::array, 2> view, + std::array, 2> viewport, + std::array transform); + MouseEventBuilder& AddMouseDeviceInfo(uint32_t id, + std::vector buttons); + fuchsia::ui::pointer::MouseEvent Build(); + std::vector BuildAsVector(); + + private: + std::optional time_; + std::optional sample_; + std::optional params_; + std::optional device_info_; +}; + +} // namespace flutter_runner::testing + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_POINTER_EVENT_UTILITY_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/test_manifest.json b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/test_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..f0d6adc96a5e604b0848203361fbe503f60f15ed --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/test_manifest.json @@ -0,0 +1,27 @@ +{ + "families": [ + { + "family": "Roboto", + "fallback": true, + "fallback_group": "sans-serif", + "fonts": [ + { + "asset": "Roboto-Regular.ttf" + } + ] + }, + { + "family": "Roboto Slab", + "aliases": [ + "RobotoSlab" + ], + "fallback": true, + "fallback_group": "serif", + "fonts": [ + { + "asset": "RobotoSlab-Regular.ttf" + } + ] + } + ] +} \ No newline at end of file diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/tzdata/2019a/44/le/metaZones.res b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/tzdata/2019a/44/le/metaZones.res new file mode 100644 index 0000000000000000000000000000000000000000..3b3ee01349732bfdb4e2fb54e674bc7e3de8da14 Binary files /dev/null and b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/tzdata/2019a/44/le/metaZones.res differ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/tzdata/2019a/44/le/timezoneTypes.res b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/tzdata/2019a/44/le/timezoneTypes.res new file mode 100644 index 0000000000000000000000000000000000000000..895ed2174c0d381a3d660a3b353f7c07a1001582 Binary files /dev/null and b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/tzdata/2019a/44/le/timezoneTypes.res differ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/tzdata/README.md b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/tzdata/README.md new file mode 100644 index 0000000000000000000000000000000000000000..bc384ec4083b5b22fd38a5e3d93c55ac5d75a8cc --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/tests/tzdata/README.md @@ -0,0 +1,6 @@ +# Timezone data for testing + +This directory contains the fixed timezone data version 2019a for testing. It +is used in the runner tests to show that loading these files from a specified +location results in the TZ data version "2019a" becoming available to the +binaries. diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/text_delegate.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/text_delegate.cc new file mode 100644 index 0000000000000000000000000000000000000000..7b933e85829e9ffd8387e3982d75f40f858433a5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/text_delegate.cc @@ -0,0 +1,449 @@ +// 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 "text_delegate.h" + +#include +#include +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/mapping.h" +#include "flutter/lib/ui/window/platform_message.h" +#include "flutter/shell/platform/fuchsia/flutter/keyboard.h" +#include "flutter/shell/platform/fuchsia/runtime/dart/utils/inlines.h" +#include "third_party/rapidjson/include/rapidjson/document.h" +#include "third_party/rapidjson/include/rapidjson/stringbuffer.h" +#include "third_party/rapidjson/include/rapidjson/writer.h" + +#include "logging.h" + +namespace flutter_runner { + +static constexpr char kInputActionKey[] = "inputAction"; + +// See: https://api.flutter.dev/flutter/services/TextInputAction.html +// Only the actions relevant for Fuchsia are listed here. +static constexpr char kTextInputActionDone[] = "TextInputAction.done"; +static constexpr char kTextInputActionNewline[] = "TextInputAction.newline"; +static constexpr char kTextInputActionGo[] = "TextInputAction.go"; +static constexpr char kTextInputActionNext[] = "TextInputAction.next"; +static constexpr char kTextInputActionPrevious[] = "TextInputAction.previous"; +static constexpr char kTextInputActionNone[] = "TextInputAction.none"; +static constexpr char kTextInputActionSearch[] = "TextInputAction.search"; +static constexpr char kTextInputActionSend[] = "TextInputAction.send"; +static constexpr char kTextInputActionUnspecified[] = + "TextInputAction.unspecified"; + +// Converts Flutter TextInputAction to Fuchsia action enum. +static fuchsia::ui::input::InputMethodAction IntoInputMethodAction( + const std::string action_string) { + if (action_string == kTextInputActionNewline) { + return fuchsia::ui::input::InputMethodAction::NEWLINE; + } else if (action_string == kTextInputActionDone) { + return fuchsia::ui::input::InputMethodAction::DONE; + } else if (action_string == kTextInputActionGo) { + return fuchsia::ui::input::InputMethodAction::GO; + } else if (action_string == kTextInputActionNext) { + return fuchsia::ui::input::InputMethodAction::NEXT; + } else if (action_string == kTextInputActionPrevious) { + return fuchsia::ui::input::InputMethodAction::PREVIOUS; + } else if (action_string == kTextInputActionNone) { + return fuchsia::ui::input::InputMethodAction::NONE; + } else if (action_string == kTextInputActionSearch) { + return fuchsia::ui::input::InputMethodAction::SEARCH; + } else if (action_string == kTextInputActionSend) { + return fuchsia::ui::input::InputMethodAction::SEND; + } else if (action_string == kTextInputActionUnspecified) { + return fuchsia::ui::input::InputMethodAction::UNSPECIFIED; + } + // If this message comes along it means we should really add the missing 'if' + // above. + FML_VLOG(1) << "unexpected action_string: " << action_string; + // Substituting DONE for an unexpected action string will probably be OK. + return fuchsia::ui::input::InputMethodAction::DONE; +} + +// Converts the Fuchsia action enum into Flutter TextInputAction. +static const std::string IntoTextInputAction( + fuchsia::ui::input::InputMethodAction action) { + if (action == fuchsia::ui::input::InputMethodAction::NEWLINE) { + return kTextInputActionNewline; + } else if (action == fuchsia::ui::input::InputMethodAction::DONE) { + return kTextInputActionDone; + } else if (action == fuchsia::ui::input::InputMethodAction::GO) { + return kTextInputActionGo; + } else if (action == fuchsia::ui::input::InputMethodAction::NEXT) { + return kTextInputActionNext; + } else if (action == fuchsia::ui::input::InputMethodAction::PREVIOUS) { + return kTextInputActionPrevious; + } else if (action == fuchsia::ui::input::InputMethodAction::NONE) { + return kTextInputActionNone; + } else if (action == fuchsia::ui::input::InputMethodAction::SEARCH) { + return kTextInputActionSearch; + } else if (action == fuchsia::ui::input::InputMethodAction::SEND) { + return kTextInputActionSend; + } else if (action == fuchsia::ui::input::InputMethodAction::UNSPECIFIED) { + return kTextInputActionUnspecified; + } + // If this message comes along it means we should really add the missing 'if' + // above. + FML_VLOG(1) << "unexpected action: " << static_cast(action); + // Substituting "done" for an unexpected text input action will probably + // be OK. + return kTextInputActionDone; +} + +// TODO(fxbug.dev/8868): Terminate engine if Fuchsia system FIDL connections +// have error. +template +void SetInterfaceErrorHandler(fidl::InterfacePtr& interface, + std::string name) { + interface.set_error_handler([name](zx_status_t status) { + FML_LOG(ERROR) << "Interface error on: " << name << ", status: " << status; + }); +} +template +void SetInterfaceErrorHandler(fidl::Binding& binding, std::string name) { + binding.set_error_handler([name](zx_status_t status) { + FML_LOG(ERROR) << "Binding error on: " << name << ", status: " << status; + }); +} + +TextDelegate::TextDelegate( + fuchsia::ui::views::ViewRef view_ref, + fuchsia::ui::input::ImeServiceHandle ime_service, + fuchsia::ui::input3::KeyboardHandle keyboard, + std::function)> + dispatch_callback) + : dispatch_callback_(dispatch_callback), + ime_client_(this), + text_sync_service_(ime_service.Bind()), + keyboard_listener_binding_(this), + keyboard_(keyboard.Bind()) { + // Register all error handlers. + SetInterfaceErrorHandler(ime_, "Input Method Editor"); + SetInterfaceErrorHandler(ime_client_, "IME Client"); + SetInterfaceErrorHandler(text_sync_service_, "Text Sync Service"); + SetInterfaceErrorHandler(keyboard_listener_binding_, "Keyboard Listener"); + SetInterfaceErrorHandler(keyboard_, "Keyboard"); + + // Configure keyboard listener. + keyboard_->AddListener(std::move(view_ref), + keyboard_listener_binding_.NewBinding(), [] {}); +} + +void TextDelegate::ActivateIme() { + ActivateIme(requested_text_action_.value_or( + fuchsia::ui::input::InputMethodAction::DONE)); +} + +void TextDelegate::ActivateIme(fuchsia::ui::input::InputMethodAction action) { + FML_DCHECK(last_text_state_.has_value()); + + requested_text_action_ = action; + text_sync_service_->GetInputMethodEditor( + fuchsia::ui::input::KeyboardType::TEXT, // keyboard type + action, // input method action + last_text_state_.value(), // initial state + ime_client_.NewBinding(), // client + ime_.NewRequest() // editor + ); +} + +void TextDelegate::DeactivateIme() { + if (ime_) { + text_sync_service_->HideKeyboard(); + ime_ = nullptr; + } + if (ime_client_.is_bound()) { + ime_client_.Unbind(); + } +} + +// |fuchsia::ui::input::InputMethodEditorClient| +void TextDelegate::DidUpdateState( + fuchsia::ui::input::TextInputState state, + std::unique_ptr input_event) { + rapidjson::Document document; + auto& allocator = document.GetAllocator(); + rapidjson::Value encoded_state(rapidjson::kObjectType); + encoded_state.AddMember("text", state.text, allocator); + encoded_state.AddMember("selectionBase", state.selection.base, allocator); + encoded_state.AddMember("selectionExtent", state.selection.extent, allocator); + switch (state.selection.affinity) { + case fuchsia::ui::input::TextAffinity::UPSTREAM: + encoded_state.AddMember("selectionAffinity", + rapidjson::Value("TextAffinity.upstream"), + allocator); + break; + case fuchsia::ui::input::TextAffinity::DOWNSTREAM: + encoded_state.AddMember("selectionAffinity", + rapidjson::Value("TextAffinity.downstream"), + allocator); + break; + } + encoded_state.AddMember("selectionIsDirectional", true, allocator); + encoded_state.AddMember("composingBase", state.composing.start, allocator); + encoded_state.AddMember("composingExtent", state.composing.end, allocator); + + rapidjson::Value args(rapidjson::kArrayType); + args.PushBack(current_text_input_client_, allocator); + args.PushBack(encoded_state, allocator); + + document.SetObject(); + document.AddMember("method", + rapidjson::Value("TextInputClient.updateEditingState"), + allocator); + document.AddMember("args", args, allocator); + + rapidjson::StringBuffer buffer; + rapidjson::Writer writer(buffer); + document.Accept(writer); + + const uint8_t* data = reinterpret_cast(buffer.GetString()); + dispatch_callback_(std::make_unique( + kTextInputChannel, // channel + fml::MallocMapping::Copy(data, buffer.GetSize()), // message + nullptr) // response + ); + last_text_state_ = std::move(state); +} + +// |fuchsia::ui::input::InputMethodEditorClient| +void TextDelegate::OnAction(fuchsia::ui::input::InputMethodAction action) { + rapidjson::Document document; + auto& allocator = document.GetAllocator(); + + rapidjson::Value args(rapidjson::kArrayType); + args.PushBack(current_text_input_client_, allocator); + + const std::string action_string = IntoTextInputAction(action); + args.PushBack(rapidjson::Value{}.SetString(action_string.c_str(), + action_string.length()), + allocator); + + document.SetObject(); + document.AddMember( + "method", rapidjson::Value("TextInputClient.performAction"), allocator); + document.AddMember("args", args, allocator); + + rapidjson::StringBuffer buffer; + rapidjson::Writer writer(buffer); + document.Accept(writer); + + const uint8_t* data = reinterpret_cast(buffer.GetString()); + dispatch_callback_(std::make_unique( + kTextInputChannel, // channel + fml::MallocMapping::Copy(data, buffer.GetSize()), // message + nullptr) // response + ); +} + +// Channel handler for kTextInputChannel +bool TextDelegate::HandleFlutterTextInputChannelPlatformMessage( + std::unique_ptr message) { + FML_DCHECK(message->channel() == kTextInputChannel); + const auto& data = message->data(); + + rapidjson::Document document; + document.Parse(reinterpret_cast(data.GetMapping()), + data.GetSize()); + if (document.HasParseError() || !document.IsObject()) { + return false; + } + auto root = document.GetObject(); + auto method = root.FindMember("method"); + if (method == root.MemberEnd() || !method->value.IsString()) { + return false; + } + + if (method->value == "TextInput.show") { + if (ime_) { + text_sync_service_->ShowKeyboard(); + } + } else if (method->value == "TextInput.hide") { + if (ime_) { + text_sync_service_->HideKeyboard(); + } + } else if (method->value == "TextInput.setClient") { + // Sample "setClient" message: + // + // { + // "method": "TextInput.setClient", + // "args": [ + // 7, + // { + // "inputType": { + // "name": "TextInputType.multiline", + // "signed":null, + // "decimal":null + // }, + // "readOnly": false, + // "obscureText": false, + // "autocorrect":true, + // "smartDashesType":"1", + // "smartQuotesType":"1", + // "enableSuggestions":true, + // "enableInteractiveSelection":true, + // "actionLabel":null, + // "inputAction":"TextInputAction.newline", + // "textCapitalization":"TextCapitalization.none", + // "keyboardAppearance":"Brightness.dark", + // "enableIMEPersonalizedLearning":true, + // "enableDeltaModel":false + // } + // ] + // } + + current_text_input_client_ = 0; + DeactivateIme(); + auto args = root.FindMember("args"); + if (args == root.MemberEnd() || !args->value.IsArray() || + args->value.Size() != 2) + return false; + const auto& configuration = args->value[1]; + if (!configuration.IsObject()) { + return false; + } + // TODO(abarth): Read the keyboard type from the configuration. + current_text_input_client_ = args->value[0].GetInt(); + + auto initial_text_input_state = fuchsia::ui::input::TextInputState{}; + initial_text_input_state.text = ""; + last_text_state_ = std::move(initial_text_input_state); + + const auto configuration_object = configuration.GetObject(); + if (!configuration_object.HasMember(kInputActionKey)) { + return false; + } + const auto& action_object = configuration_object[kInputActionKey]; + if (!action_object.IsString()) { + return false; + } + const auto action_string = + std::string(action_object.GetString(), action_object.GetStringLength()); + ActivateIme(IntoInputMethodAction(std::move(action_string))); + } else if (method->value == "TextInput.setEditingState") { + if (ime_) { + auto args_it = root.FindMember("args"); + if (args_it == root.MemberEnd() || !args_it->value.IsObject()) { + return false; + } + const auto& args = args_it->value; + fuchsia::ui::input::TextInputState state; + state.text = ""; + // TODO(abarth): Deserialize state. + auto text = args.FindMember("text"); + if (text != args.MemberEnd() && text->value.IsString()) { + state.text = text->value.GetString(); + } + auto selection_base = args.FindMember("selectionBase"); + if (selection_base != args.MemberEnd() && selection_base->value.IsInt()) { + state.selection.base = selection_base->value.GetInt(); + } + auto selection_extent = args.FindMember("selectionExtent"); + if (selection_extent != args.MemberEnd() && + selection_extent->value.IsInt()) { + state.selection.extent = selection_extent->value.GetInt(); + } + auto selection_affinity = args.FindMember("selectionAffinity"); + if (selection_affinity != args.MemberEnd() && + selection_affinity->value.IsString() && + selection_affinity->value == "TextAffinity.upstream") { + state.selection.affinity = fuchsia::ui::input::TextAffinity::UPSTREAM; + } else { + state.selection.affinity = fuchsia::ui::input::TextAffinity::DOWNSTREAM; + } + // We ignore selectionIsDirectional because that concept doesn't exist on + // Fuchsia. + auto composing_base = args.FindMember("composingBase"); + if (composing_base != args.MemberEnd() && composing_base->value.IsInt()) { + state.composing.start = composing_base->value.GetInt(); + } + auto composing_extent = args.FindMember("composingExtent"); + if (composing_extent != args.MemberEnd() && + composing_extent->value.IsInt()) { + state.composing.end = composing_extent->value.GetInt(); + } + ime_->SetState(std::move(state)); + } + } else if (method->value == "TextInput.clearClient") { + current_text_input_client_ = 0; + last_text_state_ = std::nullopt; + requested_text_action_ = std::nullopt; + DeactivateIme(); + } else if (method->value == "TextInput.setCaretRect" || + method->value == "TextInput.setEditableSizeAndTransform" || + method->value == "TextInput.setMarkedTextRect" || + method->value == "TextInput.setStyle") { + // We don't have these methods implemented and they get + // sent a lot during text input, so we create an empty case for them + // here to avoid "Unknown flutter/textinput method TextInput.*" + // log spam. + // + // TODO(fxb/101619): We should implement these. + } else { + FML_LOG(ERROR) << "Unknown " << message->channel() << " method " + << method->value.GetString(); + } + // Complete with an empty response. + return false; +} + +// |fuchsia::ui:input3::KeyboardListener| +void TextDelegate::OnKeyEvent( + fuchsia::ui::input3::KeyEvent key_event, + fuchsia::ui::input3::KeyboardListener::OnKeyEventCallback callback) { + const char* type = nullptr; + switch (key_event.type()) { + case fuchsia::ui::input3::KeyEventType::PRESSED: + type = "keydown"; + break; + case fuchsia::ui::input3::KeyEventType::RELEASED: + type = "keyup"; + break; + case fuchsia::ui::input3::KeyEventType::SYNC: + // SYNC means the key was pressed while focus was not on this application. + // This should possibly behave like PRESSED in the future, though it + // doesn't hurt to ignore it today. + case fuchsia::ui::input3::KeyEventType::CANCEL: + // CANCEL means the key was released while focus was not on this + // application. + // This should possibly behave like RELEASED in the future to ensure that + // a key is not repeated forever if it is pressed while focus is lost. + default: + break; + } + if (type == nullptr) { + FML_VLOG(1) << "Unknown key event phase."; + callback(fuchsia::ui::input3::KeyEventStatus::NOT_HANDLED); + return; + } + keyboard_translator_.ConsumeEvent(std::move(key_event)); + + rapidjson::Document document; + auto& allocator = document.GetAllocator(); + document.SetObject(); + document.AddMember("type", rapidjson::Value(type, strlen(type)), allocator); + document.AddMember("keymap", rapidjson::Value("fuchsia"), allocator); + document.AddMember("hidUsage", keyboard_translator_.LastHIDUsage(), + allocator); + document.AddMember("codePoint", keyboard_translator_.LastCodePoint(), + allocator); + document.AddMember("modifiers", keyboard_translator_.Modifiers(), allocator); + rapidjson::StringBuffer buffer; + rapidjson::Writer writer(buffer); + document.Accept(writer); + + const uint8_t* data = reinterpret_cast(buffer.GetString()); + dispatch_callback_(std::make_unique( + kKeyEventChannel, // channel + fml::MallocMapping::Copy(data, buffer.GetSize()), // data + nullptr) // response + ); + callback(fuchsia::ui::input3::KeyEventStatus::HANDLED); +} +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/text_delegate.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/text_delegate.h new file mode 100644 index 0000000000000000000000000000000000000000..a1b935369dd2eea0d98182811afec9a13ed052f4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/text_delegate.h @@ -0,0 +1,154 @@ +// 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. + +/// Text editing functionality delegated from |PlatformView|. +/// See |TextDelegate| for details. + +#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TEXT_DELEGATE_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TEXT_DELEGATE_H_ + +#include + +#include +#include +#include +#include + +#include "flutter/lib/ui/window/platform_message.h" +#include "flutter/shell/common/platform_view.h" +#include "flutter/shell/platform/fuchsia/flutter/keyboard.h" + +#include "logging.h" + +namespace flutter_runner { + +/// The channel name used for text editing platofrm messages. +constexpr char kTextInputChannel[] = "flutter/textinput"; + +/// The channel name used for key event platform messages. +constexpr char kKeyEventChannel[] = "flutter/keyevent"; + +/// TextDelegate handles keyboard inpout and text editing. +/// +/// It mediates between Fuchsia's input and Flutter's platform messages. When it +/// is initialized, it contacts `fuchsia.ui.input.Keyboard` to register itself +/// as listener of key events. +/// +/// Whenever a text editing request comes from the +/// Flutter app, it will activate Fuchsia's input method editor, and will send +/// text edit actions coming from the Fuchsia platform over to the Flutter app, +/// by converting FIDL messages (`fuchsia.ui.input.InputMethodEditorClient` +/// calls) to appropriate text editing Flutter platform messages. +/// +/// For details refer to: +/// * Flutter side: +/// https://api.flutter.dev/javadoc/io/flutter/embedding/engine/systemchannels/TextInputChannel.html +/// * Fuchsia side: https://fuchsia.dev/reference/fidl/fuchsia.ui.input +class TextDelegate : public fuchsia::ui::input3::KeyboardListener, + public fuchsia::ui::input::InputMethodEditorClient { + public: + /// Creates a new TextDelegate. + /// + /// Args: + /// view_ref: the reference to the app's view. Required for registration + /// with Fuchsia. + /// ime_service: a handle to Fuchsia's input method service. + /// keyboard: the keyboard listener, gets notified of key presses and + /// releases. + /// dispatch_callback: a function used to send a Flutter platform message. + TextDelegate(fuchsia::ui::views::ViewRef view_ref, + fuchsia::ui::input::ImeServiceHandle ime_service, + fuchsia::ui::input3::KeyboardHandle keyboard, + std::function)> + dispatch_callback); + + /// |fuchsia.ui.input3.KeyboardListener| + /// Called by the embedder every time there is a key event to process. + void OnKeyEvent(fuchsia::ui::input3::KeyEvent key_event, + fuchsia::ui::input3::KeyboardListener::OnKeyEventCallback + callback) override; + + /// |fuchsia::ui::input::InputMethodEditorClient| + /// Called by the embedder every time the edit state is updated. + void DidUpdateState( + fuchsia::ui::input::TextInputState state, + std::unique_ptr event) override; + + /// |fuchsia::ui::input::InputMethodEditorClient| + /// Called by the embedder when the action key is pressed, and the requested + /// action is supplied to Flutter. + void OnAction(fuchsia::ui::input::InputMethodAction action) override; + + /// Gets a new input method editor from the input connection. Run when both + /// Scenic has focus and Flutter has requested input with setClient. + void ActivateIme(); + + /// Detaches the input method editor connection, ending the edit session and + /// closing the onscreen keyboard. Call when input is no longer desired, + /// either because Scenic says we lost focus or when Flutter no longer has a + /// text field focused. + void DeactivateIme(); + + /// Channel handler for kTextInputChannel + bool HandleFlutterTextInputChannelPlatformMessage( + std::unique_ptr message); + + /// Returns true if there is a text state (i.e. if some text editing is in + /// progress). + bool HasTextState() { return last_text_state_.has_value(); } + + private: + // Activates the input method editor, assigning |action| to the "enter" key. + // This action will be reported by |OnAction| above when the "enter" key is + // pressed. Note that in the case of multi-line text editors, |OnAction| will + // never be called: instead, the text editor will insert a newline into the + // edited text. + void ActivateIme(fuchsia::ui::input::InputMethodAction action); + + // Converts Fuchsia platform key codes into Flutter key codes. + Keyboard keyboard_translator_; + + // A callback for sending a single Flutter platform message. + std::function)> + dispatch_callback_; + + // TextDelegate server-side binding. Methods called when the text edit state + // is updated. + fidl::Binding ime_client_; + + // An interface for interacting with a text input control. + fuchsia::ui::input::InputMethodEditorPtr ime_; + + // An interface for requesting the InputMethodEditor. + fuchsia::ui::input::ImeServicePtr text_sync_service_; + + // The locally-unique identifier of the text input currently in use. Flutter + // usually uses only one at a time. + int current_text_input_client_ = 0; + + // TextDelegate server side binding. Methods called when a key is pressed. + fidl::Binding + keyboard_listener_binding_; + + // The client-side stub for calling the Keyboard protocol. + fuchsia::ui::input3::KeyboardPtr keyboard_; + + // last_text_state_ is the last state of the text input as reported by the IME + // or initialized by Flutter. We set it to null if Flutter doesn't want any + // input, since then there is no text input state at all. + // If nullptr, then no editing is in progress. + std::optional last_text_state_; + + // The action that Flutter expects to happen when the user presses the "enter" + // key. For example, it could be `InputMethodAction::DONE` which would cause + // text editing to stop and the current text to be accepted. + // If set to std::nullopt, then no editing is in progress. + std::optional requested_text_action_; + + FML_DISALLOW_COPY_AND_ASSIGN(TextDelegate); +}; + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TEXT_DELEGATE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/text_delegate_unittests.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/text_delegate_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..b56e076d1dc66129d23189151baa016b8dee9b6a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/text_delegate_unittests.cc @@ -0,0 +1,293 @@ +// 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 "text_delegate.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "tests/fakes/platform_message.h" + +#include "flutter/lib/ui/window/platform_message.h" + +#include + +namespace flutter_runner::testing { + +// Convert a |PlatformMessage| to string for ease of testing. +static std::string MessageToString(PlatformMessage& message) { + const char* data = reinterpret_cast(message.data().GetMapping()); + return std::string(data, message.data().GetSize()); +} + +// Fake |KeyboardService| implementation. Only responsibility is to remember +// what it was called with. +class FakeKeyboardService : public fuchsia::ui::input3::Keyboard { + public: + // |fuchsia.ui.input3/Keyboard.AddListener| + virtual void AddListener( + fuchsia::ui::views::ViewRef, + fidl::InterfaceHandle listener, + fuchsia::ui::input3::Keyboard::AddListenerCallback callback) { + listener_ = listener.Bind(); + callback(); + } + + fidl::InterfacePtr listener_; +}; + +// Fake ImeService implementation. Only responsibility is to remember what +// it was called with. +class FakeImeService : public fuchsia::ui::input::ImeService { + public: + virtual void GetInputMethodEditor( + fuchsia::ui::input::KeyboardType keyboard_type, + fuchsia::ui::input::InputMethodAction action, + fuchsia::ui::input::TextInputState input_state, + fidl::InterfaceHandle client, + fidl::InterfaceRequest ime) { + keyboard_type_ = std::move(keyboard_type); + action_ = std::move(action); + input_state_ = std::move(input_state); + client_ = client.Bind(); + ime_ = std::move(ime); + } + + virtual void ShowKeyboard() { keyboard_shown_ = true; } + + virtual void HideKeyboard() { keyboard_shown_ = false; } + + bool IsKeyboardShown() { return keyboard_shown_; } + + bool keyboard_shown_ = false; + + fuchsia::ui::input::KeyboardType keyboard_type_; + fuchsia::ui::input::InputMethodAction action_; + fuchsia::ui::input::TextInputState input_state_; + fidl::InterfacePtr client_; + fidl::InterfaceRequest ime_; +}; + +class TextDelegateTest : public ::testing::Test { + protected: + TextDelegateTest() + : loop_(&kAsyncLoopConfigAttachToCurrentThread), + keyboard_service_binding_(&keyboard_service_), + ime_service_binding_(&ime_service_) { + fidl::InterfaceHandle keyboard_handle; + auto keyboard_request = keyboard_handle.NewRequest(); + keyboard_service_binding_.Bind(keyboard_request.TakeChannel()); + + fidl::InterfaceHandle ime_service_handle; + ime_service_binding_.Bind(ime_service_handle.NewRequest().TakeChannel()); + + fuchsia::ui::views::ViewRefControl view_ref_control; + fuchsia::ui::views::ViewRef view_ref; + auto status = zx::eventpair::create( + /*options*/ 0u, &view_ref_control.reference, &view_ref.reference); + ZX_ASSERT(status == ZX_OK); + view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference); + + text_delegate_ = std::make_unique( + std::move(view_ref), std::move(ime_service_handle), + std::move(keyboard_handle), + // Should this be accessed through a weak pointer? + [this](std::unique_ptr message) { + last_message_ = std::move(message); + }); + + // TextDelegate has some async initialization that needs to happen. + RunLoopUntilIdle(); + } + + // Runs the event loop until all scheduled events are spent. + void RunLoopUntilIdle() { loop_.RunUntilIdle(); } + + void TearDown() override { + loop_.Quit(); + ASSERT_EQ(loop_.ResetQuit(), 0); + } + + async::Loop loop_; + + FakeKeyboardService keyboard_service_; + fidl::Binding keyboard_service_binding_; + + FakeImeService ime_service_; + fidl::Binding ime_service_binding_; + + // Unit under test. + std::unique_ptr text_delegate_; + + std::unique_ptr last_message_; +}; + +// Goes through several steps of a text edit protocol. These are hard to test +// in isolation because the text edit protocol depends on the correct method +// invocation sequence. The text editor is initialized with the editing +// parameters, and we verify that the correct input action is parsed out. We +// then exercise showing and hiding the keyboard, as well as a text state +// update. +TEST_F(TextDelegateTest, ActivateIme) { + auto fake_platform_message_response = FakePlatformMessageResponse::Create(); + { + // Initialize the editor. Without this initialization, the protocol code + // will crash. + const auto set_client_msg = R"( + { + "method": "TextInput.setClient", + "args": [ + 7, + { + "inputType": { + "name": "TextInputType.multiline", + "signed":null, + "decimal":null + }, + "readOnly": false, + "obscureText": false, + "autocorrect":true, + "smartDashesType":"1", + "smartQuotesType":"1", + "enableSuggestions":true, + "enableInteractiveSelection":true, + "actionLabel":null, + "inputAction":"TextInputAction.newline", + "textCapitalization":"TextCapitalization.none", + "keyboardAppearance":"Brightness.dark", + "enableIMEPersonalizedLearning":true, + "enableDeltaModel":false + } + ] + } + )"; + auto message = fake_platform_message_response->WithMessage( + kTextInputChannel, set_client_msg); + text_delegate_->HandleFlutterTextInputChannelPlatformMessage( + std::move(message)); + RunLoopUntilIdle(); + EXPECT_EQ(ime_service_.action_, + fuchsia::ui::input::InputMethodAction::NEWLINE); + EXPECT_FALSE(ime_service_.IsKeyboardShown()); + } + + { + // Verify that showing keyboard results in the correct platform effect. + const auto set_client_msg = R"( + { + "method": "TextInput.show" + } + )"; + auto message = fake_platform_message_response->WithMessage( + kTextInputChannel, set_client_msg); + text_delegate_->HandleFlutterTextInputChannelPlatformMessage( + std::move(message)); + RunLoopUntilIdle(); + EXPECT_TRUE(ime_service_.IsKeyboardShown()); + } + + { + // Verify that hiding keyboard results in the correct platform effect. + const auto set_client_msg = R"( + { + "method": "TextInput.hide" + } + )"; + auto message = fake_platform_message_response->WithMessage( + kTextInputChannel, set_client_msg); + text_delegate_->HandleFlutterTextInputChannelPlatformMessage( + std::move(message)); + RunLoopUntilIdle(); + EXPECT_FALSE(ime_service_.IsKeyboardShown()); + } + + { + // Update the editing state from the Fuchsia platform side. + fuchsia::ui::input::TextInputState state = { + .revision = 42, + .text = "Foo", + .selection = fuchsia::ui::input::TextSelection{}, + .composing = fuchsia::ui::input::TextRange{}, + }; + auto input_event = std::make_unique(); + ime_service_.client_->DidUpdateState(std::move(state), + std::move(input_event)); + RunLoopUntilIdle(); + EXPECT_EQ( + R"({"method":"TextInputClient.updateEditingState","args":[7,{"text":"Foo","selectionBase":0,"selectionExtent":0,"selectionAffinity":"TextAffinity.upstream","selectionIsDirectional":true,"composingBase":-1,"composingExtent":-1}]})", + MessageToString(*last_message_)); + } + + { + // Notify Flutter that the action key has been pressed. + ime_service_.client_->OnAction(fuchsia::ui::input::InputMethodAction::DONE); + RunLoopUntilIdle(); + EXPECT_EQ( + R"({"method":"TextInputClient.performAction","args":[7,"TextInputAction.done"]})", + MessageToString(*last_message_)); + } +} + +// Hands a few typical |KeyEvent|s to the text delegate. Regular key events are +// handled, "odd" key events are rejected (not handled). "Handling" a key event +// means converting it to an appropriate |PlatformMessage| and forwarding it. +TEST_F(TextDelegateTest, OnAction) { + { + // A sensible key event is converted into a platform message. + fuchsia::ui::input3::KeyEvent key_event; + *key_event.mutable_type() = fuchsia::ui::input3::KeyEventType::PRESSED; + *key_event.mutable_key() = fuchsia::input::Key::A; + key_event.mutable_key_meaning()->set_codepoint('a'); + + fuchsia::ui::input3::KeyEventStatus status; + keyboard_service_.listener_->OnKeyEvent( + std::move(key_event), [&status](fuchsia::ui::input3::KeyEventStatus s) { + status = std::move(s); + }); + RunLoopUntilIdle(); + EXPECT_EQ(fuchsia::ui::input3::KeyEventStatus::HANDLED, status); + EXPECT_EQ( + R"({"type":"keydown","keymap":"fuchsia","hidUsage":458756,"codePoint":97,"modifiers":0})", + MessageToString(*last_message_)); + } + + { + // SYNC event is not handled. + // This is currently expected, though we may need to change that behavior. + fuchsia::ui::input3::KeyEvent key_event; + *key_event.mutable_type() = fuchsia::ui::input3::KeyEventType::SYNC; + + fuchsia::ui::input3::KeyEventStatus status; + keyboard_service_.listener_->OnKeyEvent( + std::move(key_event), [&status](fuchsia::ui::input3::KeyEventStatus s) { + status = std::move(s); + }); + RunLoopUntilIdle(); + EXPECT_EQ(fuchsia::ui::input3::KeyEventStatus::NOT_HANDLED, status); + } + + { + // CANCEL event is not handled. + // This is currently expected, though we may need to change that behavior. + fuchsia::ui::input3::KeyEvent key_event; + *key_event.mutable_type() = fuchsia::ui::input3::KeyEventType::CANCEL; + + fuchsia::ui::input3::KeyEventStatus status; + keyboard_service_.listener_->OnKeyEvent( + std::move(key_event), [&status](fuchsia::ui::input3::KeyEventStatus s) { + status = std::move(s); + }); + RunLoopUntilIdle(); + EXPECT_EQ(fuchsia::ui::input3::KeyEventStatus::NOT_HANDLED, status); + } +} + +} // namespace flutter_runner::testing diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/unique_fdio_ns.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/unique_fdio_ns.h new file mode 100644 index 0000000000000000000000000000000000000000..eb8cbf4f80dae268f038cdd64907b7e8380f9822 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/unique_fdio_ns.h @@ -0,0 +1,37 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_UNIQUE_FDIO_NS_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_UNIQUE_FDIO_NS_H_ + +#include "flutter/fml/logging.h" +#include "flutter/fml/unique_object.h" +#include "lib/fdio/namespace.h" + +namespace flutter_runner { + +struct UniqueFDIONSTraits { + static fdio_ns_t* InvalidValue() { return nullptr; } + + static bool IsValid(fdio_ns_t* ns) { return ns != InvalidValue(); } + + static void Free(fdio_ns_t* ns) { + auto status = fdio_ns_destroy(ns); + FML_DCHECK(status == ZX_OK); + } +}; + +using UniqueFDIONS = fml::UniqueObject; + +inline UniqueFDIONS UniqueFDIONSCreate() { + fdio_ns_t* ns = nullptr; + if (fdio_ns_create(&ns) == ZX_OK) { + return UniqueFDIONS{ns}; + } + return UniqueFDIONS{nullptr}; +} + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_UNIQUE_FDIO_NS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vsync_waiter.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vsync_waiter.cc new file mode 100644 index 0000000000000000000000000000000000000000..aa7d3c2ebfe0e7cd07baa7cde3d112de44b15bee --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vsync_waiter.cc @@ -0,0 +1,77 @@ +// 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 "vsync_waiter.h" + +#include + +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/make_copyable.h" +#include "flutter/fml/synchronization/waitable_event.h" +#include "flutter/fml/time/time_delta.h" +#include "flutter/fml/trace_event.h" + +#include "flutter_runner_product_configuration.h" + +namespace flutter_runner { + +VsyncWaiter::VsyncWaiter(AwaitVsyncCallback await_vsync_callback, + AwaitVsyncForSecondaryCallbackCallback + await_vsync_for_secondary_callback_callback, + flutter::TaskRunners task_runners) + : flutter::VsyncWaiter(task_runners), + await_vsync_callback_(await_vsync_callback), + await_vsync_for_secondary_callback_callback_( + await_vsync_for_secondary_callback_callback), + weak_factory_ui_(nullptr), + weak_factory_(this) { + fire_callback_callback_ = [this](fml::TimePoint frame_start, + fml::TimePoint frame_end) { + task_runners_.GetUITaskRunner()->PostTaskForTime( + [frame_start, frame_end, weak_this = weak_ui_]() { + if (weak_this) { + // Note: It is VERY important to set |pause_secondary_tasks| to + // false, else Animator will almost immediately crash on Fuchsia. + // FML_LOG(INFO) << "CRASH:: VsyncWaiter about to FireCallback"; + weak_this->FireCallback(frame_start, frame_end, + /*pause_secondary_tasks*/ false); + } + }, + frame_start); + }; + + // Generate a WeakPtrFactory for use with the UI thread. This does not need + // to wait on a latch because we only ever use the WeakPtrFactory on the UI + // thread so we have ordering guarantees (see ::AwaitVSync()) + fml::TaskRunner::RunNowOrPostTask( + task_runners_.GetUITaskRunner(), fml::MakeCopyable([this]() mutable { + weak_factory_ui_ = + std::make_unique>(this); + weak_ui_ = weak_factory_ui_->GetWeakPtr(); + })); +} + +VsyncWaiter::~VsyncWaiter() { + fml::AutoResetWaitableEvent ui_latch; + fml::TaskRunner::RunNowOrPostTask( + task_runners_.GetUITaskRunner(), + fml::MakeCopyable( + [weak_factory_ui = std::move(weak_factory_ui_), &ui_latch]() mutable { + weak_factory_ui.reset(); + ui_latch.Signal(); + })); + ui_latch.Wait(); +} + +void VsyncWaiter::AwaitVSync() { + await_vsync_callback_(fire_callback_callback_); +} + +void VsyncWaiter::AwaitVSyncForSecondaryCallback() { + await_vsync_for_secondary_callback_callback_(fire_callback_callback_); +} + +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vsync_waiter.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vsync_waiter.h new file mode 100644 index 0000000000000000000000000000000000000000..ce46b90d362a7baecaf8a29176481b174d89b8ce --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vsync_waiter.h @@ -0,0 +1,58 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_VSYNC_WAITER_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_VSYNC_WAITER_H_ + +#include + +#include "flutter/fml/macros.h" +#include "flutter/fml/memory/weak_ptr.h" +#include "flutter/fml/time/time_delta.h" +#include "flutter/fml/time/time_point.h" +#include "flutter/shell/common/vsync_waiter.h" +#include "flutter_runner_product_configuration.h" + +namespace flutter_runner { + +using FireCallbackCallback = + std::function; + +using AwaitVsyncCallback = std::function; + +using AwaitVsyncForSecondaryCallbackCallback = + std::function; + +class VsyncWaiter final : public flutter::VsyncWaiter { + public: + VsyncWaiter(AwaitVsyncCallback await_vsync_callback, + AwaitVsyncForSecondaryCallbackCallback + await_vsync_for_secondary_callback_callback, + flutter::TaskRunners task_runners); + + ~VsyncWaiter() override; + + private: + // |flutter::VsyncWaiter| + void AwaitVSync() override; + + // |flutter::VsyncWaiter| + void AwaitVSyncForSecondaryCallback() override; + + FireCallbackCallback fire_callback_callback_; + + AwaitVsyncCallback await_vsync_callback_; + AwaitVsyncForSecondaryCallbackCallback + await_vsync_for_secondary_callback_callback_; + + fml::WeakPtr weak_ui_; + std::unique_ptr> weak_factory_ui_; + fml::WeakPtrFactory weak_factory_; + + FML_DISALLOW_COPY_AND_ASSIGN(VsyncWaiter); +}; + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_VSYNC_WAITER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vsync_waiter_unittest.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vsync_waiter_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..3be48a61aee6e0e182932826b455452fb1cb551c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vsync_waiter_unittest.cc @@ -0,0 +1,63 @@ +// 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 + +#include + +#include "flutter/fml/task_runner.h" +#include "flutter/shell/common/thread_host.h" +#include "fml/make_copyable.h" +#include "fml/message_loop.h" +#include "fml/synchronization/waitable_event.h" +#include "fml/time/time_delta.h" +#include "fml/time/time_point.h" +#include "vsync_waiter.h" + +namespace flutter_runner { + +TEST(VSyncWaiterFuchsia, FrameScheduledForStartTime) { + using flutter::ThreadHost; + std::string prefix = "vsync_waiter_test"; + + fml::MessageLoop::EnsureInitializedForCurrentThread(); + auto platform_task_runner = fml::MessageLoop::GetCurrent().GetTaskRunner(); + + ThreadHost thread_host = + ThreadHost(prefix, flutter::ThreadHost::Type::kRaster | + flutter::ThreadHost::Type::kUi | + flutter::ThreadHost::Type::kIo); + const flutter::TaskRunners task_runners( + prefix, // Dart thread labels + platform_task_runner, // platform + thread_host.raster_thread->GetTaskRunner(), // raster + thread_host.ui_thread->GetTaskRunner(), // ui + thread_host.io_thread->GetTaskRunner() // io + ); + + // await vsync will invoke the callback right away, but vsync waiter will post + // the task for frame_start time. + VsyncWaiter vsync_waiter( + [](FireCallbackCallback callback) { + const auto now = fml::TimePoint::Now(); + const auto frame_start = now + fml::TimeDelta::FromMilliseconds(20); + const auto frame_end = now + fml::TimeDelta::FromMilliseconds(36); + callback(frame_start, frame_end); + }, + /*secondary callback*/ nullptr, task_runners); + + fml::AutoResetWaitableEvent latch; + task_runners.GetUITaskRunner()->PostTask([&]() { + vsync_waiter.AsyncWaitForVsync( + [&](std::unique_ptr recorder) { + const auto now = fml::TimePoint::Now(); + EXPECT_GT(now, recorder->GetVsyncStartTime()); + latch.Signal(); + }); + }); + + latch.Wait(); +} + +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface.cc new file mode 100644 index 0000000000000000000000000000000000000000..24d5d8eaee2cceb81eca6ecb3f5f71907172b5ba --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface.cc @@ -0,0 +1,554 @@ +// 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 "vulkan_surface.h" + +#include +#include + +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/trace_event.h" +#include "runtime/dart/utils/inlines.h" +#include "third_party/skia/include/core/SkCanvas.h" +#include "third_party/skia/include/core/SkColorSpace.h" +#include "third_party/skia/include/core/SkSurfaceProps.h" +#include "third_party/skia/include/gpu/ganesh/GrBackendSemaphore.h" +#include "third_party/skia/include/gpu/ganesh/GrBackendSurface.h" +#include "third_party/skia/include/gpu/ganesh/GrDirectContext.h" +#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" +#include "third_party/skia/include/gpu/ganesh/vk/GrVkBackendSurface.h" +#include "third_party/skia/include/gpu/ganesh/vk/GrVkTypes.h" +#include "third_party/skia/include/gpu/vk/VulkanTypes.h" +#include "vulkan/vulkan_core.h" +#include "vulkan/vulkan_fuchsia.h" + +#define LOG_AND_RETURN(cond, msg) \ + if (cond) { \ + FML_LOG(ERROR) << msg; \ + return false; \ + } + +namespace flutter_runner { + +namespace { + +constexpr SkColorType kSkiaColorType = kRGBA_8888_SkColorType; +constexpr VkFormat kVulkanFormat = VK_FORMAT_R8G8B8A8_UNORM; +constexpr VkImageCreateFlags kVulkanImageCreateFlags = 0; +// TODO: We should only keep usages that are actually required by Skia. +constexpr VkImageUsageFlags kVkImageUsage = + VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | + VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; +const VkSysmemColorSpaceFUCHSIA kSrgbColorSpace = { + .sType = VK_STRUCTURE_TYPE_SYSMEM_COLOR_SPACE_FUCHSIA, + .pNext = nullptr, + .colorSpace = static_cast(fuchsia::images2::ColorSpace::SRGB), +}; + +} // namespace + +bool VulkanSurface::CreateVulkanImage(vulkan::VulkanProvider& vulkan_provider, + const SkISize& size, + VulkanImage* out_vulkan_image) { + TRACE_EVENT0("flutter", "CreateVulkanImage"); + + FML_CHECK(!size.isEmpty()); + FML_CHECK(out_vulkan_image != nullptr); + + out_vulkan_image->vk_collection_image_create_info = { + .sType = VK_STRUCTURE_TYPE_BUFFER_COLLECTION_IMAGE_CREATE_INFO_FUCHSIA, + .pNext = nullptr, + .collection = collection_, + .index = 0, + }; + + out_vulkan_image->vk_image_create_info = { + .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, + .pNext = &out_vulkan_image->vk_collection_image_create_info, + .flags = kVulkanImageCreateFlags, + .imageType = VK_IMAGE_TYPE_2D, + .format = kVulkanFormat, + .extent = VkExtent3D{static_cast(size.width()), + static_cast(size.height()), 1}, + .mipLevels = 1, + .arrayLayers = 1, + .samples = VK_SAMPLE_COUNT_1_BIT, + .tiling = VK_IMAGE_TILING_OPTIMAL, + .usage = kVkImageUsage, + .sharingMode = VK_SHARING_MODE_EXCLUSIVE, + .queueFamilyIndexCount = 0, + .pQueueFamilyIndices = nullptr, + .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, + }; + + const VkImageFormatConstraintsInfoFUCHSIA format_constraints = { + .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_CONSTRAINTS_INFO_FUCHSIA, + .pNext = nullptr, + .imageCreateInfo = out_vulkan_image->vk_image_create_info, + .requiredFormatFeatures = VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT, + .flags = {}, + .sysmemPixelFormat = {}, + .colorSpaceCount = 1, + .pColorSpaces = &kSrgbColorSpace, + }; + + const VkImageConstraintsInfoFUCHSIA image_constraints = { + .sType = VK_STRUCTURE_TYPE_IMAGE_CONSTRAINTS_INFO_FUCHSIA, + .pNext = nullptr, + .formatConstraintsCount = 1, + .pFormatConstraints = &format_constraints, + .bufferCollectionConstraints = + { + .sType = + VK_STRUCTURE_TYPE_BUFFER_COLLECTION_CONSTRAINTS_INFO_FUCHSIA, + .pNext = nullptr, + .minBufferCount = 1, + // Using the default value 0 means that we don't have any other + // constraints except for the minimum buffer count. + .maxBufferCount = 0, + .minBufferCountForCamping = 0, + .minBufferCountForDedicatedSlack = 0, + .minBufferCountForSharedSlack = 0, + }, + .flags = {}, + }; + + if (VK_CALL_LOG_ERROR( + vulkan_provider.vk().SetBufferCollectionImageConstraintsFUCHSIA( + vulkan_provider.vk_device(), collection_, &image_constraints)) != + VK_SUCCESS) { + return false; + } + + { + VkImage vk_image = VK_NULL_HANDLE; + if (VK_CALL_LOG_ERROR(vulkan_provider.vk().CreateImage( + vulkan_provider.vk_device(), + &out_vulkan_image->vk_image_create_info, nullptr, &vk_image)) != + VK_SUCCESS) { + return false; + } + + out_vulkan_image->vk_image = vulkan::VulkanHandle{ + vk_image, [&vulkan_provider = vulkan_provider](VkImage image) { + vulkan_provider.vk().DestroyImage(vulkan_provider.vk_device(), image, + NULL); + }}; + } + + vulkan_provider.vk().GetImageMemoryRequirements( + vulkan_provider.vk_device(), out_vulkan_image->vk_image, + &out_vulkan_image->vk_memory_requirements); + + return true; +} + +VulkanSurface::VulkanSurface( + vulkan::VulkanProvider& vulkan_provider, + fuchsia::sysmem2::AllocatorSyncPtr& sysmem_allocator, + fuchsia::ui::composition::AllocatorPtr& flatland_allocator, + sk_sp context, + const SkISize& size) + : vulkan_provider_(vulkan_provider), wait_(this) { + FML_CHECK(flatland_allocator.is_bound()); + FML_CHECK(context != nullptr); + + if (!AllocateDeviceMemory(sysmem_allocator, flatland_allocator, + std::move(context), size)) { + FML_LOG(ERROR) << "VulkanSurface: Could not allocate device memory."; + return; + } + + if (!CreateFences()) { + FML_LOG(ERROR) << "VulkanSurface: Could not create signal fences."; + return; + } + + std::fill(size_history_.begin(), size_history_.end(), SkISize::MakeEmpty()); + + wait_.set_object(release_event_.get()); + wait_.set_trigger(ZX_EVENT_SIGNALED); + Reset(); + + valid_ = true; +} + +VulkanSurface::~VulkanSurface() { + if (release_image_callback_) { + release_image_callback_(); + } + wait_.Cancel(); + wait_.set_object(ZX_HANDLE_INVALID); +} + +bool VulkanSurface::IsValid() const { + return valid_; +} + +SkISize VulkanSurface::GetSize() const { + if (!valid_) { + return SkISize::Make(0, 0); + } + + return SkISize::Make(sk_surface_->width(), sk_surface_->height()); +} + +vulkan::VulkanHandle VulkanSurface::SemaphoreFromEvent( + const zx::event& event) const { + VkResult result; + VkSemaphore semaphore; + + zx::event semaphore_event; + zx_status_t status = event.duplicate(ZX_RIGHT_SAME_RIGHTS, &semaphore_event); + if (status != ZX_OK) { + FML_LOG(ERROR) << "VulkanSurface: Failed to duplicate semaphore event"; + return vulkan::VulkanHandle(); + } + + VkSemaphoreCreateInfo create_info = { + .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, + .pNext = nullptr, + .flags = 0, + }; + + result = VK_CALL_LOG_ERROR(vulkan_provider_.vk().CreateSemaphore( + vulkan_provider_.vk_device(), &create_info, nullptr, &semaphore)); + if (result != VK_SUCCESS) { + return vulkan::VulkanHandle(); + } + + VkImportSemaphoreZirconHandleInfoFUCHSIA import_info = { + .sType = VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_ZIRCON_HANDLE_INFO_FUCHSIA, + .pNext = nullptr, + .semaphore = semaphore, + .handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_ZIRCON_EVENT_BIT_FUCHSIA, + .zirconHandle = static_cast(semaphore_event.release())}; + + result = VK_CALL_LOG_ERROR( + vulkan_provider_.vk().ImportSemaphoreZirconHandleFUCHSIA( + vulkan_provider_.vk_device(), &import_info)); + if (result != VK_SUCCESS) { + return vulkan::VulkanHandle(); + } + + return vulkan::VulkanHandle( + semaphore, [&vulkan_provider = vulkan_provider_](VkSemaphore semaphore) { + vulkan_provider.vk().DestroySemaphore(vulkan_provider.vk_device(), + semaphore, nullptr); + }); +} + +bool VulkanSurface::CreateFences() { + if (zx::event::create(0, &acquire_event_) != ZX_OK) { + FML_LOG(ERROR) << "VulkanSurface: Failed to create acquire event"; + return false; + } + + acquire_semaphore_ = SemaphoreFromEvent(acquire_event_); + if (!acquire_semaphore_) { + FML_LOG(ERROR) << "VulkanSurface: Failed to create acquire semaphore"; + return false; + } + + if (zx::event::create(0, &release_event_) != ZX_OK) { + FML_LOG(ERROR) << "VulkanSurface: Failed to create release event"; + return false; + } + + command_buffer_fence_ = vulkan_provider_.CreateFence(); + + return true; +} + +bool VulkanSurface::AllocateDeviceMemory( + fuchsia::sysmem2::AllocatorSyncPtr& sysmem_allocator, + fuchsia::ui::composition::AllocatorPtr& flatland_allocator, + sk_sp context, + const SkISize& size) { + if (size.isEmpty()) { + FML_LOG(ERROR) + << "VulkanSurface: Failed to allocate surface, size is empty"; + return false; + } + + fuchsia::sysmem2::BufferCollectionTokenSyncPtr vulkan_token; + zx_status_t status = sysmem_allocator->AllocateSharedCollection( + std::move(fuchsia::sysmem2::AllocatorAllocateSharedCollectionRequest{} + .set_token_request(vulkan_token.NewRequest()))); + LOG_AND_RETURN(status != ZX_OK, + "VulkanSurface: Failed to allocate collection"); + fuchsia::sysmem2::BufferCollectionTokenSyncPtr scenic_token; + status = vulkan_token->Duplicate( + std::move(fuchsia::sysmem2::BufferCollectionTokenDuplicateRequest{} + .set_rights_attenuation_mask(ZX_RIGHT_SAME_RIGHTS) + .set_token_request(scenic_token.NewRequest()))); + LOG_AND_RETURN(status != ZX_OK, + "VulkanSurface: Failed to duplicate collection token"); + fuchsia::sysmem2::Node_Sync_Result sync_result; + status = vulkan_token->Sync(&sync_result); + LOG_AND_RETURN(status != ZX_OK, + "VulkanSurface: Failed to sync collection token"); + + fuchsia::ui::composition::BufferCollectionExportToken export_token; + status = zx::eventpair::create(0, &export_token.value, &import_token_.value); + + fuchsia::ui::composition::RegisterBufferCollectionArgs args; + args.set_export_token(std::move(export_token)); + args.set_buffer_collection_token2(std::move(scenic_token)); + args.set_usage( + fuchsia::ui::composition::RegisterBufferCollectionUsage::DEFAULT); + flatland_allocator->RegisterBufferCollection( + std::move(args), + [](fuchsia::ui::composition::Allocator_RegisterBufferCollection_Result + result) { + if (result.is_err()) { + FML_LOG(ERROR) + << "RegisterBufferCollection call to Scenic Allocator failed"; + } + }); + + VkBufferCollectionCreateInfoFUCHSIA import_info{ + .sType = VK_STRUCTURE_TYPE_BUFFER_COLLECTION_CREATE_INFO_FUCHSIA, + .pNext = nullptr, + .collectionToken = vulkan_token.Unbind().TakeChannel().release(), + }; + VkBufferCollectionFUCHSIA collection; + if (VK_CALL_LOG_ERROR(vulkan_provider_.vk().CreateBufferCollectionFUCHSIA( + vulkan_provider_.vk_device(), &import_info, nullptr, &collection)) != + VK_SUCCESS) { + return false; + } + + collection_ = vulkan::VulkanHandle{ + collection, [&vulkan_provider = + vulkan_provider_](VkBufferCollectionFUCHSIA collection) { + vulkan_provider.vk().DestroyBufferCollectionFUCHSIA( + vulkan_provider.vk_device(), collection, nullptr); + }}; + + VulkanImage vulkan_image; + LOG_AND_RETURN(!CreateVulkanImage(vulkan_provider_, size, &vulkan_image), + "VulkanSurface: Failed to create VkImage"); + + vulkan_image_ = std::move(vulkan_image); + const VkMemoryRequirements& memory_requirements = + vulkan_image_.vk_memory_requirements; + VkImageCreateInfo& image_create_info = vulkan_image_.vk_image_create_info; + + VkBufferCollectionPropertiesFUCHSIA properties{ + .sType = VK_STRUCTURE_TYPE_BUFFER_COLLECTION_PROPERTIES_FUCHSIA}; + if (VK_CALL_LOG_ERROR( + vulkan_provider_.vk().GetBufferCollectionPropertiesFUCHSIA( + vulkan_provider_.vk_device(), collection_, &properties)) != + VK_SUCCESS) { + return false; + } + + VkImportMemoryBufferCollectionFUCHSIA import_memory_info = { + .sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_BUFFER_COLLECTION_FUCHSIA, + .pNext = nullptr, + .collection = collection_, + .index = 0, + }; + auto bits = memory_requirements.memoryTypeBits & properties.memoryTypeBits; + FML_DCHECK(bits != 0); + VkMemoryAllocateInfo allocation_info = { + .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + .pNext = &import_memory_info, + .allocationSize = memory_requirements.size, + .memoryTypeIndex = static_cast(__builtin_ctz(bits)), + }; + + { + TRACE_EVENT1("flutter", "vkAllocateMemory", "allocationSize", + allocation_info.allocationSize); + VkDeviceMemory vk_memory = VK_NULL_HANDLE; + if (VK_CALL_LOG_ERROR(vulkan_provider_.vk().AllocateMemory( + vulkan_provider_.vk_device(), &allocation_info, NULL, + &vk_memory)) != VK_SUCCESS) { + return false; + } + + vk_memory_ = vulkan::VulkanHandle{ + vk_memory, + [&vulkan_provider = vulkan_provider_](VkDeviceMemory memory) { + vulkan_provider.vk().FreeMemory(vulkan_provider.vk_device(), memory, + NULL); + }}; + + vk_memory_info_ = allocation_info; + } + + // Bind image memory. + if (VK_CALL_LOG_ERROR(vulkan_provider_.vk().BindImageMemory( + vulkan_provider_.vk_device(), vulkan_image_.vk_image, vk_memory_, + 0)) != VK_SUCCESS) { + return false; + } + + return SetupSkiaSurface(std::move(context), size, kSkiaColorType, + image_create_info, memory_requirements); +} + +bool VulkanSurface::SetupSkiaSurface(sk_sp context, + const SkISize& size, + SkColorType color_type, + const VkImageCreateInfo& image_create_info, + const VkMemoryRequirements& memory_reqs) { + FML_CHECK(context != nullptr); + + skgpu::VulkanAlloc alloc; + alloc.fMemory = vk_memory_; + alloc.fOffset = 0; + alloc.fSize = memory_reqs.size; + alloc.fFlags = 0; + + GrVkImageInfo image_info; + image_info.fImage = vulkan_image_.vk_image; + image_info.fAlloc = alloc; + image_info.fImageTiling = image_create_info.tiling; + image_info.fImageLayout = image_create_info.initialLayout; + image_info.fFormat = image_create_info.format; + image_info.fImageUsageFlags = image_create_info.usage; + image_info.fSampleCount = 1; + image_info.fLevelCount = image_create_info.mipLevels; + + auto sk_render_target = + GrBackendRenderTargets::MakeVk(size.width(), size.height(), image_info); + + SkSurfaceProps sk_surface_props(0, kUnknown_SkPixelGeometry); + + auto sk_surface = + SkSurfaces::WrapBackendRenderTarget(context.get(), // + sk_render_target, // + kTopLeft_GrSurfaceOrigin, // + color_type, // + SkColorSpace::MakeSRGB(), // + &sk_surface_props // + ); + + if (!sk_surface || sk_surface->getCanvas() == nullptr) { + FML_LOG(ERROR) + << "VulkanSurface: SkSurfaces::WrapBackendRenderTarget failed"; + return false; + } + sk_surface_ = std::move(sk_surface); + + return true; +} + +void VulkanSurface::SetImageId(uint32_t image_id) { + FML_CHECK(image_id_ == 0); + image_id_ = image_id; +} + +uint32_t VulkanSurface::GetImageId() { + return image_id_; +} + +sk_sp VulkanSurface::GetSkiaSurface() const { + return valid_ ? sk_surface_ : nullptr; +} + +fuchsia::ui::composition::BufferCollectionImportToken +VulkanSurface::GetBufferCollectionImportToken() { + fuchsia::ui::composition::BufferCollectionImportToken import_dup; + import_token_.value.duplicate(ZX_RIGHT_SAME_RIGHTS, &import_dup.value); + return import_dup; +} + +zx::event VulkanSurface::GetAcquireFence() { + zx::event fence; + acquire_event_.duplicate(ZX_RIGHT_SAME_RIGHTS, &fence); + return fence; +} + +zx::event VulkanSurface::GetReleaseFence() { + zx::event fence; + release_event_.duplicate(ZX_RIGHT_SAME_RIGHTS, &fence); + return fence; +} +void VulkanSurface::SetReleaseImageCallback( + ReleaseImageCallback release_image_callback) { + release_image_callback_ = release_image_callback; +} + +size_t VulkanSurface::AdvanceAndGetAge() { + size_history_[size_history_index_] = GetSize(); + size_history_index_ = (size_history_index_ + 1) % kSizeHistorySize; + age_++; + return age_; +} + +bool VulkanSurface::FlushSessionAcquireAndReleaseEvents() { + age_ = 0; + return true; +} + +void VulkanSurface::SignalWritesFinished( + const std::function& on_writes_committed) { + FML_CHECK(on_writes_committed); + + if (!valid_) { + on_writes_committed(); + return; + } + + FML_CHECK(pending_on_writes_committed_ == nullptr) + << "Attempted to signal a write on the surface when the " + "previous write has not yet been acknowledged by the " + "compositor."; + + pending_on_writes_committed_ = on_writes_committed; +} + +void VulkanSurface::Reset() { + if (acquire_event_.signal(ZX_EVENT_SIGNALED, 0u) != ZX_OK || + release_event_.signal(ZX_EVENT_SIGNALED, 0u) != ZX_OK) { + valid_ = false; + FML_LOG(ERROR) << "Could not reset fences. The surface is no longer valid."; + } + + VkFence fence = command_buffer_fence_; + + if (command_buffer_) { + VK_CALL_LOG_FATAL(vulkan_provider_.vk().WaitForFences( + vulkan_provider_.vk_device(), 1, &fence, VK_TRUE, UINT64_MAX)); + command_buffer_.reset(); + } + + VK_CALL_LOG_ERROR(vulkan_provider_.vk().ResetFences( + vulkan_provider_.vk_device(), 1, &fence)); + + // Need to make a new acquire semaphore every frame or else validation layers + // get confused about why no one is waiting on it in this VkInstance + acquire_semaphore_.Reset(); + acquire_semaphore_ = SemaphoreFromEvent(acquire_event_); + if (!acquire_semaphore_) { + FML_LOG(ERROR) << "failed to create acquire semaphore"; + } + + wait_.Begin(async_get_default_dispatcher()); + + // It is safe for the caller to collect the surface in the callback. + auto callback = pending_on_writes_committed_; + pending_on_writes_committed_ = nullptr; + if (callback) { + callback(); + } +} + +void VulkanSurface::OnHandleReady(async_dispatcher_t* dispatcher, + async::WaitBase* wait, + zx_status_t status, + const zx_packet_signal_t* signal) { + if (status != ZX_OK) + return; + FML_DCHECK(signal->observed & ZX_EVENT_SIGNALED); + Reset(); +} + +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface.h new file mode 100644 index 0000000000000000000000000000000000000000..3e051b14763527df7e1b4737c451dd5261c610fa --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface.h @@ -0,0 +1,187 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_VULKAN_SURFACE_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_VULKAN_SURFACE_H_ + +#include +#include +#include +#include + +#include +#include +#include + +#include "flutter/fml/macros.h" +#include "flutter/vulkan/procs/vulkan_handle.h" +#include "flutter/vulkan/procs/vulkan_proc_table.h" +#include "flutter/vulkan/vulkan_command_buffer.h" +#include "flutter/vulkan/vulkan_provider.h" +#include "third_party/skia/include/core/SkColorType.h" +#include "third_party/skia/include/core/SkRefCnt.h" +#include "third_party/skia/include/core/SkSize.h" +#include "third_party/skia/include/core/SkSurface.h" + +#include "surface_producer.h" + +namespace flutter_runner { + +// A |VkImage| and its relevant metadata. +struct VulkanImage { + VulkanImage() = default; + VulkanImage(VulkanImage&&) = default; + VulkanImage& operator=(VulkanImage&&) = default; + + VkBufferCollectionImageCreateInfoFUCHSIA vk_collection_image_create_info; + VkImageCreateInfo vk_image_create_info; + VkMemoryRequirements vk_memory_requirements; + vulkan::VulkanHandle vk_image; + + FML_DISALLOW_COPY_AND_ASSIGN(VulkanImage); +}; + +class VulkanSurface final : public SurfaceProducerSurface { + public: + VulkanSurface(vulkan::VulkanProvider& vulkan_provider, + fuchsia::sysmem2::AllocatorSyncPtr& sysmem_allocator, + fuchsia::ui::composition::AllocatorPtr& flatland_allocator, + sk_sp context, + const SkISize& size); + + ~VulkanSurface() override; + + // |SurfaceProducerSurface| + size_t AdvanceAndGetAge() override; + + // |SurfaceProducerSurface| + bool FlushSessionAcquireAndReleaseEvents() override; + + // |SurfaceProducerSurface| + bool IsValid() const override; + + // |SurfaceProducerSurface| + SkISize GetSize() const override; + + // Note: It is safe for the caller to collect the surface in the + // |on_writes_committed| callback. + void SignalWritesFinished( + const std::function& on_writes_committed) override; + + // |SurfaceProducerSurface| + void SetImageId(uint32_t image_id) override; + + // |SurfaceProducerSurface| + uint32_t GetImageId() override; + + // |SurfaceProducerSurface| + sk_sp GetSkiaSurface() const override; + + // |SurfaceProducerSurface| + fuchsia::ui::composition::BufferCollectionImportToken + GetBufferCollectionImportToken() override; + + // |SurfaceProducerSurface| + zx::event GetAcquireFence() override; + + // |SurfaceProducerSurface| + zx::event GetReleaseFence() override; + + // |SurfaceProducerSurface| + void SetReleaseImageCallback( + ReleaseImageCallback release_image_callback) override; + + const vulkan::VulkanHandle& GetVkImage() { + return vulkan_image_.vk_image; + } + + const vulkan::VulkanHandle& GetAcquireVkSemaphore() { + return acquire_semaphore_; + } + + vulkan::VulkanCommandBuffer* GetCommandBuffer( + const vulkan::VulkanHandle& pool) { + if (!command_buffer_) + command_buffer_ = std::make_unique( + vulkan_provider_.vk(), vulkan_provider_.vk_device(), pool); + return command_buffer_.get(); + } + + const vulkan::VulkanHandle& GetCommandBufferFence() { + return command_buffer_fence_; + } + + size_t GetAllocationSize() const { return vk_memory_info_.allocationSize; } + + size_t GetImageMemoryRequirementsSize() const { + return vulkan_image_.vk_memory_requirements.size; + } + + bool IsOversized() const { + return GetAllocationSize() > GetImageMemoryRequirementsSize(); + } + + bool HasStableSizeHistory() const { + return std::equal(size_history_.begin() + 1, size_history_.end(), + size_history_.begin()); + } + + private: + static constexpr int kSizeHistorySize = 4; + + void OnHandleReady(async_dispatcher_t* dispatcher, + async::WaitBase* wait, + zx_status_t status, + const zx_packet_signal_t* signal); + + bool AllocateDeviceMemory( + fuchsia::sysmem2::AllocatorSyncPtr& sysmem_allocator, + fuchsia::ui::composition::AllocatorPtr& flatland_allocator, + sk_sp context, + const SkISize& size); + + bool CreateVulkanImage(vulkan::VulkanProvider& vulkan_provider, + const SkISize& size, + VulkanImage* out_vulkan_image); + + bool SetupSkiaSurface(sk_sp context, + const SkISize& size, + SkColorType color_type, + const VkImageCreateInfo& image_create_info, + const VkMemoryRequirements& memory_reqs); + + bool CreateFences(); + + void Reset(); + + vulkan::VulkanHandle SemaphoreFromEvent( + const zx::event& event) const; + + vulkan::VulkanProvider& vulkan_provider_; + VulkanImage vulkan_image_; + vulkan::VulkanHandle vk_memory_; + VkMemoryAllocateInfo vk_memory_info_; + vulkan::VulkanHandle command_buffer_fence_; + sk_sp sk_surface_; + fuchsia::ui::composition::BufferCollectionImportToken import_token_; + uint32_t image_id_ = 0; + vulkan::VulkanHandle collection_; + zx::event acquire_event_; + vulkan::VulkanHandle acquire_semaphore_; + std::unique_ptr command_buffer_; + zx::event release_event_; + async::WaitMethod wait_; + std::function pending_on_writes_committed_; + std::array size_history_; + int size_history_index_ = 0; + size_t age_ = 0; + bool valid_ = false; + ReleaseImageCallback release_image_callback_; + + FML_DISALLOW_COPY_AND_ASSIGN(VulkanSurface); +}; + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_VULKAN_SURFACE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface_pool.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface_pool.cc new file mode 100644 index 0000000000000000000000000000000000000000..a0df602dd76e8090f23bc2c5ee85c9be01b6c974 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface_pool.cc @@ -0,0 +1,270 @@ +// 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 "vulkan_surface_pool.h" + +#include +#include + +#include +#include + +#include "flutter/fml/trace_event.h" +#include "third_party/skia/include/gpu/ganesh/GrDirectContext.h" + +namespace flutter_runner { + +static std::string GetCurrentProcessName() { + char name[ZX_MAX_NAME_LEN]; + zx_status_t status = + zx::process::self()->get_property(ZX_PROP_NAME, name, sizeof(name)); + return status == ZX_OK ? std::string(name) : std::string(); +} + +static zx_koid_t GetCurrentProcessId() { + zx_info_handle_basic_t info; + zx_status_t status = zx::process::self()->get_info( + ZX_INFO_HANDLE_BASIC, &info, sizeof(info), nullptr, nullptr); + return status == ZX_OK ? info.koid : ZX_KOID_INVALID; +} + +VulkanSurfacePool::VulkanSurfacePool(vulkan::VulkanProvider& vulkan_provider, + sk_sp context) + : vulkan_provider_(vulkan_provider), context_(std::move(context)) { + FML_CHECK(context_ != nullptr); + + zx_status_t status = fdio_service_connect( + "/svc/fuchsia.sysmem2.Allocator", + sysmem_allocator_.NewRequest().TakeChannel().release()); + sysmem_allocator_->SetDebugClientInfo( + std::move(fuchsia::sysmem2::AllocatorSetDebugClientInfoRequest{} + .set_name(GetCurrentProcessName()) + .set_id(GetCurrentProcessId()))); + FML_DCHECK(status == ZX_OK); + + status = fdio_service_connect( + "/svc/fuchsia.ui.composition.Allocator", + flatland_allocator_.NewRequest().TakeChannel().release()); + FML_DCHECK(status == ZX_OK); +} + +VulkanSurfacePool::~VulkanSurfacePool() {} + +std::unique_ptr VulkanSurfacePool::AcquireSurface( + const SkISize& size) { + auto surface = GetCachedOrCreateSurface(size); + + if (surface == nullptr) { + FML_LOG(ERROR) << "VulkanSurfaceProducer: Could not acquire surface"; + return nullptr; + } + + if (!surface->FlushSessionAcquireAndReleaseEvents()) { + FML_LOG(ERROR) << "VulkanSurfaceProducer: Could not flush acquire/release " + "events for buffer."; + return nullptr; + } + + return surface; +} + +std::unique_ptr VulkanSurfacePool::GetCachedOrCreateSurface( + const SkISize& size) { + TRACE_EVENT2("flutter", "VulkanSurfacePool::GetCachedOrCreateSurface", + "width", size.width(), "height", size.height()); + // First try to find a surface that exactly matches |size|. + { + auto exact_match_it = + std::find_if(available_surfaces_.begin(), available_surfaces_.end(), + [&size](const auto& surface) { + return surface->IsValid() && surface->GetSize() == size; + }); + if (exact_match_it != available_surfaces_.end()) { + auto acquired_surface = std::move(*exact_match_it); + available_surfaces_.erase(exact_match_it); + TRACE_EVENT_INSTANT0("flutter", "Exact match found"); + return acquired_surface; + } + } + + return CreateSurface(size); +} + +void VulkanSurfacePool::SubmitSurface( + std::unique_ptr p_surface) { + TRACE_EVENT0("flutter", "VulkanSurfacePool::SubmitSurface"); + + // This cast is safe because |VulkanSurface| is the only implementation of + // |SurfaceProducerSurface| for Flutter on Fuchsia. Additionally, it is + // required, because we need to access |VulkanSurface| specific information + // of the surface (such as the amount of VkDeviceMemory it contains). + auto vulkan_surface = std::unique_ptr( + static_cast(p_surface.release())); + if (!vulkan_surface) { + return; + } + + uintptr_t surface_key = reinterpret_cast(vulkan_surface.get()); + auto insert_iterator = pending_surfaces_.insert(std::make_pair( + surface_key, // key + std::move(vulkan_surface) // value + )); + if (insert_iterator.second) { + insert_iterator.first->second->SignalWritesFinished(std::bind( + &VulkanSurfacePool::RecyclePendingSurface, this, surface_key)); + } +} + +std::unique_ptr VulkanSurfacePool::CreateSurface( + const SkISize& size) { + TRACE_EVENT2("flutter", "VulkanSurfacePool::CreateSurface", "width", + size.width(), "height", size.height()); + auto surface = std::make_unique( + vulkan_provider_, sysmem_allocator_, flatland_allocator_, context_, size); + if (!surface->IsValid()) { + FML_LOG(ERROR) << "VulkanSurfaceProducer: Created surface is invalid"; + return nullptr; + } + trace_surfaces_created_++; + return surface; +} + +void VulkanSurfacePool::RecyclePendingSurface(uintptr_t surface_key) { + // Before we do anything, we must clear the surface from the collection of + // pending surfaces. + auto found_in_pending = pending_surfaces_.find(surface_key); + if (found_in_pending == pending_surfaces_.end()) { + return; + } + + // Grab a hold of the surface to recycle and clear the entry in the pending + // surfaces collection. + auto surface_to_recycle = std::move(found_in_pending->second); + pending_surfaces_.erase(found_in_pending); + + RecycleSurface(std::move(surface_to_recycle)); +} + +void VulkanSurfacePool::RecycleSurface(std::unique_ptr surface) { + // The surface may have become invalid (for example it the fences could + // not be reset). + if (!surface->IsValid()) { + return; + } + + TRACE_EVENT0("flutter", "VulkanSurfacePool::RecycleSurface"); + // Recycle the buffer by putting it in the list of available surfaces if we + // have not reached the maximum amount of cached surfaces. + if (available_surfaces_.size() < kMaxSurfaces) { + available_surfaces_.push_back(std::move(surface)); + } else { + TRACE_EVENT_INSTANT0("flutter", "Too many surfaces in pool, dropping"); + } + TraceStats(); +} + +void VulkanSurfacePool::AgeAndCollectOldBuffers() { + TRACE_EVENT0("flutter", "VulkanSurfacePool::AgeAndCollectOldBuffers"); + + // Remove all surfaces that are no longer valid or are too old. + size_t size_before = available_surfaces_.size(); + available_surfaces_.erase( + std::remove_if(available_surfaces_.begin(), available_surfaces_.end(), + [&](auto& surface) { + return !surface->IsValid() || + surface->AdvanceAndGetAge() >= kMaxSurfaceAge; + }), + available_surfaces_.end()); + TRACE_EVENT1("flutter", "AgeAndCollect", "aged surfaces", + (size_before - available_surfaces_.size())); + + // Look for a surface that has both a larger |VkDeviceMemory| allocation + // than is necessary for its |VkImage|, and has a stable size history. + auto surface_to_remove_it = std::find_if( + available_surfaces_.begin(), available_surfaces_.end(), + [](const auto& surface) { + return surface->IsOversized() && surface->HasStableSizeHistory(); + }); + // If we found such a surface, then destroy it and cache a new one that only + // uses a necessary amount of memory. + if (surface_to_remove_it != available_surfaces_.end()) { + TRACE_EVENT_INSTANT0("flutter", "replacing surface with smaller one"); + auto size = (*surface_to_remove_it)->GetSize(); + available_surfaces_.erase(surface_to_remove_it); + auto new_surface = CreateSurface(size); + if (new_surface != nullptr) { + available_surfaces_.push_back(std::move(new_surface)); + } else { + FML_LOG(ERROR) + << "VulkanSurfaceProducer: Failed to create a new shrunk surface"; + } + } + + TraceStats(); +} + +void VulkanSurfacePool::ShrinkToFit() { + TRACE_EVENT0("flutter", "VulkanSurfacePool::ShrinkToFit"); + // Reset all oversized surfaces in |available_surfaces_| so that the old + // surfaces and new surfaces don't exist at the same time at any point, + // reducing our peak memory footprint. + std::vector sizes_to_recreate; + for (auto& surface : available_surfaces_) { + if (surface->IsOversized()) { + sizes_to_recreate.push_back(surface->GetSize()); + surface.reset(); + } + } + available_surfaces_.erase(std::remove(available_surfaces_.begin(), + available_surfaces_.end(), nullptr), + available_surfaces_.end()); + for (const auto& size : sizes_to_recreate) { + auto surface = CreateSurface(size); + if (surface != nullptr) { + available_surfaces_.push_back(std::move(surface)); + } else { + FML_LOG(ERROR) + << "VulkanSurfaceProducer: Failed to create resized surface"; + } + } + + TraceStats(); +} + +void VulkanSurfacePool::TraceStats() { + // Resources held in cached buffers. + size_t cached_surfaces_bytes = 0; + for (const auto& surface : available_surfaces_) { + cached_surfaces_bytes += surface->GetAllocationSize(); + } + + // Resources held by Skia. + int skia_resources = 0; + size_t skia_bytes = 0; + context_->getResourceCacheUsage(&skia_resources, &skia_bytes); + const size_t skia_cache_purgeable = + context_->getResourceCachePurgeableBytes(); + + TRACE_COUNTER("flutter", "SurfacePoolCounts", 0u, "CachedCount", + available_surfaces_.size(), // + "Created", trace_surfaces_created_, // + "Reused", trace_surfaces_reused_, // + "PendingInCompositor", pending_surfaces_.size(), // + "Retained", 0, // + "SkiaCacheResources", skia_resources // + ); + + TRACE_COUNTER("flutter", "SurfacePoolBytes", 0u, // + "CachedBytes", cached_surfaces_bytes, // + "RetainedBytes", 0, // + "SkiaCacheBytes", skia_bytes, // + "SkiaCachePurgeable", skia_cache_purgeable // + ); + + // Reset per present/frame stats. + trace_surfaces_created_ = 0; + trace_surfaces_reused_ = 0; +} + +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface_pool.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface_pool.h new file mode 100644 index 0000000000000000000000000000000000000000..df4d0b994ad1b7fc24fb775cd3d6ba75a181d668 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface_pool.h @@ -0,0 +1,67 @@ +// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_VULKAN_SURFACE_POOL_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_VULKAN_SURFACE_POOL_H_ + +#include + +#include +#include + +#include "flutter/fml/macros.h" +#include "vulkan_surface.h" + +namespace flutter_runner { + +class VulkanSurfacePool final { + public: + // Only keep 12 surfaces at a time. This value was based on how many + // surfaces got cached in the old, exact-match-only caching logic. + static constexpr int kMaxSurfaces = 12; + // If a surface doesn't get used for 3 or more generations, we discard it. + static constexpr int kMaxSurfaceAge = 3; + + VulkanSurfacePool(vulkan::VulkanProvider& vulkan_provider, + sk_sp context); + + ~VulkanSurfacePool(); + + std::unique_ptr CreateSurface(const SkISize& size); + std::unique_ptr AcquireSurface(const SkISize& size); + + void SubmitSurface(std::unique_ptr surface); + + void AgeAndCollectOldBuffers(); + + // Shrink all oversized |VulkanSurfaces| in |available_surfaces_| to as + // small as they can be. + void ShrinkToFit(); + + private: + vulkan::VulkanProvider& vulkan_provider_; + sk_sp context_; + fuchsia::sysmem2::AllocatorSyncPtr sysmem_allocator_; + fuchsia::ui::composition::AllocatorPtr flatland_allocator_; + std::vector> available_surfaces_; + std::unordered_map> + pending_surfaces_; + + size_t trace_surfaces_created_ = 0; + size_t trace_surfaces_reused_ = 0; + + std::unique_ptr GetCachedOrCreateSurface(const SkISize& size); + + void RecycleSurface(std::unique_ptr surface); + + void RecyclePendingSurface(uintptr_t surface_key); + + void TraceStats(); + + FML_DISALLOW_COPY_AND_ASSIGN(VulkanSurfacePool); +}; + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_VULKAN_SURFACE_POOL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface_producer.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface_producer.cc new file mode 100644 index 0000000000000000000000000000000000000000..3b86007400bc09f7dce0191f8da50408d869f232 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface_producer.cc @@ -0,0 +1,293 @@ +// 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 "vulkan_surface_producer.h" + +#include +#include + +#include +#include +#include + +#include "flutter/fml/trace_event.h" +#include "flutter/vulkan/vulkan_skia_proc_table.h" +#include "flutter_vma/flutter_skia_vma.h" + +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/include/gpu/ganesh/GrBackendSemaphore.h" +#include "third_party/skia/include/gpu/ganesh/GrBackendSurface.h" +#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" +#include "third_party/skia/include/gpu/ganesh/vk/GrVkBackendSurface.h" +#include "third_party/skia/include/gpu/ganesh/vk/GrVkDirectContext.h" +#include "third_party/skia/include/gpu/ganesh/vk/GrVkTypes.h" +#include "third_party/skia/include/gpu/vk/VulkanBackendContext.h" +#include "third_party/skia/include/gpu/vk/VulkanExtensions.h" + +namespace flutter_runner { + +namespace { + +// Tuning advice: +// If you see the following 3 things happening simultaneously in a trace: +// * Over budget ("flutter", "GPURasterizer::Draw") durations +// * Many ("skia", "GrGpu::createTexture") events within the +// "GPURasterizer::Draw"s +// * The Skia GPU resource cache is full, as indicated by the +// "SkiaCacheBytes" field in the ("flutter", "SurfacePool") trace counter +// (compare it to the bytes value here) +// then you should consider increasing the size of the GPU resource cache. +constexpr size_t kGrCacheMaxByteSize = 1024 * 600 * 12 * 4; + +} // namespace + +VulkanSurfaceProducer::VulkanSurfaceProducer() { + valid_ = Initialize(); + + if (!valid_) { + FML_LOG(FATAL) << "VulkanSurfaceProducer: Initialization failed"; + } +} + +VulkanSurfaceProducer::~VulkanSurfaceProducer() { + // Make sure queue is idle before we start destroying surfaces + if (valid_) { + VkResult wait_result = VK_CALL_LOG_ERROR( + vk_->QueueWaitIdle(logical_device_->GetQueueHandle())); + FML_DCHECK(wait_result == VK_SUCCESS); + } +}; + +bool VulkanSurfaceProducer::Initialize() { + vk_ = fml::MakeRefCounted(); + + std::vector extensions = { + VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_EXTENSION_NAME, + }; + + // On Fuchsia, the validation layers need to be packaged as part of the + // flutter_runner in order to work. As a result, we can use the presence + // of the layers to mean that we want the layers enabled. + application_ = std::make_unique( + *vk_, "FlutterRunner", std::move(extensions), VK_MAKE_VERSION(1, 0, 0), + VK_MAKE_VERSION(1, 1, 0), true /* enable_validation_layers */); + + if (!application_->IsValid() || !vk_->AreInstanceProcsSetup()) { + // Make certain the application instance was created and it set up the + // instance proc table entries. + FML_LOG(ERROR) << "VulkanSurfaceProducer: Instance proc addresses have not " + "been set up."; + return false; + } + + // Create the device. + + logical_device_ = application_->AcquireFirstCompatibleLogicalDevice(); + + if (logical_device_ == nullptr || !logical_device_->IsValid() || + !vk_->AreDeviceProcsSetup()) { + // Make certain the device was created and it set up the device proc table + // entries. + FML_LOG(ERROR) + << "VulkanSurfaceProducer: Device proc addresses have not been set up."; + return false; + } + + if (!vk_->HasAcquiredMandatoryProcAddresses()) { + FML_LOG(ERROR) + << "VulkanSurfaceProducer: Failed to acquire mandatory proc addresses."; + return false; + } + + if (!vk_->IsValid()) { + FML_LOG(ERROR) << "VulkanSurfaceProducer: VulkanProcTable invalid"; + return false; + } + + auto getProc = CreateSkiaGetProc(vk_); + + if (getProc == nullptr) { + FML_LOG(ERROR) << "VulkanSurfaceProducer: Failed to create skia getProc."; + return false; + } + + VkPhysicalDeviceFeatures features; + if (!logical_device_->GetPhysicalDeviceFeatures(&features)) { + FML_LOG(ERROR) + << "VulkanSurfaceProducer: Failed to get physical device features."; + + return false; + } + + memory_allocator_ = flutter::FlutterSkiaVulkanMemoryAllocator::Make( + application_->GetAPIVersion(), application_->GetInstance(), + logical_device_->GetPhysicalDeviceHandle(), logical_device_->GetHandle(), + vk_, true); + + skgpu::VulkanBackendContext backend_context; + backend_context.fInstance = application_->GetInstance(); + backend_context.fPhysicalDevice = logical_device_->GetPhysicalDeviceHandle(); + backend_context.fDevice = logical_device_->GetHandle(); + backend_context.fQueue = logical_device_->GetQueueHandle(); + backend_context.fGraphicsQueueIndex = + logical_device_->GetGraphicsQueueIndex(); + backend_context.fMaxAPIVersion = application_->GetAPIVersion(); + backend_context.fDeviceFeatures = &features; + backend_context.fGetProc = std::move(getProc); + backend_context.fMemoryAllocator = memory_allocator_; + + // The memory_requirements_2 extension is required on Fuchsia as the AMD + // memory allocator used by Skia benefit from it. + const char* device_extensions[] = { + VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME, + }; + const int device_extensions_count = + sizeof(device_extensions) / sizeof(device_extensions[0]); + skgpu::VulkanExtensions vk_extensions; + vk_extensions.init(backend_context.fGetProc, backend_context.fInstance, + backend_context.fPhysicalDevice, 0, nullptr, + device_extensions_count, device_extensions); + backend_context.fVkExtensions = &vk_extensions; + GrContextOptions options; + options.fReduceOpsTaskSplitting = GrContextOptions::Enable::kNo; + + context_ = GrDirectContexts::MakeVulkan(backend_context, options); + + if (context_ == nullptr) { + FML_LOG(ERROR) + << "VulkanSurfaceProducer: Failed to create GrDirectContext."; + return false; + } + + // Use local limits specified in this file above instead of flutter defaults. + context_->setResourceCacheLimit(kGrCacheMaxByteSize); + + surface_pool_ = std::make_unique(*this, context_); + + return true; +} + +void VulkanSurfaceProducer::SubmitSurfaces( + std::vector> surfaces) { + TRACE_EVENT0("flutter", "VulkanSurfaceProducer::SubmitSurfaces"); + + // Do a single flush for all canvases derived from the context. + { + TRACE_EVENT0("flutter", "GrDirectContext::flushAndSignalSemaphores"); + context_->flushAndSubmit(); + } + + if (!TransitionSurfacesToExternal(surfaces)) + FML_LOG(ERROR) << "TransitionSurfacesToExternal failed"; + + // Submit surface + for (auto& surface : surfaces) { + SubmitSurface(std::move(surface)); + } + + // Buffer management. + surface_pool_->AgeAndCollectOldBuffers(); + + // If no further surface production has taken place for 10 frames (TODO: + // Don't hardcode refresh rate here), then shrink our surface pool to fit. + constexpr auto kShouldShrinkThreshold = zx::msec(10 * 16.67); + async::PostDelayedTask( + async_get_default_dispatcher(), + [self = weak_factory_.GetWeakPtr(), kShouldShrinkThreshold] { + if (!self) { + return; + } + auto time_since_last_produce = + async::Now(async_get_default_dispatcher()) - + self->last_produce_time_; + if (time_since_last_produce >= kShouldShrinkThreshold) { + self->surface_pool_->ShrinkToFit(); + } + }, + kShouldShrinkThreshold); +} + +bool VulkanSurfaceProducer::TransitionSurfacesToExternal( + const std::vector>& surfaces) { + for (auto& surface : surfaces) { + auto vk_surface = static_cast(surface.get()); + if (!vk_surface) { + continue; + } + + vulkan::VulkanCommandBuffer* command_buffer = + vk_surface->GetCommandBuffer(logical_device_->GetCommandPool()); + if (!command_buffer->Begin()) + return false; + + GrBackendRenderTarget backendRT = SkSurfaces::GetBackendRenderTarget( + vk_surface->GetSkiaSurface().get(), + SkSurfaces::BackendHandleAccess::kFlushRead); + if (!backendRT.isValid()) { + return false; + } + GrVkImageInfo imageInfo; + if (!GrBackendRenderTargets::GetVkImageInfo(backendRT, &imageInfo)) { + return false; + } + + VkImageMemoryBarrier image_barrier = { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, + .pNext = nullptr, + .srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + .dstAccessMask = 0, + .oldLayout = imageInfo.fImageLayout, + // Understand why this is causing issues on Intel. TODO(fxb/53449) +#if defined(__aarch64__) + .newLayout = imageInfo.fImageLayout, +#else + .newLayout = VK_IMAGE_LAYOUT_GENERAL, +#endif + .srcQueueFamilyIndex = 0, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_EXTERNAL_KHR, + .image = vk_surface->GetVkImage(), + .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}}; + + if (!command_buffer->InsertPipelineBarrier( + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, + 0, // dependencyFlags + 0, nullptr, // memory barriers + 0, nullptr, // buffer barriers + 1, &image_barrier)) + return false; + + GrBackendRenderTargets::SetVkImageLayout(&backendRT, + image_barrier.newLayout); + + if (!command_buffer->End()) + return false; + + if (!logical_device_->QueueSubmit( + {}, {}, {vk_surface->GetAcquireVkSemaphore()}, + {command_buffer->Handle()}, vk_surface->GetCommandBufferFence())) + return false; + } + return true; +} + +std::unique_ptr VulkanSurfaceProducer::ProduceSurface( + const SkISize& size) { + FML_CHECK(valid_); + last_produce_time_ = async::Now(async_get_default_dispatcher()); + return surface_pool_->AcquireSurface(size); +} + +void VulkanSurfaceProducer::SubmitSurface( + std::unique_ptr surface) { + FML_CHECK(valid_); + surface_pool_->SubmitSurface(std::move(surface)); +} + +std::unique_ptr +VulkanSurfaceProducer::ProduceOffscreenSurface(const SkISize& size) { + return surface_pool_->CreateSurface(size); +} + +} // namespace flutter_runner diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface_producer.h b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface_producer.h new file mode 100644 index 0000000000000000000000000000000000000000..187442b0478f1ca948e7c8f5307b35a9da194bd1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface_producer.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_SHELL_PLATFORM_FUCHSIA_FLUTTER_VULKAN_SURFACE_PRODUCER_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_VULKAN_SURFACE_PRODUCER_H_ + +#include +#include + +#include "flutter/flutter_vma/flutter_skia_vma.h" +#include "flutter/fml/macros.h" +#include "flutter/fml/memory/weak_ptr.h" +#include "flutter/vulkan/procs/vulkan_proc_table.h" +#include "flutter/vulkan/vulkan_application.h" +#include "flutter/vulkan/vulkan_device.h" +#include "flutter/vulkan/vulkan_provider.h" +#include "third_party/skia/include/gpu/ganesh/GrDirectContext.h" + +#include "logging.h" +#include "vulkan_surface.h" +#include "vulkan_surface_pool.h" + +namespace flutter_runner { + +class VulkanSurfaceProducer final : public SurfaceProducer, + public vulkan::VulkanProvider { + public: + explicit VulkanSurfaceProducer(); + ~VulkanSurfaceProducer() override; + + bool IsValid() const { return valid_; } + + // |SurfaceProducer| + GrDirectContext* gr_context() const override { return context_.get(); } + + // |SurfaceProducer| + std::unique_ptr ProduceOffscreenSurface( + const SkISize& size) override; + + // |SurfaceProducer| + std::unique_ptr ProduceSurface( + const SkISize& size) override; + + // |SurfaceProducer| + void SubmitSurfaces( + std::vector> surfaces) override; + + private: + // VulkanProvider + const vulkan::VulkanProcTable& vk() override { return *vk_.get(); } + const vulkan::VulkanHandle& vk_device() override { + return logical_device_->GetHandle(); + } + + bool Initialize(); + + void SubmitSurface(std::unique_ptr surface); + bool TransitionSurfacesToExternal( + const std::vector>& surfaces); + + // Keep track of the last time we produced a surface. This is used to + // determine whether it is safe to shrink |surface_pool_| or not. + zx::time last_produce_time_ = async::Now(async_get_default_dispatcher()); + + // Disallow copy and assignment. + VulkanSurfaceProducer(const VulkanSurfaceProducer&) = delete; + VulkanSurfaceProducer& operator=(const VulkanSurfaceProducer&) = delete; + + // Note: the order here is very important. The proctable must be destroyed + // last because it contains the function pointers for VkDestroyDevice and + // VkDestroyInstance. + fml::RefPtr vk_; + std::unique_ptr application_; + std::unique_ptr logical_device_; + sk_sp context_; + std::unique_ptr surface_pool_; + sk_sp memory_allocator_; + bool valid_ = false; + + // WeakPtrFactory must be the last member. + fml::WeakPtrFactory weak_factory_{this}; +}; + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_VULKAN_SURFACE_PRODUCER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..61b63713e3467d3e552a14e924f7842d67ab602d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols/BUILD.gn @@ -0,0 +1,60 @@ +# 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. + +import("//build/toolchain/toolchain.gni") +import("//flutter/build/dart/dart.gni") +import("//flutter/tools/fuchsia/clang.gni") + +import("$dart_src/build/dart/dart_action.gni") + +template("generate_dart_profiler_symbols") { + assert(defined(invoker.library_label), "Must define 'library_label'") + assert(defined(invoker.library_path), "Must define 'library_path'") + assert(defined(invoker.output), "Must define 'output'") + + prebuilt_dart_action(target_name) { + deps = [ invoker.library_label ] + inputs = [ invoker.library_path ] + outputs = [ invoker.output ] + + script = "dart_profiler_symbols.dart" + + packages = rebase_path("$dart_src/.dart_tool/package_config.json") + + args = [ + "--nm", + rebase_path("$buildtools_path/${host_os}-${host_cpu}/clang/bin/llvm-nm"), + "--binary", + rebase_path(invoker.library_path), + "--output", + rebase_path(invoker.output), + ] + } +} + +generate_dart_profiler_symbols("dart_jit_runner") { + library_label = + "//flutter/shell/platform/fuchsia/dart_runner:dart_jit_runner_bin" + library_path = "${root_out_dir}/exe.unstripped/dart_jit_runner" + output = "${target_gen_dir}/dart_jit_runner.dartprofilersymbols" +} + +generate_dart_profiler_symbols("dart_aot_runner") { + library_label = + "//flutter/shell/platform/fuchsia/dart_runner:dart_aot_runner_bin" + library_path = "${root_out_dir}/exe.unstripped/dart_aot_runner" + output = "${target_gen_dir}/dart_aot_runner.dartprofilersymbols" +} + +generate_dart_profiler_symbols("flutter_jit_runner") { + library_label = "//flutter/shell/platform/fuchsia/flutter:jit" + library_path = "${root_out_dir}/exe.unstripped/flutter_jit_runner" + output = "${target_gen_dir}/flutter_jit_runner.dartprofilersymbols" +} + +generate_dart_profiler_symbols("flutter_aot_runner") { + library_label = "//flutter/shell/platform/fuchsia/flutter:aot" + library_path = "${root_out_dir}/exe.unstripped/flutter_aot_runner" + output = "${target_gen_dir}/flutter_aot_runner.dartprofilersymbols" +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols/analysis_options.yaml b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols/analysis_options.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5e8ae01a4e1f874fb757f8a017d621fb1cdb789a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols/analysis_options.yaml @@ -0,0 +1,3 @@ +# 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. diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols/dart_profiler_symbols.dart b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols/dart_profiler_symbols.dart new file mode 100644 index 0000000000000000000000000000000000000000..da3eed0e09bd9a1dcdee43420349c14477364f43 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols/dart_profiler_symbols.dart @@ -0,0 +1,152 @@ +// 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. + +// On Fuchsia, in lieu of the ELF dynamic symbol table consumed through dladdr, +// the Dart VM profiler consumes symbols produced by this tool, which have the +// format +// +// struct { +// uint32_t num_entries; +// struct { +// uint32_t offset; +// uint32_t size; +// uint32_t string_table_offset; +// } entries[num_entries]; +// const char* string_table; +// } +// +// Entries are sorted by offset. String table entries are NUL-terminated. +// +// See also //third_party/dart/runtime/vm/native_symbol_fuchsia.cc + +import "dart:convert"; +import "dart:io"; +import "dart:typed_data"; + +import "package:args/args.dart"; +import "package:path/path.dart" as path; + +Future main(List args) async { + final parser = new ArgParser(); + parser.addOption("nm", help: "Path to `nm` tool"); + parser.addOption( + "binary", + help: "Path to the ELF file to extract symbols from", + ); + parser.addOption("output", help: "Path to output symbol table"); + final usage = """ +Usage: dart_profiler_symbols.dart [options] + +Options: +${parser.usage}; +"""; + + String? buildIdDir; + String? buildIdScript; + String? nm; + String? binary; + String? output; + + try { + final options = parser.parse(args); + nm = options["nm"]; + if (nm == null) { + throw "Must specify --nm"; + } + if (!FileSystemEntity.isFileSync(nm)) { + throw "Cannot find $nm"; + } + binary = options["binary"]; + if (binary == null) { + throw "Must specify --binary"; + } + if (!FileSystemEntity.isFileSync(binary)) { + throw "Cannot find $binary"; + } + output = options["output"]; + if (output == null) { + throw "Must specify --output"; + } + } catch (e) { + print("ERROR: $e\n"); + print(usage); + exitCode = 1; + return; + } + + await run(buildIdDir, buildIdScript, nm, binary, output); +} + +class Symbol { + int offset; + int size; + String name; + + Symbol({required this.offset, required this.size, required this.name}); +} + +Future run( + String? buildIdDir, + String? buildIdScript, + String nm, + String binary, + String output, +) async { + final unstrippedFile = binary; + final args = ["--demangle", "--numeric-sort", "--print-size", unstrippedFile]; + final result = await Process.run(nm, args); + if (result.exitCode != 0) { + print(result.stdout); + print(result.stderr); + throw "Command failed: $nm $args"; + } + + var symbols = []; + + var regex = new RegExp("([0-9A-Za-z]+) ([0-9A-Za-z]+) (t|T|w|W) (.*)"); + for (final line in result.stdout.split("\n")) { + var match = regex.firstMatch(line); + if (match == null) { + continue; // Ignore non-text symbols. + } + + // Note that capture groups start at 1. + final symbol = new Symbol( + offset: int.parse(match[1]!, radix: 16), + size: int.parse(match[2]!, radix: 16), + name: match[4]!.split("(")[0], + ); + + if (symbol.name.startsWith("\$")) { + continue; // Ignore compiler/assembler temps. + } + + symbols.add(symbol); + } + + if (symbols.isEmpty) { + throw "$unstrippedFile has no symbols"; + } + + var nameTable = new BytesBuilder(); + var binarySearchTable = new Uint32List(symbols.length * 3 + 1); + var binarySearchTableIndex = 0; + binarySearchTable[binarySearchTableIndex++] = symbols.length; + // Symbols are sorted by offset because of --numeric-sort. + for (var symbol in symbols) { + var nameOffset = nameTable.length; + nameTable.add(utf8.encode(symbol.name)); + nameTable.addByte(0); + binarySearchTable[binarySearchTableIndex++] = symbol.offset; + binarySearchTable[binarySearchTableIndex++] = symbol.size; + binarySearchTable[binarySearchTableIndex++] = nameOffset; + } + + var file = new File(output); + await file.parent.create(recursive: true); + var sink = file.openWrite(); + sink.add(binarySearchTable.buffer.asUint8List()); + sink.add(nameTable.takeBytes()); + await sink.close(); +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols/pubspec.yaml b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..50ff8e43b8af28a4c997ffe7f23f6b1ad6f03c78 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols/pubspec.yaml @@ -0,0 +1,10 @@ +# 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. + +name: profiler_symbols +environment: + sdk: ^3.7.0-0 +version: 0 +description: Extracts a minimal symbols table for the Dart VM profiler +author: Dart Team diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/BUILD.gn b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..3a4a1bf0c0372a1dc497fe724ce16022ffb06070 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/BUILD.gn @@ -0,0 +1,115 @@ +# 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. + +assert(is_fuchsia) + +import("//flutter/common/config.gni") +import("//flutter/shell/version/version.gni") +import("//flutter/testing/testing.gni") +import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") + +config("utils_config") { + include_dirs = [ "../../.." ] +} + +template("make_utils") { + source_set(target_name) { + sources = [ + "$target_gen_dir/build_info.cc", + "build_info.h", + "files.cc", + "files.h", + "handle_exception.cc", + "handle_exception.h", + "inlines.h", + "logging.h", + "mapped_resource.cc", + "mapped_resource.h", + "root_inspect_node.cc", + "root_inspect_node.h", + "tempfs.cc", + "tempfs.h", + "vmo.cc", + "vmo.h", + "vmservice_object.cc", + "vmservice_object.h", + ] + + deps = invoker.deps + [ + ":generate_build_info_cc_file", + "${fuchsia_sdk}/fidl/fuchsia.feedback", + "${fuchsia_sdk}/fidl/fuchsia.mem", + "${fuchsia_sdk}/pkg/async-loop", + "${fuchsia_sdk}/pkg/async-loop-cpp", + "${fuchsia_sdk}/pkg/async-loop-default", + "${fuchsia_sdk}/pkg/fdio", + "${fuchsia_sdk}/pkg/inspect_component_cpp", + "${fuchsia_sdk}/pkg/sys_cpp", + "${fuchsia_sdk}/pkg/trace", + "${fuchsia_sdk}/pkg/vfs_cpp", + "${fuchsia_sdk}/pkg/zx", + "//flutter/fml", + "//flutter/third_party/tonic", + ] + + public_configs = [ ":utils_config" ] + } +} + +action("generate_build_info_cc_file") { + inputs = [ + "build_info_in.cc", + "//fuchsia/sdk/$host_os/meta/manifest.json", + "$dart_src/.git/logs/HEAD", + ] + outputs = [ "$target_gen_dir/build_info.cc" ] + + script = "//flutter/tools/fuchsia/make_build_info.py" + args = [ + "--input", + rebase_path("build_info_in.cc", root_build_dir), + "--output", + rebase_path(outputs[0], root_build_dir), + "--buildroot", + rebase_path("//", root_build_dir), + "--engine-version", + engine_version, + ] +} + +make_utils("utils") { + deps = [ "$dart_src/runtime/bin:elf_loader" ] +} + +test_fixtures("utils_fixtures") { + fixtures = [] +} + +executable("dart_utils_unittests") { + testonly = true + + output_name = "dart_utils_unittests" + + sources = [ "build_info_unittests.cc" ] + + libs = [ + # This is needed for //flutter/third_party/googletest for linking zircon + # symbols. + "${fuchsia_arch_root}/sysroot/lib/libzircon.so", + ] + + deps = [ + ":utils", + ":utils_fixtures", + "$dart_src/runtime:libdart_jit", + "$dart_src/runtime/bin:dart_io_api", + "${fuchsia_sdk}/pkg/inspect_component_cpp", + "${fuchsia_sdk}/pkg/sys_cpp", + "//flutter/testing", + ] +} + +make_utils("utils_product") { + deps = [ "$dart_src/runtime/bin:elf_loader_product" ] +} diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/build_info.h b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/build_info.h new file mode 100644 index 0000000000000000000000000000000000000000..e6a818ca529a8db26d71ea172d1bef2241c0ef5d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/build_info.h @@ -0,0 +1,26 @@ +// 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_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_BUILD_INFO_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_BUILD_INFO_H_ + +#include "root_inspect_node.h" + +namespace dart_utils { + +class BuildInfo { + public: + static const char* DartSdkGitRevision(); + static const char* DartSdkSemanticVersion(); + static const char* FlutterEngineGitRevision(); + static const char* FuchsiaSdkVersion(); + + /// Appends the above properties to the specified node on the inspect tree for + /// the duration of the node's lifetime. + static void Dump(inspect::Node& node); +}; + +} // namespace dart_utils + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_BUILD_INFO_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/build_info_in.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/build_info_in.cc new file mode 100644 index 0000000000000000000000000000000000000000..9353e5ca8fa1d1fb5a317f0e9b37a468796ef225 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/build_info_in.cc @@ -0,0 +1,36 @@ +// 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 "runtime/dart/utils/build_info.h" + +namespace dart_utils { + +const char* BuildInfo::DartSdkGitRevision() { + return "{{DART_SDK_GIT_REVISION}}"; +} + +const char* BuildInfo::DartSdkSemanticVersion() { + return "{{DART_SDK_SEMANTIC_VERSION}}"; +} + +const char* BuildInfo::FlutterEngineGitRevision() { + return "{{FLUTTER_ENGINE_GIT_REVISION}}"; +} + +const char* BuildInfo::FuchsiaSdkVersion() { + return "{{FUCHSIA_SDK_VERSION}}"; +} + +void BuildInfo::Dump(inspect::Node& node) { + node.CreateString("dart_sdk_git_revision", DartSdkGitRevision(), + RootInspectNode::GetInspector()); + node.CreateString("dart_sdk_semantic_version", DartSdkSemanticVersion(), + RootInspectNode::GetInspector()); + node.CreateString("flutter_engine_git_revision", FlutterEngineGitRevision(), + RootInspectNode::GetInspector()); + node.CreateString("fuchsia_sdk_version", FuchsiaSdkVersion(), + RootInspectNode::GetInspector()); +} + +} // namespace dart_utils diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/build_info_unittests.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/build_info_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..0bfbf48493a5a4789b76d6da3d7e66b7751013e3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/build_info_unittests.cc @@ -0,0 +1,63 @@ +// 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 "build_info.h" + +#include +#include +#include +#include +#include + +const std::string& inspect_node_name = "build_info_unittests"; + +void checkProperty(inspect::Hierarchy& root, + const std::string& name, + const std::string& expected_value) { + const inspect::Hierarchy* build_info = root.GetByPath({inspect_node_name}); + EXPECT_TRUE(build_info != nullptr); + auto* actual_value = + build_info->node().get_property(name); + EXPECT_TRUE(actual_value != nullptr); + EXPECT_EQ(actual_value->value(), expected_value); +} + +namespace dart_utils { + +class BuildInfoTest : public ::testing::Test { + public: + static void SetUpTestSuite() { + async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread); + auto context = sys::ComponentContext::Create(); + RootInspectNode::Initialize(context.get()); + } +}; + +TEST_F(BuildInfoTest, AllPropertiesAreDefined) { + EXPECT_NE(BuildInfo::DartSdkGitRevision(), "{{DART_SDK_GIT_REVISION}}"); + EXPECT_NE(BuildInfo::DartSdkSemanticVersion(), + "{{DART_SDK_SEMANTIC_VERSION}}"); + EXPECT_NE(BuildInfo::FlutterEngineGitRevision(), + "{{FLUTTER_ENGINE_GIT_REVISION}}"); + EXPECT_NE(BuildInfo::FuchsiaSdkVersion(), "{{FUCHSIA_SDK_VERSION}}"); +} + +TEST_F(BuildInfoTest, AllPropertiesAreDumped) { + inspect::Node node = + dart_utils::RootInspectNode::CreateRootChild(inspect_node_name); + BuildInfo::Dump(node); + inspect::Hierarchy root = + inspect::ReadFromVmo( + std::move( + dart_utils::RootInspectNode::GetInspector()->DuplicateVmo())) + .take_value(); + checkProperty(root, "dart_sdk_git_revision", BuildInfo::DartSdkGitRevision()); + checkProperty(root, "dart_sdk_semantic_version", + BuildInfo::DartSdkSemanticVersion()); + checkProperty(root, "flutter_engine_git_revision", + BuildInfo::FlutterEngineGitRevision()); + checkProperty(root, "fuchsia_sdk_version", BuildInfo::FuchsiaSdkVersion()); +} + +} // namespace dart_utils diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/files.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/files.cc new file mode 100644 index 0000000000000000000000000000000000000000..08391b320b928a41b4e83efdf38b574c545ac0a7 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/files.cc @@ -0,0 +1,79 @@ +// 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 "files.h" + +#include +#include + +#include + +#include "flutter/fml/logging.h" + +namespace dart_utils { + +namespace { + +bool ReadFileDescriptor(int fd, std::string* result) { + FML_DCHECK(result); + result->clear(); + + if (fd < 0) { + return false; + } + + constexpr size_t kBufferSize = 1 << 16; + size_t offset = 0; + ssize_t bytes_read = 0; + do { + offset += bytes_read; + result->resize(offset + kBufferSize); + bytes_read = read(fd, &(*result)[offset], kBufferSize); + } while (bytes_read > 0); + + if (bytes_read < 0) { + result->clear(); + return false; + } + + result->resize(offset + bytes_read); + return true; +} + +bool WriteFileDescriptor(int fd, const char* data, ssize_t size) { + ssize_t total = 0; + for (ssize_t partial = 0; total < size; total += partial) { + partial = write(fd, data + total, size - total); + if (partial < 0) + return false; + } + return true; +} + +} // namespace + +bool ReadFileToString(const std::string& path, std::string* result) { + return ReadFileToStringAt(AT_FDCWD, path, result); +} + +bool ReadFileToStringAt(int dirfd, + const std::string& path, + std::string* result) { + int fd = openat(dirfd, path.c_str(), O_RDONLY); + bool status = ReadFileDescriptor(fd, result); + close(fd); + return status; +} + +bool WriteFile(const std::string& path, const char* data, ssize_t size) { + int fd = openat(AT_FDCWD, path.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0666); + if (fd < 0) { + return false; + } + bool status = WriteFileDescriptor(fd, data, size); + close(fd); + return status; +} + +} // namespace dart_utils diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/files.h b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/files.h new file mode 100644 index 0000000000000000000000000000000000000000..2b3212e6f541cc009aad3600678c263e096b1e8d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/files.h @@ -0,0 +1,27 @@ +// 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_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_FILES_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_FILES_H_ + +#include + +namespace dart_utils { + +// Reads the contents of the file at the given path or file descriptor and +// stores the data in result. Returns true if the file was read successfully, +// otherwise returns false. If this function returns false, |result| will be +// the empty string. +bool ReadFileToString(const std::string& path, std::string* result); +bool ReadFileToStringAt(int dirfd, + const std::string& path, + std::string* result); + +// Writes the given data to the file at the given path. Returns true if the data +// was successfully written, otherwise returns false. +bool WriteFile(const std::string& path, const char* data, ssize_t size); + +} // namespace dart_utils + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_FILES_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/handle_exception.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/handle_exception.cc new file mode 100644 index 0000000000000000000000000000000000000000..e1b12beb085d557e510360d8a6b5fa80ee006522 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/handle_exception.cc @@ -0,0 +1,124 @@ +// 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 "handle_exception.h" + +#include +#include +#include +#include +#include + +#include + +#include "flutter/fml/logging.h" +#include "third_party/tonic/converter/dart_converter.h" + +namespace { +static bool SetStackTrace(const std::string& data, + fuchsia::feedback::RuntimeCrashReport* report) { + uint64_t num_bytes = data.size(); + zx::vmo vmo; + + if (zx::vmo::create(num_bytes, 0u, &vmo) < 0) { + return false; + } + + if (num_bytes > 0) { + if (vmo.write(data.data(), 0, num_bytes) < 0) { + return false; + } + } + + fuchsia::mem::Buffer buffer; + buffer.vmo = std::move(vmo); + buffer.size = num_bytes; + report->set_exception_stack_trace(std::move(buffer)); + + return true; +} + +fuchsia::feedback::CrashReport BuildCrashReport( + const std::string& component_url, + const std::string& error, + const std::string& stack_trace) { + // The runtime type has already been pre-pended to the error message so we + // expect the format to be '$RuntimeType: $Message'. + std::string error_type; + std::string error_message; + const size_t delimiter_pos = error.find_first_of(':'); + if (delimiter_pos == std::string::npos) { + FML_LOG(ERROR) << "error parsing Dart exception: expected format " + "'$RuntimeType: $Message', got '" + << error << "'"; + // We still need to specify a type, otherwise the stack trace does not + // show up in the crash server UI. + error_type = "UnknownError"; + error_message = error; + } else { + error_type = error.substr(0, delimiter_pos); + error_message = + error.substr(delimiter_pos + 2 /*to get rid of the leading ': '*/); + } + + // Truncate error message to the maximum length allowed for the crash_reporter + // FIDL call + error_message = error_message.substr( + 0, fuchsia::feedback::MAX_EXCEPTION_MESSAGE_LENGTH - 1); + + fuchsia::feedback::RuntimeCrashReport dart_report; + dart_report.set_exception_type(error_type); + dart_report.set_exception_message(error_message); + if (!SetStackTrace(stack_trace, &dart_report)) { + FML_LOG(ERROR) << "Failed to convert Dart stack trace to VMO"; + } + + fuchsia::feedback::SpecificCrashReport specific_report; + specific_report.set_dart(std::move(dart_report)); + fuchsia::feedback::CrashReport report; + report.set_program_name(component_url); + report.set_specific_report(std::move(specific_report)); + report.set_is_fatal(false); + return report; +} + +} // namespace + +namespace dart_utils { + +void HandleIfException(std::shared_ptr<::sys::ServiceDirectory> services, + const std::string& component_url, + Dart_Handle result) { + if (!Dart_IsError(result) || !Dart_ErrorHasException(result)) { + return; + } + + const std::string error = + tonic::StdStringFromDart(Dart_ToString(Dart_ErrorGetException(result))); + const std::string stack_trace = + tonic::StdStringFromDart(Dart_ToString(Dart_ErrorGetStackTrace(result))); + + return HandleException(services, component_url, error, stack_trace); +} + +void HandleException(std::shared_ptr<::sys::ServiceDirectory> services, + const std::string& component_url, + const std::string& error, + const std::string& stack_trace) { + fuchsia::feedback::CrashReport crash_report = + BuildCrashReport(component_url, error, stack_trace); + + fuchsia::feedback::CrashReporterPtr crash_reporter = + services->Connect(); + crash_reporter->FileReport( + std::move(crash_report), + [](fuchsia::feedback::CrashReporter_FileReport_Result result) { + if (result.is_err()) { + FML_LOG(ERROR) << "Failed to report Dart exception: " + << static_cast(result.err()); + } + }); +} + +} // namespace dart_utils diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/handle_exception.h b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/handle_exception.h new file mode 100644 index 0000000000000000000000000000000000000000..5781aad0aa7bb2ef79c7b5188d72c202f9956846 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/handle_exception.h @@ -0,0 +1,32 @@ +// 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_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_HANDLE_EXCEPTION_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_HANDLE_EXCEPTION_H_ + +#include + +#include +#include + +#include "third_party/dart/runtime/include/dart_api.h" + +namespace dart_utils { + +// If |result| is a Dart Exception, passes the exception message and stack trace +// to the crash analyzer service for further handling. +void HandleIfException(std::shared_ptr<::sys::ServiceDirectory> services, + const std::string& component_url, + Dart_Handle result); + +// Passes the exception message and stack trace to the crash analyzer service +// for further handling. +void HandleException(std::shared_ptr<::sys::ServiceDirectory> services, + const std::string& component_url, + const std::string& error, + const std::string& stack_trace); + +} // namespace dart_utils + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_HANDLE_EXCEPTION_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/inlines.h b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/inlines.h new file mode 100644 index 0000000000000000000000000000000000000000..d80ae301ffb932a3721eb9eafd209facb442d02d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/inlines.h @@ -0,0 +1,17 @@ +// 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_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_INLINES_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_INLINES_H_ + +namespace dart_utils { + +template +inline size_t ArraySize(T (&array)[SIZE]) { + return SIZE; +} + +} // namespace dart_utils + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_INLINES_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/logging.h b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/logging.h new file mode 100644 index 0000000000000000000000000000000000000000..fdb60e94b31281cd955af1093f1c23a7d3e36102 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/logging.h @@ -0,0 +1,15 @@ +// 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_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_LOGGING_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_LOGGING_H_ + +namespace dart_utils { + +// Use to mark logs published via the syslog API. +#define LOG_TAG "dart-utils" + +} // namespace dart_utils + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_LOGGING_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/mapped_resource.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/mapped_resource.cc new file mode 100644 index 0000000000000000000000000000000000000000..41445c980f52c17bc0b28e09542193bf645b38ed --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/mapped_resource.cc @@ -0,0 +1,160 @@ +// 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 "mapped_resource.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "flutter/fml/logging.h" +#include "third_party/dart/runtime/include/dart_api.h" + +#include "inlines.h" +#include "vmo.h" + +namespace dart_utils { + +static bool OpenVmo(fuchsia::mem::Buffer* resource_vmo, + fdio_ns_t* namespc, + const std::string& path, + bool executable) { + TRACE_DURATION("dart", "LoadFromNamespace", "path", path); + + if (namespc == nullptr) { + // Opening a file in the root namespace expects an absolute path. + FML_CHECK(path[0] == '/'); + if (!VmoFromFilename(path, executable, resource_vmo)) { + return false; + } + } else { + // openat of a path with a leading '/' ignores the namespace fd. + // require a relative path. + FML_CHECK(path[0] != '/'); + + auto root_dir = fdio_ns_opendir(namespc); + if (root_dir < 0) { + FML_LOG(ERROR) << "Failed to open namespace directory"; + return false; + } + + bool result = + dart_utils::VmoFromFilenameAt(root_dir, path, executable, resource_vmo); + close(root_dir); + if (!result) { + return result; + } + } + + return true; +} + +bool MappedResource::LoadFromNamespace(fdio_ns_t* namespc, + const std::string& path, + MappedResource& resource, + bool executable) { + fuchsia::mem::Buffer resource_vmo; + return OpenVmo(&resource_vmo, namespc, path, executable) && + LoadFromVmo(path, std::move(resource_vmo), resource, executable); +} + +bool MappedResource::LoadFromVmo(const std::string& path, + fuchsia::mem::Buffer resource_vmo, + MappedResource& resource, + bool executable) { + if (resource_vmo.size == 0) { + return true; + } + + uint32_t flags = ZX_VM_PERM_READ; + if (executable) { + flags |= ZX_VM_PERM_EXECUTE; + } + uintptr_t addr; + zx_status_t status = zx::vmar::root_self()->map(flags, 0, resource_vmo.vmo, 0, + resource_vmo.size, &addr); + if (status != ZX_OK) { + FML_LOG(ERROR) << "Failed to map: " << zx_status_get_string(status); + return false; + } + + resource.address_ = reinterpret_cast(addr); + resource.size_ = resource_vmo.size; + return true; +} + +MappedResource::~MappedResource() { + if (address_ != nullptr) { + zx::vmar::root_self()->unmap(reinterpret_cast(address_), size_); + address_ = nullptr; + size_ = 0; + } +} + +static int OpenFdExec(const std::string& path, int dirfd) { + int fd = -1; + // fdio_open3_fd_at only allows relative paths + const char* path_ptr = path.c_str(); + if (path_ptr && path_ptr[0] == '/') { + ++path_ptr; + } + zx_status_t result = fdio_open3_fd_at( + dirfd, path_ptr, + uint64_t{fuchsia::io::PERM_READABLE | fuchsia::io::PERM_EXECUTABLE}, &fd); + if (result != ZX_OK) { + FML_LOG(ERROR) << "fdio_open3_fd_at(" << path << ") " + << "failed: " << zx_status_get_string(result); + return -1; + } + return fd; +} + +bool ElfSnapshot::Load(fdio_ns_t* namespc, const std::string& path) { + int root_dir = -1; + if (namespc == nullptr) { + root_dir = AT_FDCWD; + } else { + root_dir = fdio_ns_opendir(namespc); + if (root_dir < 0) { + FML_LOG(ERROR) << "Failed to open namespace directory"; + return false; + } + } + return Load(root_dir, path); +} + +bool ElfSnapshot::Load(int dirfd, const std::string& path) { + const int fd = OpenFdExec(path, dirfd); + if (fd < 0) { + FML_LOG(ERROR) << "Failed to open VMO for " << path << " from dir."; + return false; + } + return Load(fd); +} + +bool ElfSnapshot::Load(int fd) { + const char* error; + handle_ = Dart_LoadELF_Fd(fd, 0, &error, &vm_data_, &vm_instrs_, + &isolate_data_, &isolate_instrs_); + if (handle_ == nullptr) { + FML_LOG(ERROR) << "Failed load ELF: " << error; + return false; + } + return true; +} + +ElfSnapshot::~ElfSnapshot() { + Dart_UnloadELF(handle_); +} + +} // namespace dart_utils diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/mapped_resource.h b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/mapped_resource.h new file mode 100644 index 0000000000000000000000000000000000000000..41f3bdfcf6765bcbf9830f63740ab28be81f546f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/mapped_resource.h @@ -0,0 +1,108 @@ +// 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_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_MAPPED_RESOURCE_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_MAPPED_RESOURCE_H_ + +#include +#include + +#include "third_party/dart/runtime/bin/elf_loader.h" + +namespace dart_utils { + +class ElfSnapshot { + public: + ElfSnapshot() {} + ~ElfSnapshot(); + ElfSnapshot(ElfSnapshot&& other) : handle_(other.handle_) { + other.handle_ = nullptr; + } + ElfSnapshot& operator=(ElfSnapshot&& other) { + std::swap(handle_, other.handle_); + return *this; + } + + bool Load(fdio_ns_t* namespc, const std::string& path); + bool Load(int dirfd, const std::string& path); + + const uint8_t* VmData() const { return vm_data_; } + const uint8_t* VmInstrs() const { return vm_instrs_; } + const uint8_t* IsolateData() const { return isolate_data_; } + const uint8_t* IsolateInstrs() const { return isolate_instrs_; } + + private: + bool Load(int fd); + + Dart_LoadedElf* handle_ = nullptr; + + const uint8_t* vm_data_ = nullptr; + const uint8_t* vm_instrs_ = nullptr; + const uint8_t* isolate_data_ = nullptr; + const uint8_t* isolate_instrs_ = nullptr; + + // Disallow copy and assignment. + ElfSnapshot(const ElfSnapshot&) = delete; + ElfSnapshot& operator=(const ElfSnapshot&) = delete; +}; + +class MappedResource { + public: + MappedResource() : address_(nullptr), size_(0) {} + MappedResource(MappedResource&& other) + : address_(other.address_), size_(other.size_) { + other.address_ = nullptr; + other.size_ = 0; + } + MappedResource& operator=(MappedResource&& other) { + address_ = other.address_; + size_ = other.size_; + other.address_ = nullptr; + other.size_ = 0; + return *this; + } + ~MappedResource(); + + // Loads the content of a file from the given namespace and maps it into the + // current process's address space. If namespace is null, the fdio "global" + // namespace is used (in which case, ./pkg means the dart_runner's package). + // The content is unmapped when the MappedResource goes out of scope. Returns + // true on success. + static bool LoadFromNamespace(fdio_ns_t* namespc, + const std::string& path, + MappedResource& resource, + bool executable = false); + + // Same as LoadFromNamespace, but takes a file descriptor to an opened + // directory instead of a namespace. + static bool LoadFromDir(int dirfd, + const std::string& path, + MappedResource& resource, + bool executable = false); + + // Maps a VMO into the current process's address space. The content is + // unmapped when the MappedResource goes out of scope. Returns true on + // success. The path is used only for error messages. + static bool LoadFromVmo(const std::string& path, + fuchsia::mem::Buffer resource_vmo, + MappedResource& resource, + bool executable = false); + + const uint8_t* address() const { + return reinterpret_cast(address_); + } + size_t size() const { return size_; } + + private: + void* address_; + size_t size_; + + // Disallow copy and assignment. + MappedResource(const MappedResource&) = delete; + MappedResource& operator=(const MappedResource&) = delete; +}; + +} // namespace dart_utils + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_MAPPED_RESOURCE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/root_inspect_node.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/root_inspect_node.cc new file mode 100644 index 0000000000000000000000000000000000000000..474fa29eef29220c47565a26f5e37e91af04e8c6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/root_inspect_node.cc @@ -0,0 +1,30 @@ +// 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 "root_inspect_node.h" +#include + +namespace dart_utils { + +std::unique_ptr RootInspectNode::inspector_; +std::mutex RootInspectNode::mutex_; + +void RootInspectNode::Initialize(sys::ComponentContext* context) { + std::lock_guard lock(mutex_); + if (!inspector_) { + inspector_ = std::make_unique( + async_get_default_dispatcher(), inspect::PublishOptions{}); + } +} + +inspect::Node RootInspectNode::CreateRootChild(const std::string& name) { + std::lock_guard lock(mutex_); + return inspector_->inspector().GetRoot().CreateChild(name); +} + +inspect::Inspector* RootInspectNode::GetInspector() { + return &inspector_->inspector(); +} + +} // namespace dart_utils diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/root_inspect_node.h b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/root_inspect_node.h new file mode 100644 index 0000000000000000000000000000000000000000..f9c9153b3050b848e5605eb66b010dcd67d346a4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/root_inspect_node.h @@ -0,0 +1,46 @@ +// 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_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_ROOT_INSPECT_NODE_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_ROOT_INSPECT_NODE_H_ + +#include +#include + +#include +#include + +namespace dart_utils { + +// This singleton object offers a way to create a new inspect node under the +// root node in a thread safe way. +// +// Usage notes: +// RootInspectNode::Initialize() must be invoked once in the program's +// main before trying to obtain a child node. +class RootInspectNode { + private: + RootInspectNode() = default; + ~RootInspectNode() = default; + + public: + // Initializes the underlying component inspector. Must be invoked at least + // once before calling CreateRootChild(). + static void Initialize(sys::ComponentContext* context); + + // Creates an inspect node which is a child of the component's root inspect + // node with the provided |name|. + static inspect::Node CreateRootChild(const std::string& name); + + // Gets an instance to the component's inspector. + static inspect::Inspector* GetInspector(); + + private: + static std::unique_ptr inspector_; + static std::mutex mutex_; +}; + +} // namespace dart_utils + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_ROOT_INSPECT_NODE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/run_vmservice_object_tests.sh b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/run_vmservice_object_tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..61173b8b630c52f1e18b3073cb66277a3191e8ba --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/run_vmservice_object_tests.sh @@ -0,0 +1,33 @@ +#!/boot/bin/sh +# 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. + +set -x + +# Kill any existing dart runners. +killall dart* || true + +# Start up a dart runner app that is guaranteed to be JIT, non-product, and +# won't terminate. +run -d fuchsia-pkg://fuchsia.com/hello_dart_jit#meta/hello_dart_jit.cmx + +# Wait for it to come up. +sleep 2 + +# Find the path to its vm service port. +# NB: This is the command used by the Flutter host-side command line tools. +# If the use of 'find' here breaks, the Flutter host-side command line tools +# will also be broken. If this is intentional, then craft and land a Flutter PR. +# See: https://github.com/flutter/flutter/commit/b18a2b1794606a6cddb6d7f3486557e473e3bfbb +# Then, land a hard transition to GI that updates Flutter and this test. +FIND_RESULT=`find /hub -name vmservice-port | grep dart_jit_runner` + +echo "find result:\n${FIND_RESULT}" + +killall dart* || true +if [ -z "${FIND_RESULT}" ]; then + echo "FAILURE: Dart VM service not found in the Hub!" + exit 1 +fi +exit 0 diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/tempfs.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/tempfs.cc new file mode 100644 index 0000000000000000000000000000000000000000..2545e4e5b15e66fc00d851f9f15332b124074e23 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/tempfs.cc @@ -0,0 +1,51 @@ +// 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 "tempfs.h" + +#include + +#include +#include +#include + +#include "flutter/fml/logging.h" + +namespace { + +constexpr char kTmpPath[] = "/tmp"; + +} // namespace + +namespace dart_utils { + +void BindTemp(fdio_ns_t* ns) { + // TODO(zra): Should isolates share a /tmp file system within a process, or + // should isolates each get their own private file system for /tmp? For now, + // sharing the process-wide /tmp simplifies hot reload since the hot reload + // devfs requires sharing between the service isolate and the app isolates. + fdio_flat_namespace_t* rootns; + if (zx_status_t status = fdio_ns_export_root(&rootns); status != ZX_OK) { + FML_LOG(ERROR) << "Failed to export root ns: " + << zx_status_get_string(status); + return; + } + + zx_handle_t tmp_dir_handle; + for (size_t i = 0; i < rootns->count; i++) { + if (std::string_view{rootns->path[i]} == kTmpPath) { + tmp_dir_handle = std::exchange(rootns->handle[i], ZX_HANDLE_INVALID); + } + } + fdio_ns_free_flat_ns(rootns); + + if (zx_status_t status = fdio_ns_bind(ns, kTmpPath, tmp_dir_handle); + status != ZX_OK) { + zx_handle_close(tmp_dir_handle); + FML_LOG(ERROR) << "Failed to bind /tmp directory into isolate namespace: " + << zx_status_get_string(status); + } +} + +} // namespace dart_utils diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/tempfs.h b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/tempfs.h new file mode 100644 index 0000000000000000000000000000000000000000..1c89ab42f24f975be22c02ec63724faa066593d3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/tempfs.h @@ -0,0 +1,18 @@ +// 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_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_TEMPFS_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_TEMPFS_H_ + +#include + +namespace dart_utils { + +// Take the virtual filesystem mapped into the process-wide namespace for /tmp, +// and map it to /tmp in the given namespace. +void BindTemp(fdio_ns_t* ns); + +} // namespace dart_utils + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_TEMPFS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/vmo.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/vmo.cc new file mode 100644 index 0000000000000000000000000000000000000000..dc79f01e14e985f18a299cad429cd8805363d67c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/vmo.cc @@ -0,0 +1,101 @@ +// 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 "vmo.h" + +#include +#include + +#include +#include +#include +#include +#include + +#include + +#include "flutter/fml/logging.h" + +namespace { + +bool VmoFromFd(int fd, bool executable, fuchsia::mem::Buffer* buffer) { + if (!buffer) { + FML_LOG(FATAL) << "Invalid buffer pointer"; + } + + struct stat stat_struct; + if (fstat(fd, &stat_struct) == -1) { + FML_LOG(ERROR) << "fstat failed: " << strerror(errno); + return false; + } + + zx_handle_t result = ZX_HANDLE_INVALID; + zx_status_t status; + if (executable) { + status = fdio_get_vmo_exec(fd, &result); + } else { + status = fdio_get_vmo_copy(fd, &result); + } + + if (status != ZX_OK) { + FML_LOG(ERROR) << (executable ? "fdio_get_vmo_exec" : "fdio_get_vmo_copy") + << " failed: " << zx_status_get_string(status); + return false; + } + + buffer->vmo = zx::vmo(result); + buffer->size = stat_struct.st_size; + + return true; +} + +} // namespace + +namespace dart_utils { + +bool VmoFromFilename(const std::string& filename, + bool executable, + fuchsia::mem::Buffer* buffer) { + return VmoFromFilenameAt(AT_FDCWD, filename, executable, buffer); +} + +bool VmoFromFilenameAt(int dirfd, + const std::string& filename, + bool executable, + fuchsia::mem::Buffer* buffer) { + fuchsia::io::Flags flags = fuchsia::io::PERM_READABLE; + if (executable) { + flags |= fuchsia::io::PERM_EXECUTABLE; + } + // fdio_open3_fd_at only allows relative paths + const char* path = filename.c_str(); + if (path && path[0] == '/') { + ++path; + } + int fd; + const zx_status_t status = + fdio_open3_fd_at(dirfd, path, uint64_t{flags}, &fd); + if (status != ZX_OK) { + FML_LOG(ERROR) << "fdio_open3_fd_at(" << dirfd << ", \"" << filename + << "\", " << std::hex << uint64_t{flags} + << ") failed: " << zx_status_get_string(status); + return false; + } + bool result = VmoFromFd(fd, executable, buffer); + close(fd); + return result; +} + +zx_status_t IsSizeValid(const fuchsia::mem::Buffer& buffer, bool* is_valid) { + size_t vmo_size; + zx_status_t status = buffer.vmo.get_size(&vmo_size); + if (status == ZX_OK) { + *is_valid = vmo_size >= buffer.size; + } else { + *is_valid = false; + } + return status; +} + +} // namespace dart_utils diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/vmo.h b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/vmo.h new file mode 100644 index 0000000000000000000000000000000000000000..52871d2e32751a1626a392a82babeee06f70b39d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/vmo.h @@ -0,0 +1,27 @@ +// 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_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_VMO_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_VMO_H_ + +#include + +#include + +namespace dart_utils { + +bool VmoFromFilename(const std::string& filename, + bool executable, + fuchsia::mem::Buffer* buffer); + +bool VmoFromFilenameAt(int dirfd, + const std::string& filename, + bool executable, + fuchsia::mem::Buffer* buffer); + +zx_status_t IsSizeValid(const fuchsia::mem::Buffer& buffer, bool* is_valid); + +} // namespace dart_utils + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_VMO_H_ diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/vmservice_object.cc b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/vmservice_object.cc new file mode 100644 index 0000000000000000000000000000000000000000..d36257ba816bc567b10177614b1c7814f3fdf6b4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/vmservice_object.cc @@ -0,0 +1,61 @@ +// 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 "vmservice_object.h" + +#include +#include +#include + +#include +#include + +#include "flutter/fml/logging.h" + +namespace { + +bool ReadDirContents(const std::string& path, std::vector* out) { + out->clear(); + DIR* dir = opendir(path.c_str()); + if (!dir) { + return false; + } + struct dirent* de; + errno = 0; + while ((de = readdir(dir)) != nullptr) { + out->push_back(de->d_name); + } + closedir(dir); + return !errno; +} + +} // namespace + +namespace dart_utils { + +void VMServiceObject::GetContents(LazyEntryVector* out_vector) const { + // List /tmp/dart.services if it exists, and push its contents as + // the contents of this directory. + std::vector files; + if (!ReadDirContents(kPortDir, &files)) { + FML_LOG(ERROR) << "Failed to read Dart VM service port directory '" + << kPortDir << "': " << strerror(errno); + return; + } + for (const auto& file : files) { + if ((file == ".") || (file == "..")) { + continue; + } + out_vector->push_back({std::stoul(file) + GetStartingId(), file, + fuchsia::io::MODE_TYPE_FILE}); + } +} + +zx_status_t VMServiceObject::GetFile(Node** out_node, + uint64_t id, + std::string name) const { + return ZX_ERR_NOT_FOUND; +} + +} // namespace dart_utils diff --git a/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/vmservice_object.h b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/vmservice_object.h new file mode 100644 index 0000000000000000000000000000000000000000..697922491a27794e5c36e55993a92ce71fe9ff4b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/fuchsia/runtime/dart/utils/vmservice_object.h @@ -0,0 +1,26 @@ +// 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_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_VMSERVICE_OBJECT_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_VMSERVICE_OBJECT_H_ + +#include + +namespace dart_utils { + +class VMServiceObject : public vfs::LazyDir { + public: + static constexpr const char* kDirName = "DartVM"; + static constexpr const char* kPortDirName = "vmservice-port"; + static constexpr const char* kPortDir = "/tmp/dart.services"; + + void GetContents(LazyEntryVector* out_vector) const override; + zx_status_t GetFile(Node** out_node, + uint64_t id, + std::string name) const override; +}; + +} // namespace dart_utils + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_VMSERVICE_OBJECT_H_ diff --git a/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/BUILD.gn b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..d9c24fb5133075c66f57ad9548e641905b7c37e1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/BUILD.gn @@ -0,0 +1,96 @@ +# 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. + +import("//flutter/shell/platform/common/client_wrapper/publish.gni") +import("//flutter/testing/testing.gni") + +_wrapper_includes = [ + "include/flutter/flutter_engine.h", + "include/flutter/flutter_window.h", + "include/flutter/flutter_window_controller.h", + "include/flutter/plugin_registrar_glfw.h", +] + +_wrapper_sources = [ + "flutter_engine.cc", + "flutter_window_controller.cc", +] + +# This code will be merged into .../common/cpp/client_wrapper for client use, +# so uses header paths that assume the merged state. Include the header +# directory of the core wrapper files so these includes will work. +config("relative_core_wrapper_headers") { + include_dirs = + [ "//flutter/shell/platform/common/client_wrapper/include/flutter" ] +} + +# GLFW client wrapper build for internal use by the shell implementation. +source_set("client_wrapper_glfw") { + sources = _wrapper_sources + public = _wrapper_includes + + deps = [ + "//flutter/shell/platform/common:common_cpp_library_headers", + "//flutter/shell/platform/common/client_wrapper:client_wrapper", + "//flutter/shell/platform/glfw:flutter_glfw_headers", + ] + + configs += + [ "//flutter/shell/platform/common:desktop_library_implementation" ] + + public_configs = [ + ":relative_core_wrapper_headers", + "//flutter/shell/platform/common:relative_flutter_library_headers", + "//flutter/shell/platform/glfw:relative_flutter_glfw_headers", + ] +} + +# Copies the GLFW client wrapper code to the output directory with a _glfw +# suffix. +publish_client_wrapper_extension("publish_wrapper_glfw") { + public = _wrapper_includes + sources = _wrapper_sources + directory_suffix = "glfw" +} + +source_set("client_wrapper_library_stubs_glfw") { + sources = [ + "testing/stub_flutter_glfw_api.cc", + "testing/stub_flutter_glfw_api.h", + ] + + defines = [ "FLUTTER_DESKTOP_LIBRARY" ] + + public_deps = [ "//flutter/shell/platform/glfw:flutter_glfw_headers" ] +} + +test_fixtures("client_wrapper_glfw_fixtures") { + fixtures = [] +} + +executable("client_wrapper_glfw_unittests") { + testonly = true + + sources = [ + "flutter_engine_unittests.cc", + "flutter_window_controller_unittests.cc", + "flutter_window_unittests.cc", + "plugin_registrar_glfw_unittests.cc", + ] + + defines = [ "FLUTTER_DESKTOP_LIBRARY" ] + + deps = [ + ":client_wrapper_glfw", + ":client_wrapper_glfw_fixtures", + ":client_wrapper_library_stubs_glfw", + "//flutter/shell/platform/common/client_wrapper:client_wrapper_library_stubs", + "//flutter/testing", + + # TODO(chunhtai): Consider refactoring flutter_root/testing so that there's a testing + # target that doesn't require a Dart runtime to be linked in. + # https://github.com/flutter/flutter/issues/41414. + "$dart_src/runtime:libdart_jit", + ] +} diff --git a/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/flutter_engine.cc b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/flutter_engine.cc new file mode 100644 index 0000000000000000000000000000000000000000..9b6889bd2f861324ac5e4f2f8a1eed70d57db27a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/flutter_engine.cc @@ -0,0 +1,84 @@ +// 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 "include/flutter/flutter_engine.h" + +#include +#include + +namespace flutter { + +FlutterEngine::FlutterEngine() {} + +FlutterEngine::~FlutterEngine() {} + +bool FlutterEngine::Start(const std::string& icu_data_path, + const std::string& assets_path, + const std::vector& arguments, + const std::string& aot_library_path) { + if (engine_) { + std::cerr << "Cannot run an already running engine. Create a new instance " + "or call ShutDown first." + << std::endl; + return false; + } + + FlutterDesktopEngineProperties c_engine_properties = {}; + c_engine_properties.assets_path = assets_path.c_str(); + c_engine_properties.icu_data_path = icu_data_path.c_str(); + c_engine_properties.aot_library_path = aot_library_path.c_str(); + std::vector engine_switches; + std::transform( + arguments.begin(), arguments.end(), std::back_inserter(engine_switches), + [](const std::string& arg) -> const char* { return arg.c_str(); }); + if (!engine_switches.empty()) { + c_engine_properties.switches = &engine_switches[0]; + c_engine_properties.switches_count = engine_switches.size(); + } + + engine_ = UniqueEnginePtr(FlutterDesktopRunEngine(c_engine_properties), + FlutterDesktopShutDownEngine); + if (!engine_) { + std::cerr << "Failed to start engine." << std::endl; + return false; + } + return true; +} + +void FlutterEngine::ShutDown() { + engine_ = nullptr; +} + +FlutterDesktopPluginRegistrarRef FlutterEngine::GetRegistrarForPlugin( + const std::string& plugin_name) { + if (!engine_) { + std::cerr << "Cannot get plugin registrar on an engine that isn't running; " + "call Run first." + << std::endl; + return nullptr; + } + return FlutterDesktopGetPluginRegistrar(engine_.get(), plugin_name.c_str()); +} + +void FlutterEngine::RunEventLoopWithTimeout(std::chrono::milliseconds timeout) { + if (!engine_) { + std::cerr << "Cannot run event loop without a running engine; call " + "Run first." + << std::endl; + return; + } + uint32_t timeout_milliseconds; + if (timeout == std::chrono::milliseconds::max()) { + // The C API uses 0 to represent no timeout, so convert |max| to 0. + timeout_milliseconds = 0; + } else if (timeout.count() > UINT32_MAX) { + timeout_milliseconds = UINT32_MAX; + } else { + timeout_milliseconds = static_cast(timeout.count()); + } + FlutterDesktopRunEngineEventLoopWithTimeout(engine_.get(), + timeout_milliseconds); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/flutter_engine_unittests.cc b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/flutter_engine_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..2a4da96fc8fe4bf73611a22b46d8817dd5524a28 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/flutter_engine_unittests.cc @@ -0,0 +1,103 @@ +// 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 +#include + +#include "flutter/shell/platform/glfw/client_wrapper/include/flutter/flutter_engine.h" +#include "flutter/shell/platform/glfw/client_wrapper/testing/stub_flutter_glfw_api.h" +#include "gtest/gtest.h" + +namespace flutter { + +namespace { + +// Stub implementation to validate calls to the API. +class TestGlfwApi : public testing::StubFlutterGlfwApi { + public: + // |flutter::testing::StubFlutterGlfwApi| + FlutterDesktopEngineRef RunEngine( + const FlutterDesktopEngineProperties& properties) override { + run_called_ = true; + return reinterpret_cast(1); + } + + // |flutter::testing::StubFlutterGlfwApi| + void RunEngineEventLoopWithTimeout(uint32_t millisecond_timeout) override { + last_run_loop_timeout_ = millisecond_timeout; + } + + // |flutter::testing::StubFlutterGlfwApi| + bool ShutDownEngine() override { + shut_down_called_ = true; + return true; + } + + bool run_called() { return run_called_; } + + bool shut_down_called() { return shut_down_called_; } + + uint32_t last_run_loop_timeout() { return last_run_loop_timeout_; } + + private: + bool run_called_ = false; + bool shut_down_called_ = false; + uint32_t last_run_loop_timeout_ = 0; +}; + +} // namespace + +TEST(FlutterEngineTest, CreateDestroy) { + const std::string icu_data_path = "fake/path/to/icu"; + const std::string assets_path = "fake/path/to/assets"; + testing::ScopedStubFlutterGlfwApi scoped_api_stub( + std::make_unique()); + auto test_api = static_cast(scoped_api_stub.stub()); + { + FlutterEngine engine; + engine.Start(icu_data_path, assets_path, {}); + EXPECT_EQ(test_api->run_called(), true); + EXPECT_EQ(test_api->shut_down_called(), false); + } + // Destroying should implicitly shut down if it hasn't been done manually. + EXPECT_EQ(test_api->shut_down_called(), true); +} + +TEST(FlutterEngineTest, ExplicitShutDown) { + const std::string icu_data_path = "fake/path/to/icu"; + const std::string assets_path = "fake/path/to/assets"; + testing::ScopedStubFlutterGlfwApi scoped_api_stub( + std::make_unique()); + auto test_api = static_cast(scoped_api_stub.stub()); + + FlutterEngine engine; + engine.Start(icu_data_path, assets_path, {}); + EXPECT_EQ(test_api->run_called(), true); + EXPECT_EQ(test_api->shut_down_called(), false); + engine.ShutDown(); + EXPECT_EQ(test_api->shut_down_called(), true); +} + +TEST(FlutterEngineTest, RunloopTimeoutTranslation) { + const std::string icu_data_path = "fake/path/to/icu"; + const std::string assets_path = "fake/path/to/assets"; + testing::ScopedStubFlutterGlfwApi scoped_api_stub( + std::make_unique()); + auto test_api = static_cast(scoped_api_stub.stub()); + + FlutterEngine engine; + engine.Start(icu_data_path, assets_path, {}); + + engine.RunEventLoopWithTimeout(std::chrono::milliseconds(100)); + EXPECT_EQ(test_api->last_run_loop_timeout(), 100U); + + engine.RunEventLoopWithTimeout(std::chrono::milliseconds::max() - + std::chrono::milliseconds(1)); + EXPECT_EQ(test_api->last_run_loop_timeout(), UINT32_MAX); + + engine.RunEventLoopWithTimeout(std::chrono::milliseconds::max()); + EXPECT_EQ(test_api->last_run_loop_timeout(), 0U); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/flutter_window_controller.cc b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/flutter_window_controller.cc new file mode 100644 index 0000000000000000000000000000000000000000..5d59e2a75aa27ef0a2921faaee4ae7841a45c574 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/flutter_window_controller.cc @@ -0,0 +1,123 @@ +// 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 "include/flutter/flutter_window_controller.h" + +#include +#include + +namespace flutter { + +FlutterWindowController::FlutterWindowController( + const std::string& icu_data_path) + : icu_data_path_(icu_data_path) { + init_succeeded_ = FlutterDesktopInit(); +} + +FlutterWindowController::~FlutterWindowController() { + if (controller_) { + FlutterDesktopDestroyWindow(controller_); + } + if (init_succeeded_) { + FlutterDesktopTerminate(); + } +} + +bool FlutterWindowController::CreateWindow( + const WindowProperties& window_properties, + const std::string& assets_path, + const std::vector& arguments, + const std::string& aot_library_path) { + if (!init_succeeded_) { + std::cerr << "Could not create window; FlutterDesktopInit failed." + << std::endl; + return false; + } + + if (controller_) { + std::cerr << "Only one Flutter window can exist at a time." << std::endl; + return false; + } + + FlutterDesktopWindowProperties c_window_properties = {}; + c_window_properties.title = window_properties.title.c_str(); + c_window_properties.width = window_properties.width; + c_window_properties.height = window_properties.height; + c_window_properties.prevent_resize = window_properties.prevent_resize; + + FlutterDesktopEngineProperties c_engine_properties = {}; + c_engine_properties.assets_path = assets_path.c_str(); + c_engine_properties.aot_library_path = aot_library_path.c_str(); + c_engine_properties.icu_data_path = icu_data_path_.c_str(); + std::vector engine_switches; + std::transform( + arguments.begin(), arguments.end(), std::back_inserter(engine_switches), + [](const std::string& arg) -> const char* { return arg.c_str(); }); + if (!engine_switches.empty()) { + c_engine_properties.switches = &engine_switches[0]; + c_engine_properties.switches_count = engine_switches.size(); + } + + controller_ = + FlutterDesktopCreateWindow(c_window_properties, c_engine_properties); + if (!controller_) { + std::cerr << "Failed to create window." << std::endl; + return false; + } + window_ = + std::make_unique(FlutterDesktopGetWindow(controller_)); + return true; +} + +void FlutterWindowController::DestroyWindow() { + if (controller_) { + FlutterDesktopDestroyWindow(controller_); + controller_ = nullptr; + window_ = nullptr; + } +} + +FlutterDesktopPluginRegistrarRef FlutterWindowController::GetRegistrarForPlugin( + const std::string& plugin_name) { + if (!controller_) { + std::cerr << "Cannot get plugin registrar without a window; call " + "CreateWindow first." + << std::endl; + return nullptr; + } + return FlutterDesktopGetPluginRegistrar(FlutterDesktopGetEngine(controller_), + plugin_name.c_str()); +} + +bool FlutterWindowController::RunEventLoopWithTimeout( + std::chrono::milliseconds timeout) { + if (!controller_) { + std::cerr << "Cannot run event loop without a window window; call " + "CreateWindow first." + << std::endl; + return false; + } + uint32_t timeout_milliseconds; + if (timeout == std::chrono::milliseconds::max()) { + // The C API uses 0 to represent no timeout, so convert |max| to 0. + timeout_milliseconds = 0; + } else if (timeout.count() > UINT32_MAX) { + timeout_milliseconds = UINT32_MAX; + } else { + timeout_milliseconds = static_cast(timeout.count()); + } + bool still_running = FlutterDesktopRunWindowEventLoopWithTimeout( + controller_, timeout_milliseconds); + if (!still_running) { + DestroyWindow(); + } + return still_running; +} + +void FlutterWindowController::RunEventLoop() { + while (RunEventLoopWithTimeout()) { + } +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/flutter_window_controller_unittests.cc b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/flutter_window_controller_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..d0e90fcb5056c2d97af79d5dd9012d9425ff8451 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/flutter_window_controller_unittests.cc @@ -0,0 +1,54 @@ +// 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/shell/platform/glfw/client_wrapper/include/flutter/flutter_window_controller.h" + +#include +#include + +#include "flutter/shell/platform/glfw/client_wrapper/testing/stub_flutter_glfw_api.h" +#include "gtest/gtest.h" + +namespace flutter { + +namespace { + +// Stub implementation to validate calls to the API. +class TestGlfwApi : public testing::StubFlutterGlfwApi { + public: + // |flutter::testing::StubFlutterGlfwApi| + bool Init() override { + init_called_ = true; + return true; + } + + // |flutter::testing::StubFlutterGlfwApi| + void Terminate() override { terminate_called_ = true; } + + bool init_called() { return init_called_; } + + bool terminate_called() { return terminate_called_; } + + private: + bool init_called_ = false; + bool terminate_called_ = false; +}; + +} // namespace + +TEST(FlutterViewControllerTest, CreateDestroy) { + const std::string icu_data_path = "fake/path/to/icu"; + testing::ScopedStubFlutterGlfwApi scoped_api_stub( + std::make_unique()); + auto test_api = static_cast(scoped_api_stub.stub()); + { + FlutterWindowController controller(icu_data_path); + EXPECT_EQ(test_api->init_called(), true); + EXPECT_EQ(test_api->terminate_called(), false); + } + EXPECT_EQ(test_api->init_called(), true); + EXPECT_EQ(test_api->terminate_called(), true); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/flutter_window_unittests.cc b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/flutter_window_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..31065d7e771d35ae45494c9e69e020231792dc68 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/flutter_window_unittests.cc @@ -0,0 +1,57 @@ +// 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/shell/platform/glfw/client_wrapper/include/flutter/flutter_window.h" + +#include +#include + +#include "flutter/shell/platform/glfw/client_wrapper/testing/stub_flutter_glfw_api.h" +#include "gtest/gtest.h" + +namespace flutter { + +namespace { + +// Stub implementation to validate calls to the API. +class TestGlfwApi : public testing::StubFlutterGlfwApi { + public: + // |flutter::testing::StubFlutterGlfwApi| + void SetSizeLimits(FlutterDesktopSize minimum_size, + FlutterDesktopSize maximum_size) override { + set_size_limits_called_ = true; + } + + bool set_size_limits_called() { return set_size_limits_called_; } + + private: + bool set_size_limits_called_ = false; +}; + +} // namespace + +TEST(FlutterWindowTest, SetSizeLimits) { + const std::string icu_data_path = "fake/path/to/icu"; + testing::ScopedStubFlutterGlfwApi scoped_api_stub( + std::make_unique()); + auto test_api = static_cast(scoped_api_stub.stub()); + // This is not actually used so any non-zero value works. + auto raw_window = reinterpret_cast(1); + + auto window = std::make_unique(raw_window); + + FlutterDesktopSize minimum_size = {}; + minimum_size.width = 100; + minimum_size.height = 100; + + FlutterDesktopSize maximum_size = {}; + maximum_size.width = -1; + maximum_size.height = -1; + + window->SetSizeLimits(minimum_size, maximum_size); + + EXPECT_EQ(test_api->set_size_limits_called(), true); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/include/flutter/flutter_engine.h b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/include/flutter/flutter_engine.h new file mode 100644 index 0000000000000000000000000000000000000000..d2365ff7ad213ff30a6118a78d21803df24607a3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/include/flutter/flutter_engine.h @@ -0,0 +1,61 @@ +// 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_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_ENGINE_H_ +#define FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_ENGINE_H_ + +#include + +#include +#include +#include +#include + +#include "plugin_registrar.h" +#include "plugin_registry.h" + +namespace flutter { + +// An engine for running a headless Flutter application. +class FlutterEngine : public PluginRegistry { + public: + explicit FlutterEngine(); + + virtual ~FlutterEngine(); + + // Prevent copying. + FlutterEngine(FlutterEngine const&) = delete; + FlutterEngine& operator=(FlutterEngine const&) = delete; + + // Starts running the engine with the given parameters, returning true if + // successful. + bool Start(const std::string& icu_data_path, + const std::string& assets_path, + const std::vector& arguments, + const std::string& aot_library_path = ""); + + // Terminates the running engine. + void ShutDown(); + + // Processes the next event for the engine, or returns early if |timeout| is + // reached before the next event. + void RunEventLoopWithTimeout( + std::chrono::milliseconds timeout = std::chrono::milliseconds::max()); + + // flutter::PluginRegistry: + FlutterDesktopPluginRegistrarRef GetRegistrarForPlugin( + const std::string& plugin_name) override; + + private: + using UniqueEnginePtr = std::unique_ptr; + + // Handle for interacting with the C API's engine reference. + UniqueEnginePtr engine_ = + UniqueEnginePtr(nullptr, FlutterDesktopShutDownEngine); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_ENGINE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/include/flutter/flutter_window.h b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/include/flutter/flutter_window.h new file mode 100644 index 0000000000000000000000000000000000000000..0f52c32c502885763ad091543116811cef9423fc --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/include/flutter/flutter_window.h @@ -0,0 +1,107 @@ +// 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_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_WINDOW_H_ +#define FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_WINDOW_H_ + +#include + +#include +#include + +#include "plugin_registrar.h" + +namespace flutter { + +// A data type for window position and size. +struct WindowFrame { + int left; + int top; + int width; + int height; +}; + +// A window displaying Flutter content. +class FlutterWindow { + public: + explicit FlutterWindow(FlutterDesktopWindowRef window) : window_(window) {} + + ~FlutterWindow() = default; + + // Prevent copying. + FlutterWindow(FlutterWindow const&) = delete; + FlutterWindow& operator=(FlutterWindow const&) = delete; + + // Enables or disables hover tracking. + // + // If hover is enabled, mouse movement will send hover events to the Flutter + // engine, rather than only tracking the mouse while the button is pressed. + // Defaults to off. + void SetHoverEnabled(bool enabled) { + FlutterDesktopWindowSetHoverEnabled(window_, enabled); + } + + // Sets the displayed title of the window. + void SetTitle(const std::string& title) { + FlutterDesktopWindowSetTitle(window_, title.c_str()); + } + + // Sets the displayed icon for the window. + // + // The pixel format is 32-bit RGBA. The provided image data only needs to be + // valid for the duration of the call to this method. Pass a nullptr to revert + // to the default icon. + void SetIcon(uint8_t* pixel_data, int width, int height) { + FlutterDesktopWindowSetIcon(window_, pixel_data, width, height); + } + + // Returns the frame of the window, including any decoration (e.g., title + // bar), in screen coordinates. + WindowFrame GetFrame() { + WindowFrame frame = {}; + FlutterDesktopWindowGetFrame(window_, &frame.left, &frame.top, &frame.width, + &frame.height); + return frame; + } + + // Set the frame of the window, including any decoration (e.g., title + // bar), in screen coordinates. + void SetFrame(const WindowFrame& frame) { + FlutterDesktopWindowSetFrame(window_, frame.left, frame.top, frame.width, + frame.height); + } + + // Returns the number of pixels per screen coordinate for the window. + // + // Flutter uses pixel coordinates, so this is the ratio of positions and sizes + // seen by Flutter as compared to the screen. + double GetScaleFactor() { + return FlutterDesktopWindowGetScaleFactor(window_); + } + + // Forces a specific pixel ratio for Flutter rendering, rather than one + // computed automatically from screen information. + // + // To clear a previously set override, pass an override value of zero. + void SetPixelRatioOverride(double pixel_ratio) { + FlutterDesktopWindowSetPixelRatioOverride(window_, pixel_ratio); + } + + // Sets the min/max size of |flutter_window| in screen coordinates. Use + // kFlutterDesktopDontCare for any dimension you wish to leave unconstrained. + void SetSizeLimits(FlutterDesktopSize minimum_size, + FlutterDesktopSize maximum_size) { + FlutterDesktopWindowSetSizeLimits(window_, minimum_size, maximum_size); + } + + private: + // Handle for interacting with the C API's window. + // + // Note: window_ is conceptually owned by the controller, not this object. + FlutterDesktopWindowRef window_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_WINDOW_H_ diff --git a/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/include/flutter/flutter_window_controller.h b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/include/flutter/flutter_window_controller.h new file mode 100644 index 0000000000000000000000000000000000000000..22cf2d2fa3c18e3efd049948c50481f8888721bb --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/include/flutter/flutter_window_controller.h @@ -0,0 +1,121 @@ +// 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_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_WINDOW_CONTROLLER_H_ +#define FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_WINDOW_CONTROLLER_H_ + +#include + +#include +#include +#include +#include + +#include "flutter_window.h" +#include "plugin_registrar.h" +#include "plugin_registry.h" + +namespace flutter { + +// Properties for Flutter window creation. +struct WindowProperties { + // The display title. + std::string title; + // Width in screen coordinates. + int32_t width; + // Height in screen coordinates. + int32_t height; + // Whether or not the user is prevented from resizing the window. + // Reversed so that the default for a cleared struct is to allow resizing. + bool prevent_resize; +}; + +// A controller for a window displaying Flutter content. +// +// This is the primary wrapper class for the desktop C API. +// If you use this class, you should not call any of the setup or teardown +// methods in the C API directly, as this class will do that internally. +// +// Note: This is an early implementation (using GLFW internally) which +// requires control of the application's event loop, and is thus useful +// primarily for building a simple one-window shell hosting a Flutter +// application. The final implementation and API will be very different. +class FlutterWindowController : public PluginRegistry { + public: + // There must be only one instance of this class in an application at any + // given time, as Flutter does not support multiple engines in one process, + // or multiple views in one engine. + // + // |icu_data_path| is the path to the icudtl.dat file for the version of + // Flutter you are using. + explicit FlutterWindowController(const std::string& icu_data_path); + + virtual ~FlutterWindowController(); + + // Prevent copying. + FlutterWindowController(FlutterWindowController const&) = delete; + FlutterWindowController& operator=(FlutterWindowController const&) = delete; + + // Creates and displays a window for displaying Flutter content. + // + // The |assets_path| is the path to the flutter_assets folder for the Flutter + // application to be run. + // + // The |arguments| are passed to the Flutter engine. See: + // https://github.com/flutter/engine/blob/main/shell/common/switches.h for + // details. Not all arguments will apply to desktop. + // + // The |aot_library_path| is the path to the libapp.so file for the Flutter + // application to be run. While this parameter is only required in AOT mode, + // it is perfectly safe to provide the path in non-AOT mode too. + // + // Only one Flutter window can exist at a time; see constructor comment. + bool CreateWindow(const WindowProperties& window_properties, + const std::string& assets_path, + const std::vector& arguments, + const std::string& aot_library_path = ""); + + // Destroys the current window, if any. + // + // Because only one window can exist at a time, this method must be called + // between calls to CreateWindow, or the second one will fail. + void DestroyWindow(); + + // The FlutterWindow managed by this controller, if any. Returns nullptr + // before CreateWindow is called, after DestroyWindow is called, and after + // RunEventLoop returns; + FlutterWindow* window() { return window_.get(); } + + // Processes the next event on this window, or returns early if |timeout| is + // reached before the next event. + // + // Returns false if the window was closed as a result of event processing. + bool RunEventLoopWithTimeout( + std::chrono::milliseconds timeout = std::chrono::milliseconds::max()); + + // Deprecated. Use RunEventLoopWithTimeout. + void RunEventLoop(); + + // flutter::PluginRegistry: + FlutterDesktopPluginRegistrarRef GetRegistrarForPlugin( + const std::string& plugin_name) override; + + private: + // The path to the ICU data file. Set at creation time since it is the same + // for any window created. + std::string icu_data_path_; + + // Whether or not FlutterDesktopInit succeeded at creation time. + bool init_succeeded_ = false; + + // The owned FlutterWindow, if any. + std::unique_ptr window_; + + // Handle for interacting with the C API's window controller, if any. + FlutterDesktopWindowControllerRef controller_ = nullptr; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_WINDOW_CONTROLLER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/include/flutter/plugin_registrar_glfw.h b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/include/flutter/plugin_registrar_glfw.h new file mode 100644 index 0000000000000000000000000000000000000000..2459dde60bf296fb138b02274814e63b3172b0f2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/include/flutter/plugin_registrar_glfw.h @@ -0,0 +1,58 @@ +// 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_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRAR_GLFW_H_ +#define FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRAR_GLFW_H_ + +#include + +#include + +#include "flutter_window.h" +#include "plugin_registrar.h" + +namespace flutter { + +// An extension to PluginRegistrar providing access to GLFW-shell-specific +// functionality. +class PluginRegistrarGlfw : public PluginRegistrar { + public: + // Creates a new PluginRegistrar. |core_registrar| and the messenger it + // provides must remain valid as long as this object exists. + explicit PluginRegistrarGlfw(FlutterDesktopPluginRegistrarRef core_registrar) + : PluginRegistrar(core_registrar) { + window_ = std::make_unique( + FlutterDesktopPluginRegistrarGetWindow(core_registrar)); + } + + virtual ~PluginRegistrarGlfw() { + // Must be the first call. + ClearPlugins(); + // Explicitly cleared to facilitate destruction order testing. + window_.reset(); + } + + // Prevent copying. + PluginRegistrarGlfw(PluginRegistrarGlfw const&) = delete; + PluginRegistrarGlfw& operator=(PluginRegistrarGlfw const&) = delete; + + FlutterWindow* window() { return window_.get(); } + + // Enables input blocking on the given channel name. + // + // If set, then the parent window should disable input callbacks + // while waiting for the handler for messages on that channel to run. + void EnableInputBlockingForChannel(const std::string& channel) { + FlutterDesktopPluginRegistrarEnableInputBlocking(registrar(), + channel.c_str()); + } + + private: + // The owned FlutterWindow, if any. + std::unique_ptr window_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRAR_GLFW_H_ diff --git a/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/plugin_registrar_glfw_unittests.cc b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/plugin_registrar_glfw_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..ff95921fb35e38fb442e80e8097db83ef333f861 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/plugin_registrar_glfw_unittests.cc @@ -0,0 +1,60 @@ +// 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 +#include + +#include "flutter/shell/platform/glfw/client_wrapper/include/flutter/plugin_registrar_glfw.h" +#include "flutter/shell/platform/glfw/client_wrapper/testing/stub_flutter_glfw_api.h" +#include "gtest/gtest.h" + +namespace flutter { + +namespace { + +// A test plugin that tries to access registrar state during destruction and +// reports it out via a flag provided at construction. +class TestPlugin : public Plugin { + public: + // registrar_valid_at_destruction will be set at destruction to indicate + // whether or not |registrar->window()| was non-null. + TestPlugin(PluginRegistrarGlfw* registrar, + bool* registrar_valid_at_destruction) + : registrar_(registrar), + registrar_valid_at_destruction_(registrar_valid_at_destruction) {} + virtual ~TestPlugin() { + *registrar_valid_at_destruction_ = registrar_->window() != nullptr; + } + + private: + PluginRegistrarGlfw* registrar_; + bool* registrar_valid_at_destruction_; +}; + +} // namespace + +TEST(PluginRegistrarGlfwTest, GetView) { + testing::ScopedStubFlutterGlfwApi scoped_api_stub( + std::make_unique()); + PluginRegistrarGlfw registrar( + reinterpret_cast(1)); + EXPECT_NE(registrar.window(), nullptr); +} + +// Tests that the registrar runs plugin destructors before its own teardown. +TEST(PluginRegistrarGlfwTest, PluginDestroyedBeforeRegistrar) { + auto dummy_registrar_handle = + reinterpret_cast(1); + bool registrar_valid_at_destruction = false; + { + PluginRegistrarGlfw registrar(dummy_registrar_handle); + + auto plugin = std::make_unique(®istrar, + ®istrar_valid_at_destruction); + registrar.AddPlugin(std::move(plugin)); + } + EXPECT_TRUE(registrar_valid_at_destruction); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/testing/stub_flutter_glfw_api.cc b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/testing/stub_flutter_glfw_api.cc new file mode 100644 index 0000000000000000000000000000000000000000..df61b345507159d2b20ebb777ee49c01537be3f2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/testing/stub_flutter_glfw_api.cc @@ -0,0 +1,198 @@ +// 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/shell/platform/glfw/client_wrapper/testing/stub_flutter_glfw_api.h" + +static flutter::testing::StubFlutterGlfwApi* s_stub_implementation; + +namespace flutter { +namespace testing { + +// static +void StubFlutterGlfwApi::SetTestStub(StubFlutterGlfwApi* stub) { + s_stub_implementation = stub; +} + +// static +StubFlutterGlfwApi* StubFlutterGlfwApi::GetTestStub() { + return s_stub_implementation; +} + +ScopedStubFlutterGlfwApi::ScopedStubFlutterGlfwApi( + std::unique_ptr stub) + : stub_(std::move(stub)) { + previous_stub_ = StubFlutterGlfwApi::GetTestStub(); + StubFlutterGlfwApi::SetTestStub(stub_.get()); +} + +ScopedStubFlutterGlfwApi::~ScopedStubFlutterGlfwApi() { + StubFlutterGlfwApi::SetTestStub(previous_stub_); +} + +} // namespace testing +} // namespace flutter + +// Forwarding dummy implementations of the C API. + +bool FlutterDesktopInit() { + if (s_stub_implementation) { + s_stub_implementation->Init(); + } + return true; +} + +void FlutterDesktopTerminate() { + if (s_stub_implementation) { + s_stub_implementation->Terminate(); + } +} + +FlutterDesktopWindowControllerRef FlutterDesktopCreateWindow( + const FlutterDesktopWindowProperties& window_properties, + const FlutterDesktopEngineProperties& engine_properties) { + if (s_stub_implementation) { + return s_stub_implementation->CreateWindow(window_properties, + engine_properties); + } + return nullptr; +} + +void FlutterDesktopDestroyWindow(FlutterDesktopWindowControllerRef controller) { + if (s_stub_implementation) { + s_stub_implementation->DestroyWindow(); + } +} + +void FlutterDesktopWindowSetHoverEnabled(FlutterDesktopWindowRef flutter_window, + bool enabled) { + if (s_stub_implementation) { + s_stub_implementation->SetHoverEnabled(enabled); + } +} + +void FlutterDesktopWindowSetTitle(FlutterDesktopWindowRef flutter_window, + const char* title) { + if (s_stub_implementation) { + s_stub_implementation->SetWindowTitle(title); + } +} + +void FlutterDesktopWindowSetIcon(FlutterDesktopWindowRef flutter_window, + uint8_t* pixel_data, + int width, + int height) { + if (s_stub_implementation) { + s_stub_implementation->SetWindowIcon(pixel_data, width, height); + } +} + +void FlutterDesktopWindowGetFrame(FlutterDesktopWindowRef flutter_window, + int* x, + int* y, + int* width, + int* height) { + if (s_stub_implementation) { + s_stub_implementation->GetWindowFrame(x, y, width, height); + } +} + +void FlutterDesktopWindowSetFrame(FlutterDesktopWindowRef flutter_window, + int x, + int y, + int width, + int height) { + if (s_stub_implementation) { + s_stub_implementation->SetWindowFrame(x, y, width, height); + } +} + +void FlutterDesktopWindowSetSizeLimits(FlutterDesktopWindowRef flutter_window, + FlutterDesktopSize minimum_size, + FlutterDesktopSize maximum_size) { + if (s_stub_implementation) { + s_stub_implementation->SetSizeLimits(minimum_size, maximum_size); + } +} + +double FlutterDesktopWindowGetScaleFactor( + FlutterDesktopWindowRef flutter_window) { + if (s_stub_implementation) { + return s_stub_implementation->GetWindowScaleFactor(); + } + return 1.0; +} + +void FlutterDesktopWindowSetPixelRatioOverride( + FlutterDesktopWindowRef flutter_window, + double pixel_ratio) { + if (s_stub_implementation) { + return s_stub_implementation->SetPixelRatioOverride(pixel_ratio); + } +} + +bool FlutterDesktopRunWindowEventLoopWithTimeout( + FlutterDesktopWindowControllerRef controller, + uint32_t millisecond_timeout) { + if (s_stub_implementation) { + return s_stub_implementation->RunWindowEventLoopWithTimeout( + millisecond_timeout); + } + return true; +} + +FlutterDesktopEngineRef FlutterDesktopRunEngine( + const FlutterDesktopEngineProperties& properties) { + if (s_stub_implementation) { + return s_stub_implementation->RunEngine(properties); + } + return nullptr; +} + +void FlutterDesktopRunEngineEventLoopWithTimeout( + FlutterDesktopEngineRef engine, + uint32_t timeout_milliseconds) { + if (s_stub_implementation) { + s_stub_implementation->RunEngineEventLoopWithTimeout(timeout_milliseconds); + } +} + +bool FlutterDesktopShutDownEngine(FlutterDesktopEngineRef engine_ref) { + if (s_stub_implementation) { + return s_stub_implementation->ShutDownEngine(); + } + return true; +} + +FlutterDesktopWindowRef FlutterDesktopGetWindow( + FlutterDesktopWindowControllerRef controller) { + // The stub ignores this, so just return an arbitrary non-zero value. + return reinterpret_cast(1); +} + +FlutterDesktopEngineRef FlutterDesktopGetEngine( + FlutterDesktopWindowControllerRef controller) { + // The stub ignores this, so just return an arbitrary non-zero value. + return reinterpret_cast(3); +} + +FlutterDesktopPluginRegistrarRef FlutterDesktopGetPluginRegistrar( + FlutterDesktopEngineRef engine, + const char* plugin_name) { + // The stub ignores this, so just return an arbitrary non-zero value. + return reinterpret_cast(2); +} + +FlutterDesktopWindowRef FlutterDesktopPluginRegistrarGetWindow( + FlutterDesktopPluginRegistrarRef registrar) { + // The stub ignores this, so just return an arbitrary non-zero value. + return reinterpret_cast(3); +} + +void FlutterDesktopPluginRegistrarEnableInputBlocking( + FlutterDesktopPluginRegistrarRef registrar, + const char* channel) { + if (s_stub_implementation) { + s_stub_implementation->PluginRegistrarEnableInputBlocking(channel); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/testing/stub_flutter_glfw_api.h b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/testing/stub_flutter_glfw_api.h new file mode 100644 index 0000000000000000000000000000000000000000..82ee361198c85ec4e94edd74e3bd5e683eb25394 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/glfw/client_wrapper/testing/stub_flutter_glfw_api.h @@ -0,0 +1,117 @@ +// 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_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_TESTING_STUB_FLUTTER_GLFW_API_H_ +#define FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_TESTING_STUB_FLUTTER_GLFW_API_H_ + +#include + +#include "flutter/shell/platform/glfw/public/flutter_glfw.h" + +namespace flutter { +namespace testing { + +// Base class for a object that provides test implementations of the APIs in +// the headers in platform/glfw/public/. + +// Linking this class into a test binary will provide dummy forwarding +// implementations of that C API, so that the wrapper can be tested separately +// from the actual library. +class StubFlutterGlfwApi { + public: + // Sets |stub| as the instance to which calls to the Flutter library C APIs + // will be forwarded. + static void SetTestStub(StubFlutterGlfwApi* stub); + + // Returns the current stub, as last set by SetTestFlutterStub. + static StubFlutterGlfwApi* GetTestStub(); + + virtual ~StubFlutterGlfwApi() {} + + // Called for FlutterDesktopInit. + virtual bool Init() { return true; } + + // Called for FlutterDesktopTerminate. + virtual void Terminate() {} + + // Called for FlutterDesktopCreateWindow. + virtual FlutterDesktopWindowControllerRef CreateWindow( + const FlutterDesktopWindowProperties& window_properties, + const FlutterDesktopEngineProperties& engine_properties) { + return nullptr; + } + + // Called for FlutterDesktopDestroyWindow + virtual void DestroyWindow() {} + + // Called for FlutterDesktopWindowSetHoverEnabled. + virtual void SetHoverEnabled(bool enabled) {} + + // Called for FlutterDesktopWindowSetTitle. + virtual void SetWindowTitle(const char* title) {} + + // Called for FlutterDesktopWindowSetIcon. + virtual void SetWindowIcon(uint8_t* pixel_data, int width, int height) {} + + // Called for FlutterDesktopWindowGetFrame. + virtual void GetWindowFrame(int* x, int* y, int* width, int* height) { + x = y = width = height = 0; + } + + // Called for FlutterDesktopWindowGetFrame. + virtual void SetWindowFrame(int x, int y, int width, int height) {} + + // Called for FlutterDesktopWindowGetScaleFactor. + virtual double GetWindowScaleFactor() { return 1.0; } + + // Called for FlutterDesktopWindowSetPixelRatioOverride. + virtual void SetPixelRatioOverride(double pixel_ratio) {} + + // Called for FlutterDesktopWindowSetSizeLimits. + virtual void SetSizeLimits(FlutterDesktopSize minimum_size, + FlutterDesktopSize maximum_size) {} + + // Called for FlutterDesktopRunWindowEventLoopWithTimeout. + virtual bool RunWindowEventLoopWithTimeout(uint32_t millisecond_timeout) { + return true; + } + + // Called for FlutterDesktopRunEngine. + virtual FlutterDesktopEngineRef RunEngine( + const FlutterDesktopEngineProperties& properties) { + return nullptr; + } + + // Called for FlutterDesktopRunEngineEventLoopWithTimeout. + virtual void RunEngineEventLoopWithTimeout(uint32_t millisecond_timeout) {} + + // Called for FlutterDesktopShutDownEngine. + virtual bool ShutDownEngine() { return true; } + + // Called for FlutterDesktopPluginRegistrarEnableInputBlocking. + virtual void PluginRegistrarEnableInputBlocking(const char* channel) {} +}; + +// A test helper that owns a stub implementation, making it the test stub for +// the lifetime of the object, then restoring the previous value. +class ScopedStubFlutterGlfwApi { + public: + // Calls SetTestFlutterStub with |stub|. + explicit ScopedStubFlutterGlfwApi(std::unique_ptr stub); + + // Restores the previous test stub. + ~ScopedStubFlutterGlfwApi(); + + StubFlutterGlfwApi* stub() { return stub_.get(); } + + private: + std::unique_ptr stub_; + // The previous stub. + StubFlutterGlfwApi* previous_stub_; +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_TESTING_STUB_FLUTTER_GLFW_API_H_ diff --git a/flutter/engine/src/flutter/shell/platform/glfw/public/flutter_glfw.h b/flutter/engine/src/flutter/shell/platform/glfw/public/flutter_glfw.h new file mode 100644 index 0000000000000000000000000000000000000000..7dbb8b9395ff0117f7f4f4624022a639ddd4532c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/glfw/public/flutter_glfw.h @@ -0,0 +1,246 @@ +// 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_SHELL_PLATFORM_GLFW_PUBLIC_FLUTTER_GLFW_H_ +#define FLUTTER_SHELL_PLATFORM_GLFW_PUBLIC_FLUTTER_GLFW_H_ + +#include +#include + +#include "flutter_export.h" +#include "flutter_messenger.h" +#include "flutter_plugin_registrar.h" + +#if defined(__cplusplus) +extern "C" { +#endif + +// Indicates that any value is acceptable for an otherwise required property. +extern const int32_t kFlutterDesktopDontCare; + +// Opaque reference to a Flutter window controller. +typedef struct FlutterDesktopWindowControllerState* + FlutterDesktopWindowControllerRef; + +// Opaque reference to a Flutter window. +typedef struct FlutterDesktopWindow* FlutterDesktopWindowRef; + +// Opaque reference to a Flutter engine instance. +typedef struct FlutterDesktopEngineState* FlutterDesktopEngineRef; + +// Properties representing a generic rectangular size. +typedef struct { + int32_t width; + int32_t height; +} FlutterDesktopSize; + +// Properties for configuring a Flutter engine instance. +typedef struct { + // The path to the flutter_assets folder for the application to be run. + // This can either be an absolute path, or on Windows or Linux, a path + // relative to the directory containing the executable. + const char* assets_path; + // The path to the icudtl.dat file for the version of Flutter you are using. + // This can either be an absolute path, or on Windows or Linux, a path + // relative to the directory containing the executable. + const char* icu_data_path; + // The path to the libapp.so file for the application to be run. + // This can either be an absolute path or a path relative to the directory + // containing the executable. + const char* aot_library_path; + // The switches to pass to the Flutter engine. + // + // See: https://github.com/flutter/engine/blob/main/shell/common/switches.h + // for details. Not all arguments will apply to desktop. + const char** switches; + // The number of elements in |switches|. + size_t switches_count; +} FlutterDesktopEngineProperties; + +// Properties for configuring the initial settings of a Flutter window. +typedef struct { + // The display title. + const char* title; + // Width in screen coordinates. + int32_t width; + // Height in screen coordinates. + int32_t height; + // Whether or not the user is prevented from resizing the window. + // Reversed so that the default for a cleared struct is to allow resizing. + bool prevent_resize; +} FlutterDesktopWindowProperties; + +// Sets up the library's graphic context. Must be called before any other +// methods. +// +// Note: Internally, this library uses GLFW, which does not support multiple +// copies within the same process. Internally this calls glfwInit, which will +// fail if you have called glfwInit elsewhere in the process. +FLUTTER_EXPORT bool FlutterDesktopInit(); + +// Tears down library state. Must be called before the process terminates. +FLUTTER_EXPORT void FlutterDesktopTerminate(); + +// Creates a Window running a Flutter Application. +// +// FlutterDesktopInit() must be called prior to this function. +// +// This will set up and run an associated Flutter engine using the settings in +// |engine_properties|. +// +// Returns a null pointer in the event of an error. Otherwise, the pointer is +// valid until FlutterDesktopDestroyWindow is called. +// Note that calling FlutterDesktopCreateWindow without later calling +// FlutterDesktopDestroyWindow on the returned reference is a memory leak. +FLUTTER_EXPORT FlutterDesktopWindowControllerRef FlutterDesktopCreateWindow( + const FlutterDesktopWindowProperties& window_properties, + const FlutterDesktopEngineProperties& engine_properties); + +// Shuts down the engine instance associated with |controller|, and cleans up +// associated state. +// +// |controller| is no longer valid after this call. +FLUTTER_EXPORT void FlutterDesktopDestroyWindow( + FlutterDesktopWindowControllerRef controller); + +// Waits for and processes the next event before |timeout_milliseconds|. +// +// If |timeout_milliseconds| is zero, it will wait for the next event +// indefinitely. A non-zero timeout is needed only if processing unrelated to +// the event loop is necessary (e.g., to handle events from another source). +// +// Returns false if the window should be closed as a result of the last event +// processed. +FLUTTER_EXPORT bool FlutterDesktopRunWindowEventLoopWithTimeout( + FlutterDesktopWindowControllerRef controller, + uint32_t timeout_milliseconds); + +// Returns the window handle for the window associated with +// FlutterDesktopWindowControllerRef. +// +// Its lifetime is the same as the |controller|'s. +FLUTTER_EXPORT FlutterDesktopWindowRef FlutterDesktopGetWindow( + FlutterDesktopWindowControllerRef controller); + +// Returns the handle for the engine running in +// FlutterDesktopWindowControllerRef. +// +// Its lifetime is the same as the |controller|'s. +FLUTTER_EXPORT FlutterDesktopEngineRef FlutterDesktopGetEngine( + FlutterDesktopWindowControllerRef controller); + +// Returns the plugin registrar handle for the plugin with the given name. +// +// The name must be unique across the application. +FLUTTER_EXPORT FlutterDesktopPluginRegistrarRef +FlutterDesktopGetPluginRegistrar(FlutterDesktopEngineRef engine, + const char* plugin_name); + +// Enables or disables hover tracking. +// +// If hover is enabled, mouse movement will send hover events to the Flutter +// engine, rather than only tracking the mouse while the button is pressed. +// Defaults to on. +FLUTTER_EXPORT void FlutterDesktopWindowSetHoverEnabled( + FlutterDesktopWindowRef flutter_window, + bool enabled); + +// Sets the displayed title for |flutter_window|. +FLUTTER_EXPORT void FlutterDesktopWindowSetTitle( + FlutterDesktopWindowRef flutter_window, + const char* title); + +// Sets the displayed icon for |flutter_window|. +// +// The pixel format is 32-bit RGBA. The provided image data only needs to be +// valid for the duration of the call to this method. Pass a nullptr to revert +// to the default icon. +FLUTTER_EXPORT void FlutterDesktopWindowSetIcon( + FlutterDesktopWindowRef flutter_window, + uint8_t* pixel_data, + int width, + int height); + +// Gets the position and size of |flutter_window| in screen coordinates. +FLUTTER_EXPORT void FlutterDesktopWindowGetFrame( + FlutterDesktopWindowRef flutter_window, + int* x, + int* y, + int* width, + int* height); + +// Sets the position and size of |flutter_window| in screen coordinates. +FLUTTER_EXPORT void FlutterDesktopWindowSetFrame( + FlutterDesktopWindowRef flutter_window, + int x, + int y, + int width, + int height); + +// Returns the scale factor--the number of pixels per screen coordinate--for +// |flutter_window|. +FLUTTER_EXPORT double FlutterDesktopWindowGetScaleFactor( + FlutterDesktopWindowRef flutter_window); + +// Forces a specific pixel ratio for Flutter rendering in |flutter_window|, +// rather than one computed automatically from screen information. +// +// To clear a previously set override, pass an override value of zero. +FLUTTER_EXPORT void FlutterDesktopWindowSetPixelRatioOverride( + FlutterDesktopWindowRef flutter_window, + double pixel_ratio); + +// Sets the min/max size of |flutter_window| in screen coordinates. Use +// kFlutterDesktopDontCare for any dimension you wish to leave unconstrained. +FLUTTER_EXPORT void FlutterDesktopWindowSetSizeLimits( + FlutterDesktopWindowRef flutter_window, + FlutterDesktopSize minimum_size, + FlutterDesktopSize maximum_size); + +// Runs an instance of a headless Flutter engine. +// +// Returns a null pointer in the event of an error. +FLUTTER_EXPORT FlutterDesktopEngineRef FlutterDesktopRunEngine( + const FlutterDesktopEngineProperties& properties); + +// Waits for and processes the next event before |timeout_milliseconds|. +// +// If |timeout_milliseconds| is zero, it will wait for the next event +// indefinitely. A non-zero timeout is needed only if processing unrelated to +// the event loop is necessary (e.g., to handle events from another source). +FLUTTER_EXPORT void FlutterDesktopRunEngineEventLoopWithTimeout( + FlutterDesktopEngineRef engine, + uint32_t timeout_milliseconds); + +// Shuts down the given engine instance. Returns true if the shutdown was +// successful. |engine_ref| is no longer valid after this call. +FLUTTER_EXPORT bool FlutterDesktopShutDownEngine( + FlutterDesktopEngineRef engine); + +// Returns the window associated with this registrar's engine instance. +// +// This is a GLFW shell-specific extension to flutter_plugin_registrar.h +FLUTTER_EXPORT FlutterDesktopWindowRef FlutterDesktopPluginRegistrarGetWindow( + FlutterDesktopPluginRegistrarRef registrar); + +// Enables input blocking on the given channel. +// +// If set, then the Flutter window will disable input callbacks +// while waiting for the handler for messages on that channel to run. This is +// useful if handling the message involves showing a modal window, for instance. +// +// This must be called after FlutterDesktopSetMessageHandler, as setting a +// handler on a channel will reset the input blocking state back to the +// default of disabled. +// +// This is a GLFW shell-specific extension to flutter_plugin_registrar.h +FLUTTER_EXPORT void FlutterDesktopPluginRegistrarEnableInputBlocking( + FlutterDesktopPluginRegistrarRef registrar, + const char* channel); + +#if defined(__cplusplus) +} // extern "C" +#endif + +#endif // FLUTTER_SHELL_PLATFORM_GLFW_PUBLIC_FLUTTER_GLFW_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/config/BUILD.gn b/flutter/engine/src/flutter/shell/platform/linux/config/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..da0ac056bc567f2e6cacc816f365edaea6cac287 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/config/BUILD.gn @@ -0,0 +1,22 @@ +# 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. + +import("//build/config/linux/pkg_config.gni") +import("//flutter/shell/platform/glfw/config.gni") + +pkg_config("x11") { + packages = [ "x11" ] +} + +pkg_config("gtk") { + packages = [ "gtk+-3.0" ] +} + +pkg_config("egl") { + packages = [ "egl" ] +} + +pkg_config("epoxy") { + packages = [ "epoxy" ] +} diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_application.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_application.h new file mode 100644 index 0000000000000000000000000000000000000000..c4c4133bdf5a222fcd2a36c343bbc2eca9bea9f9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_application.h @@ -0,0 +1,81 @@ +// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_APPLICATION_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_APPLICATION_H_ + +#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) +#error "Only can be included directly." +#endif + +#include "fl_plugin_registry.h" +#include "fl_view.h" + +#include +#include + +G_BEGIN_DECLS + +G_MODULE_EXPORT +G_DECLARE_DERIVABLE_TYPE(FlApplication, + fl_application, + FL, + APPLICATION, + GtkApplication); + +/** + * FlApplicationClass: + * @register_plugins: invoked when plugins should be registered. + */ +struct _FlApplicationClass { + GtkApplicationClass parent_class; + + /** + * FlApplication::register_plugins: + * @application: the application + * @registry: registry to use. + * + * The ::register_plugins signal is emitted when plugins can be registered. + */ + void (*register_plugins)(FlApplication* application, + FlPluginRegistry* registry); + + /** + * FlApplication::create_window: + * @application: the application + * @view: the view to add to this window. + * + * The ::create_window signal is emitted when a needs to be created for a + * view. By handling this signal the application can create the appropriate + * window for the given view and set any window properties or additional + * widgets required. + * + * If this signal is not handled a standard GTK window will be created. + */ + GtkWindow* (*create_window)(FlApplication* application, FlView* view); +}; + +/** + * FlApplication: + * + * #Flutter-based application with the GTK embedder. + * + * Provides default behaviour for basic Flutter applications. + */ + +/** + * fl_application_new: + * @application_id: (allow-none): The application ID or %NULL. + * @flags: The application flags. + * + * Creates a new Flutter-based application. + * + * Returns: a new #FlApplication + */ +FlApplication* fl_application_new(const gchar* application_id, + GApplicationFlags flags); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_APPLICATION_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_basic_message_channel.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_basic_message_channel.h new file mode 100644 index 0000000000000000000000000000000000000000..44a4217920e67a7d7ee45154f45541fb5730cf70 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_basic_message_channel.h @@ -0,0 +1,209 @@ +// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_BASIC_MESSAGE_CHANNEL_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_BASIC_MESSAGE_CHANNEL_H_ + +#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) +#error "Only can be included directly." +#endif + +#include +#include +#include + +#include "fl_binary_messenger.h" +#include "fl_message_codec.h" + +G_BEGIN_DECLS + +G_MODULE_EXPORT +G_DECLARE_FINAL_TYPE(FlBasicMessageChannel, + fl_basic_message_channel, + FL, + BASIC_MESSAGE_CHANNEL, + GObject) + +G_MODULE_EXPORT +G_DECLARE_FINAL_TYPE(FlBasicMessageChannelResponseHandle, + fl_basic_message_channel_response_handle, + FL, + BASIC_MESSAGE_CHANNEL_RESPONSE_HANDLE, + GObject) + +/** + * FlBasicMessageChannel: + * + * #FlBasicMessageChannel is an object that allows sending and receiving + * messages to/from Dart code over platform channels. + * + * The following example shows how to send messages on a channel: + * + * |[ + * static FlBasicMessageChannel *channel = NULL; + * + * static void message_cb (FlBasicMessageChannel* channel, + * FlValue* message, + * FlBasicMessageChannelResponseHandle* response_handle, + * gpointer user_data) { + * g_autoptr(FlValue) response = handle_message (message); + * g_autoptr(GError) error = NULL; + * if (!fl_basic_message_channel_respond (channel, response_handle, response, + * &error)) + * g_warning ("Failed to send channel response: %s", error->message); + * } + * + * static void message_response_cb (GObject *object, + * GAsyncResult *result, + * gpointer user_data) { + * g_autoptr(GError) error = NULL; + * g_autoptr(FlValue) response = + * fl_basic_message_channel_send_finish (FL_BASIC_MESSAGE_CHANNEL (object), + * result, &error); + * if (response == NULL) { + * g_warning ("Failed to send message: %s", error->message); + * return; + * } + * + * handle_response (response); + * } + * + * static void setup_channel () { + * g_autoptr(FlStandardMessageCodec) codec = fl_standard_message_codec_new (); + * channel = fl_basic_message_channel_new (messenger, "flutter/foo", + * FL_MESSAGE_CODEC (codec)); + * fl_basic_message_channel_set_message_handler (channel, message_cb, NULL, + * NULL); + * + * g_autoptr(FlValue) message = fl_value_new_string ("Hello World"); + * fl_basic_message_channel_send (channel, message, NULL, + * message_response_cb, NULL); + * } + * ]| + * + * #FlBasicMessageChannel matches the BasicMessageChannel class in the Flutter + * services library. + */ + +/** + * FlBasicMessageChannelResponseHandle: + * + * #FlBasicMessageChannelResponseHandle is an object used to send responses + * with. + */ + +/** + * FlBasicMessageChannelMessageHandler: + * @channel: an #FlBasicMessageChannel. + * @message: message received. + * @response_handle: a handle to respond to the message with. + * @user_data: (closure): data provided when registering this handler. + * + * Function called when a message is received. Call + * fl_basic_message_channel_respond() to respond to this message. If the + * response is not occurring in this callback take a reference to + * @response_handle and release that once it has been responded to. Failing to + * respond before the last reference to @response_handle is dropped is a + * programming error. + */ +typedef void (*FlBasicMessageChannelMessageHandler)( + FlBasicMessageChannel* channel, + FlValue* message, + FlBasicMessageChannelResponseHandle* response_handle, + gpointer user_data); + +/** + * fl_basic_message_channel_new: + * @messenger: an #FlBinaryMessenger. + * @name: a channel name. + * @codec: the message codec. + * + * Creates a basic message channel. @codec must match the codec used on the Dart + * end of the channel. + * + * Returns: a new #FlBasicMessageChannel. + */ +FlBasicMessageChannel* fl_basic_message_channel_new( + FlBinaryMessenger* messenger, + const gchar* name, + FlMessageCodec* codec); + +/** + * fl_basic_message_channel_set_message_handler: + * @channel: an #FlBasicMessageChannel. + * @handler: (allow-none): function to call when a message is received on this + * channel or %NULL to disable the handler. + * @user_data: (closure): user data to pass to @handler. + * @destroy_notify: (allow-none): a function which gets called to free + * @user_data, or %NULL. + * + * Sets the function called when a message is received from the Dart side of the + * channel. See #FlBasicMessageChannelMessageHandler for details on how to + * respond to messages. + * + * The handler is removed if the channel is closed or is replaced by another + * handler, set @destroy_notify if you want to detect this. + */ +void fl_basic_message_channel_set_message_handler( + FlBasicMessageChannel* channel, + FlBasicMessageChannelMessageHandler handler, + gpointer user_data, + GDestroyNotify destroy_notify); + +/** + * fl_basic_message_channel_respond: + * @channel: an #FlBasicMessageChannel. + * @response_handle: handle that was provided in a + * #FlBasicMessageChannelMessageHandler. + * @message: (allow-none): message response to send or %NULL for an empty + * response. + * @error: (allow-none): #GError location to store the error occurring, or %NULL + * to ignore. + * + * Responds to a message. + * + * Returns: %TRUE on success. + */ +gboolean fl_basic_message_channel_respond( + FlBasicMessageChannel* channel, + FlBasicMessageChannelResponseHandle* response_handle, + FlValue* message, + GError** error); + +/** + * fl_basic_message_channel_send: + * @channel: an #FlBasicMessageChannel. + * @message: (allow-none): message to send, must match what the #FlMessageCodec + * supports. + * @cancellable: (allow-none): a #GCancellable or %NULL. + * @callback: (scope async): (allow-none): a #GAsyncReadyCallback to call when + * the request is satisfied or %NULL to ignore the response. + * @user_data: (closure): user data to pass to @callback. + * + * Asynchronously sends a message. + */ +void fl_basic_message_channel_send(FlBasicMessageChannel* channel, + FlValue* message, + GCancellable* cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +/** + * fl_basic_message_channel_send_finish: + * @channel: an #FlBasicMessageChannel. + * @result: a #GAsyncResult. + * @error: (allow-none): #GError location to store the error occurring, or %NULL + * to ignore. + * + * Completes request started with fl_basic_message_channel_send(). + * + * Returns: message response on success or %NULL on error. + */ +FlValue* fl_basic_message_channel_send_finish(FlBasicMessageChannel* channel, + GAsyncResult* result, + GError** error); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_BASIC_MESSAGE_CHANNEL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_binary_codec.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_binary_codec.h new file mode 100644 index 0000000000000000000000000000000000000000..c8febfd583ed260aaab91bf5bac90e6f17eabed9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_binary_codec.h @@ -0,0 +1,48 @@ +// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_BINARY_CODEC_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_BINARY_CODEC_H_ + +#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) +#error "Only can be included directly." +#endif + +#include + +#include "fl_message_codec.h" + +G_BEGIN_DECLS + +G_MODULE_EXPORT +G_DECLARE_FINAL_TYPE(FlBinaryCodec, + fl_binary_codec, + FL, + BINARY_CODEC, + FlMessageCodec) + +/** + * FlBinaryCodec: + * + * #FlBinaryCodec is an #FlMessageCodec that implements the Flutter binary + * message encoding. This only encodes and decodes #FlValue of type + * #FL_VALUE_TYPE_UINT8_LIST, other types #FlValues will generate an error + * during encoding. + * + * #FlBinaryCodec matches the BinaryCodec class in the Flutter services + * library. + */ + +/** + * fl_binary_codec_new: + * + * Creates an #FlBinaryCodec. + * + * Returns: a new #FlBinaryCodec. + */ +FlBinaryCodec* fl_binary_codec_new(); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_BINARY_CODEC_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h new file mode 100644 index 0000000000000000000000000000000000000000..adc11f71b8e0459e03bf49a453248de1f6125465 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h @@ -0,0 +1,233 @@ +// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_BINARY_MESSENGER_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_BINARY_MESSENGER_H_ + +#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) +#error "Only can be included directly." +#endif + +#include "fl_value.h" + +#include +#include +#include + +G_BEGIN_DECLS + +/** + * FlBinaryMessengerError: + * @FL_BINARY_MESSENGER_ERROR_ALREADY_RESPONDED: unable to send response, this + * message has already been responded to. + * + * Errors for #FlBinaryMessenger objects to set on failures. + */ +#define FL_BINARY_MESSENGER_ERROR fl_binary_messenger_codec_error_quark() + +typedef enum { + // Part of the public API, so fixing the name is a breaking change. + FL_BINARY_MESSENGER_ERROR_ALREADY_RESPONDED, +} FlBinaryMessengerError; + +G_MODULE_EXPORT +GQuark fl_binary_messenger_codec_error_quark(void) G_GNUC_CONST; + +G_MODULE_EXPORT +G_DECLARE_INTERFACE(FlBinaryMessenger, + fl_binary_messenger, + FL, + BINARY_MESSENGER, + GObject) + +G_MODULE_EXPORT +G_DECLARE_DERIVABLE_TYPE(FlBinaryMessengerResponseHandle, + fl_binary_messenger_response_handle, + FL, + BINARY_MESSENGER_RESPONSE_HANDLE, + GObject) + +/** + * FlBinaryMessengerMessageHandler: + * @messenger: an #FlBinaryMessenger. + * @channel: channel message received on. + * @message: message content received from Dart. + * @response_handle: a handle to respond to the message with. + * @user_data: (closure): data provided when registering this handler. + * + * Function called when platform messages are received. Call + * fl_binary_messenger_send_response() to respond to this message. If the + * response is not occurring in this callback take a reference to + * @response_handle and release that once it has been responded to. Failing to + * respond before the last reference to @response_handle is dropped is a + * programming error. + */ +typedef void (*FlBinaryMessengerMessageHandler)( + FlBinaryMessenger* messenger, + const gchar* channel, + GBytes* message, + FlBinaryMessengerResponseHandle* response_handle, + gpointer user_data); + +struct _FlBinaryMessengerInterface { + GTypeInterface parent_iface; + + void (*set_message_handler_on_channel)( + FlBinaryMessenger* messenger, + const gchar* channel, + FlBinaryMessengerMessageHandler handler, + gpointer user_data, + GDestroyNotify destroy_notify); + + gboolean (*send_response)(FlBinaryMessenger* messenger, + FlBinaryMessengerResponseHandle* response_handle, + GBytes* response, + GError** error); + + void (*send_on_channel)(FlBinaryMessenger* messenger, + const gchar* channel, + GBytes* message, + GCancellable* cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + + GBytes* (*send_on_channel_finish)(FlBinaryMessenger* messenger, + GAsyncResult* result, + GError** error); + + void (*resize_channel)(FlBinaryMessenger* messenger, + const gchar* channel, + int64_t new_size); + + void (*set_warns_on_channel_overflow)(FlBinaryMessenger* messenger, + const gchar* channel, + bool warns); + + void (*shutdown)(FlBinaryMessenger* messenger); +}; + +struct _FlBinaryMessengerResponseHandleClass { + GObjectClass parent_class; +}; + +/** + * FlBinaryMessenger: + * + * #FlBinaryMessenger is an object that allows sending and receiving of platform + * messages with an #FlEngine. + */ + +/** + * FlBinaryMessengerResponseHandle: + * + * #FlBinaryMessengerResponseHandle is an object used to send responses with. + */ + +/** + * fl_binary_messenger_set_platform_message_handler: + * @binary_messenger: an #FlBinaryMessenger. + * @channel: channel to listen on. + * @handler: (allow-none): function to call when a message is received on this + * channel or %NULL to disable a handler + * @user_data: (closure): user data to pass to @handler. + * @destroy_notify: (allow-none): a function which gets called to free + * @user_data, or %NULL. + * + * Sets the function called when a platform message is received on the given + * channel. See #FlBinaryMessengerMessageHandler for details on how to respond + * to messages. + * + * The handler is removed if the channel is closed or is replaced by another + * handler, set @destroy_notify if you want to detect this. + */ +void fl_binary_messenger_set_message_handler_on_channel( + FlBinaryMessenger* messenger, + const gchar* channel, + FlBinaryMessengerMessageHandler handler, + gpointer user_data, + GDestroyNotify destroy_notify); + +/** + * fl_binary_messenger_send_response: + * @binary_messenger: an #FlBinaryMessenger. + * @response_handle: handle that was provided in a + * #FlBinaryMessengerMessageHandler. + * @response: (allow-none): response to send or %NULL for an empty response. + * @error: (allow-none): #GError location to store the error occurring, or %NULL + * to ignore. + * + * Responds to a platform message. This function is thread-safe. + * + * Returns: %TRUE on success. + */ +gboolean fl_binary_messenger_send_response( + FlBinaryMessenger* messenger, + FlBinaryMessengerResponseHandle* response_handle, + GBytes* response, + GError** error); + +/** + * fl_binary_messenger_send_on_channel: + * @binary_messenger: an #FlBinaryMessenger. + * @channel: channel to send to. + * @message: (allow-none): message buffer to send or %NULL for an empty message. + * @cancellable: (allow-none): a #GCancellable or %NULL. + * @callback: (scope async): a #GAsyncReadyCallback to call when the request is + * satisfied. + * @user_data: (closure): user data to pass to @callback. + * + * Asynchronously sends a platform message. + */ +void fl_binary_messenger_send_on_channel(FlBinaryMessenger* messenger, + const gchar* channel, + GBytes* message, + GCancellable* cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +/** + * fl_binary_messenger_send_on_channel_finish: + * @messenger: an #FlBinaryMessenger. + * @result: a #GAsyncResult. + * @error: (allow-none): #GError location to store the error occurring, or %NULL + * to ignore. + * + * Completes request started with fl_binary_messenger_send_on_channel(). + * + * Returns: (transfer full): message response on success or %NULL on error. + */ +GBytes* fl_binary_messenger_send_on_channel_finish(FlBinaryMessenger* messenger, + GAsyncResult* result, + GError** error); + +/** + * fl_binary_messenger_resize_channel: + * @binary_messenger: an #FlBinaryMessenger. + * @channel: channel to be resize. + * @new_size: the new size for the channel buffer. + * + * Sends a message to the control channel asking to resize a channel buffer. + */ +void fl_binary_messenger_resize_channel(FlBinaryMessenger* messenger, + const gchar* channel, + int64_t new_size); + +/** + * fl_binary_messenger_set_warns_on_channel_overflow: + * @messenger: an #FlBinaryMessenger. + * @channel: channel to be allowed to overflow silently. + * @warns: when false, the channel is expected to overflow and warning messages + * will not be shown. + * + * Sends a message to the control channel asking to allow or disallow a channel + * to overflow silently. + */ +void fl_binary_messenger_set_warns_on_channel_overflow( + FlBinaryMessenger* messenger, + const gchar* channel, + bool warns); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_BINARY_MESSENGER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_dart_project.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_dart_project.h new file mode 100644 index 0000000000000000000000000000000000000000..e6e1736735702c519269249ddc1e76e86f8dcc16 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_dart_project.h @@ -0,0 +1,133 @@ +// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_DART_PROJECT_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_DART_PROJECT_H_ + +#include +#include + +#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) +#error "Only can be included directly." +#endif + +G_BEGIN_DECLS + +G_MODULE_EXPORT +G_DECLARE_FINAL_TYPE(FlDartProject, fl_dart_project, FL, DART_PROJECT, GObject) + +/** + * FlDartProject: + * + * #FlDartProject represents a Dart project. It is used to provide information + * about the application when creating an #FlView. + */ + +/** + * fl_dart_project_new: + * + * Creates a Flutter project for the currently running executable. The following + * data files are required relative to the location of the executable: + * - data/flutter_assets/ (as built by the Flutter tool). + * - data/icudtl.dat (provided as a resource by the Flutter tool). + * - lib/libapp.so (as built by the Flutter tool when in AOT mode). + * + * Returns: a new #FlDartProject. + */ +FlDartProject* fl_dart_project_new(); + +/** + * fl_dart_project_set_aot_library_path: + * @project: an #FlDartProject. + * @path: the absolute path to the AOT library in the Flutter application. + * + * Sets the path to the AOT library in the Flutter application, which is + * the path to libapp.so. By default this is lib/libapp.so relative to the + * executable directory. + */ +void fl_dart_project_set_aot_library_path(FlDartProject* project, + const gchar* path); + +/** + * fl_dart_project_get_aot_library_path: + * @project: an #FlDartProject. + * + * Gets the path to the AOT library in the Flutter application. + * + * Returns: (type filename): an absolute file path, e.g. + * "/projects/my_dart_project/lib/libapp.so". + */ +const gchar* fl_dart_project_get_aot_library_path(FlDartProject* project); + +/** + * fl_dart_project_set_assets_path: + * @project: an #FlDartProject. + * @path: the absolute path to the assets directory. + * + * Sets the path to the directory containing the assets used in the Flutter + * application. By default, this is the data/flutter_assets subdirectory + * relative to the executable directory. + */ +void fl_dart_project_set_assets_path(FlDartProject* project, gchar* path); + +/** + * fl_dart_project_get_assets_path: + * @project: an #FlDartProject. + * + * Gets the path to the directory containing the assets used in the Flutter + * application. + * + * Returns: (type filename): an absolute directory path, e.g. + * "/projects/my_dart_project/data/flutter_assets". + */ +const gchar* fl_dart_project_get_assets_path(FlDartProject* project); + +/** + * fl_dart_project_set_icu_data_path: + * @project: an #FlDartProject. + * @path: the absolute path to the ICU data file. + * + * Sets the path to the ICU data file used in the Flutter application. By + * default, this is data/icudtl.dat relative to the executable directory. + */ +void fl_dart_project_set_icu_data_path(FlDartProject* project, gchar* path); + +/** + * fl_dart_project_get_icu_data_path: + * @project: an #FlDartProject. + * + * Gets the path to the ICU data file in the Flutter application. + * + * Returns: (type filename): an absolute file path, e.g. + * "/projects/my_dart_project/data/icudtl.dat". + */ +const gchar* fl_dart_project_get_icu_data_path(FlDartProject* project); + +/** + * fl_dart_project_set_dart_entrypoint_arguments: + * @project: an #FlDartProject. + * @argv: a pointer to a NULL-terminated array of C strings containing the + * command line arguments. + * + * Sets the command line arguments to be passed through to the Dart + * entrypoint function. + */ +void fl_dart_project_set_dart_entrypoint_arguments(FlDartProject* project, + char** argv); + +/** + * fl_dart_project_get_dart_entrypoint_arguments: + * @project: an #FlDartProject. + * + * Gets the command line arguments to be passed through to the Dart entrypoint + * function. + * + * Returns: a NULL-terminated array of strings containing the command line + * arguments to be passed to the Dart entrypoint. + */ +gchar** fl_dart_project_get_dart_entrypoint_arguments(FlDartProject* project); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_DART_PROJECT_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_engine.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_engine.h new file mode 100644 index 0000000000000000000000000000000000000000..94e13e213dd10d7344b7a38655774bfa6db3eba2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_engine.h @@ -0,0 +1,72 @@ +// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_ENGINE_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_ENGINE_H_ + +#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) +#error "Only can be included directly." +#endif + +#include +#include + +#include "fl_binary_messenger.h" +#include "fl_dart_project.h" +#include "fl_texture_registrar.h" + +G_BEGIN_DECLS + +G_MODULE_EXPORT +G_DECLARE_FINAL_TYPE(FlEngine, fl_engine, FL, ENGINE, GObject) + +/** + * FlEngine: + * + * #FlEngine is an object that contains a running Flutter engine. + */ + +/** + * fl_engine_new: + * @project: an #FlDartProject. + * + * Creates new Flutter engine. + * + * Returns: a new #FlEngine. + */ +FlEngine* fl_engine_new(FlDartProject* project); + +/** + * fl_engine_new_headless: + * @project: an #FlDartProject. + * + * Creates new Flutter engine running in headless mode. + * + * Returns: a new #FlEngine. + */ +FlEngine* fl_engine_new_headless(FlDartProject* project); + +/** + * fl_engine_get_binary_messenger: + * @engine: an #FlEngine. + * + * Gets the messenger to communicate with this engine. + * + * Returns: an #FlBinaryMessenger. + */ +FlBinaryMessenger* fl_engine_get_binary_messenger(FlEngine* engine); + +/** + * fl_engine_get_texture_registrar: + * @engine: an #FlEngine. + * + * Gets the texture registrar for registering textures. + * + * Returns: an #FlTextureRegistrar. + */ +FlTextureRegistrar* fl_engine_get_texture_registrar(FlEngine* engine); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_ENGINE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_event_channel.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_event_channel.h new file mode 100644 index 0000000000000000000000000000000000000000..6d1da56381c7fe4927b886ffb2151dd8953b1cd2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_event_channel.h @@ -0,0 +1,189 @@ +// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_EVENT_CHANNEL_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_EVENT_CHANNEL_H_ + +#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) +#error "Only can be included directly." +#endif + +#include +#include +#include + +#include "fl_binary_messenger.h" +#include "fl_method_channel.h" +#include "fl_method_response.h" + +G_BEGIN_DECLS + +G_MODULE_EXPORT +G_DECLARE_FINAL_TYPE(FlEventChannel, + fl_event_channel, + FL, + EVENT_CHANNEL, + GObject) + +/** + * FlEventChannel: + * + * #FlEventChannel is an object that allows sending + * an events stream to Dart code over platform channels. + * + * The following example shows how to send events on a channel: + * + * |[ + * static FlEventChannel *channel = NULL; + * static gboolean send_events = FALSE; + * + * static void event_occurs_cb (FooEvent *event) { + * if (send_events) { + * g_autoptr(FlValue) message = foo_event_to_value (event); + * g_autoptr(GError) error = NULL; + * if (!fl_event_channel_send (channel, message, NULL, &error)) { + * g_warning ("Failed to send event: %s", error->message); + * } + * } + * } + * + * static FlMethodErrorResponse* listen_cb (FlEventChannel* channel, + * FlValue *args, + * gpointer user_data) { + * send_events = TRUE; + * return NULL; + * } + * + * static FlMethodErrorResponse* cancel_cb (GObject *object, + * FlValue *args, + * gpointer user_data) { + * send_events = FALSE; + * return NULL; + * } + * + * static void setup_channel () { + * g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new (); + * channel = fl_event_channel_new (messenger, "flutter/foo", + * FL_METHOD_CODEC (codec)); + * fl_event_channel_set_stream_handlers (channel, listen_cb, cancel_cb, + * NULL, NULL); + * } + * ]| + * + * #FlEventChannel matches the EventChannel class in the Flutter + * services library. + */ + +/** + * FlEventChannelHandler: + * @channel: an #FlEventChannel. + * @args: arguments passed from the Dart end of the channel. + * @user_data: (closure): data provided when registering this handler. + * + * Function called when the stream is listened to or cancelled. + * + * Returns: (transfer full): an #FlMethodErrorResponse or %NULL if no error. + */ +typedef FlMethodErrorResponse* (*FlEventChannelHandler)(FlEventChannel* channel, + FlValue* args, + gpointer user_data); + +/** + * fl_event_channel_new: + * @messenger: an #FlBinaryMessenger. + * @name: a channel name. + * @codec: the message codec. + * + * Creates an event channel. @codec must match the codec used on the Dart + * end of the channel. + * + * Returns: a new #FlEventChannel. + */ +FlEventChannel* fl_event_channel_new(FlBinaryMessenger* messenger, + const gchar* name, + FlMethodCodec* codec); + +/** + * fl_event_channel_set_stream_handlers: + * @channel: an #FlEventChannel. + * @listen_handler: (allow-none): function to call when the Dart side of the + * channel starts listening to the stream. + * @cancel_handler: (allow-none): function to call when the Dart side of the + * channel cancels their subscription to the stream. + * @user_data: (closure): user data to pass to @listen_handler and + * @cancel_handler. + * @destroy_notify: (allow-none): a function which gets called to free + * @user_data, or %NULL. + * + * Sets the functions called when the Dart side requests the stream to start and + * finish. + * + * The handlers are removed if the channel is closed or is replaced by another + * handler, set @destroy_notify if you want to detect this. + */ +void fl_event_channel_set_stream_handlers(FlEventChannel* channel, + FlEventChannelHandler listen_handler, + FlEventChannelHandler cancel_handler, + gpointer user_data, + GDestroyNotify destroy_notify); + +/** + * fl_event_channel_send: + * @channel: an #FlEventChannel. + * @event: event to send, must match what the #FlMethodCodec supports. + * @cancellable: (allow-none): a #GCancellable or %NULL. + * @error: (allow-none): #GError location to store the error occurring, or %NULL + * to ignore. + * + * Sends an event on the channel. + * Events should only be sent once the channel is being listened to. + * + * Returns: %TRUE if successful. + */ +gboolean fl_event_channel_send(FlEventChannel* channel, + FlValue* event, + GCancellable* cancellable, + GError** error); + +/** + * fl_event_channel_send_error: + * @channel: an #FlEventChannel. + * @code: error code to send. + * @message: error message to send. + * @details: (allow-none): error details or %NULL. + * @cancellable: (allow-none): a #GCancellable or %NULL. + * @error: (allow-none): #GError location to store the error occurring, or %NULL + * to ignore. + * + * Sends an error on the channel. + * Errors should only be sent once the channel is being listened to. + * + * Returns: %TRUE if successful. + */ +gboolean fl_event_channel_send_error(FlEventChannel* channel, + const gchar* code, + const gchar* message, + FlValue* details, + GCancellable* cancellable, + GError** error); + +/** + * fl_event_channel_send_end_of_stream: + * @channel: an #FlEventChannel. + * @cancellable: (allow-none): a #GCancellable or %NULL. + * @error: (allow-none): #GError location to store the error occurring, or %NULL + * to ignore. + * + * Indicates the stream has completed. + * It is a programmer error to send any more events after calling this. + * + * Returns: %TRUE if successful. + */ +gboolean fl_event_channel_send_end_of_stream(FlEventChannel* channel, + GCancellable* cancellable, + GError** error); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_EVENT_CHANNEL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_json_message_codec.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_json_message_codec.h new file mode 100644 index 0000000000000000000000000000000000000000..0560511ecb291a0f880c53512cb98551b336afbd --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_json_message_codec.h @@ -0,0 +1,100 @@ +// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_JSON_MESSAGE_CODEC_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_JSON_MESSAGE_CODEC_H_ + +#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) +#error "Only can be included directly." +#endif + +#include + +#include "fl_message_codec.h" + +G_BEGIN_DECLS + +/** + * FlJsonMessageCodecError: + * @FL_JSON_MESSAGE_CODEC_ERROR_INVALID_UTF8: Message is not valid UTF-8. + * @FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON: Message is not valid JSON. + * @FL_JSON_MESSAGE_CODEC_ERROR_INVALID_OBJECT_KEY_TYPE: Invalid object key + * type. + * + * Errors for #FlJsonMessageCodec objects to set on failures. + */ +#define FL_JSON_MESSAGE_CODEC_ERROR fl_json_message_codec_error_quark() + +typedef enum { + FL_JSON_MESSAGE_CODEC_ERROR_INVALID_UTF8, + FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON, + FL_JSON_MESSAGE_CODEC_ERROR_INVALID_OBJECT_KEY_TYPE, +} FlJsonMessageCodecError; + +G_MODULE_EXPORT +GQuark fl_json_message_codec_error_quark(void) G_GNUC_CONST; + +G_MODULE_EXPORT +G_DECLARE_FINAL_TYPE(FlJsonMessageCodec, + fl_json_message_codec, + FL, + JSON_CODEC, + FlMessageCodec) + +/** + * FlJsonMessageCodec: + * + * #FlJsonMessageCodec is an #FlMessageCodec that implements the encodes + * #FlValue to/from JSON. This codec encodes and decodes #FlValue of type + * #FL_VALUE_TYPE_NULL, #FL_VALUE_TYPE_BOOL, #FL_VALUE_TYPE_INT, + * #FL_VALUE_TYPE_FLOAT, #FL_VALUE_TYPE_STRING, #FL_VALUE_TYPE_UINT8_LIST, + * #FL_VALUE_TYPE_INT32_LIST, #FL_VALUE_TYPE_INT64_LIST, + * #FL_VALUE_TYPE_FLOAT_LIST, #FL_VALUE_TYPE_LIST, and #FL_VALUE_TYPE_MAP. + * + * #FlJsonMessageCodec matches the JSONMessageCodec class in the Flutter + * services library. + */ + +/** + * fl_json_message_codec_new: + * + * Creates an #FlJsonMessageCodec. + * + * Returns: a new #FlJsonMessageCodec. + */ +FlJsonMessageCodec* fl_json_message_codec_new(); + +/** + * fl_json_message_codec_encode: + * @codec: an #FlJsonMessageCodec. + * @value: value to encode. + * @error: (allow-none): #GError location to store the error occurring, or + * %NULL. + * + * Encodes a value to a JSON string. + * + * Returns: a JSON representation of this value or %NULL on error. + */ +gchar* fl_json_message_codec_encode(FlJsonMessageCodec* codec, + FlValue* value, + GError** error); + +/** + * fl_json_message_codec_decode: + * @codec: an #FlJsonMessageCodec. + * @text: UTF-8 text in JSON format. + * @error: (allow-none): #GError location to store the error occurring, or + * %NULL. + * + * Decodes a value from a JSON string. + * + * Returns: an #FlValue or %NULL on error. + */ +FlValue* fl_json_message_codec_decode(FlJsonMessageCodec* codec, + const gchar* text, + GError** error); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_JSON_MESSAGE_CODEC_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_json_method_codec.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_json_method_codec.h new file mode 100644 index 0000000000000000000000000000000000000000..a79c6666764c12b3486ac7326a94792d0a8a671a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_json_method_codec.h @@ -0,0 +1,47 @@ +// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_JSON_METHOD_CODEC_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_JSON_METHOD_CODEC_H_ + +#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) +#error "Only can be included directly." +#endif + +#include + +#include "fl_method_codec.h" + +G_BEGIN_DECLS + +G_MODULE_EXPORT +G_DECLARE_FINAL_TYPE(FlJsonMethodCodec, + fl_json_method_codec, + FL, + JSON_METHOD_CODEC, + FlMethodCodec) + +/** + * FlJsonMethodCodec: + * + * #FlJsonMessageCodec is an #FlMethodCodec that implements method calls using + * the Flutter JSON message encoding. It should be used with an + * #FlMethodChannel. + * + * #FlJsonMethodCodec matches the JSONMethodCodec class in the Flutter services + * library. + */ + +/** + * fl_json_method_codec_new: + * + * Creates an #FlJsonMethodCodec. + * + * Returns: a new #FlJsonMethodCodec. + */ +FlJsonMethodCodec* fl_json_method_codec_new(); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_JSON_METHOD_CODEC_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_message_codec.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_message_codec.h new file mode 100644 index 0000000000000000000000000000000000000000..1ab5627952bdcd57c9d2e6cff4bb0fa36c34844f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_message_codec.h @@ -0,0 +1,132 @@ +// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_MESSAGE_CODEC_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_MESSAGE_CODEC_H_ + +#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) +#error "Only can be included directly." +#endif + +#include +#include + +#include "fl_value.h" + +G_BEGIN_DECLS + +/** + * FlMessageCodecError: + * @FL_MESSAGE_CODEC_ERROR_FAILED: Codec failed due to an unspecified error. + * @FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA: Codec ran out of data reading a value. + * @FL_MESSAGE_CODEC_ERROR_ADDITIONAL_DATA: Additional data encountered in + * message. + * @FL_MESSAGE_CODEC_ERROR_UNSUPPORTED_TYPE: Codec encountered an unsupported + * #FlValue. + * + * Errors for #FlMessageCodec objects to set on failures. + */ +#define FL_MESSAGE_CODEC_ERROR fl_message_codec_error_quark() + +typedef enum { + FL_MESSAGE_CODEC_ERROR_FAILED, + FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA, + FL_MESSAGE_CODEC_ERROR_ADDITIONAL_DATA, + FL_MESSAGE_CODEC_ERROR_UNSUPPORTED_TYPE, +} FlMessageCodecError; + +G_MODULE_EXPORT +GQuark fl_message_codec_error_quark(void) G_GNUC_CONST; + +G_MODULE_EXPORT +G_DECLARE_DERIVABLE_TYPE(FlMessageCodec, + fl_message_codec, + FL, + MESSAGE_CODEC, + GObject) + +/** + * FlMessageCodec: + * + * #FlMessageCodec is a message encoding/decoding mechanism that operates on + * #FlValue objects. Both operations returns errors if the conversion fails. + * Such situations should be treated as programming errors. + * + * #FlMessageCodec matches the MethodCodec class in the Flutter services + * library. + */ + +struct _FlMessageCodecClass { + GObjectClass parent_class; + + /** + * FlMessageCodec::encode_message: + * @codec: an #FlMessageCodec. + * @message: message to encode or %NULL to encode the null value. + * @error: (allow-none): #GError location to store the error occurring, or + * %NULL. + * + * Virtual method to encode a message. A subclass must implement this method. + * If the subclass cannot handle the type of @message then it must generate a + * FL_MESSAGE_CODEC_ERROR_UNSUPPORTED_TYPE error. + * + * Returns: a binary message or %NULL on error. + */ + GBytes* (*encode_message)(FlMessageCodec* codec, + FlValue* message, + GError** error); + + /** + * FlMessageCodec::decode_message: + * @codec: an #FlMessageCodec. + * @message: binary message to decode. + * @error: (allow-none): #GError location to store the error occurring, or + * %NULL. + * + * Virtual method to decode a message. A subclass must implement this method. + * If @message is too small then a #FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA error + * must be generated. If @message is too large then a + * #FL_MESSAGE_CODEC_ERROR_ADDITIONAL_DATA error must be generated. + * + * Returns: an #FlValue or %NULL on error. + */ + FlValue* (*decode_message)(FlMessageCodec* codec, + GBytes* message, + GError** error); +}; + +/** + * fl_message_codec_encode_message: + * @codec: an #FlMessageCodec. + * @buffer: buffer to write to. + * @message: message to encode or %NULL to encode the null value. + * @error: (allow-none): #GError location to store the error occurring, or + * %NULL. + * + * Encodes a message into a binary representation. + * + * Returns: a binary encoded message or %NULL on error. + */ +GBytes* fl_message_codec_encode_message(FlMessageCodec* codec, + FlValue* message, + GError** error); + +/** + * fl_message_codec_decode_message: + * @codec: an #FlMessageCodec. + * @message: binary message to decode. + * @error: (allow-none): #GError location to store the error occurring, or + * %NULL. + * + * Decodes a message from a binary encoding. + * + * Returns: an #FlValue or %NULL on error. + */ +FlValue* fl_message_codec_decode_message(FlMessageCodec* codec, + GBytes* message, + GError** error); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_MESSAGE_CODEC_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_method_call.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_method_call.h new file mode 100644 index 0000000000000000000000000000000000000000..93d424cb5f34c409a98340f8b8a049db01951a90 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_method_call.h @@ -0,0 +1,117 @@ +// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_METHOD_CALL_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_METHOD_CALL_H_ + +#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) +#error "Only can be included directly." +#endif + +#include +#include + +#include "fl_method_response.h" +#include "fl_value.h" + +G_BEGIN_DECLS + +G_MODULE_EXPORT +G_DECLARE_FINAL_TYPE(FlMethodCall, fl_method_call, FL, METHOD_CALL, GObject) + +/** + * FlMethodCall: + * + * #FlMethodCall represents and incoming method call as returned by an + * #FlMethodChannel. + */ + +/** + * fl_method_call_get_name: + * @method_call: an #FlMethodCall. + * + * Gets the name of the method call. + * + * Returns: a method name. + */ +const gchar* fl_method_call_get_name(FlMethodCall* method_call); + +/** + * fl_method_call_get_args: + * @method_call: an #FlMethodCall. + * + * Gets the arguments passed to the method. + * + * Returns: an #FlValue. + */ +FlValue* fl_method_call_get_args(FlMethodCall* method_call); + +/** + * fl_method_call_respond: + * @method_call: an #FlMethodCall. + * @response: an #FlMethodResponse. + * @error: (allow-none): #GError location to store the error occurring, or %NULL + * to ignore. + * + * Responds to a method call. + * + * Returns: %TRUE on success. + */ +gboolean fl_method_call_respond(FlMethodCall* method_call, + FlMethodResponse* response, + GError** error); + +/** + * fl_method_call_respond_success: + * @method_call: an #FlMethodCall. + * @result: (allow-none): value to respond with, must match what the + * #FlMethodCodec supports. + * @error: (allow-none): #GError location to store the error occurring, or %NULL + * to ignore. + * + * Convenience method that responds to method call with + * #FlMethodSuccessResponse. + * + * Returns: %TRUE on success. + */ +gboolean fl_method_call_respond_success(FlMethodCall* method_call, + FlValue* result, + GError** error); + +/** + * fl_method_call_respond_error: + * @method_call: an #FlMethodCall. + * @code: error code. + * @message: (allow-none): error message. + * @details: (allow-none): details for the error. + * @error: (allow-none): #GError location to store the error occurring, or %NULL + * to ignore. + * + * Convenience method that responds to method call with #FlMethodErrorResponse. + * + * Returns: %TRUE on success. + */ +gboolean fl_method_call_respond_error(FlMethodCall* method_call, + const gchar* code, + const gchar* message, + FlValue* details, + GError** error); + +/** + * fl_method_call_respond_not_implemented: + * @method_call: an #FlMethodCall. + * @error: (allow-none): #GError location to store the error occurring, or %NULL + * to ignore. + * + * Convenience method that responds to method call with + * #FlMethodNotImplementedResponse. + * + * Returns: %TRUE on success. + */ +gboolean fl_method_call_respond_not_implemented(FlMethodCall* method_call, + GError** error); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_METHOD_CALL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_method_channel.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_method_channel.h new file mode 100644 index 0000000000000000000000000000000000000000..224f94bfd73273611a34151b12f56e13367e68da --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_method_channel.h @@ -0,0 +1,197 @@ +// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_METHOD_CHANNEL_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_METHOD_CHANNEL_H_ + +#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) +#error "Only can be included directly." +#endif + +#include +#include +#include + +#include "fl_binary_messenger.h" +#include "fl_method_call.h" +#include "fl_method_codec.h" +#include "fl_method_response.h" + +G_BEGIN_DECLS + +G_MODULE_EXPORT +G_DECLARE_FINAL_TYPE(FlMethodChannel, + fl_method_channel, + FL, + METHOD_CHANNEL, + GObject) + +/** + * FlMethodChannel: + * + * #FlMethodChannel is an object that allows method calls to and from Dart code. + * + * The following example shows how to call and handle methods on a channel. + * See #FlMethodResponse for how to handle errors in more detail. + * + * |[ + * static FlMethodChannel *channel = NULL; + * + * static void method_call_cb (FlMethodChannel* channel, + * FlMethodCall* method_call, + * gpointer user_data) { + * g_autoptr(FlMethodResponse) response = NULL; + * if (strcmp (fl_method_call_get_name (method_call), "Foo.bar") == 0) { + * g_autoptr(GError) bar_error = NULL; + * g_autoptr(FlValue) result = + * do_bar (fl_method_call_get_args (method_call), &bar_error); + * if (result == NULL) { + * response = + * FL_METHOD_RESPONSE (fl_method_error_response_new ("bar error", + * bar_error->message, + * nullptr); + * } else { + * response = + * FL_METHOD_RESPONSE (fl_method_success_response_new (result)); + * } + * } else { + * response = + * FL_METHOD_RESPONSE (fl_method_not_implemented_response_new ()); + * } + * + * g_autoptr(GError) error = NULL; + * if (!fl_method_call_respond(method_call, response, &error)) + * g_warning ("Failed to send response: %s", error->message); + * } + * + * static void method_response_cb(GObject *object, + * GAsyncResult *result, + * gpointer user_data) { + * g_autoptr(GError) error = NULL; + * g_autoptr(FlMethodResponse) response = + * fl_method_channel_invoke_method_finish (FL_METHOD_CODEC (object), result, + * &error); + * if (response == NULL) { + * g_warning ("Failed to call method: %s", error->message); + * return; + * } + * + * g_autoptr(FlValue) value = + * fl_method_response_get_result (response, &error); + * if (response == NULL) { + * g_warning ("Method returned error: %s", error->message); + * return; + * } + * + * use_result (value); + * } + * + * static void call_method () { + * g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new (); + * channel = + * fl_method_channel_new(messenger, "flutter/foo", FL_METHOD_CODEC (codec)); + * fl_method_channel_set_method_call_handler (channel, method_call_cb, NULL, + * NULL); + * + * g_autoptr(FlValue) args = fl_value_new_string ("Hello World"); + * fl_method_channel_invoke_method (channel, "Foo.foo", args, + * cancellable, method_response_cb, NULL); + * } + * ]| + * + * #FlMethodChannel matches the MethodChannel class in the Flutter services + * library. + */ + +/** + * FlMethodChannelMethodCallHandler: + * @channel: an #FlMethodChannel. + * @method_call: an #FlMethodCall. + * @user_data: (closure): data provided when registering this handler. + * + * Function called when a method call is received. Respond to the method call + * with fl_method_call_respond(). If the response is not occurring in this + * callback take a reference to @method_call and release that once it has been + * responded to. Failing to respond before the last reference to @method_call is + * dropped is a programming error. + */ +typedef void (*FlMethodChannelMethodCallHandler)(FlMethodChannel* channel, + FlMethodCall* method_call, + gpointer user_data); + +/** + * fl_method_channel_new: + * @messenger: an #FlBinaryMessenger. + * @name: a channel name. + * @codec: the method codec. + * + * Creates a new method channel. @codec must match the codec used on the Dart + * end of the channel. + * + * Returns: a new #FlMethodChannel. + */ +FlMethodChannel* fl_method_channel_new(FlBinaryMessenger* messenger, + const gchar* name, + FlMethodCodec* codec); + +/** + * fl_method_channel_set_method_call_handler: + * @channel: an #FlMethodChannel. + * @handler: function to call when a method call is received on this channel. + * @user_data: (closure): user data to pass to @handler. + * @destroy_notify: (allow-none): a function which gets called to free + * @user_data, or %NULL. + * + * Sets the function called when a method call is received from the Dart side of + * the channel. See #FlMethodChannelMethodCallHandler for details on how to + * respond to method calls. + * + * The handler is removed if the channel is closed or is replaced by another + * handler, set @destroy_notify if you want to detect this. + */ +void fl_method_channel_set_method_call_handler( + FlMethodChannel* channel, + FlMethodChannelMethodCallHandler handler, + gpointer user_data, + GDestroyNotify destroy_notify); + +/** + * fl_method_channel_invoke_method: + * @channel: an #FlMethodChannel. + * @method: the method to call. + * @args: (allow-none): arguments to the method, must match what the + * #FlMethodCodec supports. + * @cancellable: (allow-none): a #GCancellable or %NULL. + * @callback: (scope async): (allow-none): a #GAsyncReadyCallback to call when + * the request is satisfied or %NULL to ignore the response. + * @user_data: (closure): user data to pass to @callback. + * + * Calls a method on this channel. + */ +void fl_method_channel_invoke_method(FlMethodChannel* channel, + const gchar* method, + FlValue* args, + GCancellable* cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +/** + * fl_method_channel_invoke_method_finish: + * @channel: an #FlMethodChannel. + * @result: #GAsyncResult. + * @error: (allow-none): #GError location to store the error occurring, or %NULL + * to ignore. + * + * Completes request started with fl_method_channel_invoke_method(). + * + * Returns: (transfer full): an #FlMethodResponse or %NULL on error. + */ +FlMethodResponse* fl_method_channel_invoke_method_finish( + FlMethodChannel* channel, + GAsyncResult* result, + GError** error); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_METHOD_CHANNEL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_method_codec.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_method_codec.h new file mode 100644 index 0000000000000000000000000000000000000000..3c741c8f5191cbded14e20bdca26d746375ddbd9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_method_codec.h @@ -0,0 +1,133 @@ +// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_METHOD_CODEC_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_METHOD_CODEC_H_ + +#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) +#error "Only can be included directly." +#endif + +#include +#include + +#include "fl_method_response.h" +#include "fl_value.h" + +G_BEGIN_DECLS + +G_MODULE_EXPORT +G_DECLARE_DERIVABLE_TYPE(FlMethodCodec, + fl_method_codec, + FL, + METHOD_CODEC, + GObject) + +/** + * FlMethodCodec: + * + * #FlMethodCodec is an abstract class that encodes and decodes method calls on + * a platform channel. Override this class to implement an encoding. + * + * #FlMethodCodec matches the MethodCodec class in the Flutter services + * library. + */ + +struct _FlMethodCodecClass { + GObjectClass parent_class; + + /** + * FlMethodCodec::encode_method_call: + * @codec: an #FlMethodCodec. + * @name: method name. + * @args: (allow-none): method arguments, or %NULL. + * @error: (allow-none): #GError location to store the error occurring, or + * %NULL. + * + * Encodes a method call. + * + * Returns: (transfer full): a binary encoding of this method call or %NULL if + * not able to encode. + */ + GBytes* (*encode_method_call)(FlMethodCodec* codec, + const gchar* name, + FlValue* args, + GError** error); + + /** + * FlMethodCodec::decode_method_call: + * @codec: an #FlMethodCodec + * @message: message to decode. + * @name: (transfer full): location to write method name or %NULL if not + * required + * @args: (transfer full): location to write method arguments, or %NULL if not + * required + * @error: (allow-none): #GError location to store the error occurring, or + * %NULL + * + * Decodes a method call. + * + * Returns: %TRUE if successfully decoded. + */ + gboolean (*decode_method_call)(FlMethodCodec* codec, + GBytes* message, + gchar** name, + FlValue** args, + GError** error); + + /** + * FlMethodCodec::encode_success_envelope: + * @codec: an #FlMethodCodec. + * @result: (allow-none): method result, or %NULL. + * @error: (allow-none): #GError location to store the error occurring, or + * %NULL. + * + * Encodes a successful response to a method call. + * + * Returns: (transfer full): a binary encoding of this response or %NULL if + * not able to encode. + */ + GBytes* (*encode_success_envelope)(FlMethodCodec* codec, + FlValue* result, + GError** error); + + /** + * FlMethodCodec::encode_error_envelope: + * @codec: an #FlMethodCodec. + * @code: an error code. + * @message: (allow-none): an error message, or %NULL. + * @details: (allow-none): error details, or %NULL. + * @error: (allow-none): #GError location to store the error occurring, or + * %NULL. + * + * Encodes an error response to a method call. + * + * Returns: (transfer full): a binary encoding of this response or %NULL if + * not able to encode. + */ + GBytes* (*encode_error_envelope)(FlMethodCodec* codec, + const gchar* code, + const gchar* message, + FlValue* details, + GError** error); + + /** + * FlMethodCodec::decode_response: + * @codec: an #FlMethodCodec. + * @message: message to decode. + * @error: (allow-none): #GError location to store the error occurring, or + * %NULL. + * + * Decodes a response to a method call. + * + * Returns: a new #FlMethodResponse or %NULL on error. + */ + FlMethodResponse* (*decode_response)(FlMethodCodec* codec, + GBytes* message, + GError** error); +}; + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_METHOD_CODEC_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_method_response.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_method_response.h new file mode 100644 index 0000000000000000000000000000000000000000..c7ceecec9aaf81e65cd9771d644f09a6a64acd15 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_method_response.h @@ -0,0 +1,218 @@ +// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_METHOD_RESPONSE_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_METHOD_RESPONSE_H_ + +#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) +#error "Only can be included directly." +#endif + +#include +#include + +#include "fl_value.h" + +G_BEGIN_DECLS + +/** + * FlMethodResponseError: + * @FL_METHOD_RESPONSE_ERROR_FAILED: Call failed due to an unspecified error. + * @FL_METHOD_RESPONSE_ERROR_REMOTE_ERROR: An error was returned by the other + * side of the channel. + * @FL_METHOD_RESPONSE_ERROR_NOT_IMPLEMENTED: The requested method is not + * implemented. + * + * Errors set by `fl_method_response_get_result` when the method call response + * is not #FlMethodSuccessResponse. + */ +#define FL_METHOD_RESPONSE_ERROR fl_method_response_error_quark() + +typedef enum { + FL_METHOD_RESPONSE_ERROR_FAILED, + FL_METHOD_RESPONSE_ERROR_REMOTE_ERROR, + FL_METHOD_RESPONSE_ERROR_NOT_IMPLEMENTED, +} FlMethodResponseError; + +G_MODULE_EXPORT +GQuark fl_method_response_error_quark(void) G_GNUC_CONST; + +G_MODULE_EXPORT +G_DECLARE_DERIVABLE_TYPE(FlMethodResponse, + fl_method_response, + FL, + METHOD_RESPONSE, + GObject) + +struct _FlMethodResponseClass { + GObjectClass parent_class; +}; + +G_MODULE_EXPORT +G_DECLARE_FINAL_TYPE(FlMethodSuccessResponse, + fl_method_success_response, + FL, + METHOD_SUCCESS_RESPONSE, + FlMethodResponse) + +G_MODULE_EXPORT +G_DECLARE_FINAL_TYPE(FlMethodErrorResponse, + fl_method_error_response, + FL, + METHOD_ERROR_RESPONSE, + FlMethodResponse) + +G_MODULE_EXPORT +G_DECLARE_FINAL_TYPE(FlMethodNotImplementedResponse, + fl_method_not_implemented_response, + FL, + METHOD_NOT_IMPLEMENTED_RESPONSE, + FlMethodResponse) + +/** + * FlMethodResponse: + * + * #FlMethodResponse contains the information returned when an #FlMethodChannel + * method call returns. If you expect the method call to be successful use + * fl_method_response_get_result(). If you want to handle error cases then you + * should use code like: + * + * |[ + * if (FL_IS_METHOD_SUCCESS_RESPONSE (response)) { + * FlValue *result = + * fl_method_success_response_get_result( + * FL_METHOD_SUCCESS_RESPONSE (response)); + * handle_result (result); + * } else if (FL_IS_METHOD_ERROR_RESPONSE (response)) { + * FlMethodErrorResponse *error_response = + * FL_METHOD_ERROR_RESPONSE (response); + * handle_error (fl_method_error_response_get_code (error_response), + * fl_method_error_response_get_message (error_response), + * fl_method_error_response_get_details (error_response)); + * } + * else if (FL_IS_METHOD_NOT_IMPLEMENTED_RESPONSE (response)) { + * handle_not_implemented (); + * } + * } + * ]| + */ + +/** + * FlMethodSuccessResponse: + * + * #FlMethodSuccessResponse is the #FlMethodResponse returned when a method call + * has successfully completed. The result of the method call is obtained using + * `fl_method_success_response_get_result`. + */ + +/** + * FlMethodErrorResponse: + * + * #FlMethodErrorResponse is the #FlMethodResponse returned when a method call + * results in an error. The error details are obtained using + * `fl_method_error_response_get_code`, `fl_method_error_response_get_message` + * and `fl_method_error_response_get_details`. + */ + +/** + * FlMethodNotImplementedResponse: + * + * #FlMethodNotImplementedResponse is the #FlMethodResponse returned when a + * method call is not implemented. + */ + +/** + * fl_method_response_get_result: + * @response: an #FlMethodResponse. + * @error: (allow-none): #GError location to store the error occurring, or %NULL + * to ignore. + * + * Gets the result of a method call, or an error if the response wasn't + * successful. + * + * Returns: an #FlValue or %NULL on error. + */ +FlValue* fl_method_response_get_result(FlMethodResponse* response, + GError** error); + +/** + * fl_method_success_response_new: + * @result: (allow-none): the #FlValue returned by the method call or %NULL. + * + * Creates a response to a method call when that method has successfully + * completed. + * + * Returns: a new #FlMethodResponse. + */ +FlMethodSuccessResponse* fl_method_success_response_new(FlValue* result); + +/** + * fl_method_success_response_get_result: + * @response: an #FlMethodSuccessResponse. + * + * Gets the result of the method call. + * + * Returns: an #FlValue. + */ +FlValue* fl_method_success_response_get_result( + FlMethodSuccessResponse* response); + +/** + * fl_method_error_response_new: + * @result: an #FlValue. + * @code: an error code. + * @message: (allow-none): an error message. + * @details: (allow-none): error details. + * + * Creates a response to a method call when that method has returned an error. + * + * Returns: a new #FlMethodErrorResponse. + */ +FlMethodErrorResponse* fl_method_error_response_new(const gchar* code, + const gchar* message, + FlValue* details); + +/** + * fl_method_error_response_get_code: + * @response: an #FlMethodErrorResponse. + * + * Gets the error code reported. + * + * Returns: an error code. + */ +const gchar* fl_method_error_response_get_code(FlMethodErrorResponse* response); + +/** + * fl_method_error_response_get_message: + * @response: an #FlMethodErrorResponse. + * + * Gets the error message reported. + * + * Returns: an error message or %NULL if no error message provided. + */ +const gchar* fl_method_error_response_get_message( + FlMethodErrorResponse* response); + +/** + * fl_method_error_response_get_details: + * @response: an #FlMethodErrorResponse. + * + * Gets the details provided with this error. + * + * Returns: an #FlValue or %NULL if no details provided. + */ +FlValue* fl_method_error_response_get_details(FlMethodErrorResponse* response); + +/** + * fl_method_not_implemented_response_new: + * + * Creates a response to a method call when that method does not exist. + * + * Returns: a new #FlMethodNotImplementedResponse. + */ +FlMethodNotImplementedResponse* fl_method_not_implemented_response_new(); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_METHOD_RESPONSE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_pixel_buffer_texture.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_pixel_buffer_texture.h new file mode 100644 index 0000000000000000000000000000000000000000..8364994792b279cb245859188b6a6b807e25cdc0 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_pixel_buffer_texture.h @@ -0,0 +1,115 @@ +// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_PIXEL_BUFFER_TEXTURE_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_PIXEL_BUFFER_TEXTURE_H_ + +#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) +#error "Only can be included directly." +#endif + +#include + +#include "fl_texture.h" + +G_BEGIN_DECLS + +G_MODULE_EXPORT +G_DECLARE_DERIVABLE_TYPE(FlPixelBufferTexture, + fl_pixel_buffer_texture, + FL, + PIXEL_BUFFER_TEXTURE, + GObject) + +/** + * FlPixelBufferTexture: + * + * #FlPixelBufferTexture represents an OpenGL texture generated from a pixel + * buffer. + * + * The following example shows how to implement an #FlPixelBufferTexture. + * ![ + * struct _MyTexture { + * FlPixelBufferTexture parent_instance; + * + * uint8_t *buffer; // your pixel buffer. + * } + * + * G_DEFINE_TYPE(MyTexture, + * my_texture, + * fl_pixel_buffer_texture_get_type ()) + * + * static gboolean + * my_texture_copy_pixels (FlPixelBufferTexture* texture, + * const uint8_t** out_buffer, + * uint32_t* width, + * uint32_t* height, + * GError** error) { + * // This method is called on Render Thread. Be careful with your + * // cross-thread operation. + * + * // @width and @height are initially stored the canvas size in Flutter. + * + * // You must prepare your pixel buffer in RGBA format. + * // So you may do some format conversion first if your original pixel + * // buffer is not in RGBA format. + * manage_your_pixel_buffer_here (); + * + * if (your_operations_are_successfully_finished) { + * // Directly return pointer to your pixel buffer here. + * // Flutter takes content of your pixel buffer after this function + * // is finished. So you must make the buffer live long enough until + * // next tick of Render Thread. + * // If it is hard to manage lifetime of your pixel buffer, you should + * // take look into #FlTextureGL. + * + * *out_buffer = buffer; + * *width = real_width_of_buffer; + * *height = real_height_of_buffer; + * return TRUE; + * } else { + * // set @error to report failure. + * return FALSE; + * } + * } + * + * static void my_texture_class_init(MyTextureClass* klass) { + * FL_PIXEL_BUFFER_TEXTURE_CLASS(klass)->copy_pixels = + * my_texture_copy_pixels; + * } + * + * static void my_texture_init(MyTexture* self) {} + * ]| + */ + +struct _FlPixelBufferTextureClass { + GObjectClass parent_class; + + /** + * FlPixelBufferTexture::copy_pixels: + * @texture: an #FlPixelBufferTexture. + * @buffer: (out): pixel data. + * @width: (inout): width of the texture in pixels. + * @height: (inout): height of the texture in pixels. + * @error: (allow-none): #GError location to store the error occurring, or + * %NULL to ignore. + * + * Retrieve pixel buffer in RGBA format. + * + * As this method is usually invoked from the render thread, you must + * take care of proper synchronization. It also needs to be ensured that + * the returned buffer is not released prior to unregistering this texture. + * + * Returns: %TRUE on success. + */ + gboolean (*copy_pixels)(FlPixelBufferTexture* texture, + const uint8_t** buffer, + uint32_t* width, + uint32_t* height, + GError** error); +}; + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_PIXEL_BUFFER_TEXTURE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_plugin_registrar.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_plugin_registrar.h new file mode 100644 index 0000000000000000000000000000000000000000..a9200ea72485f3ada8f40ad7000b13196692ec50 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_plugin_registrar.h @@ -0,0 +1,78 @@ +// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_PLUGIN_REGISTRAR_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_PLUGIN_REGISTRAR_H_ + +#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) +#error "Only can be included directly." +#endif + +#include +#include + +#include "fl_binary_messenger.h" +#include "fl_texture_registrar.h" +#include "fl_view.h" + +G_BEGIN_DECLS + +G_MODULE_EXPORT +G_DECLARE_INTERFACE(FlPluginRegistrar, + fl_plugin_registrar, + FL, + PLUGIN_REGISTRAR, + GObject) + +struct _FlPluginRegistrarInterface { + GTypeInterface parent_iface; + + FlBinaryMessenger* (*get_messenger)(FlPluginRegistrar* registrar); + + FlTextureRegistrar* (*get_texture_registrar)(FlPluginRegistrar* registrar); + + FlView* (*get_view)(FlPluginRegistrar* registrar); +}; + +/** + * FlPluginRegistrar: + * + * #FlPluginRegistrar is used when registering new plugins. + */ + +/** + * fl_plugin_registrar_get_messenger: + * @registrar: an #FlPluginRegistrar. + * + * Gets the messenger this plugin can communicate with. + * + * Returns: an #FlBinaryMessenger. + */ +FlBinaryMessenger* fl_plugin_registrar_get_messenger( + FlPluginRegistrar* registrar); + +/** + * fl_plugin_registrar_get_texture_registrar: + * @registrar: an #FlPluginRegistrar. + * + * Gets the texture registrar this plugin can communicate with. + * + * Returns: an #FlTextureRegistrar. + */ +FlTextureRegistrar* fl_plugin_registrar_get_texture_registrar( + FlPluginRegistrar* registrar); + +/** + * fl_plugin_registrar_get_view: + * @registrar: an #FlPluginRegistrar. + * + * Get the view that Flutter is rendering with. + * + * Returns: (allow-none): an #FlView or %NULL if running in headless mode. + */ +FlView* fl_plugin_registrar_get_view(FlPluginRegistrar* registrar); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_PLUGIN_REGISTRAR_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_plugin_registry.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_plugin_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..e8c805781ae592bcce1c15a844785dba90b20309 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_plugin_registry.h @@ -0,0 +1,63 @@ +// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_PLUGIN_REGISTRY_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_PLUGIN_REGISTRY_H_ + +#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) +#error "Only can be included directly." +#endif + +#include +#include + +#include "fl_plugin_registrar.h" + +G_BEGIN_DECLS + +G_MODULE_EXPORT +G_DECLARE_INTERFACE(FlPluginRegistry, + fl_plugin_registry, + FL, + PLUGIN_REGISTRY, + GObject) + +/** + * FlPluginRegistry: + * + * #FlPluginRegistry vends #FlPluginRegistrar objects for named plugins. + */ + +struct _FlPluginRegistryInterface { + GTypeInterface g_iface; + + /** + * FlPluginRegistry::get_registrar_for_plugin: + * @registry: an #FlPluginRegistry. + * @name: plugin name. + * + * Gets the plugin registrar for the plugin with @name. + * + * Returns: (transfer full): an #FlPluginRegistrar. + */ + FlPluginRegistrar* (*get_registrar_for_plugin)(FlPluginRegistry* registry, + const gchar* name); +}; + +/** + * fl_plugin_registry_get_registrar_for_plugin: + * @registry: an #FlPluginRegistry. + * @name: plugin name. + * + * Gets the plugin registrar for the plugin with @name. + * + * Returns: (transfer full): an #FlPluginRegistrar. + */ +FlPluginRegistrar* fl_plugin_registry_get_registrar_for_plugin( + FlPluginRegistry* registry, + const gchar* name); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_PLUGIN_REGISTRY_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_standard_message_codec.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_standard_message_codec.h new file mode 100644 index 0000000000000000000000000000000000000000..2115fd6aab8254e242d152abf9fde6f0618d4a5d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_standard_message_codec.h @@ -0,0 +1,176 @@ +// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_STANDARD_MESSAGE_CODEC_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_STANDARD_MESSAGE_CODEC_H_ + +#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) +#error "Only can be included directly." +#endif + +#include + +#include "fl_message_codec.h" + +G_BEGIN_DECLS + +G_MODULE_EXPORT +G_DECLARE_DERIVABLE_TYPE(FlStandardMessageCodec, + fl_standard_message_codec, + FL, + STANDARD_MESSAGE_CODEC, + FlMessageCodec) + +/** + * FlStandardMessageCodec: + * + * #FlStandardMessageCodec is an #FlMessageCodec that implements the Flutter + * standard message encoding. This codec encodes and decodes #FlValue of type + * #FL_VALUE_TYPE_NULL, #FL_VALUE_TYPE_BOOL, #FL_VALUE_TYPE_INT, + * #FL_VALUE_TYPE_FLOAT, #FL_VALUE_TYPE_STRING, #FL_VALUE_TYPE_UINT8_LIST, + * #FL_VALUE_TYPE_INT32_LIST, #FL_VALUE_TYPE_INT64_LIST, + * #FL_VALUE_TYPE_FLOAT_LIST, #FL_VALUE_TYPE_LIST, and #FL_VALUE_TYPE_MAP. + * + * If other values types are required to be supported create a new subclass that + * overrides write_value and read_value_of_type. + * + * #FlStandardMessageCodec matches the StandardCodec class in the Flutter + * services library. + */ + +struct _FlStandardMessageCodecClass { + FlMessageCodecClass parent_class; + + /** + * FlStandardMessageCodec::write_value: + * @codec: an #FlStandardMessageCodec. + * @buffer: a buffer to write into. + * @value: (allow-none): value to write. + * @error: (allow-none): #GError location to store the error occurring, or + * %NULL. + * + * Virtual method to write an #FlValue in Flutter Standard encoding. + * + * If a codec needs to support custom #FlValue objects it must override this + * method to encode those values. For non-custom values the parent method + * should be called. + * + * Returns: %TRUE on success. + */ + gboolean (*write_value)(FlStandardMessageCodec* codec, + GByteArray* buffer, + FlValue* value, + GError** error); + + /** + * FlStandardMessageCodec::read_value_of_type: + * @codec: an #FlStandardMessageCodec. + * @buffer: buffer to read from. + * @offset: (inout): read position in @buffer. + * @type: the type of the value. + * @error: (allow-none): #GError location to store the error occurring, or + * %NULL. + * + * Virtual method to read an #FlValue in Flutter Standard encoding. + * + * If a codec needs to support custom #FlValue objects it must override this + * method to decode those values. For non-custom values the parent method + * should be called. + * + * Returns: an #FlValue or %NULL on error. + */ + FlValue* (*read_value_of_type)(FlStandardMessageCodec* codec, + GBytes* buffer, + size_t* offset, + int type, + GError** error); +}; + +/* + * fl_standard_message_codec_new: + * + * Creates an #FlStandardMessageCodec. + * + * Returns: a new #FlStandardMessageCodec. + */ +FlStandardMessageCodec* fl_standard_message_codec_new(); + +/** + * fl_standard_message_codec_write_size: + * @codec: an #FlStandardMessageCodec. + * @buffer: buffer to write into. + * @size: size value to write. + * + * Writes a size field in Flutter Standard encoding. + */ +void fl_standard_message_codec_write_size(FlStandardMessageCodec* codec, + GByteArray* buffer, + uint32_t size); + +/** + * fl_standard_message_codec_read_size: + * @codec: an #FlStandardMessageCodec. + * @buffer: buffer to read from. + * @offset: (inout): read position in @buffer. + * @value: location to read size. + * @error: (allow-none): #GError location to store the error occurring, or + * %NULL. + * + * Reads a size field in Flutter Standard encoding. + * + * This method is intended for use by subclasses overriding + * FlStandardMessageCodec::read_value_of_type. + * + * Returns: %TRUE on success. + */ +gboolean fl_standard_message_codec_read_size(FlStandardMessageCodec* codec, + GBytes* buffer, + size_t* offset, + uint32_t* value, + GError** error); + +/** + * fl_standard_message_codec_write_value: + * @codec: an #FlStandardMessageCodec. + * @buffer: buffer to write into. + * @value: (allow-none): value to write. + * @error: (allow-none): #GError location to store the error occurring, or + * %NULL. + * + * Writes an #FlValue in Flutter Standard encoding. + * + * This method is intended for use by subclasses overriding + * FlStandardMessageCodec::write_value. + * + * Returns: %TRUE on success. + */ +gboolean fl_standard_message_codec_write_value(FlStandardMessageCodec* codec, + GByteArray* buffer, + FlValue* value, + GError** error); + +/** + * fl_standard_message_codec_read_value: + * @codec: an #FlStandardMessageCodec. + * @buffer: buffer to read from. + * @offset: (inout): read position in @buffer. + * @value: location to read size. + * @error: (allow-none): #GError location to store the error occurring, or + * %NULL. + * + * Reads an #FlValue in Flutter Standard encoding. + * + * This method is intended for use by subclasses overriding + * FlStandardMessageCodec::read_value_of_type. + * + * Returns: a new #FlValue or %NULL on error. + */ +FlValue* fl_standard_message_codec_read_value(FlStandardMessageCodec* codec, + GBytes* buffer, + size_t* offset, + GError** error); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_STANDARD_MESSAGE_CODEC_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_standard_method_codec.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_standard_method_codec.h new file mode 100644 index 0000000000000000000000000000000000000000..ba3447bfe2ab5bd0f91c0ee1e9a5dcacff2af7d5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_standard_method_codec.h @@ -0,0 +1,59 @@ +// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_STANDARD_METHOD_CODEC_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_STANDARD_METHOD_CODEC_H_ + +#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) +#error "Only can be included directly." +#endif + +#include + +#include "fl_method_codec.h" +#include "fl_standard_message_codec.h" + +G_BEGIN_DECLS + +G_MODULE_EXPORT +G_DECLARE_FINAL_TYPE(FlStandardMethodCodec, + fl_standard_method_codec, + FL, + STANDARD_METHOD_CODEC, + FlMethodCodec) + +/** + * FlStandardMethodCodec: + * + * #FlStandardMethodCodec is an #FlMethodCodec that implements method calls + * using the Flutter standard message encoding. It should be used with a + * #FlMethodChannel. + * + * #FlStandardMethodCodec matches the StandardMethodCodec class in the Flutter + * services library. + */ + +/** + * fl_standard_method_codec_new: + * + * Creates an #FlStandardMethodCodec. + * + * Returns: a new #FlStandardMethodCodec. + */ +FlStandardMethodCodec* fl_standard_method_codec_new(); + +/** + * fl_standard_method_codec_new: + * @message_codec: A #FlMessageCodec. + * + * Creates an #FlStandardMethodCodec with a custom message codec. + * + * Returns: a new #FlStandardMethodCodec. + */ +FlStandardMethodCodec* fl_standard_method_codec_new_with_message_codec( + FlStandardMessageCodec* message_codec); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_STANDARD_METHOD_CODEC_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_string_codec.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_string_codec.h new file mode 100644 index 0000000000000000000000000000000000000000..e13beb4f454829a9b10dac2bcef3ff7b8e812997 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_string_codec.h @@ -0,0 +1,47 @@ +// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_STRING_CODEC_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_STRING_CODEC_H_ + +#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) +#error "Only can be included directly." +#endif + +#include + +#include "fl_message_codec.h" + +G_BEGIN_DECLS + +G_MODULE_EXPORT +G_DECLARE_FINAL_TYPE(FlStringCodec, + fl_string_codec, + FL, + STRING_CODEC, + FlMessageCodec) + +/** + * FlStringCodec: + * + * #FlStringCodec is an #FlMessageCodec that implements the Flutter string + * message encoding. This only encodes and decodes #FlValue of type + * #FL_VALUE_TYPE_STRING, other types #FlValues will generate an error during + * encoding. + * + * #FlStringCodec matches the StringCodec class in the Flutter services library. + */ + +/** + * fl_string_codec_new: + * + * Creates an #FlStringCodec. + * + * Returns: a new #FlStringCodec. + */ +FlStringCodec* fl_string_codec_new(); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_STRING_CODEC_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_texture.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_texture.h new file mode 100644 index 0000000000000000000000000000000000000000..86b14dee3906eaff67cc37c64f46108864da83ae --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_texture.h @@ -0,0 +1,52 @@ +// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_TEXTURE_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_TEXTURE_H_ + +#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) +#error "Only can be included directly." +#endif + +#include +#include +#include + +G_BEGIN_DECLS + +G_MODULE_EXPORT +G_DECLARE_INTERFACE(FlTexture, fl_texture, FL, TEXTURE, GObject) + +/** + * FlTexture: + * + * #FlTexture represents a texture. + * + * You can derive #FlTextureGL for populating hardware-accelerated textures or + * instantiate #FlPixelBufferTexture for populating pixel buffers. Do NOT + * directly implement this interface. + */ + +struct _FlTextureInterface { + GTypeInterface g_iface; + + void (*set_id)(FlTexture* texture, int64_t id); + + int64_t (*get_id)(FlTexture* texture); +}; + +/** + * fl_texture_get_id: + * @texture: a #FlTexture. + * + * Get the ID for this texture, which can be passed to Flutter code to refer to + * this texture. + * + * Returns: a texture ID. + */ +int64_t fl_texture_get_id(FlTexture* texture); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_TEXTURE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_texture_gl.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_texture_gl.h new file mode 100644 index 0000000000000000000000000000000000000000..fc80eb7489c2426074521015916ea420b32e08b2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_texture_gl.h @@ -0,0 +1,109 @@ +// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_TEXTURE_GL_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_TEXTURE_GL_H_ + +#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) +#error "Only can be included directly." +#endif + +#include +#include +#include +#include "fl_texture.h" + +G_BEGIN_DECLS + +G_MODULE_EXPORT +G_DECLARE_DERIVABLE_TYPE(FlTextureGL, fl_texture_gl, FL, TEXTURE_GL, GObject) + +/** + * FlTextureGL: + * + * #FlTextureGL is an abstract class that represents an OpenGL texture. + * + * If you want to render textures in other OpenGL context, create and use the + * #GdkGLContext by calling gdk_window_create_gl_context () with the #GdkWindow + * of #FlView. The context will be shared with the one used by Flutter. + * + * The following example shows how to implement an #FlTextureGL. + * ![ + * #include + * + * struct _MyTextureGL { + * FlTextureGL parent_instance; + * + * GLuint texture_id; + * }; + * + * G_DEFINE_TYPE(MyTextureGL, + * my_texture_gl, + * fl_texture_gl_get_type ()) + * + * static gboolean + * my_texture_gl_populate (FlTextureGL *texture, + * uint32_t *target, + * uint32_t *name, + * uint32_t *width, + * uint32_t *height, + * GError **error) { + * MyTextureGL *self = MY_TEXTURE_GL (texture); + * if (self->texture_id == 0) { + * glGenTextures (1, &self->texture_id); + * glBindTexture (GL_TEXTURE_2D, self->texture_id); + * // further configuration here. + * } else { + * glBindTexture (GL_TEXTURE_2D, self->texture_id); + * } + * + * // For example, we render pixel buffer here. + * // Note that Flutter only accepts textures in GL_RGBA8 format. + * static char buffer[] = { 0x1f, 0x2f, 0x3f, 0x4f }; // 1x1 pixel. + * glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, + * GL_UNSIGNED_BYTE, buffer); + * + * *target = GL_TEXTURE_2D; + * *name = self->texture_id; + * *width = 1; + * *height = 1; + * + * return TRUE; + * } + * + * static void my_texture_class_init(MyTextureClass* klass) { + * FL_TEXTURE_GL_CLASS(klass)->populate = my_texture_gl_populate; + * } + * + * static void my_texture_init(MyTexture* self) {} + * ]| + */ + +struct _FlTextureGLClass { + GObjectClass parent_class; + + /** + * Virtual method called when Flutter populates this texture. The OpenGL + * context used by Flutter has been already set. + * @texture: an #FlTexture. + * @target: texture target (example GL_TEXTURE_2D or GL_TEXTURE_RECTANGLE). + * @name: (out): name of texture. + * @width: (inout): width of the texture in pixels. + * @height: (inout): height of the texture in pixels. + * @error: (allow-none): #GError location to store the error occurring, or + * %NULL to ignore. + * + * Returns: %TRUE on success. + */ + gboolean (*populate)(FlTextureGL* texture, + uint32_t* target, + uint32_t* name, + uint32_t* width, + uint32_t* height, + GError** error); +}; + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_TEXTURE_GL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_texture_registrar.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_texture_registrar.h new file mode 100644 index 0000000000000000000000000000000000000000..291f1644bee2174e612a4e0823e2773c02f632a2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_texture_registrar.h @@ -0,0 +1,95 @@ +// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_TEXTURE_REGISTRAR_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_TEXTURE_REGISTRAR_H_ + +#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) +#error "Only can be included directly." +#endif + +#include +#include +#include + +#include "fl_texture.h" + +G_BEGIN_DECLS + +G_MODULE_EXPORT +G_DECLARE_INTERFACE(FlTextureRegistrar, + fl_texture_registrar, + FL, + TEXTURE_REGISTRAR, + GObject) + +struct _FlTextureRegistrarInterface { + GTypeInterface parent_iface; + + gboolean (*register_texture)(FlTextureRegistrar* registrar, + FlTexture* texture); + + FlTexture* (*lookup_texture)(FlTextureRegistrar* registrar, int64_t id); + + gboolean (*mark_texture_frame_available)(FlTextureRegistrar* registrar, + FlTexture* texture); + + gboolean (*unregister_texture)(FlTextureRegistrar* registrar, + FlTexture* texture); + + void (*shutdown)(FlTextureRegistrar* registrar); +}; + +/** + * FlTextureRegistrar: + * + * #FlTextureRegistrar is used when registering textures. + * + * Flutter Framework accesses your texture by the related unique texture ID. To + * draw your texture in Dart, you should add Texture widget in your widget tree + * with the same texture ID. Use platform channels to send this unique texture + * ID to the Dart side. + */ + +/** + * fl_texture_registrar_register_texture: + * @registrar: an #FlTextureRegistrar. + * @texture: an #FlTexture for registration. + * + * Registers a texture. + * + * Returns: %TRUE on success. + */ +gboolean fl_texture_registrar_register_texture(FlTextureRegistrar* registrar, + FlTexture* texture); + +/** + * fl_texture_registrar_mark_texture_frame_available: + * @registrar: an #FlTextureRegistrar. + * @texture: the texture that has a frame available. + * + * Notifies the flutter engine that the texture object has updated and needs to + * be rerendered. + * + * Returns: %TRUE on success. + */ +gboolean fl_texture_registrar_mark_texture_frame_available( + FlTextureRegistrar* registrar, + FlTexture* texture); + +/** + * fl_texture_registrar_unregister_texture: + * @registrar: an #FlTextureRegistrar. + * @texture: the texture being unregistered. + * + * Unregisters an existing texture object. + * + * Returns: %TRUE on success. + */ +gboolean fl_texture_registrar_unregister_texture(FlTextureRegistrar* registrar, + FlTexture* texture); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_TEXTURE_REGISTRAR_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_value.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_value.h new file mode 100644 index 0000000000000000000000000000000000000000..86a2f9c25973c0f98156c5811e78d5e7b392aa3b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_value.h @@ -0,0 +1,688 @@ +// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_VALUE_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_VALUE_H_ + +#include +#include +#include +#include + +#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) +#error "Only can be included directly." +#endif + +G_BEGIN_DECLS + +/** + * FlValue: + * + * #FlValue is an object that contains the data types used in the platform + * channel used by Flutter. + * + * In Dart the values are represented as follows: + * - #FL_VALUE_TYPE_NULL: Null + * - #FL_VALUE_TYPE_BOOL: bool + * - #FL_VALUE_TYPE_INT: num + * - #FL_VALUE_TYPE_FLOAT: num + * - #FL_VALUE_TYPE_STRING: String + * - #FL_VALUE_TYPE_UINT8_LIST: Uint8List + * - #FL_VALUE_TYPE_INT32_LIST: Int32List + * - #FL_VALUE_TYPE_INT64_LIST: Int64List + * - #FL_VALUE_TYPE_FLOAT32_LIST: Float32List + * - #FL_VALUE_TYPE_FLOAT_LIST: Float64List + * - #FL_VALUE_TYPE_LIST: List + * - #FL_VALUE_TYPE_MAP: Map + * - #FL_VALUE_TYPE_CUSTOM: (custom type) + * + * See #FlMessageCodec to encode and decode these values. + */ +typedef struct _FlValue FlValue; + +/** + * FlValueType: + * @FL_VALUE_TYPE_NULL: The null value. + * @FL_VALUE_TYPE_BOOL: A boolean. + * @FL_VALUE_TYPE_INT: A 64 bit signed integer. + * @FL_VALUE_TYPE_FLOAT: A 64 bit floating point number. + * @FL_VALUE_TYPE_STRING: UTF-8 text. + * @FL_VALUE_TYPE_UINT8_LIST: An ordered list of unsigned 8 bit integers. + * @FL_VALUE_TYPE_INT32_LIST: An ordered list of 32 bit integers. + * @FL_VALUE_TYPE_INT64_LIST: An ordered list of 64 bit integers. + * @FL_VALUE_TYPE_FLOAT_LIST: An ordered list of floating point numbers. + * @FL_VALUE_TYPE_LIST: An ordered list of #FlValue objects. + * @FL_VALUE_TYPE_MAP: A map of #FlValue objects keyed by #FlValue object. + * @FL_VALUE_TYPE_FLOAT32_LIST: An ordered list of 32bit floating point numbers. + * @FL_VALUE_TYPE_CUSTOM: A custom value. + * + * Types of #FlValue. + */ +typedef enum { + // Parts of the public API, so fixing the names is a breaking change. + FL_VALUE_TYPE_NULL, + FL_VALUE_TYPE_BOOL, + FL_VALUE_TYPE_INT, + FL_VALUE_TYPE_FLOAT, + FL_VALUE_TYPE_STRING, + FL_VALUE_TYPE_UINT8_LIST, + FL_VALUE_TYPE_INT32_LIST, + FL_VALUE_TYPE_INT64_LIST, + FL_VALUE_TYPE_FLOAT_LIST, + FL_VALUE_TYPE_LIST, + FL_VALUE_TYPE_MAP, + FL_VALUE_TYPE_FLOAT32_LIST, + FL_VALUE_TYPE_CUSTOM, +} FlValueType; + +/** + * fl_value_new_null: + * + * Creates an #FlValue that contains a null value. The equivalent Dart type is + * null. + * + * Returns: a new #FlValue. + */ +FlValue* fl_value_new_null(); + +/** + * fl_value_new_bool: + * @value: the value. + * + * Creates an #FlValue that contains a boolean value. The equivalent Dart type + * is a bool. + * + * Returns: a new #FlValue. + */ +FlValue* fl_value_new_bool(bool value); + +/** + * fl_value_new_int: + * @value: the value. + * + * Creates an #FlValue that contains an integer number. The equivalent Dart type + * is a num. + * + * Returns: a new #FlValue. + */ +FlValue* fl_value_new_int(int64_t value); + +/** + * fl_value_new_float: + * @value: the value. + * + * Creates an #FlValue that contains a floating point number. The equivalent + * Dart type is a num. + * + * Returns: a new #FlValue. + */ +FlValue* fl_value_new_float(double value); + +/** + * fl_value_new_string: + * @value: a %NULL-terminated UTF-8 string. + * + * Creates an #FlValue that contains UTF-8 text. The equivalent Dart type is a + * String. + * + * Returns: a new #FlValue. + */ +FlValue* fl_value_new_string(const gchar* value); + +/** + * fl_value_new_string_sized: + * @value: a buffer containing UTF-8 text. It does not require a nul terminator. + * @value_length: the number of bytes to use from @value. + * + * Creates an #FlValue that contains UTF-8 text. The equivalent Dart type is a + * String. + * + * Returns: a new #FlValue. + */ +FlValue* fl_value_new_string_sized(const gchar* value, size_t value_length); + +/** + * fl_value_new_uint8_list: + * @value: an array of unsigned 8 bit integers. + * @value_length: number of elements in @value. + * + * Creates an ordered list containing 8 bit unsigned integers. The data is + * copied. The equivalent Dart type is a Uint8List. + * + * Returns: a new #FlValue. + */ +FlValue* fl_value_new_uint8_list(const uint8_t* value, size_t value_length); + +/** + * fl_value_new_uint8_list_from_bytes: + * @value: a #GBytes. + * + * Creates an ordered list containing 8 bit unsigned integers. The data is + * copied. The equivalent Dart type is a Uint8List. + * + * Returns: a new #FlValue. + */ +FlValue* fl_value_new_uint8_list_from_bytes(GBytes* value); + +/** + * fl_value_new_int32_list: + * @value: an array of signed 32 bit integers. + * @value_length: number of elements in @value. + * + * Creates an ordered list containing 32 bit integers. The equivalent Dart type + * is a Int32List. + * + * Returns: a new #FlValue. + */ +FlValue* fl_value_new_int32_list(const int32_t* value, size_t value_length); + +/** + * fl_value_new_int64_list: + * @value: an array of signed 64 bit integers. + * @value_length: number of elements in @value. + * + * Creates an ordered list containing 64 bit integers. The equivalent Dart type + * is a Int64List. + * + * Returns: a new #FlValue. + */ +FlValue* fl_value_new_int64_list(const int64_t* value, size_t value_length); + +/** + * fl_value_new_float32_list: + * @value: an array of floating point numbers. + * @value_length: number of elements in @value. + * + * Creates an ordered list containing 32 bit floating point numbers. + * The equivalent Dart type is a Float32List. + * + * Returns: a new #FlValue. + */ +FlValue* fl_value_new_float32_list(const float* value, size_t value_length); + +/** + * fl_value_new_float_list: + * @value: an array of floating point numbers. + * @value_length: number of elements in @value. + * + * Creates an ordered list containing floating point numbers. The equivalent + * Dart type is a Float64List. + * + * Returns: a new #FlValue. + */ +FlValue* fl_value_new_float_list(const double* value, size_t value_length); + +/** + * fl_value_new_list: + * + * Creates an ordered list. Children can be added to the list using + * fl_value_append(). The children are accessed using fl_value_get_length() + * and fl_value_get_list_value(). The equivalent Dart type is a List. + * + * The following example shows a simple list of values: + * + * |[ + * g_autoptr(FlValue) value = fl_value_new_list (); + * fl_value_append_take (value, fl_value_new_string ("one"); + * fl_value_append_take (value, fl_value_new_int (2); + * fl_value_append_take (value, fl_value_new_float (3.0); + * ]| + * + * This value can be decoded using: + * + * |[ + * g_assert (fl_value_get_type (value) == FL_VALUE_TYPE_LIST); + * for (size_t i = 0; i < fl_value_get_length (value); i++) { + * FlValue *child = fl_value_get_list_value (value, i); + * process_value (child); + * } + * ]| + * + * Returns: a new #FlValue. + */ +FlValue* fl_value_new_list(); + +/** + * fl_value_new_list_from_strv: + * @value: a %NULL-terminated array of strings. + * + * Creates an ordered list containing #FlString values. + * + * Returns: a new #FlValue. + */ +FlValue* fl_value_new_list_from_strv(const gchar* const* value); + +/** + * fl_value_new_map: + * + * Creates an ordered associative array. Children can be added to the map + * using fl_value_set(), fl_value_set_take(), fl_value_set_string(), + * fl_value_set_string_take(). The children are accessed using + * fl_value_get_length(), fl_value_get_map_key(), fl_value_get_map_value(), + * fl_value_lookup() and fl_value_lookup_string(). The equivalent Dart type is a + * Map. + * + * The following example shows how to create a map of values keyed by strings: + * + * |[ + * g_autoptr(FlValue) value = fl_value_new_map (); + * fl_value_set_string_take (value, "name", fl_value_new_string ("Gandalf")); + * fl_value_set_string_take (value, "occupation", + * fl_value_new_string ("Wizard")); + * fl_value_set_string_take (value, "age", fl_value_new_int (2019)); + * ]| + * + * This value can be decoded using: + * |[ + * g_assert (fl_value_get_type (value) == FL_VALUE_TYPE_MAP); + * FlValue *name = fl_value_lookup_string (value, "name"); + * g_assert (fl_value_get_type (name) == FL_VALUE_TYPE_STRING); + * FlValue *age = fl_value_lookup_string (value, "age"); + * g_assert (fl_value_get_type (age) == FL_VALUE_TYPE_INT); + * g_message ("Next customer is %s (%d years old)", + * fl_value_get_string (name), + * fl_value_get_int (age)); + * ]| + * + * Returns: a new #FlValue. + */ +FlValue* fl_value_new_map(); + +/** + * fl_value_new_custom: + * @type: an ID for this type. + * @value: pointer to the custom value. + * @destroy_notify: function to call when @value is no longer required. + * + * Creates a new custom data type. The Dart side of the channel must have + * equivalent custom code to access this object. + * + * Returns: a new #FlValue. + */ +FlValue* fl_value_new_custom(int type, + gconstpointer value, + GDestroyNotify destroy_notify); + +/** + * fl_value_new_custom_object: + * @type: an ID for this type. + * @object: the custom object. + * + * Creates a new custom data type. The Dart side of the channel must have + * equivalent custom code to access this object. + * + * Returns: a new #FlValue. + */ +FlValue* fl_value_new_custom_object(int type, GObject* object); + +/** + * fl_value_new_custom_object_take: + * @type: an ID for this type. + * @object: (transfer full): the custom object. + * + * Creates a new custom data type. The Dart side of the channel must have + * equivalent custom code to access this object. Ownership of @object is taken. + * + * Returns: a new #FlValue. + */ +FlValue* fl_value_new_custom_object_take(int type, GObject* object); + +/** + * fl_value_ref: + * @value: an #FlValue. + * + * Increases the reference count of an #FlValue. + * + * Returns: the value that was referenced. + */ +FlValue* fl_value_ref(FlValue* value); + +/** + * fl_value_unref: + * @value: an #FlValue. + * + * Decreases the reference count of an #FlValue. When the reference count hits + * zero @value is destroyed and no longer valid. + */ +void fl_value_unref(FlValue* value); + +/** + * fl_value_get_type: + * @value: an #FlValue. + * + * Gets the type of @value. + * + * Returns: an #FlValueType. + */ +FlValueType fl_value_get_type(FlValue* value); + +/** + * fl_value_equal: + * @a: an #FlValue. + * @b: an #FlValue. + * + * Compares two #FlValue to see if they are equivalent. Two values are + * considered equivalent if they are of the same type and their data is the same + * including any child values. For values of type #FL_VALUE_TYPE_MAP the order + * of the values does not matter. + * + * Returns: %TRUE if both values are equivalent. + */ +bool fl_value_equal(FlValue* a, FlValue* b); + +/** + * fl_value_append: + * @value: an #FlValue of type #FL_VALUE_TYPE_LIST. + * @child: an #FlValue. + * + * Adds @child to the end of @value. Calling this with an #FlValue that is not + * of type #FL_VALUE_TYPE_LIST is a programming error. + */ +void fl_value_append(FlValue* value, FlValue* child); + +/** + * fl_value_append_take: + * @value: an #FlValue of type #FL_VALUE_TYPE_LIST. + * @child: (transfer full): an #FlValue. + * + * Adds @child to the end of @value. Ownership of @child is taken by @value. + * Calling this with an #FlValue that is not of type #FL_VALUE_TYPE_LIST is a + * programming error. + */ +void fl_value_append_take(FlValue* value, FlValue* child); + +/** + * fl_value_set: + * @value: an #FlValue of type #FL_VALUE_TYPE_MAP. + * @key: an #FlValue. + * @child_value: an #FlValue. + * + * Sets @key in @value to @child_value. If an existing value was in the map with + * the same key it is replaced. Calling this with an #FlValue that is not of + * type #FL_VALUE_TYPE_MAP is a programming error. + */ +void fl_value_set(FlValue* value, FlValue* key, FlValue* child_value); + +/** + * fl_value_set_take: + * @value: an #FlValue of type #FL_VALUE_TYPE_MAP. + * @key: (transfer full): an #FlValue. + * @child_value: (transfer full): an #FlValue. + * + * Sets @key in @value to @child_value. Ownership of both @key and @child_value + * is taken by @value. If an existing value was in the map with the same key it + * is replaced. Calling this with an #FlValue that is not of type + * #FL_VALUE_TYPE_MAP is a programming error. + */ +void fl_value_set_take(FlValue* value, FlValue* key, FlValue* child_value); + +/** + * fl_value_set_string: + * @value: an #FlValue of type #FL_VALUE_TYPE_MAP. + * @key: a UTF-8 text key. + * @child_value: an #FlValue. + * + * Sets a value in the map with a text key. If an existing value was in the map + * with the same key it is replaced. Calling this with an #FlValue that is not + * of type #FL_VALUE_TYPE_MAP is a programming error. + */ +void fl_value_set_string(FlValue* value, + const gchar* key, + FlValue* child_value); + +/** + * fl_value_set_string_take: + * @value: an #FlValue of type #FL_VALUE_TYPE_MAP. + * @key: a UTF-8 text key. + * @child_value: (transfer full): an #FlValue. + * + * Sets a value in the map with a text key, taking ownership of the value. If an + * existing value was in the map with the same key it is replaced. Calling this + * with an #FlValue that is not of type #FL_VALUE_TYPE_MAP is a programming + * error. + */ +void fl_value_set_string_take(FlValue* value, + const gchar* key, + FlValue* child_value); + +/** + * fl_value_get_bool: + * @value: an #FlValue of type #FL_VALUE_TYPE_BOOL. + * + * Gets the boolean value of @value. Calling this with an #FlValue that is + * not of type #FL_VALUE_TYPE_BOOL is a programming error. + * + * Returns: a boolean value. + */ +bool fl_value_get_bool(FlValue* value); + +/** + * fl_value_get_int: + * @value: an #FlValue of type #FL_VALUE_TYPE_INT. + * + * Gets the integer number of @value. Calling this with an #FlValue that is + * not of type #FL_VALUE_TYPE_INT is a programming error. + * + * Returns: an integer number. + */ +int64_t fl_value_get_int(FlValue* value); + +/** + * fl_value_get_float: + * @value: an #FlValue of type #FL_VALUE_TYPE_FLOAT. + * + * Gets the floating point number of @value. Calling this with an #FlValue + * that is not of type #FL_VALUE_TYPE_FLOAT is a programming error. + * + * Returns: a floating point number. + */ +double fl_value_get_float(FlValue* value); + +/** + * fl_value_get_string: + * @value: an #FlValue of type #FL_VALUE_TYPE_STRING. + * + * Gets the UTF-8 text contained in @value. Calling this with an #FlValue + * that is not of type #FL_VALUE_TYPE_STRING is a programming error. + * + * Returns: a UTF-8 encoded string. + */ +const gchar* fl_value_get_string(FlValue* value); + +/** + * fl_value_get_length: + * @value: an #FlValue of type #FL_VALUE_TYPE_UINT8_LIST, + * #FL_VALUE_TYPE_INT32_LIST, #FL_VALUE_TYPE_INT64_LIST, + * #FL_VALUE_TYPE_FLOAT32_LIST, #FL_VALUE_TYPE_FLOAT_LIST, #FL_VALUE_TYPE_LIST + * or #FL_VALUE_TYPE_MAP. + * + * Gets the number of elements @value contains. This is only valid for list + * and map types. Calling this with other types is a programming error. + * + * Returns: the number of elements inside @value. + */ +size_t fl_value_get_length(FlValue* value); + +/** + * fl_value_get_uint8_list: + * @value: an #FlValue of type #FL_VALUE_TYPE_UINT8_LIST. + * + * Gets the array of unisigned 8 bit integers @value contains. The data + * contains fl_value_get_length() elements. Calling this with an #FlValue that + * is not of type #FL_VALUE_TYPE_UINT8_LIST is a programming error. + * + * Returns: an array of unsigned 8 bit integers. + */ +const uint8_t* fl_value_get_uint8_list(FlValue* value); + +/** + * fl_value_get_int32_list: + * @value: an #FlValue of type #FL_VALUE_TYPE_INT32_LIST. + * + * Gets the array of 32 bit integers @value contains. The data contains + * fl_value_get_length() elements. Calling this with an #FlValue that is not of + * type #FL_VALUE_TYPE_INT32_LIST is a programming error. + * + * Returns: an array of 32 bit integers. + */ +const int32_t* fl_value_get_int32_list(FlValue* value); + +/** + * fl_value_get_int64_list: + * @value: an #FlValue of type #FL_VALUE_TYPE_INT64_LIST. + * + * Gets the array of 64 bit integers @value contains. The data contains + * fl_value_get_length() elements. Calling this with an #FlValue that is not of + * type #FL_VALUE_TYPE_INT64_LIST is a programming error. + * + * Returns: an array of 64 bit integers. + */ +const int64_t* fl_value_get_int64_list(FlValue* value); + +/** + * fl_value_get_float32_list: + * @value: an #FlValue of type #FL_VALUE_TYPE_FLOAT32_LIST. + * + * Gets the array of floating point numbers @value contains. The data + * contains fl_value_get_length() elements. Calling this with an #FlValue that + * is not of type #FL_VALUE_TYPE_FLOAT32_LIST is a programming error. + * + * Returns: an array of floating point numbers. + */ +const float* fl_value_get_float32_list(FlValue* value); + +/** + * fl_value_get_float_list: + * @value: an #FlValue of type #FL_VALUE_TYPE_FLOAT_LIST. + * + * Gets the array of floating point numbers @value contains. The data + * contains fl_value_get_length() elements. Calling this with an #FlValue that + * is not of type #FL_VALUE_TYPE_FLOAT_LIST is a programming error. + * + * Returns: an array of floating point numbers. + */ +const double* fl_value_get_float_list(FlValue* value); + +/** + * fl_value_get_list_value: + * @value: an #FlValue of type #FL_VALUE_TYPE_LIST. + * @index: an index in the list. + * + * Gets a child element of the list. It is a programming error to request an + * index that is outside the size of the list as returned from + * fl_value_get_length(). Calling this with an #FlValue that is not of type + * #FL_VALUE_TYPE_LIST is a programming error. + * + * Returns: an #FlValue. + */ +FlValue* fl_value_get_list_value(FlValue* value, size_t index); + +/** + * fl_value_get_map_key: + * @value: an #FlValue of type #FL_VALUE_TYPE_MAP. + * @index: an index in the map. + * + * Gets a key from the map. It is a programming error to request an index that + * is outside the size of the list as returned from fl_value_get_length(). + * Calling this with an #FlValue that is not of type #FL_VALUE_TYPE_MAP is a + * programming error. + * + * Returns: an #FlValue. + */ +FlValue* fl_value_get_map_key(FlValue* value, size_t index); + +/** + * fl_value_get_map_value: + * @value: an #FlValue of type #FL_VALUE_TYPE_MAP. + * @index: an index in the map. + * + * Gets a value from the map. It is a programming error to request an index that + * is outside the size of the list as returned from fl_value_get_length(). + * Calling this with an #FlValue that is not of type #FL_VALUE_TYPE_MAP is a + * programming error. + * + * Returns: an #FlValue. + */ +FlValue* fl_value_get_map_value(FlValue* value, size_t index); + +/** + * fl_value_lookup: + * @value: an #FlValue of type #FL_VALUE_TYPE_MAP. + * @key: a key value. + * + * Gets the map entry that matches @key. Keys are checked using + * fl_value_equal(). Calling this with an #FlValue that is not of type + * #FL_VALUE_TYPE_MAP is a programming error. + * + * Map lookups are not optimized for performance - if you have a large map or + * need frequent access you should copy the data into another structure, e.g. + * #GHashTable. + * + * Returns: (allow-none): the value with this key or %NULL if not one present. + */ +FlValue* fl_value_lookup(FlValue* value, FlValue* key); + +/** + * fl_value_lookup_string: + * @value: an #FlValue of type #FL_VALUE_TYPE_MAP. + * @key: a key value. + * + * Gets the map entry that matches @key. Keys are checked using + * fl_value_equal(). Calling this with an #FlValue that is not of type + * #FL_VALUE_TYPE_MAP is a programming error. + * + * Map lookups are not optimized for performance - if you have a large map or + * need frequent access you should copy the data into another structure, e.g. + * #GHashTable. + * + * Returns: (allow-none): the value with this key or %NULL if not one present. + */ +FlValue* fl_value_lookup_string(FlValue* value, const gchar* key); + +/** + * fl_value_get_custom_type: + * @value: an #FlValue of type #FL_VALUE_TYPE_CUSTOM. + * + * Gets the type ID for this custom type. + * + * Returns: a type ID. + */ +int fl_value_get_custom_type(FlValue* value); + +/** + * fl_value_get_custom_value: + * @value: an #FlValue of type #FL_VALUE_TYPE_CUSTOM. + * + * Gets the address of the custom value. + * + * Returns: a pointer to the custom value. + */ +gconstpointer fl_value_get_custom_value(FlValue* value); + +/** + * fl_value_get_custom_value_object: + * @value: an #FlValue of type #FL_VALUE_TYPE_CUSTOM. + * + * Gets the custom value as an object. + * + * Returns: an object. + */ +GObject* fl_value_get_custom_value_object(FlValue* value); + +/** + * fl_value_to_string: + * @value: an #FlValue. + * + * Converts an #FlValue to a text representation, suitable for logging purposes. + * The text is formatted to be the equivalent of Dart toString() methods. + * + * Returns: UTF-8 text. + */ +gchar* fl_value_to_string(FlValue* value); + +G_DEFINE_AUTOPTR_CLEANUP_FUNC(FlValue, fl_value_unref) + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_VALUE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_view.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_view.h new file mode 100644 index 0000000000000000000000000000000000000000..486746bdcebef9e519b16a1d9f3eca9faaed78ec --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/fl_view.h @@ -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. + +#ifndef FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_VIEW_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_VIEW_H_ + +#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) +#error "Only can be included directly." +#endif + +#include +#include + +#include "fl_dart_project.h" +#include "fl_engine.h" + +G_BEGIN_DECLS + +G_MODULE_EXPORT +G_DECLARE_FINAL_TYPE(FlView, fl_view, FL, VIEW, GtkBox) + +/** + * FlView: + * + * #FlView is a GTK widget that is capable of displaying a Flutter application. + * + * The following example shows how to set up a view in a GTK application: + * |[ + * FlDartProject *project = fl_dart_project_new (); + * FlView *view = fl_view_new (project); + * gtk_widget_show (GTK_WIDGET (view)); + * gtk_container_add (GTK_CONTAINER (parent), view); + * + * FlBinaryMessenger *messenger = + * fl_engine_get_binary_messenger (fl_view_get_engine (view)); + * setup_channels_or_plugins (messenger); + * ]| + */ + +/** + * fl_view_new: + * @project: The project to show. + * + * Creates a widget to show a Flutter application. + * + * Returns: a new #FlView. + */ +FlView* fl_view_new(FlDartProject* project); + +/** + * fl_view_new_for_engine: + * @engine: an #FlEngine. + * + * Creates a widget to show a window in a Flutter application. + * The engine must be not be headless. + * + * Returns: a new #FlView. + */ +FlView* fl_view_new_for_engine(FlEngine* engine); + +/** + * fl_view_get_engine: + * @view: an #FlView. + * + * Gets the engine being rendered in the view. + * + * Returns: an #FlEngine. + */ +FlEngine* fl_view_get_engine(FlView* view); + +/** + * fl_view_get_id: + * @view: an #FlView. + * + * Gets the Flutter view ID used by this view. + * + * Returns: a view ID or -1 if now ID assigned. + */ +int64_t fl_view_get_id(FlView* view); + +/** + * fl_view_set_background_color: + * @view: an #FlView. + * @color: a background color. + * + * Set the background color for Flutter (defaults to black). + */ +void fl_view_set_background_color(FlView* view, const GdkRGBA* color); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_VIEW_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/flutter_linux.h b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/flutter_linux.h new file mode 100644 index 0000000000000000000000000000000000000000..c0d1483baa02fdaaf66f35b9e7d97656cecb0e38 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/public/flutter_linux/flutter_linux.h @@ -0,0 +1,38 @@ +// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FLUTTER_LINUX_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FLUTTER_LINUX_H_ + +#define __FLUTTER_LINUX_INSIDE__ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#undef __FLUTTER_LINUX_INSIDE__ + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FLUTTER_LINUX_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/testing/fl_mock_binary_messenger.cc b/flutter/engine/src/flutter/shell/platform/linux/testing/fl_mock_binary_messenger.cc new file mode 100644 index 0000000000000000000000000000000000000000..92e997d10cd75378f82dbb9a1574172ff2db7d01 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/testing/fl_mock_binary_messenger.cc @@ -0,0 +1,842 @@ +// 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/shell/platform/linux/testing/fl_mock_binary_messenger.h" + +#include "flutter/shell/platform/linux/fl_binary_messenger_private.h" +#include "flutter/shell/platform/linux/fl_method_codec_private.h" +#include "flutter/shell/platform/linux/public/flutter_linux/fl_json_message_codec.h" +#include "flutter/shell/platform/linux/public/flutter_linux/fl_json_method_codec.h" +#include "flutter/shell/platform/linux/public/flutter_linux/fl_standard_message_codec.h" +#include "flutter/shell/platform/linux/public/flutter_linux/fl_standard_method_codec.h" +#include "flutter/shell/platform/linux/public/flutter_linux/fl_string_codec.h" + +G_DECLARE_FINAL_TYPE(FlMockBinaryMessengerResponseHandle, + fl_mock_binary_messenger_response_handle, + FL, + MOCK_BINARY_MESSENGER_RESPONSE_HANDLE, + FlBinaryMessengerResponseHandle) + +struct _FlMockBinaryMessengerResponseHandle { + FlBinaryMessengerResponseHandle parent_instance; + + FlMockBinaryMessengerCallback callback; + gpointer user_data; +}; + +G_DEFINE_TYPE(FlMockBinaryMessengerResponseHandle, + fl_mock_binary_messenger_response_handle, + fl_binary_messenger_response_handle_get_type()) + +static void fl_mock_binary_messenger_response_handle_class_init( + FlMockBinaryMessengerResponseHandleClass* klass) {} + +static void fl_mock_binary_messenger_response_handle_init( + FlMockBinaryMessengerResponseHandle* self) {} + +FlMockBinaryMessengerResponseHandle* +fl_mock_binary_messenger_response_handle_new( + FlMockBinaryMessengerCallback callback, + gpointer user_data) { + FlMockBinaryMessengerResponseHandle* self = + FL_MOCK_BINARY_MESSENGER_RESPONSE_HANDLE(g_object_new( + fl_mock_binary_messenger_response_handle_get_type(), nullptr)); + self->callback = callback; + self->user_data = user_data; + return self; +} + +struct _FlMockBinaryMessenger { + GObject parent_instance; + + // Handlers the embedder has registered. + GHashTable* handlers; + + // Mocked Dart channels. + GHashTable* mock_channels; + GHashTable* mock_message_channels; + GHashTable* mock_method_channels; + GHashTable* mock_event_channels; + GHashTable* mock_error_channels; +}; + +typedef struct { + FlMockBinaryMessengerChannelHandler callback; + gpointer user_data; +} MockChannel; + +static MockChannel* mock_channel_new( + FlMockBinaryMessengerChannelHandler callback, + gpointer user_data) { + MockChannel* channel = g_new0(MockChannel, 1); + channel->callback = callback; + channel->user_data = user_data; + return channel; +} + +static void mock_channel_free(MockChannel* channel) { + g_free(channel); +} + +typedef struct { + FlMessageCodec* codec; + FlMockBinaryMessengerMessageChannelHandler callback; + gpointer user_data; +} MockMessageChannel; + +static MockMessageChannel* mock_message_channel_new( + FlMockBinaryMessengerMessageChannelHandler callback, + FlMessageCodec* codec, + gpointer user_data) { + MockMessageChannel* channel = g_new0(MockMessageChannel, 1); + channel->codec = FL_MESSAGE_CODEC(g_object_ref(codec)); + channel->callback = callback; + channel->user_data = user_data; + return channel; +} + +static void mock_message_channel_free(MockMessageChannel* channel) { + g_object_unref(channel->codec); + g_free(channel); +} + +typedef struct { + FlMethodCodec* codec; + FlMockBinaryMessengerMethodChannelHandler callback; + gpointer user_data; +} MockMethodChannel; + +static MockMethodChannel* mock_method_channel_new( + FlMockBinaryMessengerMethodChannelHandler callback, + FlMethodCodec* codec, + gpointer user_data) { + MockMethodChannel* channel = g_new0(MockMethodChannel, 1); + channel->codec = FL_METHOD_CODEC(g_object_ref(codec)); + channel->callback = callback; + channel->user_data = user_data; + return channel; +} + +static void mock_method_channel_free(MockMethodChannel* channel) { + g_object_unref(channel->codec); + g_free(channel); +} + +typedef struct { + FlMethodCodec* codec; + FlMockBinaryMessengerEventChannelHandler callback; + FlMockBinaryMessengerEventChannelErrorHandler error_callback; + gpointer user_data; +} MockEventChannel; + +static MockEventChannel* mock_event_channel_new( + FlMockBinaryMessengerEventChannelHandler callback, + FlMockBinaryMessengerEventChannelErrorHandler error_callback, + FlMethodCodec* codec, + gpointer user_data) { + MockEventChannel* channel = g_new0(MockEventChannel, 1); + channel->codec = FL_METHOD_CODEC(g_object_ref(codec)); + channel->callback = callback; + channel->error_callback = error_callback; + channel->user_data = user_data; + return channel; +} + +static void mock_event_channel_free(MockEventChannel* channel) { + g_object_unref(channel->codec); + g_free(channel); +} + +typedef struct { + gint code; + gchar* message; +} MockErrorChannel; + +static MockErrorChannel* mock_error_channel_new(gint code, + const gchar* message) { + MockErrorChannel* channel = g_new0(MockErrorChannel, 1); + channel->code = code; + channel->message = g_strdup(message); + return channel; +} + +static void mock_error_channel_free(MockErrorChannel* channel) { + g_free(channel->message); + g_free(channel); +} + +typedef struct { + FlBinaryMessengerMessageHandler callback; + gpointer user_data; + GDestroyNotify destroy_notify; +} Handler; + +static Handler* handler_new(FlBinaryMessengerMessageHandler callback, + gpointer user_data, + GDestroyNotify destroy_notify) { + Handler* handler = g_new0(Handler, 1); + handler->callback = callback; + handler->user_data = user_data; + handler->destroy_notify = destroy_notify; + return handler; +} + +static void handler_free(Handler* handler) { + if (handler->destroy_notify) { + handler->destroy_notify(handler->user_data); + } + g_free(handler); +} + +static void fl_mock_binary_messenger_iface_init( + FlBinaryMessengerInterface* iface); + +G_DEFINE_TYPE_WITH_CODE( + FlMockBinaryMessenger, + fl_mock_binary_messenger, + G_TYPE_OBJECT, + G_IMPLEMENT_INTERFACE(fl_binary_messenger_get_type(), + fl_mock_binary_messenger_iface_init)) + +static void fl_mock_binary_messenger_set_message_handler_on_channel( + FlBinaryMessenger* messenger, + const gchar* channel, + FlBinaryMessengerMessageHandler handler, + gpointer user_data, + GDestroyNotify destroy_notify) { + FlMockBinaryMessenger* self = FL_MOCK_BINARY_MESSENGER(messenger); + g_hash_table_insert(self->handlers, g_strdup(channel), + handler_new(handler, user_data, destroy_notify)); +} + +static gboolean fl_mock_binary_messenger_send_response( + FlBinaryMessenger* messenger, + FlBinaryMessengerResponseHandle* response_handle, + GBytes* response, + GError** error) { + FlMockBinaryMessenger* self = FL_MOCK_BINARY_MESSENGER(messenger); + + g_return_val_if_fail( + FL_IS_MOCK_BINARY_MESSENGER_RESPONSE_HANDLE(response_handle), FALSE); + FlMockBinaryMessengerResponseHandle* handle = + FL_MOCK_BINARY_MESSENGER_RESPONSE_HANDLE(response_handle); + + handle->callback(self, response, handle->user_data); + + return TRUE; +} + +static void fl_mock_binary_messenger_send_on_channel( + FlBinaryMessenger* messenger, + const gchar* channel, + GBytes* message, + GCancellable* cancellable, + GAsyncReadyCallback callback, + gpointer user_data) { + FlMockBinaryMessenger* self = FL_MOCK_BINARY_MESSENGER(messenger); + g_autoptr(GTask) task = g_task_new(self, cancellable, callback, user_data); + + MockChannel* mock_channel = static_cast( + g_hash_table_lookup(self->mock_channels, channel)); + MockMessageChannel* mock_message_channel = static_cast( + g_hash_table_lookup(self->mock_message_channels, channel)); + MockMethodChannel* mock_method_channel = static_cast( + g_hash_table_lookup(self->mock_method_channels, channel)); + MockEventChannel* mock_event_channel = static_cast( + g_hash_table_lookup(self->mock_event_channels, channel)); + MockErrorChannel* mock_error_channel = static_cast( + g_hash_table_lookup(self->mock_error_channels, channel)); + g_autoptr(GBytes) response = nullptr; + if (mock_channel != nullptr) { + response = mock_channel->callback(self, message, mock_channel->user_data); + } else if (mock_message_channel != nullptr) { + g_autoptr(GError) error = nullptr; + g_autoptr(FlValue) message_value = fl_message_codec_decode_message( + mock_message_channel->codec, message, &error); + if (message_value == nullptr) { + g_warning("Failed to decode message: %s", error->message); + } else { + g_autoptr(FlValue) response_value = mock_message_channel->callback( + self, task, message_value, mock_message_channel->user_data); + if (response_value == nullptr) { + return; + } + + response = fl_message_codec_encode_message(mock_message_channel->codec, + response_value, &error); + if (response == nullptr) { + g_warning("Failed to encode message: %s", error->message); + } + } + } else if (mock_method_channel != nullptr) { + g_autofree gchar* name = nullptr; + g_autoptr(FlValue) args = nullptr; + g_autoptr(GError) error = nullptr; + if (!fl_method_codec_decode_method_call(mock_method_channel->codec, message, + &name, &args, &error)) { + g_warning("Failed to decode method call: %s", error->message); + } else { + g_autoptr(FlMethodResponse) response_value = + mock_method_channel->callback(self, task, name, args, + mock_method_channel->user_data); + if (response_value == nullptr) { + return; + } + + response = fl_method_codec_encode_response(mock_method_channel->codec, + response_value, &error); + if (response == nullptr) { + g_warning("Failed to encode method response: %s", error->message); + } + } + } else if (mock_event_channel != nullptr) { + g_autoptr(GError) error = nullptr; + g_autoptr(FlMethodResponse) response = fl_method_codec_decode_response( + mock_event_channel->codec, message, &error); + if (response == nullptr) { + g_warning("Failed to decode event response: %s", error->message); + } else if (FL_IS_METHOD_SUCCESS_RESPONSE(response)) { + mock_event_channel->callback(self, + fl_method_success_response_get_result( + FL_METHOD_SUCCESS_RESPONSE(response)), + mock_event_channel->user_data); + } else if (FL_IS_METHOD_ERROR_RESPONSE(response)) { + mock_event_channel->error_callback( + self, + fl_method_error_response_get_code(FL_METHOD_ERROR_RESPONSE(response)), + fl_method_error_response_get_message( + FL_METHOD_ERROR_RESPONSE(response)), + fl_method_error_response_get_details( + FL_METHOD_ERROR_RESPONSE(response)), + mock_event_channel->user_data); + } else { + g_warning("Unknown event response"); + } + } else if (mock_error_channel != nullptr) { + g_task_return_new_error(task, fl_binary_messenger_codec_error_quark(), + mock_error_channel->code, "%s", + mock_error_channel->message); + return; + } + + if (response != nullptr) { + g_task_return_pointer(task, g_bytes_ref(response), + reinterpret_cast(g_bytes_unref)); + } +} + +static GBytes* fl_mock_binary_messenger_send_on_channel_finish( + FlBinaryMessenger* messenger, + GAsyncResult* result, + GError** error) { + return static_cast(g_task_propagate_pointer(G_TASK(result), error)); +} + +static void fl_mock_binary_messenger_resize_channel( + FlBinaryMessenger* messenger, + const gchar* channel, + int64_t new_size) {} + +static void fl_mock_binary_messenger_set_warns_on_channel_overflow( + FlBinaryMessenger* messenger, + const gchar* channel, + bool warns) {} + +static void fl_mock_binary_messenger_shutdown(FlBinaryMessenger* messenger) { + FlMockBinaryMessenger* self = FL_MOCK_BINARY_MESSENGER(messenger); + g_hash_table_remove_all(self->handlers); +} + +static void fl_mock_binary_messenger_dispose(GObject* object) { + FlMockBinaryMessenger* self = FL_MOCK_BINARY_MESSENGER(object); + + g_clear_pointer(&self->mock_channels, g_hash_table_unref); + g_clear_pointer(&self->mock_message_channels, g_hash_table_unref); + g_clear_pointer(&self->mock_method_channels, g_hash_table_unref); + g_clear_pointer(&self->mock_event_channels, g_hash_table_unref); + g_clear_pointer(&self->mock_error_channels, g_hash_table_unref); + + G_OBJECT_CLASS(fl_mock_binary_messenger_parent_class)->dispose(object); +} + +static void fl_mock_binary_messenger_class_init( + FlMockBinaryMessengerClass* klass) { + G_OBJECT_CLASS(klass)->dispose = fl_mock_binary_messenger_dispose; +} + +static void fl_mock_binary_messenger_iface_init( + FlBinaryMessengerInterface* iface) { + iface->set_message_handler_on_channel = + fl_mock_binary_messenger_set_message_handler_on_channel; + iface->send_response = fl_mock_binary_messenger_send_response; + iface->send_on_channel = fl_mock_binary_messenger_send_on_channel; + iface->send_on_channel_finish = + fl_mock_binary_messenger_send_on_channel_finish; + iface->resize_channel = fl_mock_binary_messenger_resize_channel; + iface->set_warns_on_channel_overflow = + fl_mock_binary_messenger_set_warns_on_channel_overflow; + iface->shutdown = fl_mock_binary_messenger_shutdown; +} + +static void fl_mock_binary_messenger_init(FlMockBinaryMessenger* self) { + self->handlers = + g_hash_table_new_full(g_str_hash, g_str_equal, g_free, + reinterpret_cast(handler_free)); + + self->mock_channels = g_hash_table_new_full( + g_str_hash, g_str_equal, g_free, + reinterpret_cast(mock_channel_free)); + self->mock_message_channels = g_hash_table_new_full( + g_str_hash, g_str_equal, g_free, + reinterpret_cast(mock_message_channel_free)); + self->mock_method_channels = g_hash_table_new_full( + g_str_hash, g_str_equal, g_free, + reinterpret_cast(mock_method_channel_free)); + self->mock_event_channels = g_hash_table_new_full( + g_str_hash, g_str_equal, g_free, + reinterpret_cast(mock_event_channel_free)); + self->mock_error_channels = g_hash_table_new_full( + g_str_hash, g_str_equal, g_free, + reinterpret_cast(mock_error_channel_free)); +} + +FlMockBinaryMessenger* fl_mock_binary_messenger_new() { + FlMockBinaryMessenger* self = FL_MOCK_BINARY_MESSENGER( + g_object_new(fl_mock_binary_messenger_get_type(), nullptr)); + return self; +} + +gboolean fl_mock_binary_messenger_has_handler(FlMockBinaryMessenger* self, + const gchar* channel) { + g_return_val_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self), FALSE); + return g_hash_table_lookup(self->handlers, channel) != nullptr; +} + +void fl_mock_binary_messenger_set_channel( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMockBinaryMessengerChannelHandler handler, + gpointer user_data) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + + g_hash_table_insert(self->mock_channels, g_strdup(channel), + mock_channel_new(handler, user_data)); +} + +void fl_mock_binary_messenger_set_message_channel( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMessageCodec* codec, + FlMockBinaryMessengerMessageChannelHandler handler, + gpointer user_data) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + + g_hash_table_insert(self->mock_message_channels, g_strdup(channel), + mock_message_channel_new(handler, codec, user_data)); +} + +void fl_mock_binary_messenger_set_standard_message_channel( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMockBinaryMessengerMessageChannelHandler handler, + gpointer user_data) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + + g_autoptr(FlStandardMessageCodec) codec = fl_standard_message_codec_new(); + return fl_mock_binary_messenger_set_message_channel( + self, channel, FL_MESSAGE_CODEC(codec), handler, user_data); +} + +void fl_mock_binary_messenger_set_string_message_channel( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMockBinaryMessengerMessageChannelHandler handler, + gpointer user_data) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + + g_autoptr(FlStringCodec) codec = fl_string_codec_new(); + return fl_mock_binary_messenger_set_message_channel( + self, channel, FL_MESSAGE_CODEC(codec), handler, user_data); +} + +void fl_mock_binary_messenger_set_json_message_channel( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMockBinaryMessengerMessageChannelHandler handler, + gpointer user_data) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + + g_autoptr(FlJsonMessageCodec) codec = fl_json_message_codec_new(); + return fl_mock_binary_messenger_set_message_channel( + self, channel, FL_MESSAGE_CODEC(codec), handler, user_data); +} + +void fl_mock_binary_messenger_message_channel_respond( + FlMockBinaryMessenger* self, + GTask* task, + FlMessageCodec* codec, + FlValue* value) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + g_autoptr(GError) error = nullptr; + g_autoptr(GBytes) response = + fl_message_codec_encode_message(codec, value, &error); + if (response == nullptr) { + g_warning("Failed to encode message: %s", error->message); + return; + } + + g_task_return_pointer(task, g_bytes_ref(response), + reinterpret_cast(g_bytes_unref)); +} + +void fl_mock_binary_messenger_standard_message_channel_respond( + FlMockBinaryMessenger* self, + GTask* task, + FlValue* value) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + + g_autoptr(FlStandardMessageCodec) codec = fl_standard_message_codec_new(); + fl_mock_binary_messenger_message_channel_respond( + self, task, FL_MESSAGE_CODEC(codec), value); +} + +void fl_mock_binary_messenger_string_message_channel_respond( + FlMockBinaryMessenger* self, + GTask* task, + FlValue* value) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + + g_autoptr(FlStringCodec) codec = fl_string_codec_new(); + fl_mock_binary_messenger_message_channel_respond( + self, task, FL_MESSAGE_CODEC(codec), value); +} + +void fl_mock_binary_messenger_json_message_channel_respond( + FlMockBinaryMessenger* self, + GTask* task, + FlValue* value) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + + g_autoptr(FlJsonMessageCodec) codec = fl_json_message_codec_new(); + fl_mock_binary_messenger_message_channel_respond( + self, task, FL_MESSAGE_CODEC(codec), value); +} + +void fl_mock_binary_messenger_set_method_channel( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMethodCodec* codec, + FlMockBinaryMessengerMethodChannelHandler handler, + gpointer user_data) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + g_hash_table_insert(self->mock_method_channels, g_strdup(channel), + mock_method_channel_new(handler, codec, user_data)); +} + +void fl_mock_binary_messenger_set_standard_method_channel( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMockBinaryMessengerMethodChannelHandler handler, + gpointer user_data) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); + fl_mock_binary_messenger_set_method_channel( + self, channel, FL_METHOD_CODEC(codec), handler, user_data); +} + +void fl_mock_binary_messenger_set_json_method_channel( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMockBinaryMessengerMethodChannelHandler handler, + gpointer user_data) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + + g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); + fl_mock_binary_messenger_set_method_channel( + self, channel, FL_METHOD_CODEC(codec), handler, user_data); +} + +void fl_mock_binary_messenger_method_channel_respond( + FlMockBinaryMessenger* self, + GTask* task, + FlMethodCodec* codec, + FlMethodResponse* response) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + + g_autoptr(GError) error = nullptr; + g_autoptr(GBytes) message = + fl_method_codec_encode_response(codec, response, &error); + if (message == nullptr) { + g_warning("Failed to encode method response: %s", error->message); + return; + } + + g_task_return_pointer(task, g_bytes_ref(message), + reinterpret_cast(g_bytes_unref)); +} + +void fl_mock_binary_messenger_standard_method_channel_respond( + FlMockBinaryMessenger* self, + GTask* task, + FlMethodResponse* response) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + + g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); + fl_mock_binary_messenger_method_channel_respond( + self, task, FL_METHOD_CODEC(codec), response); +} + +void fl_mock_binary_messenger_json_method_channel_respond( + FlMockBinaryMessenger* self, + GTask* task, + FlMethodResponse* response) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + + g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); + fl_mock_binary_messenger_method_channel_respond( + self, task, FL_METHOD_CODEC(codec), response); +} + +void fl_mock_binary_messenger_set_event_channel( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMethodCodec* codec, + FlMockBinaryMessengerEventChannelHandler handler, + FlMockBinaryMessengerEventChannelErrorHandler error_handler, + gpointer user_data) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + + g_hash_table_insert( + self->mock_event_channels, g_strdup(channel), + mock_event_channel_new(handler, error_handler, codec, user_data)); +} + +void fl_mock_binary_messenger_set_standard_event_channel( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMockBinaryMessengerEventChannelHandler handler, + FlMockBinaryMessengerEventChannelErrorHandler error_handler, + gpointer user_data) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); + fl_mock_binary_messenger_set_event_channel( + self, channel, FL_METHOD_CODEC(codec), handler, error_handler, user_data); +} + +void fl_mock_binary_messenger_set_json_event_channel( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMockBinaryMessengerEventChannelHandler handler, + FlMockBinaryMessengerEventChannelErrorHandler error_handler, + gpointer user_data) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); + fl_mock_binary_messenger_set_event_channel( + self, channel, FL_METHOD_CODEC(codec), handler, error_handler, user_data); +} + +void fl_mock_binary_messenger_set_error_channel(FlMockBinaryMessenger* self, + const gchar* channel, + gint code, + const gchar* message) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + + g_hash_table_insert(self->mock_error_channels, g_strdup(channel), + mock_error_channel_new(code, message)); +} + +void fl_mock_binary_messenger_send(FlMockBinaryMessenger* self, + const gchar* channel, + GBytes* message, + FlMockBinaryMessengerCallback callback, + gpointer user_data) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + + Handler* handler = + static_cast(g_hash_table_lookup(self->handlers, channel)); + if (handler == nullptr) { + return; + } + + handler->callback( + FL_BINARY_MESSENGER(self), channel, message, + FL_BINARY_MESSENGER_RESPONSE_HANDLE( + fl_mock_binary_messenger_response_handle_new(callback, user_data)), + handler->user_data); +} + +typedef struct { + FlMessageCodec* codec; + FlMockBinaryMessengerMessageCallback callback; + gpointer user_data; +} SendMessageData; + +static SendMessageData* send_message_data_new( + FlMessageCodec* codec, + FlMockBinaryMessengerMessageCallback callback, + gpointer user_data) { + SendMessageData* data = g_new0(SendMessageData, 1); + data->codec = FL_MESSAGE_CODEC(g_object_ref(codec)); + data->callback = callback; + data->user_data = user_data; + return data; +} + +static void send_message_data_free(SendMessageData* data) { + g_object_unref(data->codec); + free(data); +} + +G_DEFINE_AUTOPTR_CLEANUP_FUNC(SendMessageData, send_message_data_free) + +static void send_message_cb(FlMockBinaryMessenger* self, + GBytes* response, + gpointer user_data) { + g_autoptr(SendMessageData) data = static_cast(user_data); + + g_autoptr(GError) error = nullptr; + g_autoptr(FlValue) response_value = + fl_message_codec_decode_message(data->codec, response, &error); + if (response_value == nullptr) { + g_warning("Failed to decode message response: %s", error->message); + return; + } + + data->callback(self, response_value, data->user_data); +} + +void fl_mock_binary_messenger_send_message( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMessageCodec* codec, + FlValue* message, + FlMockBinaryMessengerMessageCallback callback, + gpointer user_data) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + + g_autoptr(GError) error = nullptr; + g_autoptr(GBytes) encoded_message = + fl_message_codec_encode_message(codec, message, &error); + if (encoded_message == nullptr) { + g_warning("Failed to encode message: %s", error->message); + return; + } + + fl_mock_binary_messenger_send( + self, channel, encoded_message, send_message_cb, + send_message_data_new(codec, callback, user_data)); +} + +void fl_mock_binary_messenger_send_standard_message( + FlMockBinaryMessenger* self, + const gchar* channel, + FlValue* message, + FlMockBinaryMessengerMessageCallback callback, + gpointer user_data) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + g_autoptr(FlStandardMessageCodec) codec = fl_standard_message_codec_new(); + fl_mock_binary_messenger_send_message(self, channel, FL_MESSAGE_CODEC(codec), + message, callback, user_data); +} + +void fl_mock_binary_messenger_send_json_message( + FlMockBinaryMessenger* self, + const gchar* channel, + FlValue* message, + FlMockBinaryMessengerMessageCallback callback, + gpointer user_data) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + g_autoptr(FlJsonMessageCodec) codec = fl_json_message_codec_new(); + fl_mock_binary_messenger_send_message(self, channel, FL_MESSAGE_CODEC(codec), + message, callback, user_data); +} + +typedef struct { + FlMethodCodec* codec; + FlMockBinaryMessengerMethodCallback callback; + gpointer user_data; +} InvokeMethodData; + +static InvokeMethodData* invoke_method_data_new( + FlMethodCodec* codec, + FlMockBinaryMessengerMethodCallback callback, + gpointer user_data) { + InvokeMethodData* data = g_new0(InvokeMethodData, 1); + data->codec = FL_METHOD_CODEC(g_object_ref(codec)); + data->callback = callback; + data->user_data = user_data; + return data; +} + +static void invoke_method_data_free(InvokeMethodData* data) { + g_object_unref(data->codec); + free(data); +} + +G_DEFINE_AUTOPTR_CLEANUP_FUNC(InvokeMethodData, invoke_method_data_free) + +static void invoke_method_cb(FlMockBinaryMessenger* self, + GBytes* response, + gpointer user_data) { + g_autoptr(InvokeMethodData) data = static_cast(user_data); + + g_autoptr(GError) error = nullptr; + g_autoptr(FlMethodResponse) method_response = + fl_method_codec_decode_response(data->codec, response, &error); + if (method_response == nullptr) { + g_warning("Failed to decode method response: %s", error->message); + return; + } + + data->callback(self, method_response, data->user_data); +} + +void fl_mock_binary_messenger_invoke_method( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMethodCodec* codec, + const char* name, + FlValue* args, + FlMockBinaryMessengerMethodCallback callback, + gpointer user_data) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + + g_autoptr(GError) error = nullptr; + g_autoptr(GBytes) message = + fl_method_codec_encode_method_call(codec, name, args, &error); + if (message == nullptr) { + g_warning("Failed to encode method call: %s", error->message); + return; + } + + fl_mock_binary_messenger_send( + self, channel, message, invoke_method_cb, + invoke_method_data_new(codec, callback, user_data)); +} + +void fl_mock_binary_messenger_invoke_standard_method( + FlMockBinaryMessenger* self, + const gchar* channel, + const char* name, + FlValue* args, + FlMockBinaryMessengerMethodCallback callback, + gpointer user_data) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); + fl_mock_binary_messenger_invoke_method(self, channel, FL_METHOD_CODEC(codec), + name, args, callback, user_data); +} + +void fl_mock_binary_messenger_invoke_json_method( + FlMockBinaryMessenger* self, + const gchar* channel, + const char* name, + FlValue* args, + FlMockBinaryMessengerMethodCallback callback, + gpointer user_data) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(self)); + g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); + fl_mock_binary_messenger_invoke_method(self, channel, FL_METHOD_CODEC(codec), + name, args, callback, user_data); +} diff --git a/flutter/engine/src/flutter/shell/platform/linux/testing/fl_mock_binary_messenger.h b/flutter/engine/src/flutter/shell/platform/linux/testing/fl_mock_binary_messenger.h new file mode 100644 index 0000000000000000000000000000000000000000..43a4f27f1c54d070178e8a43a9ef9ece8e5e7034 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/testing/fl_mock_binary_messenger.h @@ -0,0 +1,224 @@ +// 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_SHELL_PLATFORM_LINUX_TESTING_FL_MOCK_BINARY_MESSENGER_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_TESTING_FL_MOCK_BINARY_MESSENGER_H_ + +#include + +#include "flutter/shell/platform/linux/public/flutter_linux/fl_message_codec.h" +#include "flutter/shell/platform/linux/public/flutter_linux/fl_method_codec.h" +#include "flutter/shell/platform/linux/public/flutter_linux/fl_value.h" + +G_BEGIN_DECLS + +G_DECLARE_FINAL_TYPE(FlMockBinaryMessenger, + fl_mock_binary_messenger, + FL, + MOCK_BINARY_MESSENGER, + GObject) + +typedef GBytes* (*FlMockBinaryMessengerChannelHandler)( + FlMockBinaryMessenger* messenger, + GBytes* message, + gpointer user_data); + +typedef FlValue* (*FlMockBinaryMessengerMessageChannelHandler)( + FlMockBinaryMessenger* messenger, + GTask* task, + FlValue* message, + gpointer user_data); + +typedef FlMethodResponse* (*FlMockBinaryMessengerMethodChannelHandler)( + FlMockBinaryMessenger* messenger, + GTask* task, + const gchar* name, + FlValue* args, + gpointer user_data); + +typedef void (*FlMockBinaryMessengerEventChannelHandler)( + FlMockBinaryMessenger* messenger, + FlValue* event, + gpointer user_data); + +typedef void (*FlMockBinaryMessengerEventChannelErrorHandler)( + FlMockBinaryMessenger* messenger, + const gchar* code, + const gchar* message, + FlValue* details, + gpointer user_data); + +typedef void (*FlMockBinaryMessengerCallback)(FlMockBinaryMessenger* messenger, + GBytes* response, + gpointer user_data); + +typedef void (*FlMockBinaryMessengerMessageCallback)( + FlMockBinaryMessenger* messenger, + FlValue* response, + gpointer user_data); + +typedef void (*FlMockBinaryMessengerMethodCallback)( + FlMockBinaryMessenger* messenger, + FlMethodResponse* response, + gpointer user_data); + +FlMockBinaryMessenger* fl_mock_binary_messenger_new(); + +gboolean fl_mock_binary_messenger_has_handler(FlMockBinaryMessenger* self, + const gchar* channel); + +void fl_mock_binary_messenger_set_channel( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMockBinaryMessengerChannelHandler handler, + gpointer user_data); + +void fl_mock_binary_messenger_set_message_channel( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMessageCodec* codec, + FlMockBinaryMessengerMessageChannelHandler handler, + gpointer user_data); + +void fl_mock_binary_messenger_set_standard_message_channel( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMockBinaryMessengerMessageChannelHandler handler, + gpointer user_data); + +void fl_mock_binary_messenger_set_string_message_channel( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMockBinaryMessengerMessageChannelHandler handler, + gpointer user_data); + +void fl_mock_binary_messenger_set_json_message_channel( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMockBinaryMessengerMessageChannelHandler handler, + gpointer user_data); + +void fl_mock_binary_messenger_message_channel_respond( + FlMockBinaryMessenger* self, + GTask* task, + FlMessageCodec* codec, + FlValue* value); + +void fl_mock_binary_messenger_standard_message_channel_respond( + FlMockBinaryMessenger* self, + GTask* task, + FlValue* value); + +void fl_mock_binary_messenger_string_message_channel_respond( + FlMockBinaryMessenger* self, + GTask* task, + FlValue* value); + +void fl_mock_binary_messenger_json_message_channel_respond( + FlMockBinaryMessenger* self, + GTask* task, + FlValue* value); + +void fl_mock_binary_messenger_set_method_channel( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMethodCodec* codec, + FlMockBinaryMessengerMethodChannelHandler handler, + gpointer user_data); + +void fl_mock_binary_messenger_set_standard_method_channel( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMockBinaryMessengerMethodChannelHandler handler, + gpointer user_data); + +void fl_mock_binary_messenger_set_json_method_channel( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMockBinaryMessengerMethodChannelHandler handler, + gpointer user_data); + +void fl_mock_binary_messenger_set_event_channel( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMethodCodec* codec, + FlMockBinaryMessengerEventChannelHandler handler, + FlMockBinaryMessengerEventChannelErrorHandler error_handler, + gpointer user_data); + +void fl_mock_binary_messenger_set_standard_event_channel( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMockBinaryMessengerEventChannelHandler handler, + FlMockBinaryMessengerEventChannelErrorHandler error_handler, + gpointer user_data); + +void fl_mock_binary_messenger_set_json_event_channel( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMockBinaryMessengerEventChannelHandler handler, + FlMockBinaryMessengerEventChannelErrorHandler error_handler, + gpointer user_data); + +void fl_mock_binary_messenger_set_error_channel(FlMockBinaryMessenger* self, + const gchar* channel, + gint code, + const gchar* message); + +void fl_mock_binary_messenger_send(FlMockBinaryMessenger* self, + const gchar* channel, + GBytes* message, + FlMockBinaryMessengerCallback callback, + gpointer user_data); + +void fl_mock_binary_messenger_send_message( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMessageCodec* codec, + FlValue* message, + FlMockBinaryMessengerMessageCallback callback, + gpointer user_data); + +void fl_mock_binary_messenger_send_standard_message( + FlMockBinaryMessenger* self, + const gchar* channel, + FlValue* message, + FlMockBinaryMessengerMessageCallback callback, + gpointer user_data); + +void fl_mock_binary_messenger_send_json_message( + FlMockBinaryMessenger* self, + const gchar* channel, + FlValue* message, + FlMockBinaryMessengerMessageCallback callback, + gpointer user_data); + +void fl_mock_binary_messenger_invoke_method( + FlMockBinaryMessenger* self, + const gchar* channel, + FlMethodCodec* codec, + const char* name, + FlValue* args, + FlMockBinaryMessengerMethodCallback callback, + gpointer user_data); + +void fl_mock_binary_messenger_invoke_standard_method( + FlMockBinaryMessenger* self, + const gchar* channel, + const char* name, + FlValue* args, + FlMockBinaryMessengerMethodCallback callback, + gpointer user_data); + +void fl_mock_binary_messenger_invoke_json_method( + FlMockBinaryMessenger* self, + const gchar* channel, + const char* name, + FlValue* args, + FlMockBinaryMessengerMethodCallback callback, + gpointer user_data); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_TESTING_FL_MOCK_BINARY_MESSENGER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/testing/fl_test.cc b/flutter/engine/src/flutter/shell/platform/linux/testing/fl_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..f7c0f1515b0e61cdc1336790dd526fb65c8bee30 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/testing/fl_test.cc @@ -0,0 +1,66 @@ +// 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 "gtest/gtest.h" + +#include "flutter/shell/platform/linux/testing/fl_test.h" + +#include "flutter/shell/platform/linux/fl_engine_private.h" +#include "flutter/shell/platform/linux/testing/mock_renderable.h" + +namespace { +class ImModuleEnv : public ::testing::Environment { + public: + void SetUp() override { + setenv("GTK_IM_MODULE", "gtk-im-context-simple", true); + } +}; + +testing::Environment* const kEnv = + testing::AddGlobalTestEnvironment(new ImModuleEnv); +} // namespace + +static uint8_t hex_digit_to_int(char value) { + if (value >= '0' && value <= '9') { + return value - '0'; + } else if (value >= 'a' && value <= 'f') { + return value - 'a' + 10; + } else if (value >= 'F' && value <= 'F') { + return value - 'A' + 10; + } else { + return 0; + } +} + +static uint8_t parse_hex8(const gchar* hex_string) { + if (hex_string[0] == '\0') { + return 0x00; + } + return hex_digit_to_int(hex_string[0]) << 4 | hex_digit_to_int(hex_string[1]); +} + +GBytes* hex_string_to_bytes(const gchar* hex_string) { + GByteArray* buffer = g_byte_array_new(); + for (int i = 0; hex_string[i] != '\0' && hex_string[i + 1] != '\0'; i += 2) { + uint8_t value = parse_hex8(hex_string + i); + g_byte_array_append(buffer, &value, 1); + } + return g_byte_array_free_to_bytes(buffer); +} + +gchar* bytes_to_hex_string(GBytes* bytes) { + GString* hex_string = g_string_new(""); + size_t data_length; + const uint8_t* data = + static_cast(g_bytes_get_data(bytes, &data_length)); + for (size_t i = 0; i < data_length; i++) { + g_string_append_printf(hex_string, "%02x", data[i]); + } + return g_string_free(hex_string, FALSE); +} + +void PrintTo(FlValue* v, std::ostream* os) { + g_autofree gchar* s = fl_value_to_string(v); + *os << s; +} diff --git a/flutter/engine/src/flutter/shell/platform/linux/testing/fl_test.h b/flutter/engine/src/flutter/shell/platform/linux/testing/fl_test.h new file mode 100644 index 0000000000000000000000000000000000000000..10925577fcc576b4bb64e87220715bd82c7c9bb1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/testing/fl_test.h @@ -0,0 +1,30 @@ +// 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_SHELL_PLATFORM_LINUX_TESTING_FL_TEST_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_TESTING_FL_TEST_H_ + +#include "flutter/shell/platform/linux/public/flutter_linux/fl_engine.h" +#include "flutter/shell/platform/linux/public/flutter_linux/fl_value.h" + +#include +#include +#include + +G_BEGIN_DECLS + +// Helper functions for the tests. This is not included in the shell library. + +// Helper function to convert a hexadecimal string (e.g. "01feab") into GBytes +GBytes* hex_string_to_bytes(const gchar* hex_string); + +// Helper function to convert GBytes into a hexadecimal string (e.g. "01feab") +gchar* bytes_to_hex_string(GBytes* bytes); + +// GTest printer for FlValue. +void PrintTo(FlValue* v, std::ostream* os); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_TESTING_FL_TEST_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/testing/fl_test_gtk_logs.cc b/flutter/engine/src/flutter/shell/platform/linux/testing/fl_test_gtk_logs.cc new file mode 100644 index 0000000000000000000000000000000000000000..d9f5fd2fb53a91482962d07f3e4f6c1b3db467d9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/testing/fl_test_gtk_logs.cc @@ -0,0 +1,55 @@ +// 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 "fl_test_gtk_logs.h" +#include "gtest/gtest.h" + +namespace flutter { +namespace testing { + +namespace { + +bool gtk_initialized = false; +GLogWriterFunc log_writer_cb = nullptr; +GLogLevelFlags fl_received_log_levels = static_cast(0x0); + +GLogWriterOutput log_writer(GLogLevelFlags log_level, + const GLogField* fields, + gsize n_fields, + gpointer user_data) { + fl_received_log_levels = + static_cast(log_level | fl_received_log_levels); + if (log_writer_cb == nullptr) { + return g_log_writer_default(log_level, fields, n_fields, user_data); + } + GLogWriterOutput result = + log_writer_cb(log_level, fields, n_fields, user_data); + if (result != G_LOG_WRITER_HANDLED) { + return g_log_writer_default(log_level, fields, n_fields, user_data); + } + return result; +} + +} // namespace + +void fl_ensure_gtk_init(GLogWriterFunc writer) { + if (!gtk_initialized) { + gtk_init(0, nullptr); + g_log_set_writer_func(log_writer, nullptr, nullptr); + gtk_initialized = true; + } + fl_reset_received_gtk_log_levels(); + log_writer_cb = writer; +} + +void fl_reset_received_gtk_log_levels() { + fl_received_log_levels = static_cast(0x0); +} + +GLogLevelFlags fl_get_received_gtk_log_levels() { + return fl_received_log_levels; +} + +} // namespace testing +} // namespace flutter \ No newline at end of file diff --git a/flutter/engine/src/flutter/shell/platform/linux/testing/fl_test_gtk_logs.h b/flutter/engine/src/flutter/shell/platform/linux/testing/fl_test_gtk_logs.h new file mode 100644 index 0000000000000000000000000000000000000000..29d0988758e3b0444d2dced792953a528af0dbf0 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/testing/fl_test_gtk_logs.h @@ -0,0 +1,49 @@ +// 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_SHELL_PLATFORM_LINUX_TESTING_FL_TEST_GTK_LOGS_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_TESTING_FL_TEST_GTK_LOGS_H_ + +#include + +namespace flutter { +namespace testing { + +/** + * Ensures that GTK has been initialized. If GTK has not been initialized, it + * will be initialized using `gtk_init()`. It will also set the GTK log writer + * function to monitor the log output, recording the log levels that have been + * received in a bitfield accessible via {@link fl_get_received_gtk_log_levels} + * + * To retrieve the bitfield of recorded log levels, use + * `fl_get_received_gtk_log_levels()`. + * + * @param[in] writer The custom log writer function to use. If `nullptr`, or it + * returns G_LOG_WRITER_UNHANDLED, the default log writer function will be + * called. + * + * @brief Ensures that GTK has been initialized and starts monitoring logs. + */ +void fl_ensure_gtk_init(GLogWriterFunc writer = nullptr); + +/** + * Resets the recorded GTK log levels to zero. + * + * @brief Resets the recorded log levels. + */ +void fl_reset_received_gtk_log_levels(); + +/** + * Returns a bitfield containing the GTK log levels that have been seen since + * the last time they were reset. + * + * @brief Returns the recorded log levels. + * + * @return A `GLogLevelFlags` bitfield representing the recorded log levels. + */ +GLogLevelFlags fl_get_received_gtk_log_levels(); + +} // namespace testing +} // namespace flutter +#endif // FLUTTER_SHELL_PLATFORM_LINUX_TESTING_FL_TEST_GTK_LOGS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/testing/gschemas/README.md b/flutter/engine/src/flutter/shell/platform/linux/testing/gschemas/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8897df6ca64c0ab963f203375fa008b3e68a9541 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/testing/gschemas/README.md @@ -0,0 +1,21 @@ +# gsettings-desktop-schemas + +This directory contains a few variants of +[gsettings-desktop-schemas](https://packages.ubuntu.com/search?keywords=gsettings-desktop-schemas) +with different schemas for testing purposes. + +- [`ubuntu-20.04.compiled`](https://packages.ubuntu.com/focal/gsettings-desktop-schemas) + +### Add or update schemas + +```bash +# download gsettings-desktop-schemas package +wget http://archive.ubuntu.com/ubuntu/pool/main/g/gsettings-desktop-schemas/gsettings-desktop-schemas_.deb + +# extract schema sources (/usr/share/glib-2.0/schemas/*.gschema.xml & .override) +ar x gsettings-desktop-schemas_.deb +tar xf data.tar.zst + +# compile schemas (/usr/share/glib-2.0/schemas/gschemas.compiled) +glib-compile-schemas --targetdir path/to/testing/gschemas usr/share/glib-2.0/schemas/ +``` diff --git a/flutter/engine/src/flutter/shell/platform/linux/testing/gschemas/ubuntu-20.04.compiled b/flutter/engine/src/flutter/shell/platform/linux/testing/gschemas/ubuntu-20.04.compiled new file mode 100644 index 0000000000000000000000000000000000000000..1ad3a51de999858d248e04fa85fec96208afa885 Binary files /dev/null and b/flutter/engine/src/flutter/shell/platform/linux/testing/gschemas/ubuntu-20.04.compiled differ diff --git a/flutter/engine/src/flutter/shell/platform/linux/testing/mock_engine.cc b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_engine.cc new file mode 100644 index 0000000000000000000000000000000000000000..c414ff14a261a5c67c256c3841a18137f644fc94 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_engine.cc @@ -0,0 +1,240 @@ +// 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. + +// This file is a historical legacy, predating the proc table API. It has been +// updated to continue to work with the proc table, but new tests should not +// rely on replacements set up here, but instead use test-local replacements +// for any functions relevant to that test. +// +// Over time existing tests should be migrated and this file should be removed. + +#include +#include +#include + +#include "flutter/shell/platform/embedder/embedder.h" +#include "flutter/shell/platform/linux/fl_method_codec_private.h" +#include "flutter/shell/platform/linux/public/flutter_linux/fl_json_message_codec.h" +#include "flutter/shell/platform/linux/public/flutter_linux/fl_method_response.h" +#include "flutter/shell/platform/linux/public/flutter_linux/fl_standard_method_codec.h" +#include "gtest/gtest.h" + +struct _FlutterEngine { + _FlutterEngine() {} +}; + +namespace { + +FlutterEngineResult FlutterEngineCreateAOTData( + const FlutterEngineAOTDataSource* source, + FlutterEngineAOTData* data_out) { + return kSuccess; +} + +FlutterEngineResult FlutterEngineCollectAOTData(FlutterEngineAOTData data) { + return kSuccess; +} + +FlutterEngineResult FlutterEngineInitialize(size_t version, + const FlutterRendererConfig* config, + const FlutterProjectArgs* args, + void* user_data, + FLUTTER_API_SYMBOL(FlutterEngine) * + engine_out) { + *engine_out = new _FlutterEngine(); + return kSuccess; +} + +FlutterEngineResult FlutterEngineRunInitialized( + FLUTTER_API_SYMBOL(FlutterEngine) engine) { + return kSuccess; +} + +FlutterEngineResult FlutterEngineRun(size_t version, + const FlutterRendererConfig* config, + const FlutterProjectArgs* args, + void* user_data, + FLUTTER_API_SYMBOL(FlutterEngine) * + engine_out) { + return kSuccess; +} + +FlutterEngineResult FlutterEngineShutdown(FLUTTER_API_SYMBOL(FlutterEngine) + engine) { + delete engine; + return kSuccess; +} + +FlutterEngineResult FlutterEngineDeinitialize(FLUTTER_API_SYMBOL(FlutterEngine) + engine) { + return kSuccess; +} + +FlutterEngineResult FlutterEngineSendWindowMetricsEvent( + FLUTTER_API_SYMBOL(FlutterEngine) engine, + const FlutterWindowMetricsEvent* event) { + return kSuccess; +} + +FlutterEngineResult FlutterEngineSendPointerEvent( + FLUTTER_API_SYMBOL(FlutterEngine) engine, + const FlutterPointerEvent* events, + size_t events_count) { + return kSuccess; +} + +FlutterEngineResult FlutterEngineSendKeyEvent(FLUTTER_API_SYMBOL(FlutterEngine) + engine, + const FlutterKeyEvent* event, + FlutterKeyEventCallback callback, + void* user_data) { + return kSuccess; +} + +FLUTTER_EXPORT +FlutterEngineResult FlutterEngineSendPlatformMessage( + FLUTTER_API_SYMBOL(FlutterEngine) engine, + const FlutterPlatformMessage* message) { + return kSuccess; +} + +FlutterEngineResult FlutterPlatformMessageCreateResponseHandle( + FLUTTER_API_SYMBOL(FlutterEngine) engine, + FlutterDataCallback data_callback, + void* user_data, + FlutterPlatformMessageResponseHandle** response_out) { + return kSuccess; +} + +FlutterEngineResult FlutterPlatformMessageReleaseResponseHandle( + FLUTTER_API_SYMBOL(FlutterEngine) engine, + FlutterPlatformMessageResponseHandle* response) { + return kSuccess; +} + +FlutterEngineResult FlutterEngineSendPlatformMessageResponse( + FLUTTER_API_SYMBOL(FlutterEngine) engine, + const FlutterPlatformMessageResponseHandle* handle, + const uint8_t* data, + size_t data_length) { + return kSuccess; +} + +FlutterEngineResult FlutterEngineRunTask(FLUTTER_API_SYMBOL(FlutterEngine) + engine, + const FlutterTask* task) { + return kSuccess; +} + +bool FlutterEngineRunsAOTCompiledDartCode() { + return false; +} + +FlutterEngineResult FlutterEngineUpdateLocales(FLUTTER_API_SYMBOL(FlutterEngine) + engine, + const FlutterLocale** locales, + size_t locales_count) { + return kSuccess; +} + +FlutterEngineResult FlutterEngineUpdateSemanticsEnabled( + FLUTTER_API_SYMBOL(FlutterEngine) engine, + bool enabled) { + return kSuccess; +} + +FlutterEngineResult FlutterEngineUpdateAccessibilityFeatures( + FLUTTER_API_SYMBOL(FlutterEngine) engine, + FlutterAccessibilityFeature features) { + return kSuccess; +} + +FlutterEngineResult FlutterEngineSendSemanticsAction( + FLUTTER_API_SYMBOL(FlutterEngine) engine, + const FlutterSendSemanticsActionInfo* info) { + return kSuccess; +} + +FlutterEngineResult FlutterEngineRegisterExternalTexture( + FLUTTER_API_SYMBOL(FlutterEngine) engine, + int64_t texture_identifier) { + return kSuccess; +} + +FlutterEngineResult FlutterEngineMarkExternalTextureFrameAvailable( + FLUTTER_API_SYMBOL(FlutterEngine) engine, + int64_t texture_identifier) { + return kSuccess; +} + +FlutterEngineResult FlutterEngineUnregisterExternalTexture( + FLUTTER_API_SYMBOL(FlutterEngine) engine, + int64_t texture_identifier) { + return kSuccess; +} + +FlutterEngineResult FlutterEngineNotifyDisplayUpdate( + FLUTTER_API_SYMBOL(FlutterEngine) engine, + FlutterEngineDisplaysUpdateType update_type, + const FlutterEngineDisplay* displays, + size_t display_count) { + return kSuccess; +} + +FlutterEngineResult FlutterEngineAddView(FLUTTER_API_SYMBOL(FlutterEngine) + engine, + const FlutterAddViewInfo* info) { + return kSuccess; +} + +FlutterEngineResult FlutterEngineRemoveView(FLUTTER_API_SYMBOL(FlutterEngine) + engine, + const FlutterRemoveViewInfo* info) { + return kSuccess; +} + +} // namespace + +FlutterEngineResult FlutterEngineGetProcAddresses( + FlutterEngineProcTable* table) { + if (!table) { + return kInvalidArguments; + } + + FlutterEngineProcTable empty_table = {}; + *table = empty_table; + + table->CreateAOTData = &FlutterEngineCreateAOTData; + table->CollectAOTData = &FlutterEngineCollectAOTData; + table->Run = &FlutterEngineRun; + table->Shutdown = &FlutterEngineShutdown; + table->Initialize = &FlutterEngineInitialize; + table->Deinitialize = &FlutterEngineDeinitialize; + table->RunInitialized = &FlutterEngineRunInitialized; + table->SendWindowMetricsEvent = &FlutterEngineSendWindowMetricsEvent; + table->SendPointerEvent = &FlutterEngineSendPointerEvent; + table->SendKeyEvent = &FlutterEngineSendKeyEvent; + table->SendPlatformMessage = &FlutterEngineSendPlatformMessage; + table->PlatformMessageCreateResponseHandle = + &FlutterPlatformMessageCreateResponseHandle; + table->PlatformMessageReleaseResponseHandle = + &FlutterPlatformMessageReleaseResponseHandle; + table->SendPlatformMessageResponse = + &FlutterEngineSendPlatformMessageResponse; + table->RunTask = &FlutterEngineRunTask; + table->UpdateLocales = &FlutterEngineUpdateLocales; + table->UpdateSemanticsEnabled = &FlutterEngineUpdateSemanticsEnabled; + table->SendSemanticsAction = &FlutterEngineSendSemanticsAction; + table->RunsAOTCompiledDartCode = &FlutterEngineRunsAOTCompiledDartCode; + table->RegisterExternalTexture = &FlutterEngineRegisterExternalTexture; + table->MarkExternalTextureFrameAvailable = + &FlutterEngineMarkExternalTextureFrameAvailable; + table->UnregisterExternalTexture = &FlutterEngineUnregisterExternalTexture; + table->UpdateAccessibilityFeatures = + &FlutterEngineUpdateAccessibilityFeatures; + table->NotifyDisplayUpdate = &FlutterEngineNotifyDisplayUpdate; + table->AddView = &FlutterEngineAddView; + table->RemoveView = &FlutterEngineRemoveView; + return kSuccess; +} diff --git a/flutter/engine/src/flutter/shell/platform/linux/testing/mock_epoxy.cc b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_epoxy.cc new file mode 100644 index 0000000000000000000000000000000000000000..d453b983fd0ba2af955e9cdd4c6410755188ad25 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_epoxy.cc @@ -0,0 +1,684 @@ +// 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/shell/platform/linux/testing/mock_epoxy.h" +#include "flutter/fml/logging.h" + +using namespace flutter::testing; + +typedef struct { + EGLint config_id; + EGLint buffer_size; + EGLint color_buffer_type; + EGLint transparent_type; + EGLint level; + EGLint red_size; + EGLint green_size; + EGLint blue_size; + EGLint alpha_size; + EGLint depth_size; + EGLint stencil_size; + EGLint samples; + EGLint sample_buffers; + EGLint native_visual_id; + EGLint native_visual_type; + EGLint native_renderable; + EGLint config_caveat; + EGLint bind_to_texture_rgb; + EGLint bind_to_texture_rgba; + EGLint renderable_type; + EGLint conformant; + EGLint surface_type; + EGLint max_pbuffer_width; + EGLint max_pbuffer_height; + EGLint max_pbuffer_pixels; + EGLint min_swap_interval; + EGLint max_swap_interval; +} MockConfig; + +typedef struct { +} MockDisplay; + +typedef struct { +} MockContext; + +typedef struct { +} MockSurface; + +static MockEpoxy* mock = nullptr; +static bool display_initialized = false; +static MockDisplay mock_display; +static MockConfig mock_config; +static MockContext mock_context; +static MockSurface mock_surface; + +static EGLint mock_error = EGL_SUCCESS; + +MockEpoxy::MockEpoxy() { + mock = this; +} + +MockEpoxy::~MockEpoxy() { + if (mock == this) { + mock = nullptr; + } +} + +static bool check_display(EGLDisplay dpy) { + if (dpy == nullptr) { + mock_error = EGL_BAD_DISPLAY; + return false; + } + + return true; +} + +static bool check_initialized(EGLDisplay dpy) { + if (!display_initialized) { + mock_error = EGL_NOT_INITIALIZED; + return false; + } + + return true; +} + +static bool check_config(EGLConfig config) { + if (config == nullptr) { + mock_error = EGL_BAD_CONFIG; + return false; + } + + return true; +} + +static EGLBoolean bool_success() { + mock_error = EGL_SUCCESS; + return EGL_TRUE; +} + +static EGLBoolean bool_failure(EGLint error) { + mock_error = error; + return EGL_FALSE; +} + +EGLBoolean _eglBindAPI(EGLenum api) { + return bool_success(); +} + +EGLBoolean _eglChooseConfig(EGLDisplay dpy, + const EGLint* attrib_list, + EGLConfig* configs, + EGLint config_size, + EGLint* num_config) { + if (!check_display(dpy) || !check_initialized(dpy)) { + return EGL_FALSE; + } + + if (configs == nullptr) { + if (num_config != nullptr) { + *num_config = 1; + } + return bool_success(); + } + + EGLint n_returned = 0; + if (config_size >= 1) { + configs[0] = &mock_config; + n_returned++; + } + + if (num_config != nullptr) { + *num_config = n_returned; + } + + return bool_success(); +} + +EGLContext _eglCreateContext(EGLDisplay dpy, + EGLConfig config, + EGLContext share_context, + const EGLint* attrib_list) { + if (!check_display(dpy) || !check_initialized(dpy) || !check_config(config)) { + return EGL_NO_CONTEXT; + } + + mock_error = EGL_SUCCESS; + return &mock_context; +} + +EGLSurface _eglCreatePbufferSurface(EGLDisplay dpy, + EGLConfig config, + const EGLint* attrib_list) { + if (!check_display(dpy) || !check_initialized(dpy) || !check_config(config)) { + return EGL_NO_SURFACE; + } + + mock_error = EGL_SUCCESS; + return &mock_surface; +} + +EGLSurface _eglCreateWindowSurface(EGLDisplay dpy, + EGLConfig config, + EGLNativeWindowType win, + const EGLint* attrib_list) { + if (!check_display(dpy) || !check_initialized(dpy) || !check_config(config)) { + return EGL_NO_SURFACE; + } + + mock_error = EGL_SUCCESS; + return &mock_surface; +} + +EGLBoolean _eglGetConfigAttrib(EGLDisplay dpy, + EGLConfig config, + EGLint attribute, + EGLint* value) { + if (!check_display(dpy) || !check_initialized(dpy) || !check_config(config)) { + return EGL_FALSE; + } + + MockConfig* c = static_cast(config); + switch (attribute) { + case EGL_CONFIG_ID: + *value = c->config_id; + return bool_success(); + case EGL_BUFFER_SIZE: + *value = c->buffer_size; + return bool_success(); + case EGL_COLOR_BUFFER_TYPE: + *value = c->color_buffer_type; + return bool_success(); + case EGL_TRANSPARENT_TYPE: + *value = c->transparent_type; + return bool_success(); + case EGL_LEVEL: + *value = c->level; + return bool_success(); + case EGL_RED_SIZE: + *value = c->red_size; + return bool_success(); + case EGL_GREEN_SIZE: + *value = c->green_size; + return bool_success(); + case EGL_BLUE_SIZE: + *value = c->blue_size; + return bool_success(); + case EGL_ALPHA_SIZE: + *value = c->alpha_size; + return bool_success(); + case EGL_DEPTH_SIZE: + *value = c->depth_size; + return bool_success(); + case EGL_STENCIL_SIZE: + *value = c->stencil_size; + return bool_success(); + case EGL_SAMPLES: + *value = c->samples; + return bool_success(); + case EGL_SAMPLE_BUFFERS: + *value = c->sample_buffers; + return bool_success(); + case EGL_NATIVE_VISUAL_ID: + *value = c->native_visual_id; + return bool_success(); + case EGL_NATIVE_VISUAL_TYPE: + *value = c->native_visual_type; + return bool_success(); + case EGL_NATIVE_RENDERABLE: + *value = c->native_renderable; + return bool_success(); + case EGL_CONFIG_CAVEAT: + *value = c->config_caveat; + return bool_success(); + case EGL_BIND_TO_TEXTURE_RGB: + *value = c->bind_to_texture_rgb; + return bool_success(); + case EGL_BIND_TO_TEXTURE_RGBA: + *value = c->bind_to_texture_rgba; + return bool_success(); + case EGL_RENDERABLE_TYPE: + *value = c->renderable_type; + return bool_success(); + case EGL_CONFORMANT: + *value = c->conformant; + return bool_success(); + case EGL_SURFACE_TYPE: + *value = c->surface_type; + return bool_success(); + case EGL_MAX_PBUFFER_WIDTH: + *value = c->max_pbuffer_width; + return bool_success(); + case EGL_MAX_PBUFFER_HEIGHT: + *value = c->max_pbuffer_height; + return bool_success(); + case EGL_MAX_PBUFFER_PIXELS: + *value = c->max_pbuffer_pixels; + return bool_success(); + case EGL_MIN_SWAP_INTERVAL: + *value = c->min_swap_interval; + return bool_success(); + case EGL_MAX_SWAP_INTERVAL: + *value = c->max_swap_interval; + return bool_success(); + default: + return bool_failure(EGL_BAD_ATTRIBUTE); + } +} + +EGLDisplay _eglGetDisplay(EGLNativeDisplayType display_id) { + return &mock_display; +} + +EGLint _eglGetError() { + EGLint error = mock_error; + mock_error = EGL_SUCCESS; + return error; +} + +void (*_eglGetProcAddress(const char* procname))(void) { + mock_error = EGL_SUCCESS; + return nullptr; +} + +EGLBoolean _eglInitialize(EGLDisplay dpy, EGLint* major, EGLint* minor) { + if (!check_display(dpy)) { + return EGL_FALSE; + } + + if (!display_initialized) { + mock_config.config_id = 1; + mock_config.buffer_size = 32; + mock_config.color_buffer_type = EGL_RGB_BUFFER; + mock_config.transparent_type = EGL_NONE; + mock_config.level = 1; + mock_config.red_size = 8; + mock_config.green_size = 8; + mock_config.blue_size = 8; + mock_config.alpha_size = 0; + mock_config.depth_size = 0; + mock_config.stencil_size = 0; + mock_config.samples = 0; + mock_config.sample_buffers = 0; + mock_config.native_visual_id = 1; + mock_config.native_visual_type = 0; + mock_config.native_renderable = EGL_TRUE; + mock_config.config_caveat = EGL_NONE; + mock_config.bind_to_texture_rgb = EGL_TRUE; + mock_config.bind_to_texture_rgba = EGL_FALSE; + mock_config.renderable_type = EGL_OPENGL_ES2_BIT; + mock_config.conformant = EGL_OPENGL_ES2_BIT; + mock_config.surface_type = EGL_WINDOW_BIT | EGL_PBUFFER_BIT; + mock_config.max_pbuffer_width = 1024; + mock_config.max_pbuffer_height = 1024; + mock_config.max_pbuffer_pixels = 1024 * 1024; + mock_config.min_swap_interval = 0; + mock_config.max_swap_interval = 1000; + display_initialized = true; + } + + if (major != nullptr) { + *major = 1; + } + if (minor != nullptr) { + *minor = 5; + } + + return bool_success(); +} + +EGLBoolean _eglMakeCurrent(EGLDisplay dpy, + EGLSurface draw, + EGLSurface read, + EGLContext ctx) { + if (!check_display(dpy) || !check_initialized(dpy)) { + return EGL_FALSE; + } + + return bool_success(); +} +EGLBoolean _eglQueryContext(EGLDisplay display, + EGLContext context, + EGLint attribute, + EGLint* value) { + if (attribute == EGL_CONTEXT_CLIENT_TYPE) { + *value = EGL_OPENGL_API; + return EGL_TRUE; + } + return EGL_FALSE; +} + +EGLBoolean _eglSwapBuffers(EGLDisplay dpy, EGLSurface surface) { + if (!check_display(dpy) || !check_initialized(dpy)) { + return EGL_FALSE; + } + + return bool_success(); +} + +static GLuint bound_texture_2d; + +static std::map framebuffer_renderbuffers; + +void _glAttachShader(GLuint program, GLuint shader) {} + +static void _glBindFramebuffer(GLenum target, GLuint framebuffer) {} + +static void _glBindRenderbuffer(GLenum target, GLuint framebuffer) {} + +static void _glBindTexture(GLenum target, GLuint texture) { + if (target == GL_TEXTURE_2D) { + bound_texture_2d = texture; + } +} + +static void _glBlitFramebuffer(GLint srcX0, + GLint srcY0, + GLint srcX1, + GLint srcY1, + GLint dstX0, + GLint dstY0, + GLint dstX1, + GLint dstY1, + GLbitfield mask, + GLenum filter) { + mock->glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, + dstY1, mask, filter); +} + +GLuint _glCreateProgram() { + return 0; +} + +void _glCompileShader(GLuint shader) {} + +void _glClearColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a) { + mock->glClearColor(r, g, b, a); +} + +GLuint _glCreateShader(GLenum shaderType) { + return 0; +} + +void _glDeleteFramebuffers(GLsizei n, const GLuint* framebuffers) {} + +void _glDeleteShader(GLuint shader) {} + +void _glDeleteTextures(GLsizei n, const GLuint* textures) {} + +static void _glFramebufferRenderbuffer(GLenum target, + GLenum attachment, + GLenum renderbuffertarget, + GLuint renderbuffer) { + framebuffer_renderbuffers[attachment] = renderbuffer; +} + +static void _glFramebufferTexture2D(GLenum target, + GLenum attachment, + GLenum textarget, + GLuint texture, + GLint level) {} + +static void _glGenTextures(GLsizei n, GLuint* textures) { + for (GLsizei i = 0; i < n; i++) { + textures[i] = 0; + } +} + +static void _glGenFramebuffers(GLsizei n, GLuint* framebuffers) { + for (GLsizei i = 0; i < n; i++) { + framebuffers[i] = 0; + } +} + +static void _glGenRenderbuffers(GLsizei n, GLuint* renderbuffers) { + for (GLsizei i = 0; i < n; i++) { + renderbuffers[i] = 0; + } +} + +static void _glGetFramebufferAttachmentParameteriv(GLenum target, + GLenum attachment, + GLenum pname, + GLint* params) { + if (pname == GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE) { + auto it = framebuffer_renderbuffers.find(attachment); + *params = + (it != framebuffer_renderbuffers.end()) ? GL_RENDERBUFFER : GL_NONE; + } else if (pname == GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME) { + auto it = framebuffer_renderbuffers.find(attachment); + *params = (it != framebuffer_renderbuffers.end()) ? it->second : 0; + } +} + +static void _glGetIntegerv(GLenum pname, GLint* data) { + if (pname == GL_TEXTURE_BINDING_2D) { + *data = bound_texture_2d; + } +} + +static void _glGetProgramiv(GLuint program, GLenum pname, GLint* params) { + if (pname == GL_LINK_STATUS) { + *params = GL_TRUE; + } +} + +static void _glGetProgramInfoLog(GLuint program, + GLsizei maxLength, + GLsizei* length, + GLchar* infoLog) {} + +static void _glGetShaderiv(GLuint shader, GLenum pname, GLint* params) { + if (pname == GL_COMPILE_STATUS) { + *params = GL_TRUE; + } +} + +static void _glGetShaderInfoLog(GLuint shader, + GLsizei maxLength, + GLsizei* length, + GLchar* infoLog) {} + +static const GLubyte* _glGetString(GLenum pname) { + return mock->glGetString(pname); +} + +static void _glTexParameterf(GLenum target, GLenum pname, GLfloat param) {} + +static void _glTexParameteri(GLenum target, GLenum pname, GLint param) {} + +static void _glTexImage2D(GLenum target, + GLint level, + GLint internalformat, + GLsizei width, + GLsizei height, + GLint border, + GLenum format, + GLenum type, + const void* pixels) {} + +static GLenum _glGetError() { + return GL_NO_ERROR; +} + +void _glLinkProgram(GLuint program) {} + +void _glRenderbufferStorage(GLenum target, + GLenum internalformat, + GLsizei width, + GLsizei height) {} + +void _glShaderSource(GLuint shader, + GLsizei count, + const GLchar* const* string, + const GLint* length) {} + +bool epoxy_has_gl_extension(const char* extension) { + return mock->epoxy_has_gl_extension(extension); +} + +bool epoxy_is_desktop_gl(void) { + return mock->epoxy_is_desktop_gl(); +} + +int epoxy_gl_version(void) { + return mock->epoxy_gl_version(); +} + +#ifdef __GNUC__ +#define CONSTRUCT(_func) static void _func(void) __attribute__((constructor)); +#define DESTRUCT(_func) static void _func(void) __attribute__((destructor)); +#elif defined(_MSC_VER) && (_MSC_VER >= 1500) +#define CONSTRUCT(_func) \ + static void _func(void); \ + static int _func##_wrapper(void) { \ + _func(); \ + return 0; \ + } \ + __pragma(section(".CRT$XCU", read)) \ + __declspec(allocate(".CRT$XCU")) static int (*_array##_func)(void) = \ + _func##_wrapper; + +#else +#error "You will need constructor support for your compiler" +#endif + +CONSTRUCT(library_init) + +EGLBoolean (*epoxy_eglBindAPI)(EGLenum api); +EGLBoolean (*epoxy_eglChooseConfig)(EGLDisplay dpy, + const EGLint* attrib_list, + EGLConfig* configs, + EGLint config_size, + EGLint* num_config); +EGLContext (*epoxy_eglCreateContext)(EGLDisplay dpy, + EGLConfig config, + EGLContext share_context, + const EGLint* attrib_list); +EGLSurface (*epoxy_eglCreatePbufferSurface)(EGLDisplay dpy, + EGLConfig config, + const EGLint* attrib_list); +EGLSurface (*epoxy_eglCreateWindowSurface)(EGLDisplay dpy, + EGLConfig config, + EGLNativeWindowType win, + const EGLint* attrib_list); +EGLBoolean (*epoxy_eglGetConfigAttrib)(EGLDisplay dpy, + EGLConfig config, + EGLint attribute, + EGLint* value); +EGLDisplay (*epoxy_eglGetDisplay)(EGLNativeDisplayType display_id); +EGLint (*epoxy_eglGetError)(); +void (*(*epoxy_eglGetProcAddress)(const char* procname))(void); +EGLBoolean (*epoxy_eglInitialize)(EGLDisplay dpy, EGLint* major, EGLint* minor); +EGLBoolean (*epoxy_eglMakeCurrent)(EGLDisplay dpy, + EGLSurface draw, + EGLSurface read, + EGLContext ctx); +EGLBoolean (*epoxy_eglSwapBuffers)(EGLDisplay dpy, EGLSurface surface); + +void (*epoxy_glAttachShader)(GLuint program, GLuint shader); +void (*epoxy_glBindFramebuffer)(GLenum target, GLuint framebuffer); +void (*epoxy_glBindRenderbuffer)(GLenum target, GLuint renderbuffer); +void (*epoxy_glBindTexture)(GLenum target, GLuint texture); +void (*epoxy_glBlitFramebuffer)(GLint srcX0, + GLint srcY0, + GLint srcX1, + GLint srcY1, + GLint dstX0, + GLint dstY0, + GLint dstX1, + GLint dstY1, + GLbitfield mask, + GLenum filter); +void (*epoxy_glCompileShader)(GLuint shader); +GLuint (*epoxy_glCreateProgram)(); +GLuint (*epoxy_glCreateShader)(GLenum shaderType); +void (*epoxy_glDeleteFramebuffers)(GLsizei n, const GLuint* framebuffers); +void (*expoxy_glDeleteShader)(GLuint shader); +void (*epoxy_glDeleteTextures)(GLsizei n, const GLuint* textures); +void (*epoxy_glFramebufferRenderbuffer)(GLenum target, + GLenum attachment, + GLenum renderbuffertarget, + GLuint renderbuffer); +void (*epoxy_glFramebufferTexture2D)(GLenum target, + GLenum attachment, + GLenum textarget, + GLuint texture, + GLint level); +void (*epoxy_glGetFramebufferAttachmentParameteriv)(GLenum target, + GLenum attachment, + GLenum pname, + GLint* params); +void (*epoxy_glGenFramebuffers)(GLsizei n, GLuint* framebuffers); +void (*epoxy_glGenTextures)(GLsizei n, GLuint* textures); +void (*epoxy_glLinkProgram)(GLuint program); +void (*epoxy_glRenderbufferStorage)(GLenum target, + GLenum internalformat, + GLsizei width, + GLsizei height); +void (*epoxy_glShaderSource)(GLuint shader, + GLsizei count, + const GLchar* const* string, + const GLint* length); +void (*epoxy_glTexParameterf)(GLenum target, GLenum pname, GLfloat param); +void (*epoxy_glTexParameteri)(GLenum target, GLenum pname, GLint param); +void (*epoxy_glTexImage2D)(GLenum target, + GLint level, + GLint internalformat, + GLsizei width, + GLsizei height, + GLint border, + GLenum format, + GLenum type, + const void* pixels); +GLenum (*epoxy_glGetError)(); + +static void library_init() { + epoxy_eglBindAPI = _eglBindAPI; + epoxy_eglChooseConfig = _eglChooseConfig; + epoxy_eglCreateContext = _eglCreateContext; + epoxy_eglCreatePbufferSurface = _eglCreatePbufferSurface; + epoxy_eglCreateWindowSurface = _eglCreateWindowSurface; + epoxy_eglGetConfigAttrib = _eglGetConfigAttrib; + epoxy_eglGetDisplay = _eglGetDisplay; + epoxy_eglGetError = _eglGetError; + epoxy_eglGetProcAddress = _eglGetProcAddress; + epoxy_eglInitialize = _eglInitialize; + epoxy_eglMakeCurrent = _eglMakeCurrent; + epoxy_eglQueryContext = _eglQueryContext; + epoxy_eglSwapBuffers = _eglSwapBuffers; + + epoxy_glAttachShader = _glAttachShader; + epoxy_glBindFramebuffer = _glBindFramebuffer; + epoxy_glBindRenderbuffer = _glBindRenderbuffer; + epoxy_glBindTexture = _glBindTexture; + epoxy_glBlitFramebuffer = _glBlitFramebuffer; + epoxy_glCompileShader = _glCompileShader; + epoxy_glClearColor = _glClearColor; + epoxy_glCreateProgram = _glCreateProgram; + epoxy_glCreateShader = _glCreateShader; + epoxy_glDeleteFramebuffers = _glDeleteFramebuffers; + epoxy_glDeleteShader = _glDeleteShader; + epoxy_glDeleteTextures = _glDeleteTextures; + epoxy_glFramebufferRenderbuffer = _glFramebufferRenderbuffer; + epoxy_glFramebufferTexture2D = _glFramebufferTexture2D; + epoxy_glGenFramebuffers = _glGenFramebuffers; + epoxy_glGenRenderbuffers = _glGenRenderbuffers; + epoxy_glGenTextures = _glGenTextures; + epoxy_glGetFramebufferAttachmentParameteriv = + _glGetFramebufferAttachmentParameteriv; + epoxy_glGetIntegerv = _glGetIntegerv; + epoxy_glGetProgramiv = _glGetProgramiv; + epoxy_glGetProgramInfoLog = _glGetProgramInfoLog; + epoxy_glGetShaderiv = _glGetShaderiv; + epoxy_glGetShaderInfoLog = _glGetShaderInfoLog; + epoxy_glGetString = _glGetString; + epoxy_glLinkProgram = _glLinkProgram; + epoxy_glRenderbufferStorage = _glRenderbufferStorage; + epoxy_glShaderSource = _glShaderSource; + epoxy_glTexParameterf = _glTexParameterf; + epoxy_glTexParameteri = _glTexParameteri; + epoxy_glTexImage2D = _glTexImage2D; + epoxy_glGetError = _glGetError; +} diff --git a/flutter/engine/src/flutter/shell/platform/linux/testing/mock_epoxy.h b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_epoxy.h new file mode 100644 index 0000000000000000000000000000000000000000..80bc05bb36da42d952fa76aed570423ebfd45455 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_epoxy.h @@ -0,0 +1,43 @@ +// 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_SHELL_PLATFORM_LINUX_TESTING_MOCK_EPOXY_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_EPOXY_H_ + +#include "gmock/gmock.h" + +#include +#include + +namespace flutter { +namespace testing { + +class MockEpoxy { + public: + MockEpoxy(); + ~MockEpoxy(); + + MOCK_METHOD(bool, epoxy_has_gl_extension, (const char* extension)); + MOCK_METHOD(bool, epoxy_is_desktop_gl, ()); + MOCK_METHOD(int, epoxy_gl_version, ()); + MOCK_METHOD(void, glClearColor, (GLfloat r, GLfloat g, GLfloat b, GLfloat a)); + MOCK_METHOD(void, + glBlitFramebuffer, + (GLint srcX0, + GLint srcY0, + GLint srcX1, + GLint srcY1, + GLint dstX0, + GLint dstY0, + GLint dstX1, + GLint dstY1, + GLbitfield mask, + GLenum filter)); + MOCK_METHOD(const GLubyte*, glGetString, (GLenum pname)); +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_EPOXY_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/testing/mock_gtk.cc b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_gtk.cc new file mode 100644 index 0000000000000000000000000000000000000000..3a5c7a65f6a8ff4c5a5b89845500d18382e51595 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_gtk.cc @@ -0,0 +1,214 @@ +// 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 + +#include "flutter/shell/platform/linux/testing/mock_gtk.h" + +using namespace flutter::testing; + +G_DECLARE_FINAL_TYPE(FlMockKeymap, fl_mock_keymap, FL, MOCK_KEYMAP, GObject) + +struct _FlMockKeymap { + GObject parent_instance; +}; + +G_DEFINE_TYPE(FlMockKeymap, fl_mock_keymap, G_TYPE_OBJECT) + +static void fl_mock_keymap_class_init(FlMockKeymapClass* klass) { + g_signal_new("keys-changed", fl_mock_keymap_get_type(), G_SIGNAL_RUN_LAST, 0, + nullptr, nullptr, nullptr, G_TYPE_NONE, 0); +} + +static void fl_mock_keymap_init(FlMockKeymap* self) {} + +static MockGtk* mock = nullptr; + +MockGtk::MockGtk() { + mock = this; +} + +MockGtk::~MockGtk() { + if (mock == this) { + mock = nullptr; + } +} + +GdkKeymap* gdk_keymap_get_for_display(GdkDisplay* display) { + FlMockKeymap* keymap = + FL_MOCK_KEYMAP(g_object_new(fl_mock_keymap_get_type(), nullptr)); + (void)FL_IS_MOCK_KEYMAP(keymap); + return reinterpret_cast(keymap); +} + +guint gdk_keymap_lookup_key(GdkKeymap* keymap, const GdkKeymapKey* key) { + return mock->gdk_keymap_lookup_key(keymap, key); +} + +GdkDisplay* gdk_display_get_default() { + return GDK_DISPLAY(g_object_new(gdk_display_get_type(), nullptr)); +} + +void gdk_display_beep(GdkDisplay* display) {} + +GdkWindowState gdk_window_get_state(GdkWindow* window) { + return mock->gdk_window_get_state(window); +} + +GdkDisplay* gdk_window_get_display(GdkWindow* window) { + return GDK_DISPLAY(g_object_new(gdk_display_get_type(), nullptr)); +} + +int gdk_display_get_n_monitors(GdkDisplay* display) { + return 1; +} + +GdkMonitor* gdk_display_get_monitor(GdkDisplay* display, int n) { + return GDK_MONITOR(g_object_new(gdk_monitor_get_type(), nullptr)); +} + +GdkMonitor* gdk_display_get_monitor_at_window(GdkDisplay* display, + GdkWindow* window) { + return nullptr; +} + +GdkCursor* gdk_cursor_new_from_name(GdkDisplay* display, const gchar* name) { + return nullptr; +} + +void gdk_window_set_cursor(GdkWindow* window, GdkCursor* cursor) {} + +void gdk_gl_context_make_current(GdkGLContext* context) {} + +void gdk_gl_context_clear_current() {} + +GtkWidget* gtk_window_new(GtkWindowType type) { + GtkWindow* window = GTK_WINDOW(g_object_new(gtk_window_get_type(), nullptr)); + mock->gtk_window_new(window, type); + return GTK_WIDGET(window); +} + +void gtk_window_set_default_size(GtkWindow* window, gint width, gint height) { + mock->gtk_window_set_default_size(window, width, height); +} + +void gtk_window_set_title(GtkWindow* window, const gchar* title) { + mock->gtk_window_set_title(window, title); +} + +void gtk_window_set_geometry_hints(GtkWindow* window, + GtkWidget* widget, + GdkGeometry* geometry, + GdkWindowHints geometry_mask) { + mock->gtk_window_set_geometry_hints(window, widget, geometry, geometry_mask); +} + +void gtk_window_resize(GtkWindow* window, gint width, gint height) { + mock->gtk_window_resize(window, width, height); +} + +void gtk_window_maximize(GtkWindow* window) { + mock->gtk_window_maximize(window); +} + +void gtk_window_unmaximize(GtkWindow* window) { + mock->gtk_window_unmaximize(window); +} + +gboolean gtk_window_is_maximized(GtkWindow* window) { + return mock->gtk_window_is_maximized(window); +} + +void gtk_window_iconify(GtkWindow* window) { + mock->gtk_window_iconify(window); +} + +void gtk_window_deiconify(GtkWindow* window) { + mock->gtk_window_deiconify(window); +} + +void gtk_widget_show(GtkWidget* widget) {} + +void gtk_widget_destroy(GtkWidget* widget) { + mock->gtk_widget_destroy(widget); +} + +void fl_gtk_widget_destroy(GtkWidget* widget) { + void (*destroy)(GtkWidget*) = reinterpret_cast( + dlsym(RTLD_NEXT, "gtk_widget_destroy")); + destroy(widget); +} + +gboolean gtk_widget_translate_coordinates(GtkWidget* src_widget, + GtkWidget* dest_widget, + gint src_x, + gint src_y, + gint* dest_x, + gint* dest_y) { + if (mock == nullptr) { + *dest_x = src_x; + *dest_y = src_y; + return TRUE; + } + + return mock->gtk_widget_translate_coordinates(src_widget, dest_widget, src_x, + src_y, dest_x, dest_y); +} + +GtkWidget* gtk_widget_get_toplevel(GtkWidget* widget) { + return widget; +} + +void gtk_im_context_set_client_window(GtkIMContext* context, + GdkWindow* window) { + if (mock != nullptr) { + mock->gtk_im_context_set_client_window(context, window); + } +} + +void gtk_im_context_get_preedit_string(GtkIMContext* context, + gchar** str, + PangoAttrList** attrs, + gint* cursor_pos) { + if (mock != nullptr) { + mock->gtk_im_context_get_preedit_string(context, str, attrs, cursor_pos); + } +} + +gboolean gtk_im_context_filter_keypress(GtkIMContext* context, + GdkEventKey* event) { + if (mock == nullptr) { + return TRUE; + } + + return mock->gtk_im_context_filter_keypress(context, event); +} + +void gtk_im_context_focus_in(GtkIMContext* context) { + if (mock != nullptr) { + mock->gtk_im_context_focus_in(context); + } +} + +void gtk_im_context_focus_out(GtkIMContext* context) { + if (mock != nullptr) { + mock->gtk_im_context_focus_out(context); + } +} + +void gtk_im_context_set_cursor_location(GtkIMContext* context, + const GdkRectangle* area) { + if (mock != nullptr) { + mock->gtk_im_context_set_cursor_location(context, area); + } +} + +void gtk_im_context_set_surrounding(GtkIMContext* context, + const gchar* text, + gint len, + gint cursor_index) { + if (mock != nullptr) { + mock->gtk_im_context_set_surrounding(context, text, len, cursor_index); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/linux/testing/mock_gtk.h b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_gtk.h new file mode 100644 index 0000000000000000000000000000000000000000..735dc88ac443ea176bc2dc2b8549b338ae5c50b0 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_gtk.h @@ -0,0 +1,85 @@ +// 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_SHELL_PLATFORM_LINUX_TESTING_MOCK_GTK_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_GTK_H_ + +#include "gmock/gmock.h" + +#include + +namespace flutter { +namespace testing { + +class MockGtk { + public: + MockGtk(); + ~MockGtk(); + + MOCK_METHOD(GdkKeymap*, gdk_keymap_get_for_display, (GdkDisplay * display)); + MOCK_METHOD(guint, + gdk_keymap_lookup_key, + (GdkKeymap * keymap, const GdkKeymapKey* key)); + MOCK_METHOD(GdkWindowState, gdk_window_get_state, (GdkWindow * window)); + MOCK_METHOD(void, gtk_window_new, (GtkWindow * window, GtkWindowType type)); + MOCK_METHOD(void, + gtk_window_set_default_size, + (GtkWindow * window, gint width, gint height)); + MOCK_METHOD(void, + gtk_window_set_title, + (GtkWindow * window, const gchar* title)); + MOCK_METHOD(void, + gtk_window_set_geometry_hints, + (GtkWindow * window, + GtkWidget* widget, + GdkGeometry* geometry, + GdkWindowHints geometry_mask)); + MOCK_METHOD(void, + gtk_window_resize, + (GtkWindow * window, gint width, gint height)); + MOCK_METHOD(void, gtk_window_maximize, (GtkWindow * window)); + MOCK_METHOD(void, gtk_window_unmaximize, (GtkWindow * window)); + MOCK_METHOD(gboolean, gtk_window_is_maximized, (GtkWindow * window)); + MOCK_METHOD(void, gtk_window_iconify, (GtkWindow * window)); + MOCK_METHOD(void, gtk_window_deiconify, (GtkWindow * window)); + MOCK_METHOD(void, gtk_widget_destroy, (GtkWidget * widget)); + MOCK_METHOD(gboolean, + gtk_widget_translate_coordinates, + (GtkWidget * src_widget, + GtkWidget* dest_widget, + gint src_x, + gint src_y, + gint* dest_x, + gint* dest_y)); + MOCK_METHOD(GtkWidget*, gtk_widget_get_toplevel, (GtkWidget * widget)); + MOCK_METHOD(void, + gtk_im_context_set_client_window, + (GtkIMContext * context, GdkWindow* window)); + MOCK_METHOD(void, + gtk_im_context_get_preedit_string, + (GtkIMContext * context, + gchar** str, + PangoAttrList** attrs, + gint* cursor_pos)); + MOCK_METHOD(gboolean, + gtk_im_context_filter_keypress, + (GtkIMContext * context, GdkEventKey* event)); + MOCK_METHOD(gboolean, gtk_im_context_focus_in, (GtkIMContext * context)); + MOCK_METHOD(void, gtk_im_context_focus_out, (GtkIMContext * context)); + MOCK_METHOD(void, + gtk_im_context_set_cursor_location, + (GtkIMContext * context, const GdkRectangle* area)); + MOCK_METHOD( + void, + gtk_im_context_set_surrounding, + (GtkIMContext * context, const gchar* text, gint len, gint cursor_index)); +}; + +} // namespace testing +} // namespace flutter + +// Calls original gtk_widget_destroy. +void fl_gtk_widget_destroy(GtkWidget* widget); + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_GTK_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/testing/mock_plugin_registrar.cc b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_plugin_registrar.cc new file mode 100644 index 0000000000000000000000000000000000000000..30cf3f25dfabcf06f1ed13ad70cde044b2afa46a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_plugin_registrar.cc @@ -0,0 +1,70 @@ +// 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/shell/platform/linux/testing/mock_plugin_registrar.h" + +struct _FlMockPluginRegistrar { + GObject parent_instance; + + FlBinaryMessenger* messenger; + FlTextureRegistrar* texture_registrar; +}; + +static void fl_mock_plugin_registrar_iface_init( + FlPluginRegistrarInterface* iface); + +G_DEFINE_TYPE_WITH_CODE( + FlMockPluginRegistrar, + fl_mock_plugin_registrar, + G_TYPE_OBJECT, + G_IMPLEMENT_INTERFACE(fl_plugin_registrar_get_type(), + fl_mock_plugin_registrar_iface_init)) + +static void fl_mock_plugin_registrar_dispose(GObject* object) { + FlMockPluginRegistrar* self = FL_MOCK_PLUGIN_REGISTRAR(object); + + g_clear_object(&self->messenger); + g_clear_object(&self->texture_registrar); + + G_OBJECT_CLASS(fl_mock_plugin_registrar_parent_class)->dispose(object); +} + +static void fl_mock_plugin_registrar_class_init( + FlMockPluginRegistrarClass* klass) { + G_OBJECT_CLASS(klass)->dispose = fl_mock_plugin_registrar_dispose; +} + +static FlBinaryMessenger* get_messenger(FlPluginRegistrar* registrar) { + FlMockPluginRegistrar* self = FL_MOCK_PLUGIN_REGISTRAR(registrar); + return self->messenger; +} + +static FlTextureRegistrar* get_texture_registrar(FlPluginRegistrar* registrar) { + FlMockPluginRegistrar* self = FL_MOCK_PLUGIN_REGISTRAR(registrar); + return self->texture_registrar; +} + +static FlView* get_view(FlPluginRegistrar* registrar) { + return NULL; +} + +static void fl_mock_plugin_registrar_iface_init( + FlPluginRegistrarInterface* iface) { + iface->get_messenger = get_messenger; + iface->get_texture_registrar = get_texture_registrar; + iface->get_view = get_view; +} + +static void fl_mock_plugin_registrar_init(FlMockPluginRegistrar* self) {} + +FlPluginRegistrar* fl_mock_plugin_registrar_new( + FlBinaryMessenger* messenger, + FlTextureRegistrar* texture_registrar) { + FlMockPluginRegistrar* registrar = FL_MOCK_PLUGIN_REGISTRAR( + g_object_new(fl_mock_plugin_registrar_get_type(), NULL)); + registrar->messenger = FL_BINARY_MESSENGER(g_object_ref(messenger)); + registrar->texture_registrar = + FL_TEXTURE_REGISTRAR(g_object_ref(texture_registrar)); + return FL_PLUGIN_REGISTRAR(registrar); +} diff --git a/flutter/engine/src/flutter/shell/platform/linux/testing/mock_plugin_registrar.h b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_plugin_registrar.h new file mode 100644 index 0000000000000000000000000000000000000000..6207083c8ef285ee39fe6047a2439e0982e0ce61 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_plugin_registrar.h @@ -0,0 +1,26 @@ +// 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_SHELL_PLATFORM_LINUX_TESTING_MOCK_PLUGIN_REGISTRAR_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_PLUGIN_REGISTRAR_H_ + +#include "flutter/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h" +#include "flutter/shell/platform/linux/public/flutter_linux/fl_plugin_registrar.h" +#include "flutter/shell/platform/linux/public/flutter_linux/fl_texture_registrar.h" + +G_BEGIN_DECLS + +G_DECLARE_FINAL_TYPE(FlMockPluginRegistrar, + fl_mock_plugin_registrar, + FL, + MOCK_PLUGIN_REGISTRAR, + GObject) + +FlPluginRegistrar* fl_mock_plugin_registrar_new( + FlBinaryMessenger* messenger, + FlTextureRegistrar* texture_registrar); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_PLUGIN_REGISTRAR_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/testing/mock_renderable.cc b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_renderable.cc new file mode 100644 index 0000000000000000000000000000000000000000..292bcf446512f7d55d516b916a3a8c7eccda1378 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_renderable.cc @@ -0,0 +1,45 @@ +// 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/shell/platform/linux/testing/mock_renderable.h" + +struct _FlMockRenderable { + GObject parent_instance; + size_t redraw_count; +}; + +static void mock_renderable_iface_init(FlRenderableInterface* iface); + +G_DEFINE_TYPE_WITH_CODE(FlMockRenderable, + fl_mock_renderable, + g_object_get_type(), + G_IMPLEMENT_INTERFACE(fl_renderable_get_type(), + mock_renderable_iface_init)) + +static void mock_renderable_redraw(FlRenderable* renderable) { + FlMockRenderable* self = FL_MOCK_RENDERABLE(renderable); + self->redraw_count++; +} + +static void mock_renderable_make_current(FlRenderable* renderable) {} + +static void mock_renderable_iface_init(FlRenderableInterface* iface) { + iface->redraw = mock_renderable_redraw; + iface->make_current = mock_renderable_make_current; +} + +static void fl_mock_renderable_class_init(FlMockRenderableClass* klass) {} + +static void fl_mock_renderable_init(FlMockRenderable* self) {} + +// Creates a sub renderable. +FlMockRenderable* fl_mock_renderable_new() { + return FL_MOCK_RENDERABLE( + g_object_new(fl_mock_renderable_get_type(), nullptr)); +} + +size_t fl_mock_renderable_get_redraw_count(FlMockRenderable* self) { + g_return_val_if_fail(FL_IS_MOCK_RENDERABLE(self), FALSE); + return self->redraw_count; +} diff --git a/flutter/engine/src/flutter/shell/platform/linux/testing/mock_renderable.h b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_renderable.h new file mode 100644 index 0000000000000000000000000000000000000000..6dcb6c12a8fa602751c82e6a543bf55028e86fee --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_renderable.h @@ -0,0 +1,24 @@ +// 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_SHELL_PLATFORM_LINUX_TESTING_MOCK_RENDERABLE_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_RENDERABLE_H_ + +#include "flutter/shell/platform/linux/fl_renderable.h" + +G_BEGIN_DECLS + +G_DECLARE_FINAL_TYPE(FlMockRenderable, + fl_mock_renderable, + FL, + MOCK_RENDERABLE, + GObject) + +FlMockRenderable* fl_mock_renderable_new(); + +size_t fl_mock_renderable_get_redraw_count(FlMockRenderable* renderable); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_RENDERABLE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/testing/mock_settings.cc b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_settings.cc new file mode 100644 index 0000000000000000000000000000000000000000..ebe6fa2b49b5531ab6caff6a20582b6468b00b71 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_settings.cc @@ -0,0 +1,82 @@ +// 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/shell/platform/linux/testing/mock_settings.h" + +using namespace flutter::testing; + +G_DECLARE_FINAL_TYPE(FlMockSettings, + fl_mock_settings, + FL, + MOCK_SETTINGS, + GObject) + +struct _FlMockSettings { + GObject parent_instance; + MockSettings* mock; +}; + +static void fl_mock_settings_iface_init(FlSettingsInterface* iface); + +#define FL_UNUSED(x) (void)x; + +G_DEFINE_TYPE_WITH_CODE(FlMockSettings, + fl_mock_settings, + G_TYPE_OBJECT, + G_IMPLEMENT_INTERFACE(fl_settings_get_type(), + fl_mock_settings_iface_init) + FL_UNUSED(FL_IS_MOCK_SETTINGS)) + +static void fl_mock_settings_class_init(FlMockSettingsClass* klass) {} + +static FlClockFormat fl_mock_settings_get_clock_format(FlSettings* settings) { + FlMockSettings* self = FL_MOCK_SETTINGS(settings); + return self->mock->fl_settings_get_clock_format(settings); +} + +static FlColorScheme fl_mock_settings_get_color_scheme(FlSettings* settings) { + FlMockSettings* self = FL_MOCK_SETTINGS(settings); + return self->mock->fl_settings_get_color_scheme(settings); +} + +static gboolean fl_mock_settings_get_enable_animations(FlSettings* settings) { + FlMockSettings* self = FL_MOCK_SETTINGS(settings); + return self->mock->fl_settings_get_enable_animations(settings); +} + +static gboolean fl_mock_settings_get_high_contrast(FlSettings* settings) { + FlMockSettings* self = FL_MOCK_SETTINGS(settings); + return self->mock->fl_settings_get_high_contrast(settings); +} + +static gdouble fl_mock_settings_get_text_scaling_factor(FlSettings* settings) { + FlMockSettings* self = FL_MOCK_SETTINGS(settings); + return self->mock->fl_settings_get_text_scaling_factor(settings); +} + +static void fl_mock_settings_iface_init(FlSettingsInterface* iface) { + iface->get_clock_format = fl_mock_settings_get_clock_format; + iface->get_color_scheme = fl_mock_settings_get_color_scheme; + iface->get_enable_animations = fl_mock_settings_get_enable_animations; + iface->get_high_contrast = fl_mock_settings_get_high_contrast; + iface->get_text_scaling_factor = fl_mock_settings_get_text_scaling_factor; +} + +static void fl_mock_settings_init(FlMockSettings* self) {} + +MockSettings::MockSettings() + : instance_( + FL_SETTINGS(g_object_new(fl_mock_settings_get_type(), nullptr))) { + FL_MOCK_SETTINGS(instance_)->mock = this; +} + +MockSettings::~MockSettings() { + if (instance_ != nullptr) { + g_clear_object(&instance_); + } +} + +MockSettings::operator FlSettings*() { + return instance_; +} diff --git a/flutter/engine/src/flutter/shell/platform/linux/testing/mock_settings.h b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_settings.h new file mode 100644 index 0000000000000000000000000000000000000000..790229eb8c79544ad4269fc489f825f300109960 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_settings.h @@ -0,0 +1,50 @@ +// 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_SHELL_PLATFORM_LINUX_TESTING_MOCK_SETTINGS_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_SETTINGS_H_ + +#include "flutter/shell/platform/linux/fl_settings.h" + +#include "gmock/gmock.h" + +namespace flutter { +namespace testing { + +// Mock for FlSettings. +class MockSettings { + public: + MockSettings(); + ~MockSettings(); + + // This was an existing use of operator overloading. It's against our style + // guide but enabling clang tidy on header files is a higher priority than + // fixing this. + // NOLINTNEXTLINE(google-explicit-constructor) + operator FlSettings*(); + + MOCK_METHOD(FlClockFormat, + fl_settings_get_clock_format, + (FlSettings * settings)); + + MOCK_METHOD(FlColorScheme, + fl_settings_get_color_scheme, + (FlSettings * settings)); + + MOCK_METHOD(bool, fl_settings_get_enable_animations, (FlSettings * settings)); + + MOCK_METHOD(bool, fl_settings_get_high_contrast, (FlSettings * settings)); + + MOCK_METHOD(gdouble, + fl_settings_get_text_scaling_factor, + (FlSettings * settings)); + + private: + FlSettings* instance_ = nullptr; +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_SETTINGS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/testing/mock_signal_handler.cc b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_signal_handler.cc new file mode 100644 index 0000000000000000000000000000000000000000..a1b4d6885693657d45465ee77cfcc31945e4ec1b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_signal_handler.cc @@ -0,0 +1,27 @@ +// 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/shell/platform/linux/testing/mock_signal_handler.h" + +namespace flutter { +namespace testing { + +SignalHandler::SignalHandler(gpointer instance, + const gchar* name, + GCallback callback) + : instance_(instance) { + id_ = g_signal_connect_data(instance, name, callback, this, nullptr, + G_CONNECT_SWAPPED); + g_object_add_weak_pointer(G_OBJECT(instance), &instance_); +} + +SignalHandler::~SignalHandler() { + if (instance_) { + g_signal_handler_disconnect(instance_, id_); + g_object_remove_weak_pointer(G_OBJECT(instance_), &instance_); + } +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/linux/testing/mock_signal_handler.h b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_signal_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..98013015d8649fbb10cd24331cb94246fa1d5451 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_signal_handler.h @@ -0,0 +1,90 @@ +// 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_SHELL_PLATFORM_LINUX_TESTING_MOCK_SIGNAL_HANDLER_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_SIGNAL_HANDLER_H_ + +#include +#include + +#include "gmock/gmock.h" + +// Expects a signal that has no arguments. +// +// MockSignalHandler timeout(timer, "timeout"); +// EXPECT_SIGNAL(timeout).Times(3); +// +#define EXPECT_SIGNAL(mock) EXPECT_CALL(mock, Handler()) + +// Expects a signal that has 1 argument. +// +// MockSignalHandler1 name_changed(object, "name-changed"); +// EXPECT_SIGNAL(name_changed, testing::StrEq("example")); +// +#define EXPECT_SIGNAL1(mock, a1) EXPECT_CALL(mock, Handler1(a1)) + +// Expects a signal that has 2 arguments. +// +// MockSignalHandler2 child_added(parent, "children::add"); +// EXPECT_SIGNAL2(child_added, testing::Eq(1), testing::A()); +// +#define EXPECT_SIGNAL2(mock, a1, a2) EXPECT_CALL(mock, Handler2(a1, a2)) + +namespace flutter { +namespace testing { + +class SignalHandler { + public: + SignalHandler(gpointer instance, const gchar* name, GCallback callback); + virtual ~SignalHandler(); + + private: + gulong id_ = 0; + gpointer instance_ = nullptr; +}; + +// A mock signal handler that has no arguments. Used with EXPECT_SIGNAL(). +class MockSignalHandler : public SignalHandler { + public: + MockSignalHandler(gpointer instance, const gchar* name) + : SignalHandler(instance, name, G_CALLBACK(OnSignal)) {} + + MOCK_METHOD(void, Handler, ()); + + private: + static void OnSignal(MockSignalHandler* mock) { mock->Handler(); } +}; + +// A mock signal handler that has 1 argument. Used with EXPECT_SIGNAL1(). +template +class MockSignalHandler1 : public SignalHandler { + public: + MockSignalHandler1(gpointer instance, const gchar* name) + : SignalHandler(instance, name, G_CALLBACK(OnSignal1)) {} + + MOCK_METHOD(void, Handler1, (A1 a1)); + + private: + static void OnSignal1(MockSignalHandler1* mock, A1 a1) { mock->Handler1(a1); } +}; + +// A mock signal handler that has 2 arguments. Used with EXPECT_SIGNAL2(). +template +class MockSignalHandler2 : public SignalHandler { + public: + MockSignalHandler2(gpointer instance, const gchar* name) + : SignalHandler(instance, name, G_CALLBACK(OnSignal2)) {} + + MOCK_METHOD(void, Handler2, (A1 a1, A2 a2)); + + private: + static void OnSignal2(MockSignalHandler2* mock, A1 a1, A2 a2) { + mock->Handler2(a1, a2); + } +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_SIGNAL_HANDLER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/linux/testing/mock_texture_registrar.cc b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_texture_registrar.cc new file mode 100644 index 0000000000000000000000000000000000000000..0a91d24fbbc5235336f22bf4fcc5c950185a0057 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_texture_registrar.cc @@ -0,0 +1,98 @@ +// 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/shell/platform/linux/testing/mock_texture_registrar.h" + +struct _FlMockTextureRegistrar { + GObject parent_instance; + FlTexture* texture; + gboolean frame_available; +}; + +static void fl_mock_texture_registrar_iface_init( + FlTextureRegistrarInterface* iface); + +G_DEFINE_TYPE_WITH_CODE( + FlMockTextureRegistrar, + fl_mock_texture_registrar, + G_TYPE_OBJECT, + G_IMPLEMENT_INTERFACE(fl_texture_registrar_get_type(), + fl_mock_texture_registrar_iface_init)) + +static gboolean register_texture(FlTextureRegistrar* registrar, + FlTexture* texture) { + FlMockTextureRegistrar* self = FL_MOCK_TEXTURE_REGISTRAR(registrar); + if (self->texture != nullptr) { + return FALSE; + } + self->texture = FL_TEXTURE(g_object_ref(texture)); + return TRUE; +} + +static FlTexture* lookup_texture(FlTextureRegistrar* registrar, + int64_t texture_id) { + FlMockTextureRegistrar* self = FL_MOCK_TEXTURE_REGISTRAR(registrar); + if (self->texture != nullptr && + fl_texture_get_id(self->texture) == texture_id) { + return self->texture; + } + return nullptr; +} + +static gboolean mark_texture_frame_available(FlTextureRegistrar* registrar, + FlTexture* texture) { + FlMockTextureRegistrar* self = FL_MOCK_TEXTURE_REGISTRAR(registrar); + if (lookup_texture(registrar, fl_texture_get_id(texture)) == nullptr) { + return FALSE; + } + self->frame_available = TRUE; + return TRUE; +} + +static gboolean unregister_texture(FlTextureRegistrar* registrar, + FlTexture* texture) { + FlMockTextureRegistrar* self = FL_MOCK_TEXTURE_REGISTRAR(registrar); + if (self->texture != texture) { + return FALSE; + } + + g_clear_object(&self->texture); + + return TRUE; +} + +static void fl_mock_texture_registrar_iface_init( + FlTextureRegistrarInterface* iface) { + iface->register_texture = register_texture; + iface->lookup_texture = lookup_texture; + iface->mark_texture_frame_available = mark_texture_frame_available; + iface->unregister_texture = unregister_texture; +} + +static void fl_mock_texture_registrar_dispose(GObject* object) { + FlMockTextureRegistrar* self = FL_MOCK_TEXTURE_REGISTRAR(object); + g_clear_object(&self->texture); + G_OBJECT_CLASS(fl_mock_texture_registrar_parent_class)->dispose(object); +} + +static void fl_mock_texture_registrar_class_init( + FlMockTextureRegistrarClass* klass) { + G_OBJECT_CLASS(klass)->dispose = fl_mock_texture_registrar_dispose; +} + +static void fl_mock_texture_registrar_init(FlMockTextureRegistrar* self) {} + +FlMockTextureRegistrar* fl_mock_texture_registrar_new() { + return FL_MOCK_TEXTURE_REGISTRAR( + g_object_new(fl_mock_texture_registrar_get_type(), nullptr)); +} + +FlTexture* fl_mock_texture_registrar_get_texture(FlMockTextureRegistrar* self) { + return self->texture; +} + +gboolean fl_mock_texture_registrar_get_frame_available( + FlMockTextureRegistrar* self) { + return self->frame_available; +} diff --git a/flutter/engine/src/flutter/shell/platform/linux/testing/mock_texture_registrar.h b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_texture_registrar.h new file mode 100644 index 0000000000000000000000000000000000000000..13d59753bd05f60b3226cfc93732097fe59ce94a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/linux/testing/mock_texture_registrar.h @@ -0,0 +1,28 @@ +// 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_SHELL_PLATFORM_LINUX_TESTING_MOCK_TEXTURE_REGISTRAR_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_TEXTURE_REGISTRAR_H_ + +#include "flutter/shell/platform/linux/fl_texture_registrar_private.h" + +G_BEGIN_DECLS + +G_DECLARE_FINAL_TYPE(FlMockTextureRegistrar, + fl_mock_texture_registrar, + FL, + MOCK_TEXTURE_REGISTRAR, + GObject) + +FlMockTextureRegistrar* fl_mock_texture_registrar_new(); + +FlTexture* fl_mock_texture_registrar_get_texture( + FlMockTextureRegistrar* registrar); + +gboolean fl_mock_texture_registrar_get_frame_available( + FlMockTextureRegistrar* registrar); + +G_END_DECLS + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_TEXTURE_REGISTRAR_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/dart_project.h b/flutter/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/dart_project.h new file mode 100644 index 0000000000000000000000000000000000000000..8d18146314ff656fa176a837748cc039ceb79bf9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/dart_project.h @@ -0,0 +1,145 @@ +// 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_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_DART_PROJECT_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_DART_PROJECT_H_ + +#include +#include + +namespace flutter { + +// Configures how the Flutter engine selects a GPU. +enum class GpuPreference { + // No preference. + NoPreference, + // Prefer energy efficiency over performance, such as an integrated GPU. + // This falls back to a high performance GPU if no low power GPU is + // available. + LowPowerPreference, +}; + +// Configures the thread policy for running the UI isolate. +enum class UIThreadPolicy { + // Default value. Currently will run the UI isolate on separate thread, + // later will be changed to running the UI isolate on platform thread. + Default, + // Run the UI isolate on platform thread. + RunOnPlatformThread, + // Run the UI isolate on a separate thread. + RunOnSeparateThread, +}; + +// A set of Flutter and Dart assets used to initialize a Flutter engine. +class DartProject { + public: + // Creates a DartProject from a series of absolute paths. + // The three paths are: + // - assets_path: Path to the assets directory as built by the Flutter tool. + // - icu_data_path: Path to the icudtl.dat file. + // - aot_library_path: Path to the AOT snapshot file. + // + // The paths may either be absolute or relative to the directory containing + // the running executable. + explicit DartProject(const std::wstring& assets_path, + const std::wstring& icu_data_path, + const std::wstring& aot_library_path) { + assets_path_ = assets_path; + icu_data_path_ = icu_data_path; + aot_library_path_ = aot_library_path; + } + + // Creates a DartProject from a directory path. The directory should contain + // the following top-level items: + // - icudtl.dat (provided as a resource by the Flutter tool) + // - flutter_assets (as built by the Flutter tool) + // - app.so, for an AOT build (as built by the Flutter tool) + // + // The path can either be absolute, or relative to the directory containing + // the running executable. + explicit DartProject(const std::wstring& path) { + assets_path_ = path + L"\\flutter_assets"; + icu_data_path_ = path + L"\\icudtl.dat"; + aot_library_path_ = path + L"\\app.so"; + } + + ~DartProject() = default; + + // Sets the Dart entrypoint to the specified value. + // + // If not set, the default entrypoint (main) is used. Custom Dart entrypoints + // must be decorated with `@pragma('vm:entry-point')`. + void set_dart_entrypoint(const std::string& entrypoint) { + if (entrypoint.empty()) { + return; + } + dart_entrypoint_ = entrypoint; + } + + // Returns the Dart entrypoint. + const std::string& dart_entrypoint() const { return dart_entrypoint_; } + + // Sets the command line arguments that should be passed to the Dart + // entrypoint. + void set_dart_entrypoint_arguments(std::vector arguments) { + dart_entrypoint_arguments_ = std::move(arguments); + } + + // Returns any command line arguments that should be passed to the Dart + // entrypoint. + const std::vector& dart_entrypoint_arguments() const { + return dart_entrypoint_arguments_; + } + + // Sets the GPU usage preference for flutter engine. + void set_gpu_preference(GpuPreference gpu_preference) { + gpu_preference_ = gpu_preference; + } + + // Returns the project's GPU preference. + // Defaults to NoPreference. + GpuPreference gpu_preference() const { return gpu_preference_; } + + // Sets the thread policy for UI isolate. + void set_ui_thread_policy(UIThreadPolicy policy) { + ui_thread_policy_ = policy; + } + + // Returns the policy for UI isolate. + // Defaults to UIThreadPolicy::Default. + UIThreadPolicy ui_thread_policy() const { return ui_thread_policy_; } + + private: + // Accessors for internals are private, so that they can be changed if more + // flexible options for project structures are needed later without it + // being a breaking change. Provide access to internal classes that need + // them. + friend class FlutterEngine; + friend class FlutterViewController; + friend class DartProjectTest; + + const std::wstring& assets_path() const { return assets_path_; } + const std::wstring& icu_data_path() const { return icu_data_path_; } + const std::wstring& aot_library_path() const { return aot_library_path_; } + + // The path to the assets directory. + std::wstring assets_path_; + // The path to the ICU data. + std::wstring icu_data_path_; + // The path to the AOT library. This will always return a path, but non-AOT + // builds will not be expected to actually have a library at that path. + std::wstring aot_library_path_; + // The Dart entrypoint to launch. + std::string dart_entrypoint_; + // The list of arguments to pass through to the Dart entrypoint. + std::vector dart_entrypoint_arguments_; + // The preference for GPU to be used by flutter engine. + GpuPreference gpu_preference_ = GpuPreference::NoPreference; + // Thread policy for UI isolate. + UIThreadPolicy ui_thread_policy_ = UIThreadPolicy::Default; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_DART_PROJECT_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/flutter_engine.h b/flutter/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/flutter_engine.h new file mode 100644 index 0000000000000000000000000000000000000000..0369db35a14fc2d1a2ce71084462aad4cc4a3beb --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/flutter_engine.h @@ -0,0 +1,128 @@ +// 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_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_ENGINE_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_ENGINE_H_ + +#include + +#include +#include +#include +#include + +#include "binary_messenger.h" +#include "dart_project.h" +#include "plugin_registrar.h" +#include "plugin_registry.h" + +namespace flutter { + +// An instance of a Flutter engine. +// +// In the future, this will be the API surface used for all interactions with +// the engine, rather than having them duplicated on FlutterViewController. +// For now it is only used in the rare case where you need a headless Flutter +// engine. +class FlutterEngine : public PluginRegistry { + public: + // Creates a new engine for running the given project. + explicit FlutterEngine(const DartProject& project); + + virtual ~FlutterEngine(); + + // Prevent copying. + FlutterEngine(FlutterEngine const&) = delete; + FlutterEngine& operator=(FlutterEngine const&) = delete; + + // Starts running the engine at the entrypoint function specified in the + // DartProject used to configure the engine, or main() by default. + bool Run(); + + // Starts running the engine, with an optional entry point. + // + // If provided, entry_point must be the name of a top-level function from the + // same Dart library that contains the app's main() function, and must be + // decorated with `@pragma(vm:entry-point)` to ensure the method is not + // tree-shaken by the Dart compiler. If not provided, defaults to main(). + bool Run(const char* entry_point); + + // Terminates the running engine. + void ShutDown(); + + // Processes any pending events in the Flutter engine, and returns the + // nanosecond delay until the next scheduled event (or max, if none). + // + // This should be called on every run of the application-level runloop, and + // a wait for native events in the runloop should never be longer than the + // last return value from this function. + std::chrono::nanoseconds ProcessMessages(); + + // Tells the engine that the system font list has changed. Should be called + // by clients when OS-level font changes happen (e.g., WM_FONTCHANGE in a + // Win32 application). + void ReloadSystemFonts(); + + // Tells the engine that the platform brightness value has changed. Should be + // called by clients when OS-level theme changes happen (e.g., + // WM_DWMCOLORIZATIONCOLORCHANGED in a Win32 application). + void ReloadPlatformBrightness(); + + // flutter::PluginRegistry: + FlutterDesktopPluginRegistrarRef GetRegistrarForPlugin( + const std::string& plugin_name) override; + + // Returns the messenger to use for creating channels to communicate with the + // Flutter engine. + // + // This pointer will remain valid for the lifetime of this instance. + BinaryMessenger* messenger() { return messenger_.get(); } + + // Schedule a callback to be called after the next frame is drawn. + // + // This must be called from the platform thread. The callback is executed only + // once on the platform thread. + void SetNextFrameCallback(std::function callback); + + // Called to pass an external window message to the engine for lifecycle + // state updates. Non-Flutter windows must call this method in their WndProc + // in order to be included in the logic for application lifecycle state + // updates. Returns a result if the message should be consumed. + std::optional ProcessExternalWindowMessage(HWND hwnd, + UINT message, + WPARAM wparam, + LPARAM lparam); + + private: + // For access to the engine handle. + friend class FlutterViewController; + + // Gives up ownership of |engine_|, but keeps a weak reference to it. + // + // This is intended to be used by FlutterViewController, since the underlying + // C API for view controllers takes over engine ownership. + FlutterDesktopEngineRef RelinquishEngine(); + + // Handle for interacting with the C API's engine reference. + FlutterDesktopEngineRef engine_ = nullptr; + + // Messenger for communicating with the engine. + std::unique_ptr messenger_; + + // Whether or not this wrapper owns |engine_|. + bool owns_engine_ = true; + + // Whether |Run| has been called successfully. + // + // This is used to improve error messages. This can be false while the engine + // is running if the engine was started by creating a view. + bool run_succeeded_ = false; + + // The callback to execute once the next frame is drawn. + std::function next_frame_callback_ = nullptr; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_ENGINE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/flutter_view.h b/flutter/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/flutter_view.h new file mode 100644 index 0000000000000000000000000000000000000000..48e7607c966fc3b2db5ea49c4cbd559e343e4e62 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/flutter_view.h @@ -0,0 +1,42 @@ +// 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_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_VIEW_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_VIEW_H_ + +#include + +namespace flutter { + +// The unique identifier for a view. +typedef int64_t FlutterViewId; + +// A view displaying Flutter content. +class FlutterView { + public: + explicit FlutterView(FlutterDesktopViewRef view) : view_(view) {} + + // Destroys this reference to the view. The underlying view is not destroyed. + virtual ~FlutterView() = default; + + // Prevent copying. + FlutterView(FlutterView const&) = delete; + FlutterView& operator=(FlutterView const&) = delete; + + // Returns the backing HWND for the view. + HWND GetNativeWindow() { return FlutterDesktopViewGetHWND(view_); } + + // Returns the DXGI adapter used for rendering or nullptr in case of error. + IDXGIAdapter* GetGraphicsAdapter() { + return FlutterDesktopViewGetGraphicsAdapter(view_); + } + + private: + // Handle for interacting with the C API's view. + FlutterDesktopViewRef view_ = nullptr; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_VIEW_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/flutter_view_controller.h b/flutter/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/flutter_view_controller.h new file mode 100644 index 0000000000000000000000000000000000000000..4007534a5d73eb7231264229dc5be2be467c1ad3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/flutter_view_controller.h @@ -0,0 +1,76 @@ +// 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_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_VIEW_CONTROLLER_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_VIEW_CONTROLLER_H_ + +#include +#include + +#include +#include + +#include "dart_project.h" +#include "flutter_engine.h" +#include "flutter_view.h" + +namespace flutter { + +// A controller for a view displaying Flutter content. +// +// This is the primary wrapper class for the desktop C API. +// If you use this class, you should not call any of the setup or teardown +// methods in the C API directly, as this class will do that internally. +class FlutterViewController { + public: + // Creates a FlutterView that can be parented into a Windows View hierarchy + // either using HWNDs. + // + // This also creates a new FlutterEngine. + // + // |dart_project| will be used to configure the engine backing this view. + FlutterViewController(int width, int height, const DartProject& project); + + virtual ~FlutterViewController(); + + // Prevent copying. + FlutterViewController(FlutterViewController const&) = delete; + FlutterViewController& operator=(FlutterViewController const&) = delete; + + // Returns the view controller's view ID. + FlutterViewId view_id() const; + + // Returns the engine running Flutter content in this view. + FlutterEngine* engine() const { return engine_.get(); } + + // Returns the view managed by this controller. + FlutterView* view() const { return view_.get(); } + + // Requests new frame from the engine and repaints the view. + void ForceRedraw(); + + // Allows the Flutter engine and any interested plugins an opportunity to + // handle the given message. + // + // If a result is returned, then the message was handled in such a way that + // further handling should not be done. + std::optional HandleTopLevelWindowProc(HWND hwnd, + UINT message, + WPARAM wparam, + LPARAM lparam); + + private: + // Handle for interacting with the C API's view controller, if any. + FlutterDesktopViewControllerRef controller_ = nullptr; + + // The backing engine + std::shared_ptr engine_; + + // The owned FlutterView. + std::unique_ptr view_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_VIEW_CONTROLLER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/plugin_registrar_windows.h b/flutter/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/plugin_registrar_windows.h new file mode 100644 index 0000000000000000000000000000000000000000..7655b31ff04a8e95e77f562065b8d9b1a8ed28d6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/plugin_registrar_windows.h @@ -0,0 +1,151 @@ +// 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_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRAR_WINDOWS_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRAR_WINDOWS_H_ + +#include +#include + +#include +#include + +#include "flutter_view.h" +#include "plugin_registrar.h" + +namespace flutter { + +// A delegate callback for WindowProc delegation. +// +// Implementations should return a value only if they have handled the message +// and want to stop all further handling. +using WindowProcDelegate = std::function(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)>; + +// An extension to PluginRegistrar providing access to Windows-specific +// functionality. +class PluginRegistrarWindows : public PluginRegistrar { + public: + // Creates a new PluginRegistrar. |core_registrar| and the messenger it + // provides must remain valid as long as this object exists. + explicit PluginRegistrarWindows( + FlutterDesktopPluginRegistrarRef core_registrar) + : PluginRegistrar(core_registrar) { + FlutterDesktopViewRef implicit_view = + FlutterDesktopPluginRegistrarGetView(core_registrar); + if (implicit_view) { + implicit_view_ = std::make_unique(implicit_view); + } + } + + virtual ~PluginRegistrarWindows() { + // Must be the first call. + ClearPlugins(); + // Explicitly cleared to facilitate destruction order testing. + implicit_view_.reset(); + } + + // Prevent copying. + PluginRegistrarWindows(PluginRegistrarWindows const&) = delete; + PluginRegistrarWindows& operator=(PluginRegistrarWindows const&) = delete; + + // Returns the implicit view, or nullptr if there is no implicit view. + // + // See: + // https://api.flutter.dev/flutter/dart-ui/PlatformDispatcher/implicitView.html + // + // DEPRECATED: Use |GetViewById| instead. + FlutterView* GetView() { return implicit_view_.get(); } + + // Returns the view with the given ID, or nullptr if the view does not exist. + // + // Destroying the shared pointer destroys the reference to the view; it does + // not destroy the underlying view. + std::shared_ptr GetViewById(FlutterViewId view_id) const { + FlutterDesktopViewRef view = + FlutterDesktopPluginRegistrarGetViewById(registrar(), view_id); + if (!view) { + return nullptr; + } + + return std::make_shared(view); + } + + // Registers |delegate| to receive WindowProc callbacks for the top-level + // window containing this Flutter instance. Returns an ID that can be used to + // unregister the handler. + // + // Delegates are not guaranteed to be called: + // - The application may choose not to delegate WindowProc calls. + // - If multiple plugins are registered, the first one that returns a value + // from the delegate message will "win", and others will not be called. + // The order of delegate calls is not defined. + // + // Delegates should be implemented as narrowly as possible, only returning + // a value in cases where it's important that other delegates not run, to + // minimize the chances of conflicts between plugins. + int RegisterTopLevelWindowProcDelegate(WindowProcDelegate delegate) { + if (window_proc_delegates_.empty()) { + FlutterDesktopPluginRegistrarRegisterTopLevelWindowProcDelegate( + registrar(), PluginRegistrarWindows::OnTopLevelWindowProc, this); + } + int delegate_id = next_window_proc_delegate_id_++; + window_proc_delegates_.emplace(delegate_id, std::move(delegate)); + return delegate_id; + } + + // Unregisters a previously registered delegate. + void UnregisterTopLevelWindowProcDelegate(int proc_id) { + window_proc_delegates_.erase(proc_id); + if (window_proc_delegates_.empty()) { + FlutterDesktopPluginRegistrarUnregisterTopLevelWindowProcDelegate( + registrar(), PluginRegistrarWindows::OnTopLevelWindowProc); + } + } + + private: + // A FlutterDesktopWindowProcCallback implementation that forwards back to + // a PluginRegistarWindows instance provided as |user_data|. + static bool OnTopLevelWindowProc(HWND hwnd, + UINT message, + WPARAM wparam, + LPARAM lparam, + void* user_data, + LRESULT* result) { + const auto* registrar = static_cast(user_data); + std::optional optional_result = registrar->CallTopLevelWindowProcDelegates( + hwnd, message, wparam, lparam); + if (optional_result) { + *result = *optional_result; + } + return optional_result.has_value(); + } + + std::optional CallTopLevelWindowProcDelegates(HWND hwnd, + UINT message, + WPARAM wparam, + LPARAM lparam) const { + std::optional result; + for (const auto& pair : window_proc_delegates_) { + result = pair.second(hwnd, message, wparam, lparam); + // Stop as soon as any delegate indicates that it has handled the message. + if (result) { + break; + } + } + return result; + } + + // The associated FlutterView, if any. + std::unique_ptr implicit_view_; + + // The next ID to return from RegisterWindowProcDelegate. + int next_window_proc_delegate_id_ = 1; + + std::map window_proc_delegates_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRAR_WINDOWS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/client_wrapper/testing/stub_flutter_windows_api.cc b/flutter/engine/src/flutter/shell/platform/windows/client_wrapper/testing/stub_flutter_windows_api.cc new file mode 100644 index 0000000000000000000000000000000000000000..f51d7f14ad879113259f23a42cfb8dd1f06e95ed --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/client_wrapper/testing/stub_flutter_windows_api.cc @@ -0,0 +1,230 @@ +// 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/shell/platform/windows/client_wrapper/testing/stub_flutter_windows_api.h" + +static flutter::testing::StubFlutterWindowsApi* s_stub_implementation; + +namespace flutter { +namespace testing { + +// static +void StubFlutterWindowsApi::SetTestStub(StubFlutterWindowsApi* stub) { + s_stub_implementation = stub; +} + +// static +StubFlutterWindowsApi* StubFlutterWindowsApi::GetTestStub() { + return s_stub_implementation; +} + +ScopedStubFlutterWindowsApi::ScopedStubFlutterWindowsApi( + std::unique_ptr stub) + : stub_(std::move(stub)) { + previous_stub_ = StubFlutterWindowsApi::GetTestStub(); + StubFlutterWindowsApi::SetTestStub(stub_.get()); +} + +ScopedStubFlutterWindowsApi::~ScopedStubFlutterWindowsApi() { + StubFlutterWindowsApi::SetTestStub(previous_stub_); +} + +} // namespace testing +} // namespace flutter + +// Forwarding dummy implementations of the C API. + +FlutterDesktopViewControllerRef FlutterDesktopViewControllerCreate( + int width, + int height, + FlutterDesktopEngineRef engine) { + if (s_stub_implementation) { + return s_stub_implementation->ViewControllerCreate(width, height, engine); + } + return nullptr; +} + +void FlutterDesktopViewControllerDestroy( + FlutterDesktopViewControllerRef controller) { + if (s_stub_implementation) { + s_stub_implementation->ViewControllerDestroy(); + } +} + +FlutterDesktopViewId FlutterDesktopViewControllerGetViewId( + FlutterDesktopViewControllerRef controller) { + // The stub ignores this, so just return an arbitrary non-zero value. + return static_cast(1); +} + +FlutterDesktopEngineRef FlutterDesktopViewControllerGetEngine( + FlutterDesktopViewControllerRef controller) { + // The stub ignores this, so just return an arbitrary non-zero value. + return reinterpret_cast(1); +} + +FlutterDesktopViewRef FlutterDesktopViewControllerGetView( + FlutterDesktopViewControllerRef controller) { + // The stub ignores this, so just return an arbitrary non-zero value. + return reinterpret_cast(1); +} + +void FlutterDesktopViewControllerForceRedraw( + FlutterDesktopViewControllerRef controller) { + if (s_stub_implementation) { + s_stub_implementation->ViewControllerForceRedraw(); + } +} + +bool FlutterDesktopViewControllerHandleTopLevelWindowProc( + FlutterDesktopViewControllerRef controller, + HWND hwnd, + UINT message, + WPARAM wparam, + LPARAM lparam, + LRESULT* result) { + if (s_stub_implementation) { + return s_stub_implementation->ViewControllerHandleTopLevelWindowProc( + hwnd, message, wparam, lparam, result); + } + return false; +} + +FlutterDesktopEngineRef FlutterDesktopEngineCreate( + const FlutterDesktopEngineProperties* engine_properties) { + if (s_stub_implementation) { + return s_stub_implementation->EngineCreate(*engine_properties); + } + return nullptr; +} + +bool FlutterDesktopEngineDestroy(FlutterDesktopEngineRef engine_ref) { + if (s_stub_implementation) { + return s_stub_implementation->EngineDestroy(); + } + return true; +} + +bool FlutterDesktopEngineRun(FlutterDesktopEngineRef engine, + const char* entry_point) { + if (s_stub_implementation) { + return s_stub_implementation->EngineRun(entry_point); + } + return true; +} + +uint64_t FlutterDesktopEngineProcessMessages(FlutterDesktopEngineRef engine) { + if (s_stub_implementation) { + return s_stub_implementation->EngineProcessMessages(); + } + return 0; +} + +void FlutterDesktopEngineSetNextFrameCallback(FlutterDesktopEngineRef engine, + VoidCallback callback, + void* user_data) { + if (s_stub_implementation) { + s_stub_implementation->EngineSetNextFrameCallback(callback, user_data); + } +} + +void FlutterDesktopEngineReloadSystemFonts(FlutterDesktopEngineRef engine) { + if (s_stub_implementation) { + s_stub_implementation->EngineReloadSystemFonts(); + } +} + +FlutterDesktopPluginRegistrarRef FlutterDesktopEngineGetPluginRegistrar( + FlutterDesktopEngineRef engine, + const char* plugin_name) { + // The stub ignores this, so just return an arbitrary non-zero value. + return reinterpret_cast(1); +} + +FlutterDesktopMessengerRef FlutterDesktopEngineGetMessenger( + FlutterDesktopEngineRef engine) { + // The stub ignores this, so just return an arbitrary non-zero value. + return reinterpret_cast(2); +} + +FlutterDesktopTextureRegistrarRef FlutterDesktopEngineGetTextureRegistrar( + FlutterDesktopEngineRef engine) { + // The stub ignores this, so just return an arbitrary non-zero value. + return reinterpret_cast(3); +} + +HWND FlutterDesktopViewGetHWND(FlutterDesktopViewRef controller) { + if (s_stub_implementation) { + return s_stub_implementation->ViewGetHWND(); + } + return reinterpret_cast(-1); +} + +IDXGIAdapter* FlutterDesktopViewGetGraphicsAdapter(FlutterDesktopViewRef view) { + if (s_stub_implementation) { + return s_stub_implementation->ViewGetGraphicsAdapter(); + } + return nullptr; +} + +bool FlutterDesktopEngineProcessExternalWindowMessage( + FlutterDesktopEngineRef engine, + HWND hwnd, + UINT message, + WPARAM wparam, + LPARAM lparam, + LRESULT* result) { + if (s_stub_implementation) { + return s_stub_implementation->EngineProcessExternalWindowMessage( + engine, hwnd, message, wparam, lparam, result); + } + return false; +} + +void FlutterDesktopEngineRegisterPlatformViewType( + FlutterDesktopEngineRef engine, + const char* view_type_name, + FlutterPlatformViewTypeEntry view_type) { + if (s_stub_implementation) { + s_stub_implementation->EngineRegisterPlatformViewType(view_type_name, + view_type); + } +} + +FlutterDesktopViewRef FlutterDesktopPluginRegistrarGetView( + FlutterDesktopPluginRegistrarRef controller) { + if (s_stub_implementation) { + return s_stub_implementation->PluginRegistrarGetView(); + } + return nullptr; +} + +FlutterDesktopViewRef FlutterDesktopPluginRegistrarGetViewById( + FlutterDesktopPluginRegistrarRef controller, + FlutterDesktopViewId view_id) { + if (s_stub_implementation) { + return s_stub_implementation->PluginRegistrarGetViewById(view_id); + } + return nullptr; +} + +void FlutterDesktopPluginRegistrarRegisterTopLevelWindowProcDelegate( + FlutterDesktopPluginRegistrarRef registrar, + FlutterDesktopWindowProcCallback delegate, + void* user_data) { + if (s_stub_implementation) { + return s_stub_implementation + ->PluginRegistrarRegisterTopLevelWindowProcDelegate(delegate, + user_data); + } +} + +void FlutterDesktopPluginRegistrarUnregisterTopLevelWindowProcDelegate( + FlutterDesktopPluginRegistrarRef registrar, + FlutterDesktopWindowProcCallback delegate) { + if (s_stub_implementation) { + return s_stub_implementation + ->PluginRegistrarUnregisterTopLevelWindowProcDelegate(delegate); + } +} diff --git a/flutter/engine/src/flutter/shell/platform/windows/client_wrapper/testing/stub_flutter_windows_api.h b/flutter/engine/src/flutter/shell/platform/windows/client_wrapper/testing/stub_flutter_windows_api.h new file mode 100644 index 0000000000000000000000000000000000000000..8f3eb0905ac7ac0da46f3f19142652d46fb6628e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/client_wrapper/testing/stub_flutter_windows_api.h @@ -0,0 +1,141 @@ +// 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_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_TESTING_STUB_FLUTTER_WINDOWS_API_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_TESTING_STUB_FLUTTER_WINDOWS_API_H_ + +#include + +#include "flutter/shell/platform/windows/flutter_windows_internal.h" +#include "flutter/shell/platform/windows/public/flutter_windows.h" + +namespace flutter { +namespace testing { + +// Base class for a object that provides test implementations of the APIs in +// the headers in platform/windows/public/. + +// Linking this class into a test binary will provide dummy forwarding +// implementations of that C API, so that the wrapper can be tested separately +// from the actual library. +class StubFlutterWindowsApi { + public: + // Sets |stub| as the instance to which calls to the Flutter library C APIs + // will be forwarded. + static void SetTestStub(StubFlutterWindowsApi* stub); + + // Returns the current stub, as last set by SetTestFlutterStub. + static StubFlutterWindowsApi* GetTestStub(); + + virtual ~StubFlutterWindowsApi() {} + + // Called for FlutterDesktopViewControllerCreate. + virtual FlutterDesktopViewControllerRef + ViewControllerCreate(int width, int height, FlutterDesktopEngineRef engine) { + return nullptr; + } + + // Called for FlutterDesktopViewControllerDestroy. + virtual void ViewControllerDestroy() {} + + // Called for FlutterDesktopViewControllerForceRedraw. + virtual void ViewControllerForceRedraw() {} + + // Called for FlutterDesktopViewControllerHandleTopLevelWindowProc. + virtual bool ViewControllerHandleTopLevelWindowProc(HWND hwnd, + UINT message, + WPARAM wparam, + LPARAM lparam, + LRESULT* result) { + return false; + } + + // Called for FlutterDesktopEngineCreate. + virtual FlutterDesktopEngineRef EngineCreate( + const FlutterDesktopEngineProperties& engine_properties) { + return nullptr; + } + + // Called for FlutterDesktopEngineDestroy. + virtual bool EngineDestroy() { return true; } + + // Called for FlutterDesktopEngineRun. + virtual bool EngineRun(const char* entry_point) { return true; } + + // Called for FlutterDesktopEngineProcessMessages. + virtual uint64_t EngineProcessMessages() { return 0; } + + // Called for FlutterDesktopEngineSetNextFrameCallback. + virtual void EngineSetNextFrameCallback(VoidCallback callback, + void* user_data) {} + + // Called for FlutterDesktopEngineReloadSystemFonts. + virtual void EngineReloadSystemFonts() {} + + // Called for FlutterDesktopEngineRegisterPlatformViewType. + virtual void EngineRegisterPlatformViewType( + const char* view_type_name, + FlutterPlatformViewTypeEntry view_type) {} + + // Called for FlutterDesktopViewGetHWND. + virtual HWND ViewGetHWND() { return reinterpret_cast(1); } + + // Called for FlutterDesktopViewGetGraphicsAdapter. + virtual IDXGIAdapter* ViewGetGraphicsAdapter() { + return reinterpret_cast(2); + } + + // Called for FlutterDesktopPluginRegistrarGetView. + virtual FlutterDesktopViewRef PluginRegistrarGetView() { return nullptr; } + + // Called for FlutterDesktopPluginRegistrarGetViewById. + virtual FlutterDesktopViewRef PluginRegistrarGetViewById( + FlutterDesktopViewId view_id) { + return nullptr; + } + + // Called for FlutterDesktopPluginRegistrarRegisterTopLevelWindowProcDelegate. + virtual void PluginRegistrarRegisterTopLevelWindowProcDelegate( + FlutterDesktopWindowProcCallback delegate, + void* user_data) {} + + // Called for + // FlutterDesktopPluginRegistrarUnregisterTopLevelWindowProcDelegate. + virtual void PluginRegistrarUnregisterTopLevelWindowProcDelegate( + FlutterDesktopWindowProcCallback delegate) {} + + // Called for FlutterDesktopEngineProcessExternalWindowMessage. + virtual bool EngineProcessExternalWindowMessage( + FlutterDesktopEngineRef engine, + HWND hwnd, + UINT message, + WPARAM wparam, + LPARAM lparam, + LRESULT* result) { + return false; + } +}; + +// A test helper that owns a stub implementation, making it the test stub for +// the lifetime of the object, then restoring the previous value. +class ScopedStubFlutterWindowsApi { + public: + // Calls SetTestFlutterStub with |stub|. + ScopedStubFlutterWindowsApi(std::unique_ptr stub); + + // Restores the previous test stub. + ~ScopedStubFlutterWindowsApi(); + + StubFlutterWindowsApi* stub() { return stub_.get(); } + + private: + std::unique_ptr stub_; + // The previous stub. + StubFlutterWindowsApi* previous_stub_; +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_TESTING_STUB_FLUTTER_WINDOWS_API_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/egl/context.h b/flutter/engine/src/flutter/shell/platform/windows/egl/context.h new file mode 100644 index 0000000000000000000000000000000000000000..acbff12a8d14044a9e600561995e36e022a5c99d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/egl/context.h @@ -0,0 +1,51 @@ +// 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_SHELL_PLATFORM_WINDOWS_EGL_CONTEXT_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_CONTEXT_H_ + +#include + +#include "flutter/fml/macros.h" + +namespace flutter { +namespace egl { + +// An EGL context to interact with OpenGL. +// +// This enables automatic error logging and mocking. +// +// Flutter Windows uses this to create render and resource contexts. +class Context { + public: + Context(EGLDisplay display, EGLContext context); + ~Context(); + + // Check if this context is currently bound to the thread. + virtual bool IsCurrent() const; + + // Bind the context to the thread without any read or draw surfaces. + // + // Returns true on success. + virtual bool MakeCurrent() const; + + // Unbind any context and surfaces from the thread. + // + // Returns true on success. + virtual bool ClearCurrent() const; + + // Get the raw EGL context. + virtual const EGLContext& GetHandle() const; + + private: + EGLDisplay display_ = EGL_NO_DISPLAY; + EGLContext context_ = EGL_NO_CONTEXT; + + FML_DISALLOW_COPY_AND_ASSIGN(Context); +}; + +} // namespace egl +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_CONTEXT_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/egl/egl.cc b/flutter/engine/src/flutter/shell/platform/windows/egl/egl.cc new file mode 100644 index 0000000000000000000000000000000000000000..85af46f6858a3050036d7225327184cb0b319c58 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/egl/egl.cc @@ -0,0 +1,68 @@ +// 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/shell/platform/windows/egl/egl.h" + +#include + +#include "flutter/fml/logging.h" + +namespace flutter { +namespace egl { + +namespace { + +const char* EGLErrorToString(EGLint error) { + switch (error) { + case EGL_SUCCESS: + return "Success"; + case EGL_NOT_INITIALIZED: + return "Not Initialized"; + case EGL_BAD_ACCESS: + return "Bad Access"; + case EGL_BAD_ALLOC: + return "Bad Alloc"; + case EGL_BAD_ATTRIBUTE: + return "Bad Attribute"; + case EGL_BAD_CONTEXT: + return "Bad Context"; + case EGL_BAD_CONFIG: + return "Bad Config"; + case EGL_BAD_CURRENT_SURFACE: + return "Bad Current Surface"; + case EGL_BAD_DISPLAY: + return "Bad Display"; + case EGL_BAD_SURFACE: + return "Bad Surface"; + case EGL_BAD_MATCH: + return "Bad Match"; + case EGL_BAD_PARAMETER: + return "Bad Parameter"; + case EGL_BAD_NATIVE_PIXMAP: + return "Bad Native Pixmap"; + case EGL_BAD_NATIVE_WINDOW: + return "Bad Native Window"; + case EGL_CONTEXT_LOST: + return "Context Lost"; + } + FML_UNREACHABLE(); + return "Unknown"; +} + +} // namespace + +void LogEGLError(std::string_view message) { + const EGLint error = ::eglGetError(); + return FML_LOG(ERROR) << "EGL Error: " << EGLErrorToString(error) << " (" + << error << ") " << message; +} + +void LogEGLError(std::string_view file, int line) { + std::stringstream stream; + stream << "in " << file << ":" << line; + LogEGLError(stream.str()); +} + +} // namespace egl +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/windows/egl/egl.h b/flutter/engine/src/flutter/shell/platform/windows/egl/egl.h new file mode 100644 index 0000000000000000000000000000000000000000..a0c81a2993c9a2c4d4fed68d5dea50b68c5a0fa1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/egl/egl.h @@ -0,0 +1,24 @@ +// 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_SHELL_PLATFORM_WINDOWS_EGL_EGL_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_EGL_H_ + +#include + +namespace flutter { +namespace egl { + +/// Log the last EGL error with an error message. +void LogEGLError(std::string_view message); + +/// Log the last EGL error. +void LogEGLError(std::string_view file, int line); + +#define WINDOWS_LOG_EGL_ERROR LogEGLError(__FILE__, __LINE__); + +} // namespace egl +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_EGL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/egl/manager.cc b/flutter/engine/src/flutter/shell/platform/windows/egl/manager.cc new file mode 100644 index 0000000000000000000000000000000000000000..7584fad1e915f4766cb933b8ecbb67229f6b978d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/egl/manager.cc @@ -0,0 +1,365 @@ +// 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/shell/platform/windows/egl/manager.h" + +#include + +#include "flutter/fml/logging.h" +#include "flutter/shell/platform/windows/egl/egl.h" + +namespace flutter { +namespace egl { + +int Manager::instance_count_ = 0; + +std::unique_ptr Manager::Create(GpuPreference gpu_preference) { + std::unique_ptr manager; + manager.reset(new Manager(gpu_preference)); + if (!manager->IsValid()) { + return nullptr; + } + return std::move(manager); +} + +Manager::Manager(GpuPreference gpu_preference) { + ++instance_count_; + + if (!InitializeDisplay(gpu_preference)) { + return; + } + + if (!InitializeConfig()) { + return; + } + + if (!InitializeContexts()) { + return; + } + + is_valid_ = true; +} + +Manager::~Manager() { + CleanUp(); + --instance_count_; +} + +bool Manager::InitializeDisplay(GpuPreference gpu_preference) { + // If the request for a low power GPU is provided, + // we will attempt to select GPU explicitly, via ANGLE extension + // that allows to specify the GPU to use via LUID. + std::optional luid = std::nullopt; + if (gpu_preference == GpuPreference::LowPowerPreference) { + luid = GetLowPowerGpuLuid(); + } + + // These are preferred display attributes and request ANGLE's D3D11 + // renderer (use only in case of valid LUID returned from above). + const EGLint d3d11_display_attributes_with_luid[] = { + EGL_PLATFORM_ANGLE_TYPE_ANGLE, + EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE, + + // EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE is an option that will + // enable ANGLE to automatically call the IDXGIDevice3::Trim method on + // behalf of the application when it gets suspended. + EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE, + EGL_TRUE, + + // This extension allows angle to render directly on a D3D swapchain + // in the correct orientation on D3D11. + EGL_EXPERIMENTAL_PRESENT_PATH_ANGLE, + EGL_EXPERIMENTAL_PRESENT_PATH_FAST_ANGLE, + + // Specify the LUID of the GPU to use. + EGL_PLATFORM_ANGLE_D3D_LUID_HIGH_ANGLE, + static_cast(luid.has_value() ? luid->HighPart : 0), + EGL_PLATFORM_ANGLE_D3D_LUID_LOW_ANGLE, + static_cast(luid.has_value() ? luid->LowPart : 0), + EGL_NONE, + }; + + // These are preferred display attributes and request ANGLE's D3D11 + // renderer. eglInitialize will only succeed with these attributes if the + // hardware supports D3D11 Feature Level 10_0+. + const EGLint d3d11_display_attributes[] = { + EGL_PLATFORM_ANGLE_TYPE_ANGLE, + EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE, + + // EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE is an option that will + // enable ANGLE to automatically call the IDXGIDevice3::Trim method on + // behalf of the application when it gets suspended. + EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE, + EGL_TRUE, + + // This extension allows angle to render directly on a D3D swapchain + // in the correct orientation on D3D11. + EGL_EXPERIMENTAL_PRESENT_PATH_ANGLE, + EGL_EXPERIMENTAL_PRESENT_PATH_FAST_ANGLE, + + EGL_NONE, + }; + + // These are used to request ANGLE's D3D11 renderer, with D3D11 Feature + // Level 9_3. + const EGLint d3d11_fl_9_3_display_attributes[] = { + EGL_PLATFORM_ANGLE_TYPE_ANGLE, + EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE, + EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE, + 9, + EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE, + 3, + EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE, + EGL_TRUE, + EGL_NONE, + }; + + // These attributes request D3D11 WARP (software rendering fallback) in case + // hardware-backed D3D11 is unavailable. + const EGLint d3d11_warp_display_attributes[] = { + EGL_PLATFORM_ANGLE_TYPE_ANGLE, + EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE, + EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE, + EGL_TRUE, + EGL_NONE, + }; + + std::vector display_attributes_configs; + + if (luid) { + // If LUID value is present, obtain an adapter with that luid. + display_attributes_configs.push_back(d3d11_display_attributes_with_luid); + } + display_attributes_configs.push_back(d3d11_display_attributes); + display_attributes_configs.push_back(d3d11_fl_9_3_display_attributes); + display_attributes_configs.push_back(d3d11_warp_display_attributes); + + PFNEGLGETPLATFORMDISPLAYEXTPROC egl_get_platform_display_EXT = + reinterpret_cast( + ::eglGetProcAddress("eglGetPlatformDisplayEXT")); + if (!egl_get_platform_display_EXT) { + LogEGLError("eglGetPlatformDisplayEXT not available"); + return false; + } + + // Attempt to initialize ANGLE's renderer in order of: D3D11, D3D11 Feature + // Level 9_3 and finally D3D11 WARP. + for (auto config : display_attributes_configs) { + bool is_last = (config == display_attributes_configs.back()); + + display_ = egl_get_platform_display_EXT(EGL_PLATFORM_ANGLE_ANGLE, + EGL_DEFAULT_DISPLAY, config); + + if (display_ == EGL_NO_DISPLAY) { + if (is_last) { + LogEGLError("Failed to get a compatible EGLdisplay"); + return false; + } + + // Try the next config. + continue; + } + + if (::eglInitialize(display_, nullptr, nullptr) == EGL_FALSE) { + if (is_last) { + LogEGLError("Failed to initialize EGL via ANGLE"); + return false; + } + + // Try the next config. + continue; + } + + return true; + } + + FML_UNREACHABLE(); +} + +bool Manager::InitializeConfig() { + const EGLint config_attributes[] = {EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, + EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, + EGL_DEPTH_SIZE, 8, EGL_STENCIL_SIZE, 8, + EGL_NONE}; + + EGLint num_config = 0; + + EGLBoolean result = + ::eglChooseConfig(display_, config_attributes, &config_, 1, &num_config); + + if (result == EGL_TRUE && num_config > 0) { + return true; + } + + LogEGLError("Failed to choose EGL config"); + return false; +} + +bool Manager::InitializeContexts() { + const EGLint context_attributes[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE}; + + auto const render_context = + ::eglCreateContext(display_, config_, EGL_NO_CONTEXT, context_attributes); + if (render_context == EGL_NO_CONTEXT) { + LogEGLError("Failed to create EGL render context"); + return false; + } + + auto const resource_context = + ::eglCreateContext(display_, config_, render_context, context_attributes); + if (resource_context == EGL_NO_CONTEXT) { + LogEGLError("Failed to create EGL resource context"); + return false; + } + + render_context_ = std::make_unique(display_, render_context); + resource_context_ = std::make_unique(display_, resource_context); + return true; +} + +bool Manager::InitializeDevice() { + const auto query_display_attrib_EXT = + reinterpret_cast( + ::eglGetProcAddress("eglQueryDisplayAttribEXT")); + const auto query_device_attrib_EXT = + reinterpret_cast( + ::eglGetProcAddress("eglQueryDeviceAttribEXT")); + + if (query_display_attrib_EXT == nullptr || + query_device_attrib_EXT == nullptr) { + return false; + } + + EGLAttrib egl_device = 0; + EGLAttrib angle_device = 0; + + auto result = query_display_attrib_EXT(display_, EGL_DEVICE_EXT, &egl_device); + if (result != EGL_TRUE) { + return false; + } + + result = query_device_attrib_EXT(reinterpret_cast(egl_device), + EGL_D3D11_DEVICE_ANGLE, &angle_device); + if (result != EGL_TRUE) { + return false; + } + + resolved_device_ = reinterpret_cast(angle_device); + return true; +} + +void Manager::CleanUp() { + EGLBoolean result = EGL_FALSE; + + // Needs to be reset before destroying the contexts. + resolved_device_.Reset(); + + // Needs to be reset before destroying the EGLDisplay. + render_context_.reset(); + resource_context_.reset(); + + if (display_ != EGL_NO_DISPLAY) { + // Display is reused between instances so only terminate display + // if destroying last instance + if (instance_count_ == 1) { + ::eglTerminate(display_); + } + display_ = EGL_NO_DISPLAY; + } +} + +bool Manager::IsValid() const { + return is_valid_; +} + +std::unique_ptr Manager::CreateWindowSurface(HWND hwnd, + size_t width, + size_t height) { + if (!hwnd || !is_valid_) { + return nullptr; + } + + // Disable ANGLE's automatic surface resizing and provide an explicit size. + // The surface will need to be destroyed and re-created if the HWND is + // resized. + const EGLint surface_attributes[] = {EGL_FIXED_SIZE_ANGLE, + EGL_TRUE, + EGL_WIDTH, + static_cast(width), + EGL_HEIGHT, + static_cast(height), + EGL_NONE}; + + auto const surface = ::eglCreateWindowSurface( + display_, config_, static_cast(hwnd), + surface_attributes); + if (surface == EGL_NO_SURFACE) { + LogEGLError("Surface creation failed."); + return nullptr; + } + + return std::make_unique(display_, render_context_->GetHandle(), + surface, width, height); +} + +bool Manager::HasContextCurrent() { + return ::eglGetCurrentContext() != EGL_NO_CONTEXT; +} + +EGLSurface Manager::CreateSurfaceFromHandle(EGLenum handle_type, + EGLClientBuffer handle, + const EGLint* attributes) const { + return ::eglCreatePbufferFromClientBuffer(display_, handle_type, handle, + config_, attributes); +} + +bool Manager::GetDevice(ID3D11Device** device) { + if (!resolved_device_) { + if (!InitializeDevice()) { + return false; + } + } + + resolved_device_.CopyTo(device); + return (resolved_device_ != nullptr); +} + +Context* Manager::render_context() const { + return render_context_.get(); +} + +Context* Manager::resource_context() const { + return resource_context_.get(); +} + +std::optional Manager::GetLowPowerGpuLuid() { + Microsoft::WRL::ComPtr factory1 = nullptr; + Microsoft::WRL::ComPtr factory6 = nullptr; + Microsoft::WRL::ComPtr adapter = nullptr; + HRESULT hr = ::CreateDXGIFactory1(IID_PPV_ARGS(&factory1)); + if (FAILED(hr)) { + return std::nullopt; + } + hr = factory1->QueryInterface(IID_PPV_ARGS(&factory6)); + if (FAILED(hr)) { + // No support for IDXGIFactory6, so we will not use the selected GPU. + // We will follow with the default ANGLE selection. + return std::nullopt; + } + hr = factory6->EnumAdapterByGpuPreference( + 0, DXGI_GPU_PREFERENCE_MINIMUM_POWER, IID_PPV_ARGS(&adapter)); + if (FAILED(hr) || adapter == nullptr) { + return std::nullopt; + } + // Get the LUID of the adapter. + DXGI_ADAPTER_DESC desc; + hr = adapter->GetDesc(&desc); + if (FAILED(hr)) { + return std::nullopt; + } + return std::make_optional(desc.AdapterLuid); +} + +} // namespace egl +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/windows/egl/manager.h b/flutter/engine/src/flutter/shell/platform/windows/egl/manager.h new file mode 100644 index 0000000000000000000000000000000000000000..f0ef9106a28f1ac6f8517ac36e9247e97353350e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/egl/manager.h @@ -0,0 +1,131 @@ +// 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_SHELL_PLATFORM_WINDOWS_EGL_MANAGER_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_MANAGER_H_ + +// OpenGL ES and EGL includes +#include +#include +#include +#include +#include + +// Windows platform specific includes +#include +#include +#include +#include +#include +#include +#include + +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/windows/egl/context.h" +#include "flutter/shell/platform/windows/egl/surface.h" +#include "flutter/shell/platform/windows/egl/window_surface.h" + +namespace flutter { +namespace egl { + +enum class GpuPreference { + NoPreference, + LowPowerPreference, +}; + +// A manager for initializing ANGLE correctly and using it to create and +// destroy surfaces +class Manager { + public: + static std::unique_ptr Create(GpuPreference gpu_preference); + + virtual ~Manager(); + + // Whether the manager is currently valid. + bool IsValid() const; + + // Creates an EGL surface that can be used to render a Flutter view into a + // win32 HWND. + // + // After the surface is created, |WindowSurface::SetVSyncEnabled| should be + // called on a thread that can make the surface current. + // + // HWND is the window backing the surface. Width and height are the surface's + // physical pixel dimensions. + // + // Returns nullptr on failure. + virtual std::unique_ptr CreateWindowSurface(HWND hwnd, + size_t width, + size_t height); + + // Check if the current thread has a context bound. + bool HasContextCurrent(); + + // Creates a |EGLSurface| from the provided handle. + EGLSurface CreateSurfaceFromHandle(EGLenum handle_type, + EGLClientBuffer handle, + const EGLint* attributes) const; + + // Gets the |EGLDisplay|. + EGLDisplay egl_display() const { return display_; }; + + // Gets the |ID3D11Device| chosen by ANGLE. + bool GetDevice(ID3D11Device** device); + + // Get the EGL context used to render Flutter views. + virtual Context* render_context() const; + + // Get the EGL context used for async texture uploads. + virtual Context* resource_context() const; + + static std::optional GetLowPowerGpuLuid(); + + protected: + // Creates a new surface manager retaining reference to the passed-in target + // for the lifetime of the manager. + explicit Manager(GpuPreference gpu_preference); + + private: + // Number of active instances of Manager + static int instance_count_; + + // Initialize the EGL display. + bool InitializeDisplay(GpuPreference gpu_preference); + + // Initialize the EGL configs. + bool InitializeConfig(); + + // Initialize the EGL render and resource contexts. + bool InitializeContexts(); + + // Initialize the D3D11 device. + bool InitializeDevice(); + + void CleanUp(); + + // Whether the manager was initialized successfully. + bool is_valid_ = false; + + // EGL representation of native display. + EGLDisplay display_ = EGL_NO_DISPLAY; + + // EGL framebuffer configuration. + EGLConfig config_ = nullptr; + + // The EGL context used to render Flutter views. + std::unique_ptr render_context_; + + // The EGL context used for async texture uploads. + std::unique_ptr resource_context_; + + // The current D3D device. + Microsoft::WRL::ComPtr resolved_device_ = nullptr; + + FML_DISALLOW_COPY_AND_ASSIGN(Manager); +}; + +} // namespace egl +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_MANAGER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/egl/proc_table.cc b/flutter/engine/src/flutter/shell/platform/windows/egl/proc_table.cc new file mode 100644 index 0000000000000000000000000000000000000000..057b09bca25ab4dc088925002b6f44763fadd80a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/egl/proc_table.cc @@ -0,0 +1,68 @@ +// 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/shell/platform/windows/egl/proc_table.h" + +#include + +namespace flutter { +namespace egl { + +std::shared_ptr ProcTable::Create() { + auto gl = std::shared_ptr(new ProcTable()); + + gl->gen_textures_ = + reinterpret_cast(::eglGetProcAddress("glGenTextures")); + gl->delete_textures_ = reinterpret_cast( + ::eglGetProcAddress("glDeleteTextures")); + gl->bind_texture_ = + reinterpret_cast(::eglGetProcAddress("glBindTexture")); + gl->tex_parameteri_ = reinterpret_cast( + ::eglGetProcAddress("glTexParameteri")); + gl->tex_image_2d_ = + reinterpret_cast(::eglGetProcAddress("glTexImage2D")); + + if (!gl->gen_textures_ || !gl->delete_textures_ || !gl->bind_texture_ || + !gl->tex_parameteri_ || !gl->tex_image_2d_) { + return nullptr; + } + + return gl; +} + +ProcTable::ProcTable() = default; + +ProcTable::~ProcTable() = default; + +void ProcTable::GenTextures(GLsizei n, GLuint* textures) const { + gen_textures_(n, textures); +} + +void ProcTable::DeleteTextures(GLsizei n, const GLuint* textures) const { + delete_textures_(n, textures); +} + +void ProcTable::BindTexture(GLenum target, GLuint texture) const { + bind_texture_(target, texture); +} + +void ProcTable::TexParameteri(GLenum target, GLenum pname, GLint param) const { + tex_parameteri_(target, pname, param); +} + +void ProcTable::TexImage2D(GLenum target, + GLint level, + GLint internalformat, + GLsizei width, + GLsizei height, + GLint border, + GLenum format, + GLenum type, + const void* data) const { + tex_image_2d_(target, level, internalformat, width, height, border, format, + type, data); +} + +} // namespace egl +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/windows/egl/proc_table.h b/flutter/engine/src/flutter/shell/platform/windows/egl/proc_table.h new file mode 100644 index 0000000000000000000000000000000000000000..26a177a0e91caf4e557b31ed24914b2074bd54fd --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/egl/proc_table.h @@ -0,0 +1,72 @@ +// 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_SHELL_PLATFORM_WINDOWS_EGL_PROC_TABLE_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_PROC_TABLE_H_ + +#include +#include +#include +#include + +#include "flutter/fml/macros.h" + +namespace flutter { +namespace egl { + +// Lookup table for GLES functions. +class ProcTable { + public: + static std::shared_ptr Create(); + + virtual ~ProcTable(); + + virtual void GenTextures(GLsizei n, GLuint* textures) const; + virtual void DeleteTextures(GLsizei n, const GLuint* textures) const; + virtual void BindTexture(GLenum target, GLuint texture) const; + virtual void TexParameteri(GLenum target, GLenum pname, GLint param) const; + virtual void TexImage2D(GLenum target, + GLint level, + GLint internalformat, + GLsizei width, + GLsizei height, + GLint border, + GLenum format, + GLenum type, + const void* data) const; + + protected: + ProcTable(); + + private: + using GenTexturesProc = void(__stdcall*)(GLsizei n, GLuint* textures); + using DeleteTexturesProc = void(__stdcall*)(GLsizei n, + const GLuint* textures); + using BindTextureProc = void(__stdcall*)(GLenum target, GLuint texture); + using TexParameteriProc = void(__stdcall*)(GLenum target, + GLenum pname, + GLint param); + using TexImage2DProc = void(__stdcall*)(GLenum target, + GLint level, + GLint internalformat, + GLsizei width, + GLsizei height, + GLint border, + GLenum format, + GLenum type, + const void* data); + + GenTexturesProc gen_textures_; + DeleteTexturesProc delete_textures_; + BindTextureProc bind_texture_; + TexParameteriProc tex_parameteri_; + TexImage2DProc tex_image_2d_; + + FML_DISALLOW_COPY_AND_ASSIGN(ProcTable); +}; + +} // namespace egl +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_PROC_TABLE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/egl/surface.cc b/flutter/engine/src/flutter/shell/platform/windows/egl/surface.cc new file mode 100644 index 0000000000000000000000000000000000000000..f6534a913a0edc0a7a2b1d39b43bb42717c4cb73 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/egl/surface.cc @@ -0,0 +1,73 @@ +// 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/shell/platform/windows/egl/surface.h" + +#include "flutter/shell/platform/windows/egl/egl.h" + +namespace flutter { +namespace egl { + +Surface::Surface(EGLDisplay display, EGLContext context, EGLSurface surface) + : display_(display), context_(context), surface_(surface) {} + +Surface::~Surface() { + Destroy(); +} + +bool Surface::IsValid() const { + return is_valid_; +} + +bool Surface::Destroy() { + if (surface_ != EGL_NO_SURFACE) { + // Ensure the surface is not current before destroying it. + if (::eglMakeCurrent(display_, EGL_NO_SURFACE, EGL_NO_SURFACE, + EGL_NO_CONTEXT) != EGL_TRUE) { + WINDOWS_LOG_EGL_ERROR; + return false; + } + + if (::eglDestroySurface(display_, surface_) != EGL_TRUE) { + WINDOWS_LOG_EGL_ERROR; + return false; + } + } + + is_valid_ = false; + surface_ = EGL_NO_SURFACE; + return true; +} + +bool Surface::IsCurrent() const { + return display_ == ::eglGetCurrentDisplay() && + surface_ == ::eglGetCurrentSurface(EGL_DRAW) && + surface_ == ::eglGetCurrentSurface(EGL_READ) && + context_ == ::eglGetCurrentContext(); +} + +bool Surface::MakeCurrent() const { + if (::eglMakeCurrent(display_, surface_, surface_, context_) != EGL_TRUE) { + WINDOWS_LOG_EGL_ERROR; + return false; + } + + return true; +} + +bool Surface::SwapBuffers() const { + if (::eglSwapBuffers(display_, surface_) != EGL_TRUE) { + WINDOWS_LOG_EGL_ERROR; + return false; + } + + return true; +} + +const EGLSurface& Surface::GetHandle() const { + return surface_; +} + +} // namespace egl +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/windows/egl/surface.h b/flutter/engine/src/flutter/shell/platform/windows/egl/surface.h new file mode 100644 index 0000000000000000000000000000000000000000..6f1b107bd6852aa845f7fcb20a7ff21137cf201b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/egl/surface.h @@ -0,0 +1,60 @@ +// 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_SHELL_PLATFORM_WINDOWS_EGL_SURFACE_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_SURFACE_H_ + +#include + +#include "flutter/fml/macros.h" + +namespace flutter { +namespace egl { + +// An EGL surface. This can be window surface or an off-screen buffer. +// +// This enables automatic error logging and mocking. +class Surface { + public: + Surface(EGLDisplay display, EGLContext context, EGLSurface surface); + + virtual ~Surface(); + + // Destroy the EGL surface and invalidate this object. + // + // This also unbinds the current context from the thread. + virtual bool Destroy(); + + // Check whether the EGL surface is valid. + virtual bool IsValid() const; + + // Check whether the EGL display, context, and surface are bound + // to the current thread. + virtual bool IsCurrent() const; + + // Bind the EGL surface's context and read and draw surfaces to the + // current thread. Returns true on success. + virtual bool MakeCurrent() const; + + // Swap the surface's front the and back buffers. Used to present content. + // Returns true on success. + virtual bool SwapBuffers() const; + + // Get the raw EGL surface. + virtual const EGLSurface& GetHandle() const; + + protected: + bool is_valid_ = true; + + EGLDisplay display_ = EGL_NO_DISPLAY; + EGLContext context_ = EGL_NO_CONTEXT; + EGLSurface surface_ = EGL_NO_SURFACE; + + FML_DISALLOW_COPY_AND_ASSIGN(Surface); +}; + +} // namespace egl +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_SURFACE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/egl/window_surface.cc b/flutter/engine/src/flutter/shell/platform/windows/egl/window_surface.cc new file mode 100644 index 0000000000000000000000000000000000000000..f688c2774a590aed3028d72785bbc53c01e20c72 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/egl/window_surface.cc @@ -0,0 +1,45 @@ +// 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/shell/platform/windows/egl/window_surface.h" + +#include "flutter/fml/logging.h" +#include "flutter/shell/platform/windows/egl/egl.h" + +namespace flutter { +namespace egl { + +WindowSurface::WindowSurface(EGLDisplay display, + EGLContext context, + EGLSurface surface, + size_t width, + size_t height) + : Surface(display, context, surface), width_(width), height_(height) {} + +bool WindowSurface::SetVSyncEnabled(bool enabled) { + FML_DCHECK(IsCurrent()); + + if (::eglSwapInterval(display_, enabled ? 1 : 0) != EGL_TRUE) { + WINDOWS_LOG_EGL_ERROR; + return false; + } + + vsync_enabled_ = enabled; + return true; +} + +size_t WindowSurface::width() const { + return width_; +} + +size_t WindowSurface::height() const { + return height_; +} + +bool WindowSurface::vsync_enabled() const { + return vsync_enabled_; +} + +} // namespace egl +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/windows/egl/window_surface.h b/flutter/engine/src/flutter/shell/platform/windows/egl/window_surface.h new file mode 100644 index 0000000000000000000000000000000000000000..658e476e4f98625ec23667dc2bd098b3a7b55546 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/egl/window_surface.h @@ -0,0 +1,55 @@ +// 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_SHELL_PLATFORM_WINDOWS_EGL_WINDOW_SURFACE_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_WINDOW_SURFACE_H_ + +#include + +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/windows/egl/surface.h" + +namespace flutter { +namespace egl { + +// An EGL surface used to render a Flutter view to a win32 HWND. +// +// This enables automatic error logging and mocking. +class WindowSurface : public Surface { + public: + WindowSurface(EGLDisplay display, + EGLContext context, + EGLSurface surface, + size_t width, + size_t height); + + // If enabled, makes the surface's buffer swaps block until the v-blank. + // + // If disabled, allows one thread to swap multiple buffers per v-blank + // but can result in screen tearing if the system compositor is disabled. + // + // The surface must be current before calling this. + virtual bool SetVSyncEnabled(bool enabled); + + // Get the surface's width in physical pixels. + virtual size_t width() const; + + // Get the surface's height in physical pixels. + virtual size_t height() const; + + // Get whether the surface's buffer swap blocks until the v-blank. + virtual bool vsync_enabled() const; + + private: + size_t width_ = 0; + size_t height_ = 0; + bool vsync_enabled_ = true; + + FML_DISALLOW_COPY_AND_ASSIGN(WindowSurface); +}; + +} // namespace egl +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_WINDOW_SURFACE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/fixtures/main.dart b/flutter/engine/src/flutter/shell/platform/windows/fixtures/main.dart new file mode 100644 index 0000000000000000000000000000000000000000..a9d341cee0539ffd7b78ed80b25560fc037f73cd --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/fixtures/main.dart @@ -0,0 +1,478 @@ +// 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. + +import 'dart:async'; +import 'dart:convert'; +import 'dart:io' as io; +import 'dart:typed_data' show ByteData, Float64List, Int32List, Uint8List; +import 'dart:ui' as ui; + +// Signals a waiting latch in the native test. +@pragma('vm:external-name', 'Signal') +external void signal(); + +// Signals a waiting latch in the native test, passing a boolean value. +@pragma('vm:external-name', 'SignalBoolValue') +external void signalBoolValue(bool value); + +// Signals a waiting latch in the native test, passing a string value. +@pragma('vm:external-name', 'SignalStringValue') +external void signalStringValue(String value); + +// Signals a waiting latch in the native test, which returns a value to the fixture. +@pragma('vm:external-name', 'SignalBoolReturn') +external bool signalBoolReturn(); + +// Notify the native test that the first frame has been scheduled. +@pragma('vm:external-name', 'NotifyFirstFrameScheduled') +external void notifyFirstFrameScheduled(); + +void main() {} + +@pragma('vm:entry-point') +void hiPlatformChannels() { + ui.channelBuffers.setListener('hi', ( + ByteData? data, + ui.PlatformMessageResponseCallback callback, + ) async { + ui.PlatformDispatcher.instance.sendPlatformMessage('hi', data, (ByteData? reply) { + ui.PlatformDispatcher.instance.sendPlatformMessage('hi', reply, (ByteData? reply) {}); + }); + callback(data); + }); +} + +/// Returns a future that completes when +/// `PlatformDispatcher.instance.onSemanticsEnabledChanged` fires. +Future get semanticsChanged { + final Completer semanticsChanged = Completer(); + ui.PlatformDispatcher.instance.onSemanticsEnabledChanged = semanticsChanged.complete; + return semanticsChanged.future; +} + +@pragma('vm:entry-point') +Future sendAccessibilityAnnouncement() async { + // Wait until semantics are enabled. + if (!ui.PlatformDispatcher.instance.semanticsEnabled) { + await semanticsChanged; + } + + // Standard message codec magic number identifiers. + // See: https://github.com/flutter/flutter/blob/ee94fe262b63b0761e8e1f889ae52322fef068d2/packages/flutter/lib/src/services/message_codecs.dart#L262 + const int valueMap = 13, valueString = 7; + + // Corresponds to: {"type": "announce", "data": {"message": "hello"}} + // See: https://github.com/flutter/flutter/blob/b781da9b5822de1461a769c3b245075359f5464d/packages/flutter/lib/src/semantics/semantics_event.dart#L86 + final Uint8List data = Uint8List.fromList([ + // Map with 2 entries + valueMap, 2, + // Map key: "type" + valueString, 'type'.length, ...'type'.codeUnits, + // Map value: "announce" + valueString, 'announce'.length, ...'announce'.codeUnits, + // Map key: "data" + valueString, 'data'.length, ...'data'.codeUnits, + // Map value: map with 1 entry + valueMap, 1, + // Map key: "message" + valueString, 'message'.length, ...'message'.codeUnits, + // Map value: "hello" + valueString, 'hello'.length, ...'hello'.codeUnits, + ]); + final ByteData byteData = data.buffer.asByteData(); + + ui.PlatformDispatcher.instance.sendPlatformMessage( + 'flutter/accessibility', + byteData, + (ByteData? _) => signal(), + ); +} + +@pragma('vm:entry-point') +Future sendAccessibilityTooltipEvent() async { + // Wait until semantics are enabled. + if (!ui.PlatformDispatcher.instance.semanticsEnabled) { + await semanticsChanged; + } + + // Standard message codec magic number identifiers. + // See: https://github.com/flutter/flutter/blob/ee94fe262b63b0761e8e1f889ae52322fef068d2/packages/flutter/lib/src/services/message_codecs.dart#L262 + const int valueMap = 13, valueString = 7; + + // Corresponds to: {"type": "tooltip", "data": {"message": "hello"}} + // See: https://github.com/flutter/flutter/blob/b781da9b5822de1461a769c3b245075359f5464d/packages/flutter/lib/src/semantics/semantics_event.dart#L120 + final Uint8List data = Uint8List.fromList([ + // Map with 2 entries + valueMap, 2, + // Map key: "type" + valueString, 'type'.length, ...'type'.codeUnits, + // Map value: "tooltip" + valueString, 'tooltip'.length, ...'tooltip'.codeUnits, + // Map key: "data" + valueString, 'data'.length, ...'data'.codeUnits, + // Map value: map with 1 entry + valueMap, 1, + // Map key: "message" + valueString, 'message'.length, ...'message'.codeUnits, + // Map value: "hello" + valueString, 'hello'.length, ...'hello'.codeUnits, + ]); + final ByteData byteData = data.buffer.asByteData(); + + ui.PlatformDispatcher.instance.sendPlatformMessage( + 'flutter/accessibility', + byteData, + (ByteData? _) => signal(), + ); +} + +@pragma('vm:entry-point') +Future exitTestExit() async { + final Completer closed = Completer(); + ui.channelBuffers.setListener('flutter/platform', ( + ByteData? data, + ui.PlatformMessageResponseCallback callback, + ) async { + final String jsonString = json.encode(>[ + {'response': 'exit'}, + ]); + final ByteData responseData = ByteData.sublistView(utf8.encode(jsonString)); + callback(responseData); + closed.complete(data); + }); + await closed.future; +} + +@pragma('vm:entry-point') +Future exitTestCancel() async { + final Completer closed = Completer(); + ui.channelBuffers.setListener('flutter/platform', ( + ByteData? data, + ui.PlatformMessageResponseCallback callback, + ) async { + final String jsonString = json.encode(>[ + {'response': 'cancel'}, + ]); + final ByteData responseData = ByteData.sublistView(utf8.encode(jsonString)); + callback(responseData); + closed.complete(data); + }); + await closed.future; + + // Because the request was canceled, the below shall execute. + final Completer exited = Completer(); + final String jsonString = json.encode({ + 'method': 'System.exitApplication', + 'args': {'type': 'required', 'exitCode': 0}, + }); + ui.PlatformDispatcher.instance.sendPlatformMessage( + 'flutter/platform', + ByteData.sublistView(utf8.encode(jsonString)), + (ByteData? reply) { + exited.complete(reply); + }, + ); + await exited.future; +} + +@pragma('vm:entry-point') +Future enableLifecycleTest() async { + final Completer finished = Completer(); + ui.channelBuffers.setListener('flutter/lifecycle', ( + ByteData? data, + ui.PlatformMessageResponseCallback callback, + ) async { + if (data != null) { + ui.PlatformDispatcher.instance.sendPlatformMessage('flutter/unittest', data, ( + ByteData? reply, + ) { + finished.complete(); + }); + } + }); + await finished.future; +} + +@pragma('vm:entry-point') +Future enableLifecycleToFrom() async { + ui.channelBuffers.setListener('flutter/lifecycle', ( + ByteData? data, + ui.PlatformMessageResponseCallback callback, + ) async { + if (data != null) { + ui.PlatformDispatcher.instance.sendPlatformMessage( + 'flutter/unittest', + data, + (ByteData? reply) {}, + ); + } + }); + final Completer enabledLifecycle = Completer(); + ui.PlatformDispatcher.instance.sendPlatformMessage( + 'flutter/platform', + ByteData.sublistView(utf8.encode('{"method":"System.initializationComplete"}')), + (ByteData? data) { + enabledLifecycle.complete(data); + }, + ); +} + +@pragma('vm:entry-point') +Future sendCreatePlatformViewMethod() async { + // The platform view method channel uses the standard method codec. + // See https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/services/message_codecs.dart#L262 + // for the implementation of the encoding and magic number identifiers. + const int valueString = 7; + const int valueMap = 13; + const int valueInt32 = 3; + const String method = 'create'; + const String typeKey = 'viewType'; + const String typeValue = 'type'; + const String idKey = 'id'; + final List data = [ + // Method name + valueString, method.length, ...utf8.encode(method), + // Method arguments: {'type': 'type':, 'id': 0} + valueMap, 2, + valueString, typeKey.length, ...utf8.encode(typeKey), + valueString, typeValue.length, ...utf8.encode(typeValue), + valueString, idKey.length, ...utf8.encode(idKey), + valueInt32, 0, 0, 0, 0, + ]; + + final Completer completed = Completer(); + final ByteData bytes = ByteData.sublistView(Uint8List.fromList(data)); + ui.PlatformDispatcher.instance.sendPlatformMessage('flutter/platform_views', bytes, ( + ByteData? response, + ) { + completed.complete(response); + }); + await completed.future; +} + +@pragma('vm:entry-point') +Future sendGetKeyboardState() async { + // The keyboard method channel uses the standard method codec. + // See https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/services/message_codecs.dart#L262 + // for the implementation of the encoding and magic number identifiers. + const int valueNull = 0; + const int valueString = 7; + const int valueMap = 13; + + const String method = 'getKeyboardState'; + final List data = [ + // Method name + valueString, method.length, ...utf8.encode(method), + // Method arguments: null + valueNull, 2, + ]; + + final Completer completer = Completer(); + final ByteData bytes = ByteData.sublistView(Uint8List.fromList(data)); + ui.PlatformDispatcher.instance.sendPlatformMessage('flutter/keyboard', bytes, ( + ByteData? response, + ) { + // For magic numbers for decoding a reply envelope, see: + // https://github.com/flutter/flutter/blob/67271f69f7f88a4edba6d8023099e3bd27a072d2/packages/flutter/lib/src/services/message_codecs.dart#L577-L587 + const int replyEnvelopeSuccess = 0; + + // Ensure the response is a success containing a map of keyboard states. + if (response == null) { + signalStringValue('Unexpected null response'); + } else if (response.lengthInBytes < 2) { + signalStringValue('Unexpected response length of ${response.lengthInBytes} bytes'); + } else if (response.getUint8(0) != replyEnvelopeSuccess) { + signalStringValue('Unexpected response envelope status: ${response.getUint8(0)}'); + } else if (response.getUint8(1) != valueMap) { + signalStringValue('Unexpected response value magic number: ${response.getUint8(1)}'); + } else { + signalStringValue('Success'); + } + completer.complete(); + }); + await completer.future; +} + +@pragma('vm:entry-point') +void customEntrypoint() {} + +@pragma('vm:entry-point') +void verifyNativeFunction() { + signal(); +} + +@pragma('vm:entry-point') +void verifyNativeFunctionWithParameters() { + signalBoolValue(true); +} + +@pragma('vm:entry-point') +void verifyNativeFunctionWithReturn() { + final value = signalBoolReturn(); + signalBoolValue(value); +} + +@pragma('vm:entry-point') +void readPlatformExecutable() { + signalStringValue(io.Platform.executable); +} + +@pragma('vm:entry-point') +void drawHelloWorld() { + ui.PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + final ui.ParagraphBuilder paragraphBuilder = ui.ParagraphBuilder(ui.ParagraphStyle()) + ..addText('Hello world'); + final ui.Paragraph paragraph = paragraphBuilder.build(); + + paragraph.layout(const ui.ParagraphConstraints(width: 800.0)); + + final ui.PictureRecorder recorder = ui.PictureRecorder(); + final ui.Canvas canvas = ui.Canvas(recorder); + + canvas.drawParagraph(paragraph, ui.Offset.zero); + + final ui.Picture picture = recorder.endRecording(); + final ui.SceneBuilder sceneBuilder = + ui.SceneBuilder() + ..addPicture(ui.Offset.zero, picture) + ..pop(); + + ui.PlatformDispatcher.instance.implicitView?.render(sceneBuilder.build()); + }; + + ui.PlatformDispatcher.instance.scheduleFrame(); + notifyFirstFrameScheduled(); +} + +ui.Picture _createColoredBox(ui.Color color, ui.Size size) { + final ui.Paint paint = ui.Paint(); + paint.color = color; + final ui.PictureRecorder baseRecorder = ui.PictureRecorder(); + final ui.Canvas canvas = ui.Canvas(baseRecorder); + canvas.drawRect(ui.Rect.fromLTRB(0.0, 0.0, size.width, size.height), paint); + return baseRecorder.endRecording(); +} + +@pragma('vm:entry-point') +void renderImplicitView() { + ui.PlatformDispatcher.instance.onBeginFrame = (Duration duration) { + const ui.Size size = ui.Size(800.0, 600.0); + const ui.Color red = ui.Color.fromARGB(127, 255, 0, 0); + + final ui.SceneBuilder builder = ui.SceneBuilder(); + + builder.pushOffset(0.0, 0.0); + + builder.addPicture(ui.Offset.zero, _createColoredBox(red, size)); + + builder.pop(); + + ui.PlatformDispatcher.instance.implicitView?.render(builder.build()); + }; + ui.PlatformDispatcher.instance.scheduleFrame(); +} + +@pragma('vm:entry-point') +void signalViewIds() { + final Iterable views = ui.PlatformDispatcher.instance.views; + final List viewIds = views.map((ui.FlutterView view) => view.viewId).toList(); + + viewIds.sort(); + + signalStringValue('View IDs: [${viewIds.join(', ')}]'); +} + +@pragma('vm:entry-point') +void onMetricsChangedSignalViewIds() { + ui.PlatformDispatcher.instance.onMetricsChanged = () { + signalViewIds(); + }; + + signal(); +} + +@pragma('vm:entry-point') +void mergedUIThread() { + signal(); +} + +@pragma('vm:external-name', 'NotifyEngineId') +external void notifyEngineId(int? handle); + +@pragma('vm:entry-point') +void testEngineId() { + notifyEngineId(ui.PlatformDispatcher.instance.engineId); +} + +@pragma('vm:entry-point') +Future sendSemanticsTreeInfo() async { + // Wait until semantics are enabled. + if (!ui.PlatformDispatcher.instance.semanticsEnabled) { + await semanticsChanged; + } + + final Iterable views = ui.PlatformDispatcher.instance.views; + final ui.FlutterView view1 = views.firstWhere( + (final ui.FlutterView view) => view != ui.PlatformDispatcher.instance.implicitView, + ); + final ui.FlutterView view2 = views.firstWhere( + (final ui.FlutterView view) => + view != view1 && view != ui.PlatformDispatcher.instance.implicitView, + ); + + ui.SemanticsUpdate createSemanticsUpdate(int nodeId) { + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + final Float64List transform = Float64List(16); + final Int32List childrenInTraversalOrder = Int32List(0); + final Int32List childrenInHitTestOrder = Int32List(0); + final Int32List additionalActions = Int32List(0); + // Identity matrix 4x4. + transform[0] = 1; + transform[5] = 1; + transform[10] = 1; + builder.updateNode( + id: nodeId, + 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: const ui.Rect.fromLTRB(0, 0, 10, 10), + elevation: 0, + thickness: 0, + identifier: 'identifier', + label: 'label', + labelAttributes: const [], + value: 'value', + valueAttributes: const [], + increasedValue: 'increasedValue', + increasedValueAttributes: const [], + decreasedValue: 'decreasedValue', + decreasedValueAttributes: const [], + hint: 'hint', + hintAttributes: const [], + tooltip: 'tooltip', + textDirection: ui.TextDirection.ltr, + transform: transform, + childrenInTraversalOrder: childrenInTraversalOrder, + childrenInHitTestOrder: childrenInHitTestOrder, + additionalActions: additionalActions, + role: ui.SemanticsRole.tab, + controlsNodes: null, + inputType: ui.SemanticsInputType.none, + ); + return builder.build(); + } + + view1.updateSemantics(createSemanticsUpdate(view1.viewId + 1)); + view2.updateSemantics(createSemanticsUpdate(view2.viewId + 1)); + signal(); +} diff --git a/flutter/engine/src/flutter/shell/platform/windows/public/flutter_windows.h b/flutter/engine/src/flutter/shell/platform/windows/public/flutter_windows.h new file mode 100644 index 0000000000000000000000000000000000000000..5d2bff132be99c4a1db9c9d8ce6252896de0ecc3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/public/flutter_windows.h @@ -0,0 +1,332 @@ +// 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_SHELL_PLATFORM_WINDOWS_PUBLIC_FLUTTER_WINDOWS_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_PUBLIC_FLUTTER_WINDOWS_H_ + +#include +#include +#include +#include + +#include "flutter_export.h" +#include "flutter_messenger.h" +#include "flutter_plugin_registrar.h" + +#if defined(__cplusplus) +extern "C" { +#endif + +typedef void (*VoidCallback)(void* /* user data */); + +// Opaque reference to a Flutter view controller. +struct FlutterDesktopViewController; +typedef struct FlutterDesktopViewController* FlutterDesktopViewControllerRef; + +// Opaque reference to a Flutter window. +struct FlutterDesktopView; +typedef struct FlutterDesktopView* FlutterDesktopViewRef; + +// Opaque reference to a Flutter engine instance. +struct FlutterDesktopEngine; +typedef struct FlutterDesktopEngine* FlutterDesktopEngineRef; + +// The unique identifier for a view. +typedef int64_t FlutterDesktopViewId; + +// Configures how the Flutter engine selects a GPU. +typedef enum { + // No preference. + NoPreference, + // Prefer energy efficiency over performance, such as an integrated GPU. + // This falls back to a high performance GPU if no low power GPU is + // available. + LowPowerPreference, +} FlutterDesktopGpuPreference; + +// Configures the thread policy for running the UI isolate. +typedef enum { + // Default value. Currently will run the UI isolate on separate thread, + // later will be changed to running the UI isolate on platform thread. + Default, + // Run the UI isolate on platform thread. + RunOnPlatformThread, + // Run the UI isolate on a separate thread. + RunOnSeparateThread, +} FlutterDesktopUIThreadPolicy; + +// Properties for configuring a Flutter engine instance. +typedef struct { + // The path to the flutter_assets folder for the application to be run. + // This can either be an absolute path or a path relative to the directory + // containing the executable. + const wchar_t* assets_path; + + // The path to the icudtl.dat file for the version of Flutter you are using. + // This can either be an absolute path or a path relative to the directory + // containing the executable. + const wchar_t* icu_data_path; + + // The path to the AOT library file for your application, if any. + // This can either be an absolute path or a path relative to the directory + // containing the executable. This can be nullptr for a non-AOT build, as + // it will be ignored in that case. + const wchar_t* aot_library_path; + + // The name of the top-level Dart entrypoint function. If null or the empty + // string, 'main' is assumed. If a custom entrypoint is used, this parameter + // must specifiy the name of a top-level function in the same Dart library as + // the app's main() function. Custom entrypoint functions must be decorated + // with `@pragma('vm:entry-point')` to ensure the method is not tree-shaken + // by the Dart compiler. + const char* dart_entrypoint; + + // Number of elements in the array passed in as dart_entrypoint_argv. + int dart_entrypoint_argc; + + // Array of Dart entrypoint arguments. This is deep copied during the call + // to FlutterDesktopEngineCreate. + const char** dart_entrypoint_argv; + + // GPU choice preference + FlutterDesktopGpuPreference gpu_preference; + + // Policy for the thread that runs UI isolate. + FlutterDesktopUIThreadPolicy ui_thread_policy; +} FlutterDesktopEngineProperties; + +// ========== View Controller ========== + +// Creates a view that hosts and displays the given engine instance. +// +// This takes ownership of |engine|, so FlutterDesktopEngineDestroy should no +// longer be called on it, as it will be called internally when the view +// controller is destroyed. If creating the view controller fails, the engine +// will be destroyed immediately. +// +// If |engine| is not already running, the view controller will start running +// it automatically before displaying the window. +// +// The caller owns the returned reference, and is responsible for calling +// FlutterDesktopViewControllerDestroy. Returns a null pointer in the event of +// an error. +// +// The Win32 implementation accepts width, height with view hookup explicitly +// performed using the caller using HWND parenting. +FLUTTER_EXPORT FlutterDesktopViewControllerRef +FlutterDesktopViewControllerCreate(int width, + int height, + FlutterDesktopEngineRef engine); + +// Shuts down the engine instance associated with |controller|, and cleans up +// associated state. +// +// |controller| is no longer valid after this call. +FLUTTER_EXPORT void FlutterDesktopViewControllerDestroy( + FlutterDesktopViewControllerRef controller); + +// Returns the view controller's view ID. +FLUTTER_EXPORT FlutterDesktopViewId FlutterDesktopViewControllerGetViewId( + FlutterDesktopViewControllerRef view_controller); + +// Returns the handle for the engine running in FlutterDesktopViewControllerRef. +// +// Its lifetime is the same as the |controller|'s. +FLUTTER_EXPORT FlutterDesktopEngineRef FlutterDesktopViewControllerGetEngine( + FlutterDesktopViewControllerRef controller); + +// Returns the view managed by the given controller. +FLUTTER_EXPORT FlutterDesktopViewRef FlutterDesktopViewControllerGetView( + FlutterDesktopViewControllerRef controller); + +// Requests new frame from the engine and repaints the view. +FLUTTER_EXPORT void FlutterDesktopViewControllerForceRedraw( + FlutterDesktopViewControllerRef controller); + +// Allows the Flutter engine and any interested plugins an opportunity to +// handle the given message. +// +// If the WindowProc was handled and further handling should stop, this returns +// true and |result| will be populated. |result| is not set if returning false. +FLUTTER_EXPORT bool FlutterDesktopViewControllerHandleTopLevelWindowProc( + FlutterDesktopViewControllerRef controller, + HWND hwnd, + UINT message, + WPARAM wparam, + LPARAM lparam, + LRESULT* result); + +// ========== Engine ========== + +// Creates a Flutter engine with the given properties. +// +// The caller owns the returned reference, and is responsible for calling +// FlutterDesktopEngineDestroy. The lifetime of |engine_properties| is required +// to extend only until the end of this call. +FLUTTER_EXPORT FlutterDesktopEngineRef FlutterDesktopEngineCreate( + const FlutterDesktopEngineProperties* engine_properties); + +// Shuts down and destroys the given engine instance. Returns true if the +// shutdown was successful, or if the engine was not running. +// +// |engine| is no longer valid after this call. +FLUTTER_EXPORT bool FlutterDesktopEngineDestroy(FlutterDesktopEngineRef engine); + +// Starts running the given engine instance. +// +// The entry_point parameter is deprecated but preserved for +// backward-compatibility. If desired, a custom Dart entrypoint function can be +// set in the dart_entrypoint field of the FlutterDesktopEngineProperties +// struct passed to FlutterDesktopEngineCreate. +// +// If specified, entry_point must be the name of a top-level function from the +// same Dart library that contains the app's main() function, and must be +// decorated with `@pragma(vm:entry-point)` to ensure the method is not +// tree-shaken by the Dart compiler. If conflicting non-null values are passed +// to this function and via the FlutterDesktopEngineProperties struct, the run +// will fail. +// +// Returns false if running the engine failed. +FLUTTER_EXPORT bool FlutterDesktopEngineRun(FlutterDesktopEngineRef engine, + const char* entry_point); + +// DEPRECATED: This is no longer necessary to call, Flutter will take care of +// processing engine messages transparently through DispatchMessage. +// +// Processes any pending events in the Flutter engine, and returns the +// number of nanoseconds until the next scheduled event (or max, if none). +// +// This should be called on every run of the application-level runloop, and +// a wait for native events in the runloop should never be longer than the +// last return value from this function. +FLUTTER_EXPORT uint64_t FlutterDesktopEngineProcessMessages( + FlutterDesktopEngineRef engine); + +FLUTTER_EXPORT void FlutterDesktopEngineReloadSystemFonts( + FlutterDesktopEngineRef engine); + +// Returns the plugin registrar handle for the plugin with the given name. +// +// The name must be unique across the application. +FLUTTER_EXPORT FlutterDesktopPluginRegistrarRef +FlutterDesktopEngineGetPluginRegistrar(FlutterDesktopEngineRef engine, + const char* plugin_name); + +// Returns the messenger associated with the engine. +// +// This does not provide an owning reference, so should *not* be balanced with a +// call to |FlutterDesktopMessengerRelease|. +// +// Callers should use |FlutterDesktopMessengerAddRef| if the returned pointer +// will potentially outlive 'engine', such as when passing it to another thread. +FLUTTER_EXPORT FlutterDesktopMessengerRef FlutterDesktopEngineGetMessenger( + FlutterDesktopEngineRef engine); + +// Returns the texture registrar associated with the engine. +FLUTTER_EXPORT FlutterDesktopTextureRegistrarRef +FlutterDesktopEngineGetTextureRegistrar(FlutterDesktopEngineRef engine); + +// Schedule a callback to be called after the next frame is drawn. +// +// This must be called from the platform thread. The callback is executed only +// once on the platform thread. +FLUTTER_EXPORT void FlutterDesktopEngineSetNextFrameCallback( + FlutterDesktopEngineRef engine, + VoidCallback callback, + void* user_data); + +// ========== View ========== + +// Returns the backing HWND for manipulation in host application. +FLUTTER_EXPORT HWND FlutterDesktopViewGetHWND(FlutterDesktopViewRef view); + +// Returns the DXGI adapter used for rendering or nullptr in case of error. +FLUTTER_EXPORT IDXGIAdapter* FlutterDesktopViewGetGraphicsAdapter( + FlutterDesktopViewRef view); + +// Called to pass an external window message to the engine for lifecycle +// state updates. Non-Flutter windows must call this method in their WndProc +// in order to be included in the logic for application lifecycle state +// updates. Returns a result if the message should be consumed. +FLUTTER_EXPORT bool FlutterDesktopEngineProcessExternalWindowMessage( + FlutterDesktopEngineRef engine, + HWND hwnd, + UINT message, + WPARAM wparam, + LPARAM lparam, + LRESULT* result); + +// ========== Plugin Registrar (extensions) ========== +// These are Windows-specific extensions to flutter_plugin_registrar.h + +// Function pointer type for top level WindowProc delegate registration. +// +// The user data will be whatever was passed to +// FlutterDesktopRegisterTopLevelWindowProcHandler. +// +// Implementations should populate |result| and return true if the WindowProc +// was handled and further handling should stop. |result| is ignored if the +// function returns false. +typedef bool (*FlutterDesktopWindowProcCallback)(HWND /* hwnd */, + UINT /* uMsg */, + WPARAM /*wParam*/, + LPARAM /* lParam*/, + void* /* user data */, + LRESULT* result); + +// Returns the implicit view associated with this registrar's engine instance, +// or null if there is no implicit view. +// +// See: +// https://api.flutter.dev/flutter/dart-ui/PlatformDispatcher/implicitView.html +// +// DEPRECATED: Use |FlutterDesktopPluginRegistrarGetViewById| instead. +FLUTTER_EXPORT FlutterDesktopViewRef FlutterDesktopPluginRegistrarGetView( + FlutterDesktopPluginRegistrarRef registrar); + +// Returns the view associated with the registrar's engine instance, or null if +// the view does not exist. +FLUTTER_EXPORT FlutterDesktopViewRef FlutterDesktopPluginRegistrarGetViewById( + FlutterDesktopPluginRegistrarRef registrar, + FlutterDesktopViewId view_id); + +FLUTTER_EXPORT void +FlutterDesktopPluginRegistrarRegisterTopLevelWindowProcDelegate( + FlutterDesktopPluginRegistrarRef registrar, + FlutterDesktopWindowProcCallback delegate, + void* user_data); + +FLUTTER_EXPORT void +FlutterDesktopPluginRegistrarUnregisterTopLevelWindowProcDelegate( + FlutterDesktopPluginRegistrarRef registrar, + FlutterDesktopWindowProcCallback delegate); + +// ========== Freestanding Utilities ========== + +// Gets the DPI for a given |hwnd|, depending on the supported APIs per +// windows version and DPI awareness mode. If nullptr is passed, returns the DPI +// of the primary monitor. +// +// This uses the same logic and fallback for older Windows versions that is used +// internally by Flutter to determine the DPI to use for displaying Flutter +// content, so should be used by any code (e.g., in plugins) that translates +// between Windows and Dart sizes/offsets. +FLUTTER_EXPORT UINT FlutterDesktopGetDpiForHWND(HWND hwnd); + +// Gets the DPI for a given |monitor|. If the API is not available, a default +// DPI of 96 is returned. +// +// See FlutterDesktopGetDpiForHWND for more information. +FLUTTER_EXPORT UINT FlutterDesktopGetDpiForMonitor(HMONITOR monitor); + +// Reopens stdout and stderr and resysncs the standard library output streams. +// Should be called if output is being directed somewhere in the runner process +// (e.g., after an AllocConsole call). +FLUTTER_EXPORT void FlutterDesktopResyncOutputStreams(); + +#if defined(__cplusplus) +} // extern "C" +#endif + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_PUBLIC_FLUTTER_WINDOWS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/egl/mock_context.h b/flutter/engine/src/flutter/shell/platform/windows/testing/egl/mock_context.h new file mode 100644 index 0000000000000000000000000000000000000000..d61a096c36326d50b59c6538578a02d756a3d1b4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/egl/mock_context.h @@ -0,0 +1,32 @@ +// 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_SHELL_PLATFORM_WINDOWS_TESTING_EGL_MOCK_CONTEXT_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_EGL_MOCK_CONTEXT_H_ + +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/windows/egl/context.h" +#include "gmock/gmock.h" + +namespace flutter { +namespace testing { +namespace egl { + +/// Mock for the |Context| base class. +class MockContext : public flutter::egl::Context { + public: + MockContext() : Context(EGL_NO_DISPLAY, EGL_NO_CONTEXT) {} + + MOCK_METHOD(bool, MakeCurrent, (), (const, override)); + MOCK_METHOD(bool, ClearCurrent, (), (const, override)); + + private: + FML_DISALLOW_COPY_AND_ASSIGN(MockContext); +}; + +} // namespace egl +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_EGL_MOCK_CONTEXT_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/egl/mock_manager.h b/flutter/engine/src/flutter/shell/platform/windows/testing/egl/mock_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..1cc9f728d428b0ff4b0a20fbcbb94999724dfb0e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/egl/mock_manager.h @@ -0,0 +1,37 @@ +// 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_SHELL_PLATFORM_WINDOWS_TESTING_EGL_MOCK_MANAGER_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_EGL_MOCK_MANAGER_H_ + +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/windows/egl/manager.h" +#include "gmock/gmock.h" + +namespace flutter { +namespace testing { +namespace egl { + +/// Mock for the |Manager| base class. +class MockManager : public flutter::egl::Manager { + public: + MockManager() : Manager(flutter::egl::GpuPreference::NoPreference) {} + + MOCK_METHOD(std::unique_ptr, + CreateWindowSurface, + (HWND, size_t, size_t), + (override)); + + MOCK_METHOD(flutter::egl::Context*, render_context, (), (const, override)); + MOCK_METHOD(flutter::egl::Context*, resource_context, (), (const, override)); + + private: + FML_DISALLOW_COPY_AND_ASSIGN(MockManager); +}; + +} // namespace egl +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_EGL_MOCK_MANAGER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/egl/mock_proc_table.h b/flutter/engine/src/flutter/shell/platform/windows/testing/egl/mock_proc_table.h new file mode 100644 index 0000000000000000000000000000000000000000..49c71d2f78dfe4801441eae35d815e6ab7d3c24e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/egl/mock_proc_table.h @@ -0,0 +1,59 @@ +// 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_SHELL_PLATFORM_WINDOWS_TESTING_EGL_MOCK_PROC_TABLE_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_EGL_MOCK_PROC_TABLE_H_ + +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/windows/egl/proc_table.h" +#include "gmock/gmock.h" + +namespace flutter { +namespace testing { +namespace egl { + +/// Mock for the |ProcTable| base class. +class MockProcTable : public ::flutter::egl::ProcTable { + public: + MockProcTable() = default; + virtual ~MockProcTable() = default; + + MOCK_METHOD(void, + GenTextures, + (GLsizei n, GLuint* textures), + (const override)); + MOCK_METHOD(void, + DeleteTextures, + (GLsizei n, const GLuint* textures), + (const override)); + MOCK_METHOD(void, + BindTexture, + (GLenum target, GLuint texture), + (const override)); + MOCK_METHOD(void, + TexParameteri, + (GLenum target, GLenum pname, GLint param), + (const override)); + MOCK_METHOD(void, + TexImage2D, + (GLenum target, + GLint level, + GLint internalformat, + GLsizei width, + GLsizei height, + GLint border, + GLenum format, + GLenum type, + const void* data), + (const override)); + + private: + FML_DISALLOW_COPY_AND_ASSIGN(MockProcTable); +}; + +} // namespace egl +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_EGL_MOCK_PROC_TABLE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/egl/mock_window_surface.h b/flutter/engine/src/flutter/shell/platform/windows/testing/egl/mock_window_surface.h new file mode 100644 index 0000000000000000000000000000000000000000..7bfd739c1f20438b09a0e0a1688d1c18a8128ce7 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/egl/mock_window_surface.h @@ -0,0 +1,36 @@ +// 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_SHELL_PLATFORM_WINDOWS_TESTING_EGL_MOCK_WINDOW_SURFACE_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_EGL_MOCK_WINDOW_SURFACE_H_ + +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/windows/egl/window_surface.h" +#include "gmock/gmock.h" + +namespace flutter { +namespace testing { +namespace egl { + +/// Mock for the |WindowSurface| base class. +class MockWindowSurface : public flutter::egl::WindowSurface { + public: + MockWindowSurface() + : WindowSurface(EGL_NO_DISPLAY, EGL_NO_CONTEXT, EGL_NO_SURFACE, 0, 0) {} + + MOCK_METHOD(bool, IsValid, (), (const, override)); + MOCK_METHOD(bool, Destroy, (), (override)); + MOCK_METHOD(bool, MakeCurrent, (), (const, override)); + MOCK_METHOD(bool, SwapBuffers, (), (const, override)); + MOCK_METHOD(bool, SetVSyncEnabled, (bool), (override)); + + private: + FML_DISALLOW_COPY_AND_ASSIGN(MockWindowSurface); +}; + +} // namespace egl +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_EGL_MOCK_WINDOW_SURFACE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/engine_modifier.h b/flutter/engine/src/flutter/shell/platform/windows/testing/engine_modifier.h new file mode 100644 index 0000000000000000000000000000000000000000..e35efac302443baa868499ccc33f7f81abee62c0 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/engine_modifier.h @@ -0,0 +1,106 @@ +// 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_SHELL_PLATFORM_WINDOWS_TESTING_ENGINE_MODIFIER_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_ENGINE_MODIFIER_H_ + +#include "flutter/shell/platform/windows/flutter_windows_engine.h" + +#include + +#include "flutter/fml/macros.h" + +namespace flutter { + +// A test utility class providing the ability to access and alter various +// private fields in an Engine instance. +// +// This simply provides a way to access the normally-private embedder proc +// table, so the lifetime of any changes made to the proc table is that of the +// engine object, not this helper. +class EngineModifier { + public: + explicit EngineModifier(FlutterWindowsEngine* engine) : engine_(engine) {} + + // Returns the engine's embedder API proc table, allowing for modification. + // + // Modifications are to the engine, and will last for the lifetime of the + // engine unless overwritten again. + FlutterEngineProcTable& embedder_api() { return engine_->embedder_api_; } + + // Override the EGL manager used by the engine. + // + // Modifications are to the engine, and will last for the lifetime of the + // engine unless overwritten again. + void SetEGLManager(std::unique_ptr egl_manager) { + engine_->egl_manager_ = std::move(egl_manager); + } + + // Override the engine's implicit view. This is the "default" view + // that Flutter apps render to. + void SetImplicitView(FlutterWindowsView* view) { + engine_->views_[kImplicitViewId] = view; + } + + /// Associate a view with a view id. + void SetViewById(FlutterWindowsView* view, FlutterViewId viewId) { + engine_->views_[viewId] = view; + } + + /// Reset the start_time field that is used to align vsync events. + void SetStartTime(uint64_t start_time_nanos) { + engine_->start_time_ = std::chrono::nanoseconds(start_time_nanos); + } + + /// Override the frame interval to the provided nanosecond interval. + /// + /// This will prevent the windows engine from delegating to dwm to + /// discover the true frame interval, which can vary across machines. + void SetFrameInterval(uint64_t frame_interval_nanos) { + engine_->frame_interval_override_ = + std::optional(frame_interval_nanos); + } + + // Explicitly releases the egl::Manager being used by the + // FlutterWindowsEngine instance. This should be used if SetEGLManager is + // used to explicitly set to a non-null value (but not a valid object) to test + // a successful ANGLE initialization. + // + // Modifications are to the engine, and will last for the lifetime of the + // engine unless overwritten again. + void ReleaseEGLManager() { engine_->egl_manager_.release(); } + + // Run the FlutterWindowsEngine's handler that runs right before an engine + // restart. This resets the keyboard's state if it exists. + void Restart() { engine_->OnPreEngineRestart(); } + + // Initialize they keyboard and text input subsystems or reset them them if + // they are already initialized. + void InitializeKeyboard() { engine_->InitializeKeyboard(); } + + void SetLifecycleManager(std::unique_ptr&& handler) { + engine_->lifecycle_manager_ = std::move(handler); + } + + void SetPlatformViewPlugin(std::unique_ptr&& manager) { + engine_->platform_view_plugin_ = std::move(manager); + } + + void OnViewFocusChangeRequest(const FlutterViewFocusChangeRequest* request) { + engine_->OnViewFocusChangeRequest(request); + } + + void SetNextViewId(FlutterViewId view_id) { + engine_->next_view_id_ = view_id; + } + + private: + FlutterWindowsEngine* engine_; + + FML_DISALLOW_COPY_AND_ASSIGN(EngineModifier); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_ENGINE_MODIFIER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/flutter_windows_engine_builder.cc b/flutter/engine/src/flutter/shell/platform/windows/testing/flutter_windows_engine_builder.cc new file mode 100644 index 0000000000000000000000000000000000000000..9e122b35d4e1e132b885c38f2a2b9a8d333d2c10 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/flutter_windows_engine_builder.cc @@ -0,0 +1,108 @@ +// 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/shell/platform/windows/testing/flutter_windows_engine_builder.h" + +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/windows/windows_proc_table.h" + +namespace flutter { +namespace testing { + +class TestFlutterWindowsEngine : public FlutterWindowsEngine { + public: + TestFlutterWindowsEngine( + const FlutterProjectBundle& project, + KeyboardKeyEmbedderHandler::GetKeyStateHandler get_key_state, + KeyboardKeyEmbedderHandler::MapVirtualKeyToScanCode map_vk_to_scan, + std::shared_ptr windows_proc_table = nullptr) + : FlutterWindowsEngine(project, std::move(windows_proc_table)), + get_key_state_(std::move(get_key_state)), + map_vk_to_scan_(std::move(map_vk_to_scan)) {} + + protected: + std::unique_ptr CreateKeyboardKeyHandler( + BinaryMessenger* messenger, + KeyboardKeyEmbedderHandler::GetKeyStateHandler get_key_state, + KeyboardKeyEmbedderHandler::MapVirtualKeyToScanCode map_vk_to_scan) { + if (get_key_state_) { + get_key_state = get_key_state_; + } + + if (map_vk_to_scan_) { + map_vk_to_scan = map_vk_to_scan_; + } + + return FlutterWindowsEngine::CreateKeyboardKeyHandler( + messenger, get_key_state, map_vk_to_scan); + } + + private: + KeyboardKeyEmbedderHandler::GetKeyStateHandler get_key_state_; + KeyboardKeyEmbedderHandler::MapVirtualKeyToScanCode map_vk_to_scan_; + + FML_DISALLOW_COPY_AND_ASSIGN(TestFlutterWindowsEngine); +}; + +FlutterWindowsEngineBuilder::FlutterWindowsEngineBuilder( + WindowsTestContext& context) + : context_(context) { + properties_.assets_path = context.GetAssetsPath().c_str(); + properties_.icu_data_path = context.GetIcuDataPath().c_str(); + properties_.aot_library_path = context.GetAotLibraryPath().c_str(); +} + +FlutterWindowsEngineBuilder::~FlutterWindowsEngineBuilder() = default; + +void FlutterWindowsEngineBuilder::SetDartEntrypoint(std::string entrypoint) { + dart_entrypoint_ = std::move(entrypoint); + properties_.dart_entrypoint = dart_entrypoint_.c_str(); +} + +void FlutterWindowsEngineBuilder::AddDartEntrypointArgument(std::string arg) { + dart_entrypoint_arguments_.emplace_back(std::move(arg)); +} + +void FlutterWindowsEngineBuilder::SetSwitches( + std::vector switches) { + switches_ = std::move(switches); +} + +void FlutterWindowsEngineBuilder::SetCreateKeyboardHandlerCallbacks( + KeyboardKeyEmbedderHandler::GetKeyStateHandler get_key_state, + KeyboardKeyEmbedderHandler::MapVirtualKeyToScanCode map_vk_to_scan) { + get_key_state_ = std::move(get_key_state); + map_vk_to_scan_ = std::move(map_vk_to_scan); +} + +void FlutterWindowsEngineBuilder::SetWindowsProcTable( + std::shared_ptr windows_proc_table) { + windows_proc_table_ = std::move(windows_proc_table); +} + +std::unique_ptr FlutterWindowsEngineBuilder::Build() { + std::vector dart_args; + dart_args.reserve(dart_entrypoint_arguments_.size()); + + for (const auto& arg : dart_entrypoint_arguments_) { + dart_args.push_back(arg.c_str()); + } + + if (!dart_args.empty()) { + properties_.dart_entrypoint_argv = dart_args.data(); + properties_.dart_entrypoint_argc = dart_args.size(); + } else { + properties_.dart_entrypoint_argv = nullptr; + properties_.dart_entrypoint_argc = 0; + } + + FlutterProjectBundle project(properties_); + project.SetSwitches(switches_); + + return std::make_unique( + project, get_key_state_, map_vk_to_scan_, std::move(windows_proc_table_)); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/flutter_windows_engine_builder.h b/flutter/engine/src/flutter/shell/platform/windows/testing/flutter_windows_engine_builder.h new file mode 100644 index 0000000000000000000000000000000000000000..da7f3fb27f0457fb5c5fd511b4a8e34fb905d946 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/flutter_windows_engine_builder.h @@ -0,0 +1,55 @@ +// 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_SHELL_PLATFORM_WINDOWS_TESTING_FLUTTER_WINDOWS_ENGINE_BUILDER_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_FLUTTER_WINDOWS_ENGINE_BUILDER_H_ + +#include + +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/windows/flutter_windows_engine.h" +#include "flutter/shell/platform/windows/keyboard_key_embedder_handler.h" +#include "flutter/shell/platform/windows/public/flutter_windows.h" +#include "flutter/shell/platform/windows/testing/windows_test_context.h" + +namespace flutter { +namespace testing { + +class FlutterWindowsEngineBuilder { + public: + explicit FlutterWindowsEngineBuilder(WindowsTestContext& context); + ~FlutterWindowsEngineBuilder(); + + void SetDartEntrypoint(std::string entrypoint); + + void AddDartEntrypointArgument(std::string arg); + + void SetCreateKeyboardHandlerCallbacks( + KeyboardKeyEmbedderHandler::GetKeyStateHandler get_key_state, + KeyboardKeyEmbedderHandler::MapVirtualKeyToScanCode map_vk_to_scan); + + void SetSwitches(std::vector switches); + + void SetWindowsProcTable( + std::shared_ptr windows_proc_table); + + std::unique_ptr Build(); + + private: + WindowsTestContext& context_; + FlutterDesktopEngineProperties properties_ = {}; + std::string dart_entrypoint_; + std::vector dart_entrypoint_arguments_; + std::vector switches_; + KeyboardKeyEmbedderHandler::GetKeyStateHandler get_key_state_; + KeyboardKeyEmbedderHandler::MapVirtualKeyToScanCode map_vk_to_scan_; + std::shared_ptr windows_proc_table_; + + FML_DISALLOW_COPY_AND_ASSIGN(FlutterWindowsEngineBuilder); +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_FLUTTER_WINDOWS_ENGINE_BUILDER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/mock_direct_manipulation.h b/flutter/engine/src/flutter/shell/platform/windows/testing/mock_direct_manipulation.h new file mode 100644 index 0000000000000000000000000000000000000000..fc984cbf34fc3d40395bcf3fd37366bb8fe3d6ef --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/mock_direct_manipulation.h @@ -0,0 +1,31 @@ +// 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_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_DIRECT_MANIPULATION_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_DIRECT_MANIPULATION_H_ + +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/windows/direct_manipulation.h" +#include "gmock/gmock.h" + +namespace flutter { +namespace testing { + +/// Mock for the |DirectManipulationOwner| base class. +class MockDirectManipulationOwner : public DirectManipulationOwner { + public: + explicit MockDirectManipulationOwner(FlutterWindow* window) + : DirectManipulationOwner(window){}; + virtual ~MockDirectManipulationOwner() = default; + + MOCK_METHOD(void, SetContact, (UINT contact_id), (override)); + + private: + FML_DISALLOW_COPY_AND_ASSIGN(MockDirectManipulationOwner); +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_DIRECT_MANIPULATION_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/mock_platform_view_manager.h b/flutter/engine/src/flutter/shell/platform/windows/testing/mock_platform_view_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..a3c69222699329e5c576b6548bb1631df55b6a27 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/mock_platform_view_manager.h @@ -0,0 +1,28 @@ +// 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_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_PLATFORM_VIEW_MANAGER_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_PLATFORM_VIEW_MANAGER_H_ + +#include "flutter/shell/platform/windows/platform_view_plugin.h" + +#include "flutter/shell/platform/windows/flutter_windows_engine.h" +#include "gmock/gmock.h" + +namespace flutter { + +class MockPlatformViewManager : public PlatformViewPlugin { + public: + MockPlatformViewManager(FlutterWindowsEngine* engine) + : PlatformViewPlugin(engine->messenger_wrapper(), engine->task_runner()) { + } + + ~MockPlatformViewManager() {} + + MOCK_METHOD(bool, AddPlatformView, (PlatformViewId id, std::string_view)); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_PLATFORM_VIEW_MANAGER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/mock_text_input_manager.cc b/flutter/engine/src/flutter/shell/platform/windows/testing/mock_text_input_manager.cc new file mode 100644 index 0000000000000000000000000000000000000000..c84a9d7bfc6ac57de5cb4588333350d0508ad28e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/mock_text_input_manager.cc @@ -0,0 +1,15 @@ +// 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/shell/platform/windows/testing/mock_text_input_manager.h" + +namespace flutter { +namespace testing { + +MockTextInputManager::MockTextInputManager() : TextInputManager(){}; + +MockTextInputManager::~MockTextInputManager() = default; + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/mock_text_input_manager.h b/flutter/engine/src/flutter/shell/platform/windows/testing/mock_text_input_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..d4d611831d62cf2093935ac7135690c9cbe98220 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/mock_text_input_manager.h @@ -0,0 +1,41 @@ +// 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_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_TEXT_INPUT_MANAGER_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_TEXT_INPUT_MANAGER_H_ + +#include +#include + +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/windows/text_input_manager.h" +#include "gmock/gmock.h" + +namespace flutter { +namespace testing { + +/// Mock for the |Window| base class. +class MockTextInputManager : public TextInputManager { + public: + MockTextInputManager(); + virtual ~MockTextInputManager(); + + MOCK_METHOD(std::optional, + GetComposingString, + (), + (const, override)); + MOCK_METHOD(std::optional, + GetResultString, + (), + (const, override)); + MOCK_METHOD(long, GetComposingCursorPosition, (), (const, override)); + + private: + FML_DISALLOW_COPY_AND_ASSIGN(MockTextInputManager); +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_TEXT_INPUT_MANAGER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/mock_window.cc b/flutter/engine/src/flutter/shell/platform/windows/testing/mock_window.cc new file mode 100644 index 0000000000000000000000000000000000000000..d6f8db89887725ea69e0886f68555605be5bd7b6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/mock_window.cc @@ -0,0 +1,59 @@ +// 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/shell/platform/windows/testing/mock_window.h" + +namespace flutter { +namespace testing { +MockWindow::MockWindow() : FlutterWindow(1, 1){}; +MockWindow::MockWindow(std::unique_ptr window_proc_table, + std::unique_ptr text_input_manager) + : FlutterWindow(1, + 1, + std::move(window_proc_table), + std::move(text_input_manager)){}; + +MockWindow::~MockWindow() = default; + +UINT MockWindow::GetDpi() { + return GetCurrentDPI(); +} + +LRESULT MockWindow::Win32DefWindowProc(HWND hWnd, + UINT Msg, + WPARAM wParam, + LPARAM lParam) { + return kWmResultDefault; +} + +void MockWindow::SetDirectManipulationOwner( + std::unique_ptr owner) { + direct_manipulation_owner_ = std::move(owner); +} + +LRESULT MockWindow::InjectWindowMessage(UINT const message, + WPARAM const wparam, + LPARAM const lparam) { + return HandleMessage(message, wparam, lparam); +} + +void MockWindow::InjectMessageList(int count, const Win32Message* messages) { + for (int message_id = 0; message_id < count; message_id += 1) { + const Win32Message& message = messages[message_id]; + LRESULT result = + InjectWindowMessage(message.message, message.wParam, message.lParam); + if (message.expected_result != kWmResultDontCheck) { + EXPECT_EQ(result, message.expected_result); + } + } +} + +void MockWindow::CallOnImeComposition(UINT const message, + WPARAM const wparam, + LPARAM const lparam) { + FlutterWindow::OnImeComposition(message, wparam, lparam); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/mock_window.h b/flutter/engine/src/flutter/shell/platform/windows/testing/mock_window.h new file mode 100644 index 0000000000000000000000000000000000000000..4a1007840ba3085bd13e6af28724b249d6874eae --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/mock_window.h @@ -0,0 +1,105 @@ +// 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_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_WINDOW_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_WINDOW_H_ + +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/windows/flutter_window.h" +#include "flutter/shell/platform/windows/testing/test_keyboard.h" +#include "gmock/gmock.h" + +namespace flutter { +namespace testing { + +/// Mock for the |FlutterWindow| base class. +class MockWindow : public FlutterWindow { + public: + MockWindow(); + MockWindow(std::unique_ptr windows_proc_table, + std::unique_ptr text_input_manager); + virtual ~MockWindow(); + + // Wrapper for GetCurrentDPI() which is a protected method. + UINT GetDpi(); + + // Set the Direct Manipulation owner for testing purposes. + void SetDirectManipulationOwner( + std::unique_ptr owner); + + // Simulates a WindowProc message from the OS. + LRESULT InjectWindowMessage(UINT const message, + WPARAM const wparam, + LPARAM const lparam); + + void InjectMessageList(int count, const Win32Message* messages); + + MOCK_METHOD(void, OnDpiScale, (unsigned int), (override)); + MOCK_METHOD(void, OnResize, (unsigned int, unsigned int), (override)); + MOCK_METHOD(void, OnPaint, (), (override)); + MOCK_METHOD(void, + OnPointerMove, + (double, double, FlutterPointerDeviceKind, int32_t, int), + (override)); + MOCK_METHOD(void, + OnPointerDown, + (double, double, FlutterPointerDeviceKind, int32_t, UINT), + (override)); + MOCK_METHOD(void, + OnPointerUp, + (double, double, FlutterPointerDeviceKind, int32_t, UINT), + (override)); + MOCK_METHOD(void, + OnPointerLeave, + (double, double, FlutterPointerDeviceKind, int32_t), + (override)); + MOCK_METHOD(void, OnText, (const std::u16string&), (override)); + MOCK_METHOD(void, + OnKey, + (int, int, int, char32_t, bool, bool, KeyEventCallback), + (override)); + MOCK_METHOD(void, OnUpdateSemanticsEnabled, (bool), (override)); + MOCK_METHOD(gfx::NativeViewAccessible, + GetNativeViewAccessible, + (), + (override)); + MOCK_METHOD(void, + OnScroll, + (double, double, FlutterPointerDeviceKind, int32_t), + (override)); + MOCK_METHOD(void, OnComposeBegin, (), (override)); + MOCK_METHOD(void, OnComposeCommit, (), (override)); + MOCK_METHOD(void, OnComposeEnd, (), (override)); + MOCK_METHOD(void, OnComposeChange, (const std::u16string&, int), (override)); + MOCK_METHOD(void, + OnImeComposition, + (UINT const, WPARAM const, LPARAM const), + (override)); + + MOCK_METHOD(void, OnThemeChange, (), (override)); + + MOCK_METHOD(ui::AXFragmentRootDelegateWin*, + GetAxFragmentRootDelegate, + (), + (override)); + + MOCK_METHOD(LRESULT, OnGetObject, (UINT, WPARAM, LPARAM), (override)); + + MOCK_METHOD(void, OnWindowStateEvent, (WindowStateEvent), (override)); + + void CallOnImeComposition(UINT const message, + WPARAM const wparam, + LPARAM const lparam); + + protected: + LRESULT Win32DefWindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam); + + private: + FML_DISALLOW_COPY_AND_ASSIGN(MockWindow); +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_WINDOW_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/mock_window_binding_handler.cc b/flutter/engine/src/flutter/shell/platform/windows/testing/mock_window_binding_handler.cc new file mode 100644 index 0000000000000000000000000000000000000000..c0449152beb7295be6dd3aaf2b85540ded816ea9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/mock_window_binding_handler.cc @@ -0,0 +1,15 @@ +// 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/shell/platform/windows/testing/mock_window_binding_handler.h" + +namespace flutter { +namespace testing { + +MockWindowBindingHandler::MockWindowBindingHandler() : WindowBindingHandler(){}; + +MockWindowBindingHandler::~MockWindowBindingHandler() = default; + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/mock_window_binding_handler.h b/flutter/engine/src/flutter/shell/platform/windows/testing/mock_window_binding_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..dcb6b50d8d41a078ba7575f4423f1253fb8d1d07 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/mock_window_binding_handler.h @@ -0,0 +1,45 @@ +// 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_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_WINDOW_BINDING_HANDLER_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_WINDOW_BINDING_HANDLER_H_ + +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/windows/window_binding_handler.h" +#include "flutter/third_party/accessibility/ax/platform/ax_platform_node_win.h" +#include "gmock/gmock.h" + +namespace flutter { +namespace testing { + +/// Mock for the |Window| base class. +class MockWindowBindingHandler : public WindowBindingHandler { + public: + MockWindowBindingHandler(); + virtual ~MockWindowBindingHandler(); + + MOCK_METHOD(void, SetView, (WindowBindingHandlerDelegate * view), (override)); + MOCK_METHOD(HWND, GetWindowHandle, (), (override)); + MOCK_METHOD(float, GetDpiScale, (), (override)); + MOCK_METHOD(PhysicalWindowBounds, GetPhysicalWindowBounds, (), (override)); + MOCK_METHOD(void, OnCursorRectUpdated, (const Rect& rect), (override)); + MOCK_METHOD(void, OnResetImeComposing, (), (override)); + MOCK_METHOD(bool, OnBitmapSurfaceCleared, (), (override)); + MOCK_METHOD(bool, + OnBitmapSurfaceUpdated, + (const void* allocation, size_t row_bytes, size_t height), + (override)); + MOCK_METHOD(PointerLocation, GetPrimaryPointerLocation, (), (override)); + MOCK_METHOD(AlertPlatformNodeDelegate*, GetAlertDelegate, (), (override)); + MOCK_METHOD(ui::AXPlatformNodeWin*, GetAlert, (), (override)); + MOCK_METHOD(bool, Focus, (), (override)); + + private: + FML_DISALLOW_COPY_AND_ASSIGN(MockWindowBindingHandler); +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_WINDOW_BINDING_HANDLER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/mock_window_binding_handler_delegate.h b/flutter/engine/src/flutter/shell/platform/windows/testing/mock_window_binding_handler_delegate.h new file mode 100644 index 0000000000000000000000000000000000000000..7d50fba84d0767c3b1fca624d6d7d2d727c38c1d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/mock_window_binding_handler_delegate.h @@ -0,0 +1,91 @@ +// 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_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_WINDOW_BINDING_HANDLER_DELEGATE_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_WINDOW_BINDING_HANDLER_DELEGATE_H_ + +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/windows/window_binding_handler_delegate.h" +#include "gmock/gmock.h" + +namespace flutter { +namespace testing { + +class MockWindowBindingHandlerDelegate : public WindowBindingHandlerDelegate { + public: + MockWindowBindingHandlerDelegate() {} + + MOCK_METHOD(bool, OnWindowSizeChanged, (size_t, size_t), (override)); + MOCK_METHOD(void, OnWindowRepaint, (), (override)); + MOCK_METHOD(void, + OnPointerMove, + (double, double, FlutterPointerDeviceKind, int32_t, int), + (override)); + MOCK_METHOD(void, + OnPointerDown, + (double, + double, + FlutterPointerDeviceKind, + int32_t, + FlutterPointerMouseButtons), + (override)); + MOCK_METHOD(void, + OnPointerUp, + (double, + double, + FlutterPointerDeviceKind, + int32_t, + FlutterPointerMouseButtons), + (override)); + MOCK_METHOD(void, + OnPointerLeave, + (double, double, FlutterPointerDeviceKind, int32_t), + (override)); + MOCK_METHOD(void, OnPointerPanZoomStart, (int32_t), (override)); + MOCK_METHOD(void, + OnPointerPanZoomUpdate, + (int32_t, double, double, double, double), + (override)); + MOCK_METHOD(void, OnPointerPanZoomEnd, (int32_t), (override)); + MOCK_METHOD(void, OnText, (const std::u16string&), (override)); + MOCK_METHOD(void, + OnKey, + (int, int, int, char32_t, bool, bool, KeyEventCallback), + (override)); + MOCK_METHOD(void, + OnFocus, + (FlutterViewFocusState, FlutterViewFocusDirection), + (override)); + MOCK_METHOD(void, OnComposeBegin, (), (override)); + MOCK_METHOD(void, OnComposeCommit, (), (override)); + MOCK_METHOD(void, OnComposeEnd, (), (override)); + MOCK_METHOD(void, OnComposeChange, (const std::u16string&, int), (override)); + MOCK_METHOD(void, OnUpdateSemanticsEnabled, (bool), (override)); + MOCK_METHOD(gfx::NativeViewAccessible, + GetNativeViewAccessible, + (), + (override)); + MOCK_METHOD( + void, + OnScroll, + (double, double, double, double, int, FlutterPointerDeviceKind, int32_t), + (override)); + MOCK_METHOD(void, OnScrollInertiaCancel, (int32_t), (override)); + MOCK_METHOD(void, OnHighContrastChanged, (), (override)); + + MOCK_METHOD(ui::AXFragmentRootDelegateWin*, + GetAxFragmentRootDelegate, + (), + (override)); + + MOCK_METHOD(void, OnWindowStateEvent, (HWND, WindowStateEvent), (override)); + + private: + FML_DISALLOW_COPY_AND_ASSIGN(MockWindowBindingHandlerDelegate); +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_WINDOW_BINDING_HANDLER_DELEGATE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/mock_windows_proc_table.h b/flutter/engine/src/flutter/shell/platform/windows/testing/mock_windows_proc_table.h new file mode 100644 index 0000000000000000000000000000000000000000..f7e47b9f6030a3a6d3f69ae989b344460427c351 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/mock_windows_proc_table.h @@ -0,0 +1,51 @@ +// 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_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_WINDOWS_PROC_TABLE_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_WINDOWS_PROC_TABLE_H_ + +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/windows/windows_proc_table.h" +#include "gmock/gmock.h" + +namespace flutter { +namespace testing { + +/// Mock for the |WindowsProcTable| base class. +class MockWindowsProcTable : public WindowsProcTable { + public: + MockWindowsProcTable() = default; + virtual ~MockWindowsProcTable() = default; + + MOCK_METHOD(BOOL, + GetPointerType, + (UINT32 pointer_id, POINTER_INPUT_TYPE* pointer_type), + (const, override)); + + MOCK_METHOD(LRESULT, + GetThreadPreferredUILanguages, + (DWORD, PULONG, PZZWSTR, PULONG), + (const, override)); + + MOCK_METHOD(bool, GetHighContrastEnabled, (), (const, override)); + + MOCK_METHOD(bool, DwmIsCompositionEnabled, (), (const, override)); + + MOCK_METHOD(HRESULT, DwmFlush, (), (const, override)); + + MOCK_METHOD(HCURSOR, + LoadCursor, + (HINSTANCE instance, LPCWSTR cursor_name), + (const, override)); + + MOCK_METHOD(HCURSOR, SetCursor, (HCURSOR cursor), (const, override)); + + private: + FML_DISALLOW_COPY_AND_ASSIGN(MockWindowsProcTable); +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_WINDOWS_PROC_TABLE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/test_binary_messenger.h b/flutter/engine/src/flutter/shell/platform/windows/testing/test_binary_messenger.h new file mode 100644 index 0000000000000000000000000000000000000000..9b7f2c9b043f15c2d8ac1d7e259d817bc574fd35 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/test_binary_messenger.h @@ -0,0 +1,79 @@ +// 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_SHELL_PLATFORM_WINDOWS_TESTING_TEST_BINARY_MESSENGER_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_TEST_BINARY_MESSENGER_H_ + +#include +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/common/client_wrapper/include/flutter/binary_messenger.h" + +namespace flutter { + +// A trivial BinaryMessenger implementation for use in tests. +class TestBinaryMessenger : public BinaryMessenger { + public: + using SendHandler = std::function; + + // Creates a new messenge that forwards all calls to |send_handler|. + explicit TestBinaryMessenger(SendHandler send_handler = nullptr) + : send_handler_(std::move(send_handler)) {} + + virtual ~TestBinaryMessenger() = default; + + // Simulates a message from the engine on the given channel. + // + // Returns false if no handler is registered on that channel. + bool SimulateEngineMessage(const std::string& channel, + const uint8_t* message, + size_t message_size, + BinaryReply reply) { + auto handler = registered_handlers_.find(channel); + if (handler == registered_handlers_.end()) { + return false; + } + (handler->second)(message, message_size, reply); + return true; + } + + // |flutter::BinaryMessenger| + void Send(const std::string& channel, + const uint8_t* message, + size_t message_size, + BinaryReply reply) const override { + // If something under test sends a message, the test should be handling it. + FML_DCHECK(send_handler_); + send_handler_(channel, message, message_size, reply); + } + + // |flutter::BinaryMessenger| + void SetMessageHandler(const std::string& channel, + BinaryMessageHandler handler) override { + if (handler) { + registered_handlers_[channel] = handler; + } else { + registered_handlers_.erase(channel); + } + } + + private: + // Handler to call for SendMessage. + SendHandler send_handler_; + + // Mapping of channel name to registered handlers. + std::map registered_handlers_; + + FML_DISALLOW_COPY_AND_ASSIGN(TestBinaryMessenger); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_TEST_BINARY_MESSENGER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/test_keyboard.cc b/flutter/engine/src/flutter/shell/platform/windows/testing/test_keyboard.cc new file mode 100644 index 0000000000000000000000000000000000000000..4d2109a657108f5d6ec01c9727cfbbf18bdb66e3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/test_keyboard.cc @@ -0,0 +1,249 @@ +// 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/shell/platform/windows/testing/test_keyboard.h" + +#include + +#include "flutter/fml/logging.h" +#include "flutter/shell/platform/common/json_message_codec.h" +#include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h" + +namespace flutter { +namespace testing { + +char* clone_string(const char* string) { + if (string == nullptr) { + return nullptr; + } + size_t len = strlen(string); + char* result = new char[len + 1]; + strcpy(result, string); + return result; +} + +namespace { +std::string _print_character(const char* s) { + if (s == nullptr) { + return "nullptr"; + } + return std::string("\"") + s + "\""; +} + +std::unique_ptr> _keyHandlingResponse(bool handled) { + rapidjson::Document document; + auto& allocator = document.GetAllocator(); + document.SetObject(); + document.AddMember("handled", handled, allocator); + return flutter::JsonMessageCodec::GetInstance().EncodeMessage(document); +} + +static std::string ordinal(int num) { + switch (num) { + case 1: + return "st"; + case 2: + return "nd"; + case 3: + return "rd"; + default: + return "th"; + } +} +} // namespace + +#define _RETURN_IF_NOT_EQUALS(val1, val2) \ + if ((val1) != (val2)) { \ + return ::testing::AssertionFailure() \ + << "Expected equality of these values:\n " #val1 "\n " << val2 \ + << "\n Actual: \n " << val1; \ + } + +::testing::AssertionResult _EventEquals(const char* expr_event, + const char* expr_expected, + const FlutterKeyEvent& event, + const FlutterKeyEvent& expected) { + _RETURN_IF_NOT_EQUALS(event.struct_size, sizeof(FlutterKeyEvent)); + _RETURN_IF_NOT_EQUALS(event.type, expected.type); + _RETURN_IF_NOT_EQUALS(event.physical, expected.physical); + _RETURN_IF_NOT_EQUALS(event.logical, expected.logical); + if ((event.character == nullptr) != (expected.character == nullptr) || + strcmp(event.character, expected.character) != 0) { + return ::testing::AssertionFailure() + << "Expected equality of these values:\n expected.character\n " + << _print_character(expected.character) << "\n Actual: \n " + << _print_character(event.character); + } + _RETURN_IF_NOT_EQUALS(event.synthesized, expected.synthesized); + return ::testing::AssertionSuccess(); +} + +LPARAM CreateKeyEventLparam(USHORT scancode, + bool extended, + bool was_down, + USHORT repeat_count, + bool context_code, + bool transition_state) { + return ((LPARAM(transition_state) << 31) | (LPARAM(was_down) << 30) | + (LPARAM(context_code) << 29) | (LPARAM(extended ? 0x1 : 0x0) << 24) | + (LPARAM(scancode) << 16) | LPARAM(repeat_count)); +} + +static std::shared_ptr stored_response_controller; + +// Set EngineModifier, listen to event messages that go through the channel and +// the embedder API, while disabling other methods so that the engine can be +// run headlessly. +// +// The |channel_handler| and |embedder_handler| should return a boolean +// indicating whether the framework decides to handle the event. +void MockEmbedderApiForKeyboard( + EngineModifier& modifier, + std::shared_ptr response_controller) { + stored_response_controller = response_controller; + // This mock handles channel messages. + modifier.embedder_api() + .SendPlatformMessage = [](FLUTTER_API_SYMBOL(FlutterEngine) engine, + const FlutterPlatformMessage* message) { + if (std::string(message->channel) == std::string("flutter/settings")) { + return kSuccess; + } + if (std::string(message->channel) == std::string("flutter/keyevent")) { + stored_response_controller->HandleChannelMessage([message](bool handled) { + auto response = _keyHandlingResponse(handled); + auto response_handle = message->response_handle; + if (response_handle->callback != nullptr) { + response_handle->callback(response->data(), response->size(), + response_handle->user_data); + } + }); + return kSuccess; + } + if (std::string(message->channel) == std::string("flutter/textinput")) { + std::unique_ptr document = + flutter::JsonMessageCodec::GetInstance().DecodeMessage( + message->message, message->message_size); + if (document == nullptr) { + return kInvalidArguments; + } + stored_response_controller->HandleTextInputMessage(std::move(document)); + return kSuccess; + } + return kSuccess; + }; + + // This mock handles key events sent through the embedder API. + modifier.embedder_api().SendKeyEvent = + [](FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterKeyEvent* event, + FlutterKeyEventCallback callback, void* user_data) { + stored_response_controller->HandleEmbedderMessage( + event, [callback, user_data](bool handled) { + if (callback != nullptr) { + callback(handled, user_data); + } + }); + return kSuccess; + }; + + // The following mocks enable channel mocking. + modifier.embedder_api().PlatformMessageCreateResponseHandle = + [](auto engine, auto data_callback, auto user_data, auto response_out) { + auto response_handle = new FlutterPlatformMessageResponseHandle(); + response_handle->user_data = user_data; + response_handle->callback = data_callback; + *response_out = response_handle; + return kSuccess; + }; + + modifier.embedder_api().PlatformMessageReleaseResponseHandle = + [](FLUTTER_API_SYMBOL(FlutterEngine) engine, + FlutterPlatformMessageResponseHandle* response) { + delete response; + return kSuccess; + }; + + // The following mock disables responses for method channels sent from the + // embedding to the framework. (No code uses the response yet.) + modifier.embedder_api().SendPlatformMessageResponse = + [](FLUTTER_API_SYMBOL(FlutterEngine) engine, + const FlutterPlatformMessageResponseHandle* handle, + const uint8_t* data, size_t data_length) { return kSuccess; }; + + // The following mocks allows RunWithEntrypoint to be run, which creates a + // non-empty FlutterEngine and enables SendKeyEvent. + + modifier.embedder_api().Run = + [](size_t version, const FlutterRendererConfig* config, + const FlutterProjectArgs* args, void* user_data, + FLUTTER_API_SYMBOL(FlutterEngine) * engine_out) { + *engine_out = reinterpret_cast(1); + + return kSuccess; + }; + // Any time the associated EmbedderEngine will be mocked, such as here, + // the Update accessibility features must not attempt to actually push the + // update + modifier.embedder_api().UpdateAccessibilityFeatures = + [](FLUTTER_API_SYMBOL(FlutterEngine) engine, + FlutterAccessibilityFeature flags) { return kSuccess; }; + modifier.embedder_api().UpdateLocales = + [](auto engine, const FlutterLocale** locales, size_t locales_count) { + return kSuccess; + }; + modifier.embedder_api().SendWindowMetricsEvent = + [](auto engine, const FlutterWindowMetricsEvent* event) { + return kSuccess; + }; + modifier.embedder_api().Shutdown = [](auto engine) { return kSuccess; }; + modifier.embedder_api().NotifyDisplayUpdate = + [](auto engine, const FlutterEngineDisplaysUpdateType update_type, + const FlutterEngineDisplay* embedder_displays, + size_t display_count) { return kSuccess; }; +} + +void MockMessageQueue::PushBack(const Win32Message* message) { + _pending_messages.push_back(*message); +} + +LRESULT MockMessageQueue::DispatchFront() { + FML_DCHECK(!_pending_messages.empty()) + << "Called DispatchFront while pending message queue is empty"; + Win32Message message = _pending_messages.front(); + _pending_messages.pop_front(); + _sent_messages.push_back(message); + LRESULT result = + Win32SendMessage(message.message, message.wParam, message.lParam); + if (message.expected_result != kWmResultDontCheck) { + EXPECT_EQ(result, message.expected_result) + << " This is the " << _sent_messages.size() + << ordinal(_sent_messages.size()) << " event, with\n " << std::hex + << "Message 0x" << message.message << " LParam 0x" << message.lParam + << " WParam 0x" << message.wParam; + } + return result; +} + +BOOL MockMessageQueue::Win32PeekMessage(LPMSG lpMsg, + UINT wMsgFilterMin, + UINT wMsgFilterMax, + UINT wRemoveMsg) { + for (auto iter = _pending_messages.begin(); iter != _pending_messages.end(); + ++iter) { + if (iter->message >= wMsgFilterMin && iter->message <= wMsgFilterMax) { + *lpMsg = MSG{ + .message = iter->message, + .wParam = iter->wParam, + .lParam = iter->lParam, + }; + if ((wRemoveMsg & PM_REMOVE) == PM_REMOVE) { + _pending_messages.erase(iter); + } + return TRUE; + } + } + return FALSE; +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/test_keyboard.h b/flutter/engine/src/flutter/shell/platform/windows/testing/test_keyboard.h new file mode 100644 index 0000000000000000000000000000000000000000..bcadb6f5126629c5ad37ab5d48926cdd1f7d30ac --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/test_keyboard.h @@ -0,0 +1,161 @@ +// 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_SHELL_PLATFORM_WINDOWS_TESTING_TEST_KEYBOARD_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_TEST_KEYBOARD_H_ + +#include + +#include +#include + +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/embedder/embedder.h" +#include "flutter/shell/platform/windows/testing/engine_modifier.h" +#include "flutter/shell/platform/windows/testing/wm_builders.h" + +#include "gtest/gtest.h" + +struct _FlutterPlatformMessageResponseHandle { + FlutterDesktopBinaryReply callback; + void* user_data; +}; + +namespace flutter { +namespace testing { +::testing::AssertionResult _EventEquals(const char* expr_event, + const char* expr_expected, + const FlutterKeyEvent& event, + const FlutterKeyEvent& expected); + +// Clone string onto the heap. +// +// If #string is nullptr, returns nullptr. Otherwise, the returned pointer must +// be freed with delete[]. +char* clone_string(const char* string); + +// Creates a valid Windows LPARAM for WM_KEYDOWN and WM_CHAR from parameters +// given. +// +// While |CreateKeyEventLparam| is flexible, it's recommended to use dedicated +// functions in wm_builders.h, such as |WmKeyDownInfo|. +LPARAM CreateKeyEventLparam(USHORT scancode, + bool extended, + bool was_down, + USHORT repeat_count = 1, + bool context_code = 0, + bool transition_state = 1); + +class MockKeyResponseController { + public: + using ResponseCallback = std::function; + using EmbedderCallbackHandler = + std::function; + using ChannelCallbackHandler = std::function; + using TextInputCallbackHandler = + std::function)>; + + MockKeyResponseController() + : channel_response_(ChannelRespondFalse), + embedder_response_(EmbedderRespondFalse), + text_input_response_( + [](std::unique_ptr document) {}) {} + + void SetChannelResponse(ChannelCallbackHandler handler) { + channel_response_ = std::move(handler); + } + + void SetEmbedderResponse(EmbedderCallbackHandler handler) { + embedder_response_ = std::move(handler); + } + + void SetTextInputResponse(TextInputCallbackHandler handler) { + text_input_response_ = std::move(handler); + } + + void HandleChannelMessage(ResponseCallback callback) { + channel_response_(callback); + } + + void HandleEmbedderMessage(const FlutterKeyEvent* event, + ResponseCallback callback) { + embedder_response_(event, std::move(callback)); + } + + void HandleTextInputMessage(std::unique_ptr document) { + text_input_response_(std::move(document)); + } + + private: + EmbedderCallbackHandler embedder_response_; + ChannelCallbackHandler channel_response_; + TextInputCallbackHandler text_input_response_; + + static void ChannelRespondFalse(ResponseCallback callback) { + callback(false); + } + + static void EmbedderRespondFalse(const FlutterKeyEvent* event, + ResponseCallback callback) { + callback(false); + } + + FML_DISALLOW_COPY_AND_ASSIGN(MockKeyResponseController); +}; + +void MockEmbedderApiForKeyboard( + EngineModifier& modifier, + std::shared_ptr response_controller); + +// Simulate a message queue for WM messages. +// +// Subclasses must implement |Win32SendMessage| for how dispatched messages are +// processed. +class MockMessageQueue { + protected: + // Push a message to the message queue without dispatching it. + void PushBack(const Win32Message* message); + + // Dispatch the first message of the message queue and return its result. + // + // This method asserts that the queue is not empty. + LRESULT DispatchFront(); + + // Peak the next message in the message queue. + // + // See Win32's |PeekMessage| for documentation. + BOOL Win32PeekMessage(LPMSG lpMsg, + UINT wMsgFilterMin, + UINT wMsgFilterMax, + UINT wRemoveMsg); + + // Simulate dispatching a message to the system. + virtual LRESULT Win32SendMessage(UINT const message, + WPARAM const wparam, + LPARAM const lparam) = 0; + + std::list _pending_messages; + std::list _sent_messages; +}; + +} // namespace testing +} // namespace flutter + +// Expect the |_target| FlutterKeyEvent has the required properties. +#define EXPECT_EVENT_EQUALS(_target, _type, _physical, _logical, _character, \ + _synthesized) \ + EXPECT_PRED_FORMAT2( \ + _EventEquals, _target, \ + (FlutterKeyEvent{ \ + /* struct_size = */ sizeof(FlutterKeyEvent), \ + /* timestamp = */ 0, \ + /* type = */ _type, \ + /* physical = */ _physical, \ + /* logical = */ _logical, \ + /* character = */ _character, \ + /* synthesized = */ _synthesized, \ + /* device_type = */ kFlutterKeyEventDeviceTypeKeyboard, \ + })); + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_TEST_KEYBOARD_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/test_keyboard_unittests.cc b/flutter/engine/src/flutter/shell/platform/windows/testing/test_keyboard_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..58f2f59a00ac69a5eb64c73fafa9f4d5f985bc9f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/test_keyboard_unittests.cc @@ -0,0 +1,30 @@ +// 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 + +#include "flutter/shell/platform/windows/testing/test_keyboard.h" +#include "gtest/gtest.h" + +namespace flutter { +namespace testing { + +TEST(TestKeyboard, CloneString) { + const char* str1 = "123"; + char* cloned_str1 = clone_string(str1); + EXPECT_STREQ(str1, cloned_str1); + EXPECT_NE(str1, cloned_str1); + delete[] cloned_str1; + + EXPECT_EQ(clone_string(nullptr), nullptr); +}; + +TEST(TestKeyboard, CreateKeyEventLparam) { + EXPECT_EQ(CreateKeyEventLparam(0x1, true, true), 0xC1010001); + + EXPECT_EQ(CreateKeyEventLparam(0x05, false, false, 0, 1, 0), 0x20050000); +}; + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/view_modifier.h b/flutter/engine/src/flutter/shell/platform/windows/testing/view_modifier.h new file mode 100644 index 0000000000000000000000000000000000000000..f99f04fe903781f549915c53f80d7b91d0bbc953 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/view_modifier.h @@ -0,0 +1,36 @@ +// 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_SHELL_PLATFORM_WINDOWS_TESTING_VIEW_MODIFIER_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_VIEW_MODIFIER_H_ + +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/windows/egl/window_surface.h" +#include "flutter/shell/platform/windows/flutter_windows_view.h" + +namespace flutter { + +// A test utility class providing the ability to access and alter various +// private fields in a |FlutterWindowsView| instance. +class ViewModifier { + public: + explicit ViewModifier(FlutterWindowsView* view) : view_(view) {} + + // Override the EGL surface used by the view. + // + // Modifications are to the view, and will last for the lifetime of the + // view unless overwritten again. + void SetSurface(std::unique_ptr surface) { + view_->surface_ = std::move(surface); + } + + private: + FlutterWindowsView* view_; + + FML_DISALLOW_COPY_AND_ASSIGN(ViewModifier); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_VIEW_MODIFIER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/windows_test.cc b/flutter/engine/src/flutter/shell/platform/windows/testing/windows_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..bd5bbb1c0012a45130e014c97bd7235ec7427db4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/windows_test.cc @@ -0,0 +1,26 @@ +// 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/shell/platform/windows/testing/windows_test.h" + +#include + +#include "flutter/shell/platform/windows/testing/windows_test_context.h" +#include "flutter/testing/testing.h" + +namespace flutter { +namespace testing { + +WindowsTest::WindowsTest() : context_(GetFixturesDirectory()) {} + +std::string WindowsTest::GetFixturesDirectory() const { + return GetFixturesPath(); +} + +WindowsTestContext& WindowsTest::GetContext() { + return context_; +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/windows_test.h b/flutter/engine/src/flutter/shell/platform/windows/testing/windows_test.h new file mode 100644 index 0000000000000000000000000000000000000000..21744d0ea8634a6cb0d41592e21e4c0a81d8423f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/windows_test.h @@ -0,0 +1,47 @@ +// 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_SHELL_PLATFORM_WINDOWS_TESTING_WINDOWS_TEST_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_WINDOWS_TEST_H_ + +#include + +#include "flutter/fml/macros.h" +#include "flutter/shell/platform/windows/testing/windows_test_context.h" +#include "flutter/testing/thread_test.h" + +namespace flutter { +namespace testing { + +/// A GoogleTest test fixture for Windows tests. +/// +/// Supports looking up the test fixture data defined in the GN `test_fixtures` +/// associated with the unit test executable target. This typically includes +/// the kernel bytecode `kernel_blob.bin` compiled from the Dart file specified +/// in the test fixture's `dart_main` property, as well as any other data files +/// used in tests, such as image files used in a screenshot golden test. +/// +/// This test class can be used in GoogleTest tests using the standard +/// `TEST_F(WindowsTest, TestName)` macro. +class WindowsTest : public ThreadTest { + public: + WindowsTest(); + + // Returns the path to test fixture data such as kernel bytecode or images + // used by the C++ side of the test. + std::string GetFixturesDirectory() const; + + // Returns the test context associated with this fixture. + WindowsTestContext& GetContext(); + + private: + WindowsTestContext context_; + + FML_DISALLOW_COPY_AND_ASSIGN(WindowsTest); +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_WINDOWS_TEST_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/windows_test_config_builder.cc b/flutter/engine/src/flutter/shell/platform/windows/testing/windows_test_config_builder.cc new file mode 100644 index 0000000000000000000000000000000000000000..96b984cf0b121e2c6df592731d78bbd01cc31dee --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/windows_test_config_builder.cc @@ -0,0 +1,140 @@ +// 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/shell/platform/windows/testing/windows_test_config_builder.h" + +#include + +#include +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/shell/platform/windows/flutter_windows_engine.h" +#include "flutter/shell/platform/windows/public/flutter_windows.h" +#include "flutter/shell/platform/windows/testing/windows_test_context.h" + +namespace flutter { +namespace testing { + +WindowsConfigBuilder::WindowsConfigBuilder(WindowsTestContext& context) + : context_(context) {} + +WindowsConfigBuilder::~WindowsConfigBuilder() = default; + +void WindowsConfigBuilder::SetDartEntrypoint(std::string_view entrypoint) { + if (entrypoint.empty()) { + return; + } + dart_entrypoint_ = entrypoint; +} + +void WindowsConfigBuilder::SetUIThreadPolicy( + FlutterDesktopUIThreadPolicy policy) { + ui_thread_policy_ = policy; +} + +void WindowsConfigBuilder::AddDartEntrypointArgument(std::string_view arg) { + if (arg.empty()) { + return; + } + + dart_entrypoint_arguments_.emplace_back(std::move(arg)); +} + +void WindowsConfigBuilder::SetGpuPreference( + FlutterDesktopGpuPreference gpu_preference) { + gpu_preference_ = gpu_preference; +} + +FlutterDesktopEngineProperties WindowsConfigBuilder::GetEngineProperties() + const { + FlutterDesktopEngineProperties engine_properties = {}; + engine_properties.assets_path = context_.GetAssetsPath().c_str(); + engine_properties.icu_data_path = context_.GetIcuDataPath().c_str(); + + // Set Dart entrypoint. + engine_properties.dart_entrypoint = dart_entrypoint_.c_str(); + + // Set Dart entrypoint argc, argv. + std::vector dart_args; + dart_args.reserve(dart_entrypoint_arguments_.size()); + for (const auto& arg : dart_entrypoint_arguments_) { + dart_args.push_back(arg.c_str()); + } + if (!dart_args.empty()) { + engine_properties.dart_entrypoint_argv = dart_args.data(); + engine_properties.dart_entrypoint_argc = dart_args.size(); + } else { + // Clear this out in case this is not the first engine launch from the + // embedder config builder. + engine_properties.dart_entrypoint_argv = nullptr; + engine_properties.dart_entrypoint_argc = 0; + } + + engine_properties.gpu_preference = gpu_preference_; + engine_properties.ui_thread_policy = ui_thread_policy_; + + return engine_properties; +} + +EnginePtr WindowsConfigBuilder::InitializeEngine() const { + FlutterDesktopEngineProperties engine_properties = GetEngineProperties(); + return EnginePtr{FlutterDesktopEngineCreate(&engine_properties)}; +} + +EnginePtr WindowsConfigBuilder::RunHeadless() const { + InitializeCOM(); + + EnginePtr engine = InitializeEngine(); + if (!engine) { + return {}; + } + + // Register native functions. + FlutterWindowsEngine* windows_engine = + reinterpret_cast(engine.get()); + windows_engine->SetRootIsolateCreateCallback( + context_.GetRootIsolateCallback()); + + if (!FlutterDesktopEngineRun(engine.get(), /* entry_point */ nullptr)) { + return {}; + } + + return engine; +} + +ViewControllerPtr WindowsConfigBuilder::Run() const { + InitializeCOM(); + + EnginePtr engine = InitializeEngine(); + if (!engine) { + return {}; + } + + // Register native functions. + FlutterWindowsEngine* windows_engine = + reinterpret_cast(engine.get()); + windows_engine->SetRootIsolateCreateCallback( + context_.GetRootIsolateCallback()); + + int width = 600; + int height = 400; + + // Create a view controller that owns the engine. + ViewControllerPtr controller{ + FlutterDesktopViewControllerCreate(width, height, engine.release())}; + if (!controller) { + return {}; + } + + return controller; +} + +void WindowsConfigBuilder::InitializeCOM() const { + FML_CHECK(SUCCEEDED(::CoInitializeEx(nullptr, COINIT_MULTITHREADED))); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/windows_test_config_builder.h b/flutter/engine/src/flutter/shell/platform/windows/testing/windows_test_config_builder.h new file mode 100644 index 0000000000000000000000000000000000000000..07da63b2452bf10a685eaaf702b726ee647a7a98 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/windows_test_config_builder.h @@ -0,0 +1,105 @@ +// 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_SHELL_PLATFORM_WINDOWS_TESTING_WINDOWS_TEST_CONFIG_BUILDER_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_WINDOWS_TEST_CONFIG_BUILDER_H_ + +#include +#include +#include + +#include "flutter/fml/macros.h" +#include "flutter/fml/unique_object.h" +#include "flutter/shell/platform/windows/public/flutter_windows.h" +#include "flutter/shell/platform/windows/testing/windows_test_context.h" + +namespace flutter { +namespace testing { + +// Deleter for FlutterDesktopEngineRef objects. +struct EngineDeleter { + typedef FlutterDesktopEngineRef pointer; + void operator()(FlutterDesktopEngineRef engine) { + FML_CHECK(FlutterDesktopEngineDestroy(engine)); + } +}; + +// Unique pointer wrapper for FlutterDesktopEngineRef. +using EnginePtr = std::unique_ptr; + +// Deleter for FlutterViewControllerRef objects. +struct ViewControllerDeleter { + typedef FlutterDesktopViewControllerRef pointer; + void operator()(FlutterDesktopViewControllerRef controller) { + FlutterDesktopViewControllerDestroy(controller); + } +}; + +// Unique pointer wrapper for FlutterDesktopViewControllerRef. +using ViewControllerPtr = + std::unique_ptr; + +// Test configuration builder for WindowsTests. +// +// Utility class for configuring engine and view controller launch arguments, +// and launching the engine to run a test fixture. +class WindowsConfigBuilder { + public: + explicit WindowsConfigBuilder(WindowsTestContext& context); + ~WindowsConfigBuilder(); + + // Returns the desktop engine properties configured for this test. + FlutterDesktopEngineProperties GetEngineProperties() const; + + // Sets the Dart entrypoint to the specified value. + // + // If not set, the default entrypoint (main) is used. Custom Dart entrypoints + // must be decorated with `@pragma('vm:entry-point')`. + void SetDartEntrypoint(std::string_view entrypoint); + + // Set the UI Thread policy for the engine. + // If not set defaults to FlutterDesktopUIThreadPolicy::Default; + void SetUIThreadPolicy(FlutterDesktopUIThreadPolicy policy); + + // Adds an argument to the Dart entrypoint arguments List. + void AddDartEntrypointArgument(std::string_view arg); + + void SetGpuPreference(FlutterDesktopGpuPreference gpu_preference); + + // Returns a configured and initialized engine. + EnginePtr InitializeEngine() const; + + // Returns a configured and initialized engine that runs the configured Dart + // entrypoint. + // + // Returns null on failure. + EnginePtr RunHeadless() const; + + // Returns a configured and initialized view controller that runs the + // configured Dart entrypoint and owns its engine. + // + // Returns null on failure. + ViewControllerPtr Run() const; + + private: + // Initialize COM, so that it is available for use in the library and/or + // plugins. + void InitializeCOM() const; + + WindowsTestContext& context_; + std::string dart_entrypoint_; + std::vector dart_entrypoint_arguments_; + FlutterDesktopUIThreadPolicy ui_thread_policy_ = + FlutterDesktopUIThreadPolicy::Default; + + FlutterDesktopGpuPreference gpu_preference_ = + FlutterDesktopGpuPreference::NoPreference; + + FML_DISALLOW_COPY_AND_ASSIGN(WindowsConfigBuilder); +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_WINDOWS_TEST_CONFIG_BUILDER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/windows_test_context.cc b/flutter/engine/src/flutter/shell/platform/windows/testing/windows_test_context.cc new file mode 100644 index 0000000000000000000000000000000000000000..30b62b59d7dbe94d8626f903f53801dd1f495d8f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/windows_test_context.cc @@ -0,0 +1,52 @@ +// 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/shell/platform/windows/testing/windows_test_context.h" + +#include "flutter/fml/platform/win/wstring_conversion.h" + +namespace flutter { +namespace testing { + +WindowsTestContext::WindowsTestContext(std::string_view assets_path) + : assets_path_(fml::Utf8ToWideString(assets_path)), + native_resolver_(std::make_shared()) { + isolate_create_callbacks_.push_back( + [weak_resolver = + std::weak_ptr{native_resolver_}]() { + if (auto resolver = weak_resolver.lock()) { + resolver->SetNativeResolverForIsolate(); + } + }); +} + +WindowsTestContext::~WindowsTestContext() = default; + +const std::wstring& WindowsTestContext::GetAssetsPath() const { + return assets_path_; +} + +const std::wstring& WindowsTestContext::GetIcuDataPath() const { + return icu_data_path_; +} + +const std::wstring& WindowsTestContext::GetAotLibraryPath() const { + return aot_library_path_; +} + +void WindowsTestContext::AddNativeFunction(std::string_view name, + Dart_NativeFunction function) { + native_resolver_->AddNativeCallback(std::string{name}, function); +} + +fml::closure WindowsTestContext::GetRootIsolateCallback() { + return [this]() { + for (auto closure : this->isolate_create_callbacks_) { + closure(); + } + }; +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/windows_test_context.h b/flutter/engine/src/flutter/shell/platform/windows/testing/windows_test_context.h new file mode 100644 index 0000000000000000000000000000000000000000..f6e37ba2b49c0494610e348bb36983c0b5793ab5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/windows_test_context.h @@ -0,0 +1,64 @@ +// 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_SHELL_PLATFORM_WINDOWS_TESTING_WINDOWS_TEST_CONTEXT_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_WINDOWS_TEST_CONTEXT_H_ + +#include +#include +#include + +#include "flutter/fml/closure.h" +#include "flutter/fml/macros.h" +#include "flutter/testing/test_dart_native_resolver.h" + +namespace flutter { +namespace testing { + +// Context associated with the current Windows test fixture. +// +// Context data includes global Flutter and Dart runtime context such as the +// path of Flutter's asset directory, ICU path, and resolvers for any +// registered native functions. +class WindowsTestContext { + public: + explicit WindowsTestContext(std::string_view assets_path = ""); + virtual ~WindowsTestContext(); + + // Returns the path to assets required by the Flutter runtime. + const std::wstring& GetAssetsPath() const; + + // Returns the path to the ICU library data file. + const std::wstring& GetIcuDataPath() const; + + // Returns the path to the application's AOT library file. + const std::wstring& GetAotLibraryPath() const; + + // Registers a native function callable from Dart code in test fixtures. In + // the Dart test fixture, the associated function can be declared as: + // + // @pragma('vm:external-name', 'IdentifyingName') + // external ReturnType functionName(); + // + // where `IdentifyingName` matches the |name| parameter to this method. + void AddNativeFunction(std::string_view name, Dart_NativeFunction function); + + // Returns the root isolate create callback to register with the Flutter + // runtime. + fml::closure GetRootIsolateCallback(); + + private: + std::wstring assets_path_; + std::wstring icu_data_path_ = L"icudtl.dat"; + std::wstring aot_library_path_ = L"aot.so"; + std::vector isolate_create_callbacks_; + std::shared_ptr native_resolver_; + + FML_DISALLOW_COPY_AND_ASSIGN(WindowsTestContext); +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_WINDOWS_TEST_CONTEXT_H_ diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/wm_builders.cc b/flutter/engine/src/flutter/shell/platform/windows/testing/wm_builders.cc new file mode 100644 index 0000000000000000000000000000000000000000..a9e3ff9fdcf9dce8ffee15515b27dbfb6e92de3f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/wm_builders.cc @@ -0,0 +1,81 @@ +// 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/shell/platform/windows/testing/wm_builders.h" + +namespace flutter { +namespace testing { + +Win32Message WmKeyDownInfo::Build(LRESULT expected_result) { + LPARAM lParam = (repeat_count << 0) | (scan_code << 16) | (extended << 24) | + (prev_state << 30); + return Win32Message{ + .message = WM_KEYDOWN, + .wParam = key, + .lParam = lParam, + .expected_result = expected_result, + }; +} + +Win32Message WmKeyUpInfo::Build(LRESULT expected_result) { + LPARAM lParam = (1 /* repeat_count */ << 0) | (scan_code << 16) | + (extended << 24) | (!overwrite_prev_state_0 << 30) | + (1 /* transition */ << 31); + return Win32Message{ + .message = WM_KEYUP, + .wParam = key, + .lParam = lParam, + .expected_result = expected_result, + }; +} + +Win32Message WmCharInfo::Build(LRESULT expected_result) { + LPARAM lParam = (repeat_count << 0) | (scan_code << 16) | (extended << 24) | + (bit25 << 25) | (context << 29) | (prev_state << 30) | + (transition << 31); + return Win32Message{ + .message = WM_CHAR, + .wParam = char_code, + .lParam = lParam, + .expected_result = expected_result, + }; +} + +Win32Message WmSysKeyDownInfo::Build(LRESULT expected_result) { + LPARAM lParam = (repeat_count << 0) | (scan_code << 16) | (extended << 24) | + (context << 29) | (prev_state << 30) | + (0 /* transition */ << 31); + return Win32Message{ + .message = WM_SYSKEYDOWN, + .wParam = key, + .lParam = lParam, + .expected_result = expected_result, + }; +} + +Win32Message WmSysKeyUpInfo::Build(LRESULT expected_result) { + LPARAM lParam = (1 /* repeat_count */ << 0) | (scan_code << 16) | + (extended << 24) | (context << 29) | + (1 /* prev_state */ << 30) | (1 /* transition */ << 31); + return Win32Message{ + .message = WM_SYSKEYUP, + .wParam = key, + .lParam = lParam, + .expected_result = expected_result, + }; +} + +Win32Message WmDeadCharInfo::Build(LRESULT expected_result) { + LPARAM lParam = (repeat_count << 0) | (scan_code << 16) | (extended << 24) | + (context << 30) | (prev_state << 30) | (transition << 31); + return Win32Message{ + .message = WM_DEADCHAR, + .wParam = char_code, + .lParam = lParam, + .expected_result = expected_result, + }; +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/windows/testing/wm_builders.h b/flutter/engine/src/flutter/shell/platform/windows/testing/wm_builders.h new file mode 100644 index 0000000000000000000000000000000000000000..49b78035b7e01f56ae0df76646a1ea33f09eb626 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/windows/testing/wm_builders.h @@ -0,0 +1,186 @@ +// 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_SHELL_PLATFORM_WINDOWS_TESTING_WM_BUILDERS_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_WM_BUILDERS_H_ + +#include +#include + +namespace flutter { +namespace testing { + +constexpr LRESULT kWmResultZero = 0; +constexpr LRESULT kWmResultDefault = 0xDEADC0DE; +constexpr LRESULT kWmResultDontCheck = 0xFFFF1234; + +// A struct to hold simulated events that will be delivered after the framework +// response is handled. +struct Win32Message { + UINT message; + WPARAM wParam; + LPARAM lParam; + LRESULT expected_result; +}; + +typedef enum WmFieldExtended { + kNotExtended = 0, + kExtended = 1, +} WmFieldExtended; + +typedef enum WmFieldContext { + kNoContext = 0, + kAltHeld = 1, +} WmFieldContext; + +typedef enum WmFieldPrevState { + kWasUp = 0, + kWasDown = 1, +} WmFieldPrevState; + +typedef enum WmFieldTransitionState { + kBeingReleased = 0, + kBeingPressed = 1, +} WmFieldTransitionState; + +// WM_KEYDOWN messages. +// +// See https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-keydown. +typedef struct WmKeyDownInfo { + uint32_t key; + + uint8_t scan_code; + + WmFieldExtended extended; + + WmFieldPrevState prev_state; + + // WmFieldTransitionState transition; // Always 0. + + // WmFieldContext context; // Always 0. + + uint16_t repeat_count = 1; + + Win32Message Build(LRESULT expected_result = kWmResultDontCheck); +} WmKeyDownInfo; + +// WM_KEYUP messages. +// +// See https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-keyup. +typedef struct WmKeyUpInfo { + uint32_t key; + + uint8_t scan_code; + + WmFieldExtended extended; + + // WmFieldPrevState prev_state; // Always 1. + + // WmFieldTransitionState transition; // Always 1. + + // WmFieldContext context; // Always 0. + + // uint16_t repeat_count; // Always 1. + + // Set this flag to enforce prev_state to be 0. + // + // This occurs in rare cases when the message is synthesized. + bool overwrite_prev_state_0; + + Win32Message Build(LRESULT expected_result = kWmResultDontCheck); +} WmKeyUpInfo; + +// WM_CHAR messages. +// +// See https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-char. +typedef struct WmCharInfo { + uint32_t char_code; + + uint8_t scan_code; + + WmFieldExtended extended; + + WmFieldPrevState prev_state; + + WmFieldTransitionState transition; + + WmFieldContext context; + + uint16_t repeat_count = 1; + + // The 25th bit of the LParam. + // + // Some messages are sent with bit25 set. Its meaning is yet unknown. + bool bit25 = 0; + + Win32Message Build(LRESULT expected_result = kWmResultDontCheck); +} WmCharInfo; + +// WM_SYSKEYDOWN messages. +// +// See https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-syskeydown. +typedef struct WmSysKeyDownInfo { + uint32_t key; + + uint8_t scan_code; + + WmFieldExtended extended; + + WmFieldPrevState prev_state; + + // WmFieldTransitionState transition; // Always 0. + + WmFieldContext context; + + uint16_t repeat_count = 1; + + Win32Message Build(LRESULT expected_result = kWmResultDontCheck); +} WmSysKeyDownInfo; + +// WM_SYSKEYUP messages. +// +// See https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-syskeyup. +typedef struct WmSysKeyUpInfo { + uint32_t key; + + uint8_t scan_code; + + WmFieldExtended extended; + + // WmFieldPrevState prev_state; // Always 1. + + // WmFieldTransitionState transition; // Always 1. + + WmFieldContext context; + + // uint16_t repeat_count; // Always 1. + + Win32Message Build(LRESULT expected_result = kWmResultDontCheck); +} WmSysKeyUpInfo; + +// WM_DEADCHAR messages. +// +// See https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-deadchar. +typedef struct WmDeadCharInfo { + uint32_t char_code; + + uint8_t scan_code; + + WmFieldExtended extended; + + WmFieldPrevState prev_state; + + WmFieldTransitionState transition; + + WmFieldContext context; + + uint16_t repeat_count = 1; + + Win32Message Build(LRESULT expected_result = kWmResultDontCheck); +} WmDeadCharInfo; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_WM_BUILDERS_H_ diff --git a/novelforge-project/agent-workspace/flutter/bin/cache/artifacts/engine/android-arm-profile/flutter.jar b/novelforge-project/agent-workspace/flutter/bin/cache/artifacts/engine/android-arm-profile/flutter.jar new file mode 100644 index 0000000000000000000000000000000000000000..7bcc1dbc56f5fd9ffef883cf06a075db10a6605e --- /dev/null +++ b/novelforge-project/agent-workspace/flutter/bin/cache/artifacts/engine/android-arm-profile/flutter.jar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:27260416d007b404d5ca2a70d3f6faf84257fe844446da3a62431bca351e9944 +size 128 diff --git a/novelforge-project/agent-workspace/flutter/bin/cache/artifacts/engine/android-arm/flutter.jar b/novelforge-project/agent-workspace/flutter/bin/cache/artifacts/engine/android-arm/flutter.jar new file mode 100644 index 0000000000000000000000000000000000000000..81adc9dda349a2bff5d2e328e0350073b10cbe06 --- /dev/null +++ b/novelforge-project/agent-workspace/flutter/bin/cache/artifacts/engine/android-arm/flutter.jar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dff37df8fd6e041dc456c204f8c9714cd539b144bd56ad26ec15781a6ea9ef50 +size 128